A straightforward method for training your LLM, from downloading data to generating text.
feat: opt-in AMP, gradient checkpointing & gradient accumulation; fix CPU contiguity (fixes #5) (#29)
Fareed Khan2b9bcaaf1c12
diff --git a/README.md b/README.mdindex dd2c268..2eb5216 100644--- a/README.md+++ b/README.md@@ -274,6 +274,19 @@ python scripts/train_transformer.py --resume models/transformer_B_checkpoints/chThe periodic checkpoints include the model state, optimizer state, loss history, last completed training step, and learning-rate metadata.+If a large config runs out of VRAM (see issue #5), enable the opt-in memory optimisations (all are off by default, so default behaviour is unchanged):+```bash+# bf16 mixed precision + activation checkpointing + 8 micro-batches per step (8x effective batch)+python scripts/train_transformer.py --amp --grad-checkpointing --grad-accum 8++# print a rough VRAM budget (params + optimizer state) before training+python scripts/train_transformer.py --report-memory+```+- `--amp [--amp-dtype bf16|fp16]`: mixed-precision autocast (CUDA only; auto-disabled on CPU). `bf16` needs no loss scaler; `fp16` uses a `GradScaler`.+- `--grad-checkpointing`: recompute transformer-block activations during backprop to save activation memory (trades ~20-30% compute).+- `--grad-accum N`: accumulate gradients over N micro-batches so the effective batch size is `t_batch_size x N` without the memory of a larger batch.+- `--report-memory`: print an estimated VRAM budget so you can predict OOM before launching.+To generate text using the trained model, run:```bashpython scripts/generate_text.py --model_path models/your_model.pth --input_text hidiff --git a/config/config.py b/config/config.pyindex b9ba4f6..5e69eca 100644--- a/config/config.py+++ b/config/config.py@@ -27,6 +27,14 @@ T_CHECKPOINT_STEPS = 0 # Save periodic checkpoints every N steps (0 disableT_KEEP_LAST_CHECKPOINTS = 3 # Number of periodic checkpoints to keep (0 keeps all)T_CHECKPOINT_DIR = None # Optional checkpoint directory override+# Memory-optimisation knobs (all OFF by default => unchanged behaviour/numerics).+# These let large configs fit in less VRAM; enable them on the CLI or here. See issue #5.+USE_AMP = False # bf16/fp16 autocast (CUDA only; ignored on CPU)+AMP_DTYPE = "bf16" # "bf16" (no GradScaler) or "fp16" (GradScaler)+USE_GRADIENT_CHECKPOINTING = False # recompute block activations in backward to save VRAM+GRAD_ACCUM_STEPS = 1 # micro-batches per optimizer step (effective batch x N)+REPORT_MEMORY_BUDGET = False # print a rough VRAM budget before training (CUDA only)+# Device configurationDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'@@ -51,5 +59,10 @@ default_config = {'t_checkpoint_steps': T_CHECKPOINT_STEPS,'t_keep_last_checkpoints': T_KEEP_LAST_CHECKPOINTS,'t_checkpoint_dir': T_CHECKPOINT_DIR,+ 'use_amp': USE_AMP,+ 'amp_dtype': AMP_DTYPE,+ 'use_gradient_checkpointing': USE_GRADIENT_CHECKPOINTING,+ 'grad_accum_steps': GRAD_ACCUM_STEPS,+ 'report_memory_budget': REPORT_MEMORY_BUDGET,'device': DEVICE,}diff --git a/scripts/train_transformer.py b/scripts/train_transformer.pyindex 3655ce3..6b92a34 100644--- a/scripts/train_transformer.py+++ b/scripts/train_transformer.py@@ -1,6 +1,7 @@from __future__ import annotationsimport argparse+import contextlibimport osimport reimport sys@@ -68,6 +69,28 @@ def get_peak_memory_report(device: str) -> str:return "Peak VRAM allocated: N/A | Peak VRAM reserved: N/A"+def estimate_memory_budget(num_params: int, device: str, use_amp: bool) -> str:+ """+ Print a rough training VRAM budget so users can predict OOM before launching.++ AdamW keeps fp32 weights + grads + two moment buffers (~16 bytes/param). This is an+ estimate of optimizer/parameter state only (activations depend on batch/context and+ are reduced a lot by gradient checkpointing). CUDA-only; returns N/A otherwise.+ """+ if not (device.startswith("cuda") and torch.cuda.is_available()):+ return "VRAM budget: N/A (no CUDA device)"+ # weights(4) + grad(4) + Adam m(4) + Adam v(4); AMP adds bf16/fp16 copies but keeps+ # the fp32 master state, so ~16 B/param is a reasonable floor either way.+ state_gib = bytes_to_gib(num_params * 16)+ props = torch.cuda.get_device_properties(torch.cuda.current_device())+ total_gib = bytes_to_gib(props.total_memory)+ note = " (+ activations; reduce with --grad-checkpointing / --grad-accum)"+ return (+ f"VRAM budget: ~{state_gib:.2f} GiB params+optimizer state vs {total_gib:.2f} GiB "+ f"total on {torch.cuda.get_device_name()}{note}"+ )++# --- Checkpoint Helpers ---CHECKPOINT_RE = re.compile(r"checkpoint_step_(\d+)\.pt$")@@ -352,6 +375,41 @@ def parse_args() -> argparse.Namespace:default=None,help="Keep only the most recent N periodic checkpoints. 0 keeps all.",)+ # --- Memory-optimisation flags (opt-in; all default to the config values, which are OFF) ---+ parser.add_argument(+ "--amp",+ dest="amp",+ action="store_true",+ default=None,+ help="Enable bf16/fp16 mixed-precision autocast (CUDA only; ignored on CPU).",+ )+ parser.add_argument(+ "--amp-dtype",+ type=str,+ choices=["bf16", "fp16"],+ default=None,+ help="Autocast dtype when --amp is set: bf16 (default, no GradScaler) or fp16.",+ )+ parser.add_argument(+ "--grad-checkpointing",+ dest="grad_checkpointing",+ action="store_true",+ default=None,+ help="Recompute transformer-block activations in backward to save VRAM.",+ )+ parser.add_argument(+ "--grad-accum",+ type=int,+ default=None,+ help="Accumulate gradients over N micro-batches per optimizer step (effective batch xN).",+ )+ parser.add_argument(+ "--report-memory",+ dest="report_memory",+ action="store_true",+ default=None,+ help="Print a rough VRAM budget (params + optimizer state) before training (CUDA only).",+ )return parser.parse_args()@@ -374,6 +432,36 @@ def main() -> None:or default_checkpoint_dir(train_config['t_out_path']))+ # --- Resolve memory-optimisation options (CLI overrides config; all default OFF) ---+ use_amp = args.amp if args.amp is not None else bool(train_config.get('use_amp', False))+ amp_dtype_name = args.amp_dtype or train_config.get('amp_dtype', 'bf16')+ use_grad_ckpt = (+ args.grad_checkpointing if args.grad_checkpointing is not None+ else bool(train_config.get('use_gradient_checkpointing', False))+ )+ grad_accum = max(1, args.grad_accum if args.grad_accum is not None+ else int(train_config.get('grad_accum_steps', 1)))+ report_memory = (+ args.report_memory if args.report_memory is not None+ else bool(train_config.get('report_memory_budget', False))+ )++ device_is_cuda = train_config['device'].startswith('cuda') and torch.cuda.is_available()+ if use_amp and not device_is_cuda:+ print("[mem-opt] --amp requested but no CUDA device available; disabling AMP.")+ use_amp = False+ amp_dtype = torch.bfloat16 if amp_dtype_name == 'bf16' else torch.float16++ def autocast_ctx():+ if use_amp:+ return torch.autocast(device_type='cuda', dtype=amp_dtype)+ return contextlib.nullcontext()++ # GradScaler is only needed for fp16; bf16 has enough range. A disabled scaler is a no-op,+ # so the scale/unscale_/step/update calls below work unchanged for bf16 and CPU.+ use_scaler = use_amp and amp_dtype == torch.float16+ scaler = torch.amp.GradScaler('cuda', enabled=use_scaler)+# --- Initialize the Model and Print Parameters ---# Print runtime/device diagnostics and reset GPU peak-memory stats before training.@@ -393,6 +481,17 @@ def main() -> None:total_params = sum(p.numel() for p in model.parameters())print(f"Total number of parameters in the model: {total_params:,}")+ # Apply opt-in memory optimisations.+ model.gradient_checkpointing = use_grad_ckpt+ if report_memory:+ print(estimate_memory_budget(total_params, train_config['device'], use_amp))+ if use_amp or use_grad_ckpt or grad_accum > 1:+ print(+ f"[mem-opt] amp={use_amp}"+ f"{'(' + amp_dtype_name + ')' if use_amp else ''} "+ f"grad_checkpointing={use_grad_ckpt} grad_accum={grad_accum}"+ )+# --- Optimizer Setup and Loss Tracking ---# Set up the AdamW optimizer with the specified learning rate.@@ -428,8 +527,8 @@ def main() -> None:device=train_config['device'],)- # Number of tokens processed per step (batch_size * context_length), used for throughput.- tokens_per_step = train_config['t_batch_size'] * train_config['t_context_length']+ # Number of tokens processed per optimizer step (batch * context * grad_accum), for throughput.+ tokens_per_step = train_config['t_batch_size'] * train_config['t_context_length'] * grad_accumlast_eval_time = time.perf_counter()latest_train_loss = Nonelatest_dev_loss = None@@ -438,25 +537,31 @@ def main() -> None:pbar = tqdm(range(start_step, train_config['t_train_steps']))for step in pbar:try:- # Fetch a batch of input and target data (and start the step timer).+ # Start the step timer.step_start_time = time.perf_counter()- xb, yb = next(batch_iterator)- # Perform a forward pass and compute the loss.- _, loss = model(xb, yb)-- # Record the loss for tracking.- losses.append(float(loss.item()))- pbar.set_description(f"Train loss: {np.mean(losses[-avg_window:]):.4f}")-- # Backpropagate the loss and update the model parameters.+ # Accumulate gradients over `grad_accum` micro-batches (==1 => original behaviour).optimizer.zero_grad(set_to_none=True)- loss.backward()+ step_loss = 0.0+ for _ in range(grad_accum):+ xb, yb = next(batch_iterator)+ with autocast_ctx():+ _, loss = model(xb, yb)+ # Scale so the accumulated gradient equals the full-batch mean gradient.+ loss = loss / grad_accum+ scaler.scale(loss).backward()+ step_loss += float(loss.item())++ # Record the (accumulated) loss for tracking.+ losses.append(step_loss)+ pbar.set_description(f"Train loss: {np.mean(losses[-avg_window:]):.4f}")- # Clip gradients to prevent exploding gradients.+ # Clip gradients to prevent exploding gradients (unscale first for fp16 AMP).+ scaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)- optimizer.step()+ scaler.step(optimizer)+ scaler.update()last_completed_step = step# Measure step time and instantaneous throughput for diagnostics.diff --git a/src/models/transformer.py b/src/models/transformer.pyindex 91fc7b7..0dc728e 100644--- a/src/models/transformer.py+++ b/src/models/transformer.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport torchimport torch.nn as nnimport torch.nn.functional as F+import torch.utils.checkpoint as checkpointfrom src.models.transformer_block import Blockclass Transformer(nn.Module):@@ -33,6 +34,10 @@ class Transformer(nn.Module):super().__init__()self.context_length = context_lengthself.N_BLOCKS = N_BLOCKS+ # Opt-in activation (gradient) checkpointing; off by default so behaviour and+ # numerics are unchanged unless a caller explicitly turns it on (e.g. the+ # pretraining script's --grad-checkpointing flag to save VRAM). See issue #5.+ self.gradient_checkpointing = Falseself.token_embed = nn.Embedding(vocab_size, n_embed)self.position_embed = nn.Embedding(context_length, n_embed)self.attn_blocks = nn.ModuleList([Block(n_head, n_embed, context_length) for _ in range(N_BLOCKS)])@@ -73,7 +78,13 @@ class Transformer(nn.Module):"""x = self._pre_attn_pass(idx)for block in self.attn_blocks:- x = block(x)+ if self.gradient_checkpointing and self.training:+ # Recompute block activations in backward instead of storing them,+ # trading compute for a large activation-memory saving. use_reentrant=False+ # is the modern, correct variant.+ x = checkpoint.checkpoint(block, x, use_reentrant=False)+ else:+ x = block(x)return self.layer_norm(x)def forward(self, idx: torch.Tensor, targets: torch.Tensor = None) -> tuple[torch.Tensor, torch.Tensor | None]:@@ -92,8 +103,11 @@ class Transformer(nn.Module):loss = Noneif targets is not None:B, T, C = logits.shape- flat_logits = logits.view(B * T, C)- targets = targets.view(B * T).long()+ # reshape (not view): targets come from a non-contiguous slice of the+ # batch tensor, which makes .view() raise on CPU (the cross-device .to('cuda')+ # copy happens to make it contiguous, which is why this only bit CPU runs).+ flat_logits = logits.reshape(B * T, C)+ targets = targets.reshape(B * T).long()loss = F.cross_entropy(flat_logits, targets)return logits, loss