LH-Tech-AI commited on
Commit
80bd48b
·
verified ·
1 Parent(s): 12430c2

Create train.py

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