|
""" |
|
To train a GPT from sratch |
|
""" |
|
import argparse |
|
import os |
|
import time |
|
import math |
|
import pickle |
|
from contextlib import nullcontext |
|
|
|
import numpy as np |
|
import torch |
|
from torch.nn.parallel import DistributedDataParallel |
|
from torch.distributed import init_process_group, destroy_process_group |
|
import pynvml |
|
|
|
from model import GPTConfig, GPT |
|
|
|
parser = argparse.ArgumentParser(description="Load configuration file") |
|
parser.add_argument('--config', type=str, required=True, help='Path to the configuration file') |
|
args = parser.parse_args() |
|
|
|
config_path = args.config |
|
exec(open(config_path).read()) |
|
|
|
|
|
config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))] |
|
|
|
config = {k: globals()[k] for k in config_keys} |
|
|
|
|
|
def log_and_write(filename, message): |
|
with open(filename, 'a') as f: |
|
f.write(message + "\n") |
|
print(message) |
|
|
|
log_and_write(log_dir,f'gradient_accumulation_steps: {gradient_accumulation_steps}, batch_size: {batch_size}, \nblock_size: {block_size}, \nn_layer: {n_layer}, n_head: {n_head}, n_embd: {n_embd}, dropout: {dropout}, bias: {bias}, \nlearning_rate: {learning_rate}, max_iters: {max_iters}, \nweight_decay: {weight_decay}, beta1: {beta1}, beta2: {beta2}, grad_clip: {grad_clip}, decay_lr: {decay_lr}, \nwarmup_iters: {warmup_iters}, lr_decay_iters: {lr_decay_iters}, \nmin_lr: {min_lr}, backend: {backend}, device: {device},\n dtype: {dtype}, compile: {compile}') |
|
log_and_write(log_dir, f'meta_vocab_size: {meta_vocab_size}') |
|
log_and_write(log_dir, f'training data: {data_dir}') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ddp = int(os.environ.get('RANK', -1)) != -1 |
|
if ddp: |
|
init_process_group(backend=backend) |
|
ddp_rank = int(os.environ['RANK']) |
|
ddp_local_rank = int(os.environ['LOCAL_RANK']) |
|
ddp_world_size = int(os.environ['WORLD_SIZE']) |
|
device = f'cuda:{ddp_local_rank}' |
|
torch.cuda.set_device(device) |
|
master_process = ddp_rank == 0 |
|
seed_offset = ddp_rank |
|
|
|
|
|
assert gradient_accumulation_steps % ddp_world_size == 0 |
|
gradient_accumulation_steps //= ddp_world_size |
|
else: |
|
|
|
master_process = True |
|
seed_offset = 0 |
|
ddp_world_size = 1 |
|
|
|
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size |
|
print('ddp_world_size:',ddp_world_size) |
|
print(f"tokens per iteration will be: {tokens_per_iter:,}") |
|
|
|
pynvml.nvmlInit() |
|
def print_gpu_memory_usage(): |
|
handle = pynvml.nvmlDeviceGetHandleByIndex(0) |
|
info = pynvml.nvmlDeviceGetMemoryInfo(handle) |
|
print(f"Used: {info.used / 1024**2:.2f}MB/{info.total / 1024**2:.2f}MB ({info.used / info.total * 100:.2f}%)") |
|
|
|
if master_process: |
|
os.makedirs(out_dir, exist_ok=True) |
|
torch.manual_seed(1337 + seed_offset) |
|
torch.backends.cuda.matmul.allow_tf32 = True |
|
torch.backends.cudnn.allow_tf32 = True |
|
device_type = 'cuda' if 'cuda' in device else 'cpu' |
|
|
|
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype] |
|
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype) |
|
|
|
|
|
|
|
train_data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r') |
|
val_data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r') |
|
def get_batch(split): |
|
data = train_data if split == 'train' else val_data |
|
ix = torch.randint(len(data) - block_size, (batch_size,)) |
|
x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix]) |
|
y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix]) |
|
if device_type == 'cuda': |
|
|
|
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True) |
|
else: |
|
x, y = x.to(device), y.to(device) |
|
return x, y |
|
|
|
|
|
iter_num = 0 |
|
best_val_loss = 1e9 |
|
|
|
|
|
meta_path = os.path.join(data_dir, 'meta.pkl') |
|
if os.path.exists(meta_path): |
|
with open(meta_path, 'rb') as f: |
|
meta = pickle.load(f) |
|
meta_vocab_size = meta['vocab_size'] |
|
print(f"found vocab_size = {meta_vocab_size}") |
|
|
|
|
|
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size, |
|
bias=bias, vocab_size=None, dropout=dropout) |
|
if init_from == 'scratch': |
|
|
|
print("Initializing a new model from scratch") |
|
|
|
if meta_vocab_size is None: |
|
print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)") |
|
model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304 |
|
gptconf = GPTConfig(**model_args) |
|
model = GPT(gptconf) |
|
elif init_from == 'resume': |
|
print(f"Resuming training from {out_dir}") |
|
|
|
|
|
checkpoint = torch.load(ckpt_path, map_location=device) |
|
checkpoint_model_args = checkpoint['model_args'] |
|
|
|
|
|
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']: |
|
model_args[k] = checkpoint_model_args[k] |
|
|
|
gptconf = GPTConfig(**model_args) |
|
model = GPT(gptconf) |
|
state_dict = checkpoint['model'] |
|
|
|
|
|
unwanted_prefix = '_orig_mod.' |
|
for k,v in list(state_dict.items()): |
|
if k.startswith(unwanted_prefix): |
|
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k) |
|
model.load_state_dict(state_dict) |
|
iter_num = checkpoint['iter_num'] |
|
best_val_loss = checkpoint['best_val_loss'] |
|
elif init_from.startswith('gpt2'): |
|
print(f"Initializing from OpenAI GPT-2 weights: {init_from}") |
|
|
|
override_args = dict(dropout=dropout) |
|
model = GPT.from_pretrained(init_from, override_args) |
|
|
|
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']: |
|
model_args[k] = getattr(model.config, k) |
|
|
|
if block_size < model.config.block_size: |
|
model.crop_block_size(block_size) |
|
model_args['block_size'] = block_size |
|
model.to(device) |
|
|
|
|
|
scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float32')) |
|
|
|
|
|
optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type) |
|
if init_from == 'resume': |
|
optimizer.load_state_dict(checkpoint['optimizer']) |
|
checkpoint = None |
|
|
|
|
|
if compile: |
|
print("compiling the model... (takes a ~minute)") |
|
unoptimized_model = model |
|
model = torch.compile(model) |
|
|
|
|
|
if ddp: |
|
model = DistributedDataParallel(model, device_ids=[ddp_local_rank]) |
|
|
|
|
|
@torch.no_grad() |
|
def estimate_loss(): |
|
out = {} |
|
perplexities = {} |
|
model.eval() |
|
for split in ['train', 'val']: |
|
losses = torch.zeros(eval_iters) |
|
total_loss = 0 |
|
for k in range(eval_iters): |
|
X, Y = get_batch(split) |
|
with ctx: |
|
logits, loss = model(X, Y) |
|
losses[k] = loss.item() |
|
total_loss += loss.item() |
|
avg_loss = losses.mean() |
|
out[split] = avg_loss |
|
perplexities[split] = torch.exp(avg_loss) |
|
model.train() |
|
return out, perplexities |
|
|
|
|
|
|
|
def get_lr(it): |
|
|
|
if it < warmup_iters: |
|
return learning_rate * it / warmup_iters |
|
|
|
if it > lr_decay_iters: |
|
return min_lr |
|
|
|
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters) |
|
assert 0 <= decay_ratio <= 1 |
|
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) |
|
return min_lr + coeff * (learning_rate - min_lr) |
|
|
|
|
|
X, Y = get_batch('train') |
|
t0 = time.time() |
|
local_iter_num = 0 |
|
raw_model = model.module if ddp else model |
|
running_mfu = -1.0 |
|
while True: |
|
|
|
|
|
lr = get_lr(iter_num) if decay_lr else learning_rate |
|
for param_group in optimizer.param_groups: |
|
param_group['lr'] = lr |
|
|
|
|
|
if iter_num % eval_interval == 0 and master_process: |
|
losses, perplexities = estimate_loss() |
|
log_and_write(log_dir, f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f},train perplexity: {perplexities['train']:.4f}, val perplexity: {perplexities['val']:.4f}") |
|
if iter_num % 200 == 0: |
|
print_gpu_memory_usage() |
|
if losses['val'] < best_val_loss or always_save_checkpoint: |
|
best_val_loss = losses['val'] |
|
if iter_num > 0: |
|
checkpoint = { |
|
'model': raw_model.state_dict(), |
|
'optimizer': optimizer.state_dict(), |
|
'model_args': model_args, |
|
'iter_num': iter_num, |
|
'best_val_loss': best_val_loss, |
|
'config': config, |
|
} |
|
log_and_write(log_dir, f"saving checkpoint to {out_dir}") |
|
torch.save(checkpoint, os.path.join(out_dir, f'ckpt_{iter_num}.pt')) |
|
if iter_num == 0 and eval_only: |
|
break |
|
|
|
|
|
|
|
for micro_step in range(gradient_accumulation_steps): |
|
if ddp: |
|
|
|
model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1) |
|
with ctx: |
|
logits, loss = model(X, Y) |
|
loss = loss / gradient_accumulation_steps |
|
|
|
X, Y = get_batch('train') |
|
|
|
scaler.scale(loss).backward() |
|
|
|
if grad_clip != 0.0: |
|
scaler.unscale_(optimizer) |
|
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) |
|
|
|
scaler.step(optimizer) |
|
scaler.update() |
|
|
|
optimizer.zero_grad(set_to_none=True) |
|
|
|
|
|
t1 = time.time() |
|
dt = t1 - t0 |
|
t0 = t1 |
|
if iter_num % log_interval == 0 and master_process: |
|
|
|
|
|
lossf = loss.item() * gradient_accumulation_steps |
|
if local_iter_num >= 5: |
|
mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt) |
|
running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu |
|
log_and_write(log_dir, f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, lr {lr}, mfu {running_mfu*100:.2f}%") |
|
iter_num += 1 |
|
local_iter_num += 1 |
|
|
|
|
|
if iter_num > max_iters: |
|
break |
|
|
|
if ddp: |
|
destroy_process_group() |
|
|
|
pynvml.nvmlShutdown() |
|
|
|
|