Class: Torch::Optim::Adagrad

Inherits:
Optimizer show all
Defined in:
lib/torch/optim/adagrad.rb

Instance Attribute Summary

Attributes inherited from Optimizer

#param_groups

Instance Method Summary collapse

Methods inherited from Optimizer

#add_param_group, #load_state_dict, #state_dict, #zero_grad

Constructor Details

#initialize(params, lr: 1e-2, lr_decay: 0, weight_decay: 0, initial_accumulator_value: 0, eps: 1e-10) ⇒ Adagrad

Returns a new instance of Adagrad.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/torch/optim/adagrad.rb', line 5

def initialize(params, lr: 1e-2, lr_decay: 0, weight_decay: 0, initial_accumulator_value: 0, eps: 1e-10)
  raise ArgumentError, "Invalid learning rate: #{lr}" if lr < 0
  raise ArgumentError, "Invalid lr_decay value: #{lr_decay}" if lr_decay < 0
  raise ArgumentError, "Invalid initial_accumulator_value value: #{initial_accumulator_value}" if initial_accumulator_value < 0
  raise ArgumentError, "Invalid weight_decay value: #{weight_decay}" if weight_decay < 0
  raise ArgumentError, "Invalid epsilon value: #{eps}" if eps < 0

  defaults = {lr: lr, lr_decay: lr_decay, eps: eps, weight_decay: weight_decay, initial_accumulator_value: initial_accumulator_value}
  super(params, defaults)

  @param_groups.each do |group|
    group[:params].each do |p|
      state = @state[p]
      state[:step] = 0
      state[:sum] = Torch.full_like(p.data, initial_accumulator_value)
    end
  end
end

Instance Method Details

#share_memoryObject



24
25
26
27
28
29
30
31
# File 'lib/torch/optim/adagrad.rb', line 24

def share_memory
  @param_groups.each do |group|
    group[:params].each do |p|
      state = @state[p]
      state[:sum].share_memory!
    end
  end
end

#step(closure = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/torch/optim/adagrad.rb', line 33

def step(closure = nil)
  loss = nil
  if closure
    loss = closure.call
  end

  @param_groups.each do |group|
    group[:params].each do |p|
      next unless p.grad

      grad = p.grad.data
      state = @state[p]

      state[:step] += 1

      if group[:weight_decay] != 0
        if p.grad.data.sparse?
          raise Error, "weight_decay option is not compatible with sparse gradients"
        end
        grad = grad.add(group[:weight_decay], p.data)
      end

      clr = group[:lr] / (1 + (state[:step] - 1) * group[:lr_decay])

      if grad.sparse?
        raise NotImplementedYet
      else
        state[:sum].addcmul!(1, grad, grad)
        std = state[:sum].sqrt.add!(group[:eps])
        p.data.addcdiv!(-clr, grad, std)
      end
    end
  end

  loss
end