Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train.py 15 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...