diff --git a/config.py b/config.py new file mode 100644 index 0000000..b8b01ab --- /dev/null +++ b/config.py @@ -0,0 +1,189 @@ +from dataclasses import dataclass, field +from typing import ClassVar, Optional + + +@dataclass +class ModelConfig: + block_size: Optional[int] = None + vocab_size: Optional[int] = None + n_layer: Optional[int] = None + n_head: Optional[int] = None + n_embd: Optional[int] = None + dropout: Optional[float] = None + bias: Optional[bool] = None + + +@dataclass +class OptimizerConfig: + name: Optional[str] = None + learning_rate: Optional[float] = None + weight_decay: Optional[float] = None + beta1: Optional[float] = None + beta2: Optional[float] = None + + +@dataclass +class TrainConfig: + batch_size: Optional[int] = None + local_batch_size: Optional[int] = None + block_size: Optional[int] = None + max_iters: Optional[int] = None + optimizer: OptimizerConfig = field(default_factory=OptimizerConfig) + grad_clip: Optional[float] = None + decay_lr: Optional[bool] = None + warmup_iters: Optional[int] = None + lr_decay_iters: Optional[int] = None + min_lr: Optional[float] = None + eval_interval: Optional[int] = None + log_interval: Optional[int] = None + eval_iters: Optional[int] = None + eval_only: Optional[bool] = None + always_save_checkpoint: Optional[bool] = None + init_from: Optional[str] = None + + +@dataclass +class DatasetConfig: + name: Optional[str] = None + default_config: ClassVar[Config] = field( + default_factory=Config + ) + + +@dataclass +class OpenWebTextConfig(DatasetConfig): + name: Optional[str] = None + default_config: ClassVar[Config] = field( + default_factory=lambda: Config( + model = ModelConfig( + block_size=1024, + vocab_size=50304, + n_layer=12, + n_head=12, + n_embd=768, + dropout=0.0, + bias=False + ), + train = TrainConfig( + batch_size=480, + local_batch_size=12, + block_size=1024, + max_iters=600_000, + optimizer=field( + default_factory=lambda: OptimizerConfig( + name="adam", + learning_rate=6e-4, + weight_decay=0.1, + beta1=0.9, + beta2=0.95 + ) + ), + grad_clip=1.0, + decay_lr=True, + warmup_iters=2000, + lr_decay_iters=600_000, + min_lr=6e-5, + eval_interval=2000, + log_interval=1, + eval_iters=200, + eval_only=False, + always_save_checkpoint=True, + init_from="scratch", + ), + out_dir="out", + wandb_log=False, + wandb_project="owt", + wandb_run_name="gpt2" + ) + ) + + +@dataclass +class ShakespeareConfig(DatasetConfig): + name: str = "shakespeare" + default_config: ClassVar[Config] = field( + default_factory=lambda: Config( + model = ModelConfig( + block_size=256, + vocab_size=65, + n_layer=6, + n_head=6, + n_embd=384, + dropout=0.2 + bias=False + ), + train = TrainConfig( + batch_size=64, + local_batch_size=64, + block_size=256, + max_iters=5000, + optimizer=field( + default_factory=lambda: OptimizerConfig( + name="adam", + learning_rate=1e-3, + weight_decay=0.1, + beta1=0.9, + beta2=0.99 + ) + ), + grad_clip=1.0, + decay_lr=True, + warmup_iters=100, + lr_decay_iters=5000, + min_lr=1e-4, + eval_interval=250, + log_interval=10, + eval_iters=200, + eval_only=False, + always_save_checkpoint=False, + init_from="scratch", + ), + out_dir="out-shakespeare-char", + wandb_log=False, + wandb_project="shakespeare-char", + wandb_run_name="mini-gpt" + ) + ) + + +@dataclass +class Config: + defaults: List[Any] = field( + default_factory=lambda: [{"dataset": "openwebtext"}, "_self_"] + ) + model: ModelConfig = field(default_factory=ModelConfig) + train: TrainConfig = field(default_factory=TrainConfig) + dataset: DatasetConfig = field(default_factory=DatasetConfig) + out_dir: str = "out" + wandb_log: bool = False + wandb_project: str = "owt" + wandb_run_name: str = "gpt2" + + def __post_init__(self): + if self.train.eval_only: + if self.train.batch_size is None: + self.train.batch_size = 8 + if self.train.local_batch_size is None: + self.train.local_batch_size = 8 + if self.train.eval_iters is None: + self.train.eval_iters = 500 + + for key, value in vars(self.dataset.default_config).items(): + if key == "model": + for k_m, v_m in vars(self.dataset.default_config.model).items(): + if getattr(self.model, k_m) is None: + setattr(self.model, k_m, v_m) + + elif key == "train": + for k_t, v_t in vars(self.dataset.default_config.train).items(): + if k_t == "optimizer": + for k_o, v_o in vars(self.dataset.default_config.train.optimizer).items(): + if getattr(self.train.optimizer, k_o) is None: + setattr(self.train.optimizer, k_o, v_o) + + if getattr(self.train, k_t) is None: + setattr(self.train, k_t, v_t) + + else: + if getattr(self, key) is None: + setattr(self, key, value) diff --git a/configurator.py b/configurator.py deleted file mode 100644 index a8bba95..0000000 --- a/configurator.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -Poor Man's Configurator. Probably a terrible idea. Example usage: -$ python train.py config/override_file.py --batch_size=32 -this will first run config/override_file.py, then override batch_size to 32 - -The code in this file will be run as follows from e.g. train.py: ->>> exec(open('configurator.py').read()) - -So it's not a Python module, it's just shuttling this code away from train.py -The code in this script then overrides the globals() - -I know people are not going to love this, I just really dislike configuration -complexity and having to prepend config. to every single variable. If someone -comes up with a better simple Python solution I am all ears. -""" - -import sys -from ast import literal_eval - -for arg in sys.argv[1:]: - if '=' not in arg: - # assume it's the name of a config file - assert not arg.startswith('--') - config_file = arg - print(f"Overriding config with {config_file}:") - with open(config_file) as f: - print(f.read()) - exec(open(config_file).read()) - else: - # assume it's a --key=value argument - assert arg.startswith('--') - key, val = arg.split('=') - key = key[2:] - if key in globals(): - try: - # attempt to eval it it (e.g. if bool, number, or etc) - attempt = literal_eval(val) - except (SyntaxError, ValueError): - # if that goes wrong, just use the string - attempt = val - # ensure the types match ok - assert type(attempt) == type(globals()[key]) - # cross fingers - print(f"Overriding: {key} = {attempt}") - globals()[key] = attempt - else: - raise ValueError(f"Unknown config key: {key}") diff --git a/model.py b/model.py index c698f8b..4c28c65 100644 --- a/model.py +++ b/model.py @@ -15,9 +15,9 @@ import torch.nn as nn from torch.nn import functional as F + class LayerNorm(nn.Module): """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """ - def __init__(self, ndim, bias): super().__init__() self.weight = nn.Parameter(torch.ones(ndim)) @@ -26,8 +26,8 @@ def __init__(self, ndim, bias): def forward(self, input): return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5) -class CausalSelfAttention(nn.Module): +class CausalSelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 @@ -75,8 +75,8 @@ def forward(self, x): y = self.resid_dropout(self.c_proj(y)) return y -class MLP(nn.Module): +class MLP(nn.Module): def __init__(self, config): super().__init__() self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias) @@ -92,7 +92,6 @@ def forward(self, x): return x class Block(nn.Module): - def __init__(self, config): super().__init__() self.ln_1 = LayerNorm(config.n_embd, bias=config.bias) @@ -105,18 +104,8 @@ def forward(self, x): x = x + self.mlp(self.ln_2(x)) return x -@dataclass -class GPTConfig: - block_size: int = 1024 - vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency - n_layer: int = 12 - n_head: int = 12 - n_embd: int = 768 - dropout: float = 0.0 - bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster class GPT(nn.Module): - def __init__(self, config): super().__init__() assert config.vocab_size is not None @@ -213,22 +202,21 @@ def from_pretrained(cls, model_type, override_args=None): print("loading weights from pretrained gpt: %s" % model_type) # n_layer, n_head and n_embd are determined from model_type - config_args = { - 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params - 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params - 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params - 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params + config = { + 'gpt2': ModelConfig(n_layer=12, n_head=12, n_embd=768), # 124M params + 'gpt2-medium': ModelConfig(n_layer=24, n_head=16, n_embd=1024), # 350M params + 'gpt2-large': ModelConfig(n_layer=36, n_head=20, n_embd=1280), # 774M params + 'gpt2-xl': ModelConfig(n_layer=48, n_head=25, n_embd=1600), # 1558M params }[model_type] print("forcing vocab_size=50257, block_size=1024, bias=True") - config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints - config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints - config_args['bias'] = True # always True for GPT model checkpoints + config.vocab_size = 50257 # always 50257 for GPT model checkpoints + config.block_size = 1024 # always 1024 for GPT model checkpoints + config.bias = True # always True for GPT model checkpoints # we can override the dropout rate, if desired if 'dropout' in override_args: print(f"overriding dropout rate to {override_args['dropout']}") - config_args['dropout'] = override_args['dropout'] + config.dropout = override_args['dropout'] # create a from-scratch initialized minGPT model - config = GPTConfig(**config_args) model = GPT(config) sd = model.state_dict() sd_keys = sd.keys() @@ -260,7 +248,7 @@ def from_pretrained(cls, model_type, override_args=None): return model - def configure_optimizers(self, weight_decay, learning_rate, betas, device_type): + def configure_optimizers(self, optim_cfg, device_type): # start with all of the candidate parameters param_dict = {pn: p for pn, p in self.named_parameters()} # filter out those that do not require grad @@ -270,7 +258,7 @@ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type): decay_params = [p for n, p in param_dict.items() if p.dim() >= 2] nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2] optim_groups = [ - {'params': decay_params, 'weight_decay': weight_decay}, + {'params': decay_params, 'weight_decay': optim_cfg.weight_decay}, {'params': nodecay_params, 'weight_decay': 0.0} ] num_decay_params = sum(p.numel() for p in decay_params) @@ -281,7 +269,12 @@ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type): fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters use_fused = fused_available and device_type == 'cuda' extra_args = dict(fused=True) if use_fused else dict() - optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args) + optimizer = torch.optim.AdamW( + optim_groups, + lr=optim_cfg.learning_rate, + betas=(optim_cfg.beta1, optim_cfg.beta2), + **extra_args + ) print(f"using fused AdamW: {use_fused}") return optimizer diff --git a/train.py b/train.py index 951bda9..0e27d2d 100644 --- a/train.py +++ b/train.py @@ -16,321 +16,299 @@ (If your cluster does not have Infiniband interconnect prepend NCCL_IB_DISABLE=1) """ +from dataclasses import asdict import os import time import math import pickle from contextlib import nullcontext +import hydra +from hydra.core.config_store import ConfigStore import numpy as np +from omegaconf import OmegaConf import torch from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed import init_process_group, destroy_process_group -from model import GPTConfig, GPT +from config import Config, OpenWebTextConfig, ShakespeareConfig +from model import GPT -# ----------------------------------------------------------------------------- -# default config values designed to train a gpt2 (124M) on OpenWebText -# I/O -out_dir = 'out' -eval_interval = 2000 -log_interval = 1 -eval_iters = 200 -eval_only = False # if True, script exits right after the first eval -always_save_checkpoint = True # if True, always save a checkpoint after each eval -init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*' -# wandb logging -wandb_log = False # disabled by default -wandb_project = 'owt' -wandb_run_name = 'gpt2' # 'run' + str(time.time()) -# data -dataset = 'openwebtext' -gradient_accumulation_steps = 5 * 8 # used to simulate larger batch sizes -batch_size = 12 # if gradient_accumulation_steps > 1, this is the micro-batch size -block_size = 1024 -# model -n_layer = 12 -n_head = 12 -n_embd = 768 -dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+ -bias = False # do we use bias inside LayerNorm and Linear layers? -# adamw optimizer -learning_rate = 6e-4 # max learning rate -max_iters = 600000 # total number of training iterations -weight_decay = 1e-1 -beta1 = 0.9 -beta2 = 0.95 -grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0 -# learning rate decay settings -decay_lr = True # whether to decay the learning rate -warmup_iters = 2000 # how many steps to warm up for -lr_decay_iters = 600000 # should be ~= max_iters per Chinchilla -min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla -# DDP settings -backend = 'nccl' # 'nccl', 'gloo', etc. -# system -device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks -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 -compile = True # use PyTorch 2.0 to compile the model to be faster -# ----------------------------------------------------------------------------- -config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))] -exec(open('configurator.py').read()) # overrides from command line or config file -config = {k: globals()[k] for k in config_keys} # will be useful for logging -# ----------------------------------------------------------------------------- +cs = ConfigStore.instance() +cs.store(name="config", node=Config) +cs.store(name="openwebtext", group="dataset", node=OpenWebTextConfig) +cs.store(name="shakespeare", group="dataset", node=SharespeareConfig) -# various inits, derived attributes, I/O setup -ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run? -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 # this process will do logging, checkpointing etc. - seed_offset = ddp_rank # each process gets a different seed - # world_size number of processes will be training simultaneously, so we can scale - # down the desired gradient accumulation iterations per process proportionally - assert gradient_accumulation_steps % ddp_world_size == 0 - gradient_accumulation_steps //= ddp_world_size -else: - # if not ddp, we are running on a single gpu, and one process - master_process = True - seed_offset = 0 - ddp_world_size = 1 -tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size -print(f"tokens per iteration will be: {tokens_per_iter:,}") -if master_process: - os.makedirs(out_dir, exist_ok=True) -torch.manual_seed(1337 + seed_offset) -torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul -torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn -device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast -# note: float16 data type will automatically use a GradScaler -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) +@hydra.main(version_base=None, config_name="config") +def main(cfg: Config) -> None: + cfg = Omegaconf.to_object(cfg) -# poor man's data loader -data_dir = os.path.join('data', dataset) -def get_batch(split): - # We recreate np.memmap every batch to avoid a memory leak, as per - # https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once/61472122#61472122 - if split == 'train': - data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r') + # DDP settings + backend = 'nccl' # 'nccl', 'gloo', etc. + # system + device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks + 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 + compile = True # use PyTorch 2.0 to compile the model to be faster + # various inits, derived attributes, I/O setup + ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run? + 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 # this process will do logging, checkpointing etc. + seed_offset = ddp_rank # each process gets a different seed + # world_size number of processes will be training simultaneously, so we can scale + # down the desired gradient accumulation iterations per process proportionally else: - data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r') - 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': - # pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True) - 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 - -# init these up here, can override if init_from='resume' (i.e. from a checkpoint) -iter_num = 0 -best_val_loss = 1e9 - -# attempt to derive vocab_size from the dataset -meta_path = os.path.join(data_dir, 'meta.pkl') -meta_vocab_size = None -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} (inside {meta_path})") + # if not ddp, we are running on a single gpu, and one process + master_process = True + seed_offset = 0 + ddp_world_size = 1 -# model init -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) # start with model_args from command line -if init_from == 'scratch': - # init a new model from scratch - print("Initializing a new model from scratch") - # determine the vocab size we'll use for from-scratch training - 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}") - # resume training from a checkpoint. - ckpt_path = os.path.join(out_dir, 'ckpt.pt') - checkpoint = torch.load(ckpt_path, map_location=device) - checkpoint_model_args = checkpoint['model_args'] - # force these config attributes to be equal otherwise we can't even resume training - # the rest of the attributes (e.g. dropout) can stay as desired from command line - for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']: - model_args[k] = checkpoint_model_args[k] - # create the model - gptconf = GPTConfig(**model_args) - model = GPT(gptconf) - state_dict = checkpoint['model'] - # fix the keys of the state dictionary :( - # honestly no idea how checkpoints sometimes get this prefix, have to debug more - 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}") - # initialize from OpenAI GPT-2 weights - override_args = dict(dropout=dropout) - model = GPT.from_pretrained(init_from, override_args) - # read off the created config params, so we can store them into checkpoint correctly - for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']: - model_args[k] = getattr(model.config, k) -# crop down the model block size if desired, using model surgery -if block_size < model.config.block_size: - model.crop_block_size(block_size) - model_args['block_size'] = block_size # so that the checkpoint will have the right value -model.to(device) + assert cfg.train.batch_size % (ddp_world_size * cfg.train.local_batch_size) == 0 + gradient_accumulation_steps = cfg.train.batch_size // (ddp_world_size * cfg.train.local_batch_size) -# initialize a GradScaler. If enabled=False scaler is a no-op -scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16')) + tokens_per_iter = cfg.train.batch_size * cfg.train.block_size + print(f"tokens per iteration will be: {tokens_per_iter:,}") + + if master_process: + os.makedirs(cfg.out_dir, exist_ok=True) + torch.manual_seed(1337 + seed_offset) + torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul + torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn + device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast + # note: float16 data type will automatically use a GradScaler + 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) + + # poor man's data loader + data_dir = os.path.join('data', cfg.dataset.name) + def get_batch(split): + # We recreate np.memmap every batch to avoid a memory leak, as per + # https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once/61472122#61472122 + if split == 'train': + data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r') + else: + data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r') + ix = torch.randint(len(data) - cfg.train.block_size, (cfg.train.local_batch_size,)) + x = torch.stack([torch.from_numpy((data[i:i+cfg.train.block_size]).astype(np.int64)) for i in ix]) + y = torch.stack([torch.from_numpy((data[i+1:i+1+cfg.train.block_size]).astype(np.int64)) for i in ix]) + if device_type == 'cuda': + # pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True) + 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 + + # init these up here, can override if init_from='resume' (i.e. from a checkpoint) + iter_num = 0 + best_val_loss = 1e9 + + # attempt to derive vocab_size from the dataset + meta_path = os.path.join(data_dir, 'meta.pkl') + meta_vocab_size = None + 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} (inside {meta_path})") + + # model init + if cfg.train.init_from == 'scratch': + # init a new model from scratch + print("Initializing a new model from scratch") + # determine the vocab size we'll use for from-scratch training + if meta_vocab_size is None: + print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)") + cfg.model.vocab_size = meta_vocab_size if meta_vocab_size is not None else 50304 + model = GPT(cfg.model) -# optimizer -optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type) -if init_from == 'resume': - optimizer.load_state_dict(checkpoint['optimizer']) -checkpoint = None # free up memory + elif cfg.train.init_from == 'resume': + print(f"Resuming training from {cfg.out_dir}") + # resume training from a checkpoint. + ckpt_path = os.path.join(cfg.out_dir, 'ckpt.pt') + checkpoint = torch.load(ckpt_path, map_location=device) + checkpoint_model_config = checkpoint['model_config'] + # force these config attributes to be equal otherwise we can't even resume training + # the rest of the attributes (e.g. dropout) can stay as desired from command line + for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']: + setattr(cfg.model, k, getattr(checkpoint_model_config, k)) -# compile the model -if compile: - print("compiling the model... (takes a ~minute)") - unoptimized_model = model - model = torch.compile(model) # requires PyTorch 2.0 + # create the model + model = GPT(cfg.model) + state_dict = checkpoint['model'] + # fix the keys of the state dictionary :( + # honestly no idea how checkpoints sometimes get this prefix, have to debug more + 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'] -# wrap model into DDP container -if ddp: - model = DDP(model, device_ids=[ddp_local_rank]) + elif cfg.train.init_from.startswith('gpt2'): + print(f"Initializing from OpenAI GPT-2 weights: {cfg.train.init_from}") + # initialize from OpenAI GPT-2 weights + override_args = dict(dropout=cfg.model.dropout) + model = GPT.from_pretrained(cfg.train.init_from, override_args) + # read off the created config params, so we can store them into checkpoint correctly + for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']: + setattr(cfg.model, k, getattr(model.config, k)) -# helps estimate an arbitrarily accurate loss over either split using many batches -@torch.no_grad() -def estimate_loss(): - out = {} - model.eval() - for split in ['train', 'val']: - losses = torch.zeros(eval_iters) - for k in range(eval_iters): - X, Y = get_batch(split) + # crop down the model block size if desired, using model surgery + if cfg.train.block_size < model.config.block_size: + model.crop_block_size(cfg.train.block_size) + cfg.model.block_size = cfg.train.block_size # so that the checkpoint will have the right value + model.to(device) + + # initialize a GradScaler. If enabled=False scaler is a no-op + scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16')) + a + # optimizer + optimizer = model.configure_optimizers(cfg.optimizer, device_type) + if cfg.train.init_from == 'resume': + optimizer.load_state_dict(checkpoint['optimizer']) + checkpoint = None # free up memory + + # compile the model + if compile: + print("compiling the model... (takes a ~minute)") + unoptimized_model = model + model = torch.compile(model) # requires PyTorch 2.0 + + # wrap model into DDP container + if ddp: + model = DDP(model, device_ids=[ddp_local_rank]) + + # helps estimate an arbitrarily accurate loss over either split using many batches + @torch.no_grad() + def estimate_loss(): + out = {} + model.eval() + for split in ['train', 'val']: + losses = torch.zeros(cfg.train.eval_iters) + for k in range(cfg.train.eval_iters): + X, Y = get_batch(split) + with ctx: + logits, loss = model(X, Y) + losses[k] = loss.item() + out[split] = losses.mean() + model.train() + return out + + # learning rate decay scheduler (cosine with warmup) + def get_lr(it): + # 1) linear warmup for warmup_iters steps + if it < cfg.train.warmup_iters: + return cfg.train.optimizer.learning_rate * it / cfg.train.warmup_iters + # 2) if it > lr_decay_iters, return min learning rate + if it > cfg.train.lr_decay_iters: + return min_lr + # 3) in between, use cosine decay down to min learning rate + decay_ratio = (it - cfg.train.warmup_iters) / (cfg.train.lr_decay_iters - cfg.train.warmup_iters) + assert 0 <= decay_ratio <= 1 + coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1 + return cfg.train.min_lr + coeff * (cfg.train.optimizer.learning_rate - cfg.train.min_lr) + + # logging + if cfg.wandb_log and master_process: + import wandb + wandb.init(project=cfg.wandb_project, name=cfg.wandb_run_name, config=asdict(cfg)) + + # training loop + X, Y = get_batch('train') # fetch the very first batch + t0 = time.time() + local_iter_num = 0 # number of iterations in the lifetime of this process + raw_model = model.module if ddp else model # unwrap DDP container if needed + running_mfu = -1.0 + while True: + + # determine and set the learning rate for this iteration + lr = get_lr(iter_num) if cfg.train.decay_lr else cfg.train.optimizer.learning_rate + for param_group in optimizer.param_groups: + param_group['lr'] = lr + + # evaluate the loss on train/val sets and write checkpoints + if iter_num % cfg.train.eval_interval == 0 and master_process: + losses = estimate_loss() + print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}") + if cfg.wandb_log: + wandb.log({ + "iter": iter_num, + "train/loss": losses['train'], + "val/loss": losses['val'], + "lr": lr, + "mfu": running_mfu*100, # convert to percentage + }) + if losses['val'] < best_val_loss or cfg.train.always_save_checkpoint: + best_val_loss = losses['val'] + if iter_num > 0: + checkpoint = { + 'model': raw_model.state_dict(), + 'optimizer': optimizer.state_dict(), + 'model_config': cfg.model, + 'iter_num': iter_num, + 'best_val_loss': best_val_loss, + 'config': cfg, + } + print(f"saving checkpoint to {cfg.out_dir}") + torch.save(checkpoint, os.path.join(cfg.out_dir, 'ckpt.pt')) + if iter_num == 0 and cfg.train.eval_only: + break + + # forward backward update, with optional gradient accumulation to simulate larger batch size + # and using the GradScaler if data type is float16 + for micro_step in range(gradient_accumulation_steps): + if ddp: + # in DDP training we only need to sync gradients at the last micro step. + # the official way to do this is with model.no_sync() context manager, but + # I really dislike that this bloats the code and forces us to repeat code + # looking at the source of that context manager, it just toggles this variable + model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1) with ctx: logits, loss = model(X, Y) - losses[k] = loss.item() - out[split] = losses.mean() - model.train() - return out - -# learning rate decay scheduler (cosine with warmup) -def get_lr(it): - # 1) linear warmup for warmup_iters steps - if it < warmup_iters: - return learning_rate * it / warmup_iters - # 2) if it > lr_decay_iters, return min learning rate - if it > lr_decay_iters: - return min_lr - # 3) in between, use cosine decay down to min learning rate - 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)) # coeff ranges 0..1 - return min_lr + coeff * (learning_rate - min_lr) - -# logging -if wandb_log and master_process: - import wandb - wandb.init(project=wandb_project, name=wandb_run_name, config=config) - -# training loop -X, Y = get_batch('train') # fetch the very first batch -t0 = time.time() -local_iter_num = 0 # number of iterations in the lifetime of this process -raw_model = model.module if ddp else model # unwrap DDP container if needed -running_mfu = -1.0 -while True: - - # determine and set the learning rate for this iteration - lr = get_lr(iter_num) if decay_lr else learning_rate - for param_group in optimizer.param_groups: - param_group['lr'] = lr - - # evaluate the loss on train/val sets and write checkpoints - if iter_num % eval_interval == 0 and master_process: - losses = estimate_loss() - print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}") - if wandb_log: - wandb.log({ - "iter": iter_num, - "train/loss": losses['train'], - "val/loss": losses['val'], - "lr": lr, - "mfu": running_mfu*100, # convert to percentage - }) - 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, - } - print(f"saving checkpoint to {out_dir}") - torch.save(checkpoint, os.path.join(out_dir, 'ckpt.pt')) - if iter_num == 0 and eval_only: - break - - # forward backward update, with optional gradient accumulation to simulate larger batch size - # and using the GradScaler if data type is float16 - for micro_step in range(gradient_accumulation_steps): - if ddp: - # in DDP training we only need to sync gradients at the last micro step. - # the official way to do this is with model.no_sync() context manager, but - # I really dislike that this bloats the code and forces us to repeat code - # looking at the source of that context manager, it just toggles this variable - model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1) - with ctx: - logits, loss = model(X, Y) - loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation - # immediately async prefetch next batch while model is doing the forward pass on the GPU - X, Y = get_batch('train') - # backward pass, with gradient scaling if training in fp16 - scaler.scale(loss).backward() - # clip the gradient - if grad_clip != 0.0: - scaler.unscale_(optimizer) - torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) - # step the optimizer and scaler if training in fp16 - scaler.step(optimizer) - scaler.update() - # flush the gradients as soon as we can, no need for this memory anymore - optimizer.zero_grad(set_to_none=True) - - # timing and logging - t1 = time.time() - dt = t1 - t0 - t0 = t1 - if iter_num % log_interval == 0 and master_process: - # get loss as float. note: this is a CPU-GPU sync point - # scale up to undo the division above, approximating the true total loss (exact would have been a sum) - lossf = loss.item() * gradient_accumulation_steps - if local_iter_num >= 5: # let the training loop settle a bit - 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 - print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%") - iter_num += 1 - local_iter_num += 1 + loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation + # immediately async prefetch next batch while model is doing the forward pass on the GPU + X, Y = get_batch('train') + # backward pass, with gradient scaling if training in fp16 + scaler.scale(loss).backward() + # clip the gradient + if cfg.train.grad_clip != 0.0: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.train.grad_clip) + # step the optimizer and scaler if training in fp16 + scaler.step(optimizer) + scaler.update() + # flush the gradients as soon as we can, no need for this memory anymore + optimizer.zero_grad(set_to_none=True) + + # timing and logging + t1 = time.time() + dt = t1 - t0 + t0 = t1 + if iter_num % cfg.train.log_interval == 0 and master_process: + # get loss as float. note: this is a CPU-GPU sync point + # scale up to undo the division above, approximating the true total loss (exact would have been a sum) + lossf = loss.item() * gradient_accumulation_steps + if local_iter_num >= 5: # let the training loop settle a bit + mfu = raw_model.estimate_mfu(cfg.train.local_batch_size * gradient_accumulation_steps, dt) + running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu + print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%") + iter_num += 1 + local_iter_num += 1 + + # termination conditions + if iter_num > cfg.train.max_iters: + break + + if ddp: + destroy_process_group() - # termination conditions - if iter_num > max_iters: - break -if ddp: - destroy_process_group() +if __name__ == "__main__": + main()