Class: NanoGPT::Trainer

Inherits:
Object
  • Object
show all
Defined in:
lib/nano_gpt/trainer.rb

Overview

Training loop for GPT models Accepts a TrainConfig (or hash with same keys) for all configuration

Constant Summary collapse

OPTIMIZER_DEFAULTS =

Default optimizer parameters (can be overridden via config)

{
  weight_decay: 1e-1,
  beta1: 0.9,
  beta2: 0.99,
  grad_clip: 1.0,
  always_save_checkpoint: false,
  eval_only: false
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, data_loader:, config:) ⇒ Trainer

Returns a new instance of Trainer.



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/nano_gpt/trainer.rb', line 21

def initialize(model:, data_loader:, config:)
  @model = model
  @data_loader = data_loader
  @config = OPTIMIZER_DEFAULTS.merge(symbolize_keys(config.is_a?(Hash) ? config : config.to_h))

  @iter_num = 0
  @best_val_loss = Float::INFINITY

  setup_optimizer
  setup_lr_scheduler
end

Instance Attribute Details

#best_val_lossObject (readonly)

Returns the value of attribute best_val_loss.



19
20
21
# File 'lib/nano_gpt/trainer.rb', line 19

def best_val_loss
  @best_val_loss
end

#configObject (readonly)

Returns the value of attribute config.



19
20
21
# File 'lib/nano_gpt/trainer.rb', line 19

def config
  @config
end

#iter_numObject (readonly)

Returns the value of attribute iter_num.



19
20
21
# File 'lib/nano_gpt/trainer.rb', line 19

def iter_num
  @iter_num
end

#modelObject (readonly)

Returns the value of attribute model.



19
20
21
# File 'lib/nano_gpt/trainer.rb', line 19

def model
  @model
end

#optimizerObject (readonly)

Returns the value of attribute optimizer.



19
20
21
# File 'lib/nano_gpt/trainer.rb', line 19

def optimizer
  @optimizer
end

Instance Method Details

#estimate_lossObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/nano_gpt/trainer.rb', line 88

def estimate_loss
  @model.eval
  out = {}

  [:train, :val].each do |split|
    losses = []
    @config[:eval_iters].times do
      x, y = @data_loader.get_batch(split)
      Torch.no_grad do
        _logits, loss = @model.call(x, targets: y)
        losses << loss.item
      end
    end
    out[split] = losses.sum / losses.size
  end

  @model.train
  out
end

#load_checkpoint(path) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/nano_gpt/trainer.rb', line 125

def load_checkpoint(path)
  checkpoint = Torch.load(path)

  @model.load_state_dict(checkpoint["model"])
  @iter_num = checkpoint["iter_num"]
  @best_val_loss = checkpoint["best_val_loss"]

  setup_optimizer

  puts "Loaded checkpoint from #{path} (iter #{@iter_num})"
  checkpoint
end

#save_checkpointObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/nano_gpt/trainer.rb', line 108

def save_checkpoint
  FileUtils.mkdir_p(@config[:out_dir])
  path = File.join(@config[:out_dir], "ckpt.pt")

  # Torch.save requires string keys
  checkpoint = {
    "model" => @model.state_dict,
    "model_args" => stringify_keys(@model.config.to_h),
    "iter_num" => @iter_num,
    "best_val_loss" => @best_val_loss,
    "config" => stringify_keys(@config)
  }

  Torch.save(checkpoint, path)
  puts "Saved checkpoint to #{path}"
end

#trainObject



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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/nano_gpt/trainer.rb', line 33

def train
  puts "Starting training..."
  puts "Tokens per iteration: #{tokens_per_iter}"

  @model.train
  x, y = @data_loader.get_batch(:train)
  t0 = Time.now

  while @iter_num <= @config[:max_iters]
    lr = @config[:decay_lr] ? @lr_scheduler.step(@optimizer, @iter_num) : @config[:learning_rate]

    if @iter_num % @config[:eval_interval] == 0
      losses = estimate_loss
      puts "step #{@iter_num}: train loss #{losses[:train].round(4)}, val loss #{losses[:val].round(4)}"

      if losses[:val] < @best_val_loss || @config[:always_save_checkpoint]
        @best_val_loss = [losses[:val], @best_val_loss].min
        save_checkpoint if @iter_num > 0
      end
    end

    break if @iter_num == 0 && @config[:eval_only]

    @optimizer.zero_grad

    accumulated_loss = 0.0
    @config[:gradient_accumulation_steps].times do |_micro_step|
      _logits, loss = @model.call(x, targets: y)
      loss = loss / @config[:gradient_accumulation_steps]
      accumulated_loss += loss.item
      loss.backward

      x, y = @data_loader.get_batch(:train)
    end

    if @config[:grad_clip] > 0.0
      clip_grad_norm(@model.parameters, @config[:grad_clip])
    end

    @optimizer.step

    t1 = Time.now
    dt = t1 - t0
    t0 = t1

    if @iter_num % @config[:log_interval] == 0
      puts "iter #{@iter_num}: loss #{accumulated_loss.round(4)}, time #{(dt * 1000).round(2)}ms, lr #{lr.round(6)}"
    end

    @iter_num += 1
  end

  puts "Training complete!"
end