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