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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
# vocab size: 65
|
67 |
# train has 1003854 tokens
|
68 |
# val has 111540 tokens
|
69 |
+
|
70 |
+
|
71 |
+
"""
|
72 |
+
This training script can be run both on a single gpu in debug mode,
|
73 |
+
and also in a larger training run with distributed data parallel (ddp).
|
74 |
+
|
75 |
+
To run on a single GPU, example:
|
76 |
+
$ python train.py --batch_size=32 --compile=False
|
77 |
+
|
78 |
+
To run with DDP on 4 gpus on 1 node, example:
|
79 |
+
$ torchrun --standalone --nproc_per_node=4 train.py
|
80 |
+
|
81 |
+
To run with DDP on 4 gpus across 2 nodes, example:
|
82 |
+
- Run on the first (master) node with example IP 123.456.123.456:
|
83 |
+
$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train.py
|
84 |
+
- Run on the worker node:
|
85 |
+
$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train.py
|
86 |
+
(If your cluster does not have Infiniband interconnect prepend NCCL_IB_DISABLE=1)
|
87 |
+
"""
|
88 |
+
|
89 |
+
import os
|
90 |
+
import time
|
91 |
+
import math
|
92 |
+
import pickle
|
93 |
+
from contextlib import nullcontext
|
94 |
+
|
95 |
+
import numpy as np
|
96 |
+
import torch
|
97 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
98 |
+
from torch.distributed import init_process_group, destroy_process_group
|
99 |
+
|
100 |
+
from model import GPTConfig, GPT
|
101 |
+
|
102 |
+
# -----------------------------------------------------------------------------
|
103 |
+
# default config values designed to train a gpt2 (124M) on OpenWebText
|
104 |
+
# I/O
|
105 |
+
out_dir = 'out'
|
106 |
+
eval_interval = 2000
|
107 |
+
log_interval = 1
|
108 |
+
eval_iters = 200
|
109 |
+
eval_only = False # if True, script exits right after the first eval
|
110 |
+
always_save_checkpoint = True # if True, always save a checkpoint after each eval
|
111 |
+
init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*'
|
112 |
+
# wandb logging
|
113 |
+
wandb_log = False # disabled by default
|
114 |
+
wandb_project = 'owt'
|
115 |
+
wandb_run_name = 'gpt2' # 'run' + str(time.time())
|
116 |
+
# data
|
117 |
+
dataset = 'openwebtext'
|
118 |
+
gradient_accumulation_steps = 5 * 8 # used to simulate larger batch sizes
|
119 |
+
batch_size = 12 # if gradient_accumulation_steps > 1, this is the micro-batch size
|
120 |
+
block_size = 1024
|
121 |
+
# model
|
122 |
+
n_layer = 12
|
123 |
+
n_head = 12
|
124 |
+
n_embd = 768
|
125 |
+
dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+
|
126 |
+
bias = False # do we use bias inside LayerNorm and Linear layers?
|
127 |
+
# adamw optimizer
|
128 |
+
learning_rate = 6e-4 # max learning rate
|
129 |
+
max_iters = 600000 # total number of training iterations
|
130 |
+
weight_decay = 1e-1
|
131 |
+
beta1 = 0.9
|
132 |
+
beta2 = 0.95
|
133 |
+
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
|
134 |
+
# learning rate decay settings
|
135 |
+
decay_lr = True # whether to decay the learning rate
|
136 |
+
warmup_iters = 2000 # how many steps to warm up for
|
137 |
+
lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla
|
138 |
+
min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
|
139 |
+
# DDP settings
|
140 |
+
backend = 'nccl' # 'nccl', 'gloo', etc.
|
141 |
+
# system
|
142 |
+
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
|
143 |
+
dtype = 'bfloat16' # 'float32', 'bfloat16', or 'float16', the latter will auto implement a GradScaler
|
144 |
+
compile = True # use PyTorch 2.0 to compile the model to be faster
|
145 |
+
# -----------------------------------------------------------------------------
|
146 |
+
config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
|
147 |
+
exec(open('configurator.py').read()) # overrides from command line or config file
|
148 |
+
config = {k: globals()[k] for k in config_keys} # will be useful for logging
|
149 |
+
# -----------------------------------------------------------------------------
|
150 |
+
|
151 |
+
# various inits, derived attributes, I/O setup
|
152 |
+
ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
|
153 |
+
if ddp:
|
154 |
+
init_process_group(backend=backend)
|
155 |
+
ddp_rank = int(os.environ['RANK'])
|
156 |
+
ddp_local_rank = int(os.environ['LOCAL_RANK'])
|
157 |
+
ddp_world_size = int(os.environ['WORLD_SIZE'])
|
158 |
+
device = f'cuda:{ddp_local_rank}'
|
159 |
+
torch.cuda.set_device(device)
|
160 |
+
master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
|
161 |
+
seed_offset = ddp_rank # each process gets a different seed
|
162 |
+
assert gradient_accumulation_steps % torch.cuda.device_count() == 0
|
163 |
+
gradient_accumulation_steps //= torch.cuda.device_count()
|
164 |
+
else:
|
165 |
+
# if not ddp, we are running on a single gpu, and one process
|
166 |
+
master_process = True
|
167 |
+
seed_offset = 0
|
168 |
+
ddp_world_size = 1
|
169 |
+
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
|
170 |
+
print(f"tokens per iteration will be: {tokens_per_iter:,}")
|
171 |
+
|
172 |
+
if master_process:
|
173 |
+
os.makedirs(out_dir, exist_ok=True)
|
174 |
+
torch.manual_seed(1337 + seed_offset)
|
175 |
+
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
|
176 |
+
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
|
177 |
+
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
|
178 |
+
# note: float16 data type will automatically use a GradScaler
|
179 |
+
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
|
180 |
+
ctx = nullcontext() if device_type == 'cpu' else torch.cuda.amp.autocast(dtype=torch.float16)
|
181 |
+
|
182 |
+
# poor man's data loader
|
183 |
+
data_dir = os.path.join('data', dataset)
|
184 |
+
train_data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')
|
185 |
+
val_data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')
|
186 |
+
def get_batch(split):
|
187 |
+
data = train_data if split == 'train' else val_data
|
188 |
+
ix = torch.randint(len(data) - block_size, (batch_size,))
|
189 |
+
x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
|
190 |
+
y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
|
191 |
+
if device_type == 'cuda':
|
192 |
+
# pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
|
193 |
+
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
|
194 |
+
else:
|
195 |
+
x, y = x.to(device), y.to(device)
|
196 |
+
return x, y
|
197 |
+
|
198 |
+
# init these up here, can override if init_from='resume' (i.e. from a checkpoint)
|
199 |
+
iter_num = 0
|
200 |
+
best_val_loss = 1e9
|
201 |
+
|
202 |
+
# attempt to derive vocab_size from the dataset
|
203 |
+
meta_path = os.path.join(data_dir, 'meta.pkl')
|
204 |
+
meta_vocab_size = None
|
205 |
+
if os.path.exists(meta_path):
|
206 |
+
with open(meta_path, 'rb') as f:
|
207 |
+
meta = pickle.load(f)
|
208 |
+
meta_vocab_size = meta['vocab_size']
|
209 |
+
print(f"found vocab_size = {meta_vocab_size} (inside {meta_path})")
|
210 |
+
|
211 |
+
# model init
|
212 |
+
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
|
213 |
+
bias=bias, vocab_size=None, dropout=dropout) # start with model_args from command line
|
214 |
+
if init_from == 'scratch':
|
215 |
+
# init a new model from scratch
|
216 |
+
print("Initializing a new model from scratch")
|
217 |
+
# determine the vocab size we'll use for from-scratch training
|
218 |
+
if meta_vocab_size is None:
|
219 |
+
print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)")
|
220 |
+
model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
|
221 |
+
gptconf = GPTConfig(**model_args)
|
222 |
+
model = GPT(gptconf)
|
223 |
+
elif init_from == 'resume':
|
224 |
+
print(f"Resuming training from {out_dir}")
|
225 |
+
# resume training from a checkpoint.
|
226 |
+
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
|
227 |
+
checkpoint = torch.load(ckpt_path, map_location=device)
|
228 |
+
checkpoint_model_args = checkpoint['model_args']
|
229 |
+
# force these config attributes to be equal otherwise we can't even resume training
|
230 |
+
# the rest of the attributes (e.g. dropout) can stay as desired from command line
|
231 |
+
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
|
232 |
+
model_args[k] = checkpoint_model_args[k]
|
233 |
+
# create the model
|
234 |
+
gptconf = GPTConfig(**model_args)
|
235 |
+
model = GPT(gptconf)
|
236 |
+
state_dict = checkpoint['model']
|
237 |
+
# fix the keys of the state dictionary :(
|
238 |
+
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
|
239 |
+
unwanted_prefix = '_orig_mod.'
|
240 |
+
for k,v in list(state_dict.items()):
|
241 |
+
if k.startswith(unwanted_prefix):
|
242 |
+
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
|
243 |
+
model.load_state_dict(state_dict)
|
244 |
+
iter_num = checkpoint['iter_num']
|
245 |
+
best_val_loss = checkpoint['best_val_loss']
|
246 |
+
elif init_from.startswith('gpt2'):
|
247 |
+
print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
|
248 |
+
# initialize from OpenAI GPT-2 weights
|
249 |
+
override_args = dict(dropout=dropout)
|
250 |
+
model = GPT.from_pretrained(init_from, override_args)
|
251 |
+
# read off the created config params, so we can store them into checkpoint correctly
|
252 |
+
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
|
253 |
+
model_args[k] = getattr(model.config, k)
|
254 |
+
# crop down the model block size if desired, using model surgery
|
255 |
+
if block_size < model.config.block_size:
|
256 |
+
model.crop_block_size(block_size)
|
257 |
+
model_args['block_size'] = block_size # so that the checkpoint will have the right value
|
258 |
+
model.to(device)
|
259 |
+
|
260 |
+
# initialize a GradScaler. If enabled=False scaler is a no-op
|
261 |
+
scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
|
262 |
+
|
263 |
+
# optimizer
|
264 |
+
optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
|
265 |
+
if init_from == 'resume':
|
266 |
+
optimizer.load_state_dict(checkpoint['optimizer'])
|
267 |
+
checkpoint = None # free up memory
|
268 |
+
|
269 |
+
# compile the model
|
270 |
+
if compile:
|
271 |
+
print("compiling the model... (takes a ~minute)")
|
272 |
+
unoptimized_model = model
|
273 |
+
model = torch.compile(model) # requires PyTorch 2.0
|
274 |
+
|
275 |
+
# wrap model into DDP container
|
276 |
+
if ddp:
|
277 |
+
model = DDP(model, device_ids=[ddp_local_rank])
|
278 |
+
|
279 |
+
# helps estimate an arbitrarily accurate loss over either split using many batches
|
280 |
+
@torch.no_grad()
|
281 |
+
def estimate_loss():
|
282 |
+
out = {}
|
283 |
+
model.eval()
|
284 |
+
for split in ['train', 'val']:
|
285 |
+
losses = torch.zeros(eval_iters)
|
286 |
+
for k in range(eval_iters):
|
287 |
+
X, Y = get_batch(split)
|
288 |
+
with ctx:
|
289 |
+
logits, loss = model(X, Y)
|
290 |
+
losses[k] = loss.item()
|
291 |
+
out[split] = losses.mean()
|
292 |
+
model.train()
|
293 |
+
return out
|
294 |
+
|
295 |
+
# learning rate decay scheduler (cosine with warmup)
|
296 |
+
def get_lr(it):
|
297 |
+
# 1) linear warmup for warmup_iters steps
|
298 |
+
if it < warmup_iters:
|
299 |
+
return learning_rate * it / warmup_iters
|
300 |
+
# 2) if it > lr_decay_iters, return min learning rate
|
301 |
+
if it > lr_decay_iters:
|
302 |
+
return min_lr
|
303 |
+
# 3) in between, use cosine decay down to min learning rate
|
304 |
+
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
|
305 |
+
assert 0 <= decay_ratio <= 1
|
306 |
+
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1
|
307 |
+
return min_lr + coeff * (learning_rate - min_lr)
|
308 |
+
|
309 |
+
# logging
|
310 |
+
if wandb_log and master_process:
|
311 |
+
import wandb
|
312 |
+
wandb.init(project=wandb_project, name=wandb_run_name, config=config)
|
313 |
+
|
314 |
+
# training loop
|
315 |
+
X, Y = get_batch('train') # fetch the very first batch
|
316 |
+
t0 = time.time()
|
317 |
+
local_iter_num = 0 # number of iterations in the lifetime of this process
|
318 |
+
raw_model = model.module if ddp else model # unwrap DDP container if needed
|
319 |
+
running_mfu = -1.0
|
320 |
+
while True:
|
321 |
+
|
322 |
+
# determine and set the learning rate for this iteration
|
323 |
+
lr = get_lr(iter_num) if decay_lr else learning_rate
|
324 |
+
for param_group in optimizer.param_groups:
|
325 |
+
param_group['lr'] = lr
|
326 |
+
|
327 |
+
# evaluate the loss on train/val sets and write checkpoints
|
328 |
+
if iter_num % eval_interval == 0 and master_process:
|
329 |
+
losses = estimate_loss()
|
330 |
+
print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
331 |
+
if wandb_log:
|
332 |
+
wandb.log({
|
333 |
+
"iter": iter_num,
|
334 |
+
"train/loss": losses['train'],
|
335 |
+
"val/loss": losses['val'],
|
336 |
+
"lr": lr,
|
337 |
+
"mfu": running_mfu*100, # convert to percentage
|
338 |
+
})
|
339 |
+
if losses['val'] < best_val_loss or always_save_checkpoint:
|
340 |
+
best_val_loss = losses['val']
|
341 |
+
if iter_num > 0:
|
342 |
+
checkpoint = {
|
343 |
+
'model': raw_model.state_dict(),
|
344 |
+
'optimizer': optimizer.state_dict(),
|
345 |
+
'model_args': model_args,
|
346 |
+
'iter_num': iter_num,
|
347 |
+
'best_val_loss': best_val_loss,
|
348 |
+
'config': config,
|
349 |
+
}
|
350 |
+
print(f"saving checkpoint to {out_dir}")
|
351 |
+
torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt'))
|
352 |
+
if iter_num == 0 and eval_only:
|
353 |
+
break
|
354 |
+
|
355 |
+
# forward backward update, with optional gradient accumulation to simulate larger batch size
|
356 |
+
# and using the GradScaler if data type is float16
|
357 |
+
for micro_step in range(gradient_accumulation_steps):
|
358 |
+
if ddp:
|
359 |
+
# in DDP training we only need to sync gradients at the last micro step.
|
360 |
+
# the official way to do this is with model.no_sync() context manager, but
|
361 |
+
# I really dislike that this bloats the code and forces us to repeat code
|
362 |
+
# looking at the source of that context manager, it just toggles this variable
|
363 |
+
model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
|
364 |
+
with ctx:
|
365 |
+
logits, loss = model(X, Y)
|
366 |
+
loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation
|
367 |
+
# immediately async prefetch next batch while model is doing the forward pass on the GPU
|
368 |
+
X, Y = get_batch('train')
|
369 |
+
# backward pass, with gradient scaling if training in fp16
|
370 |
+
scaler.scale(loss).backward()
|
371 |
+
# clip the gradient
|
372 |
+
if grad_clip != 0.0:
|
373 |
+
scaler.unscale_(optimizer)
|
374 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
|
375 |
+
# step the optimizer and scaler if training in fp16
|
376 |
+
scaler.step(optimizer)
|
377 |
+
scaler.update()
|
378 |
+
# flush the gradients as soon as we can, no need for this memory anymore
|
379 |
+
optimizer.zero_grad(set_to_none=True)
|
380 |
+
|
381 |
+
# timing and logging
|
382 |
+
t1 = time.time()
|
383 |
+
dt = t1 - t0
|
384 |
+
t0 = t1
|
385 |
+
if iter_num % log_interval == 0 and master_process:
|
386 |
+
# get loss as float. note: this is a CPU-GPU sync point
|
387 |
+
# scale up to undo the division above, approximating the true total loss (exact would have been a sum)
|
388 |
+
lossf = loss.item() * gradient_accumulation_steps
|
389 |
+
if local_iter_num >= 5: # let the training loop settle a bit
|
390 |
+
mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
|
391 |
+
running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
|
392 |
+
print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%")
|
393 |
+
iter_num += 1
|
394 |
+
local_iter_num += 1
|
395 |
+
|
396 |
+
# termination conditions
|
397 |
+
if iter_num > max_iters:
|
398 |
+
break
|
399 |
+
|
400 |
+
if ddp:
|
401 |
+
destroy_process_group()
|
402 |
+
|