A straightforward method for training your LLM, from downloading data to generating text.
feat(sft): LoRA adapters written from scratch
FareedKhan-dev31de9a96c352
diff --git a/config/post_training_config.py b/config/post_training_config.pyindex 11e576b..1899de1 100644--- a/config/post_training_config.py+++ b/config/post_training_config.py@@ -135,6 +135,15 @@ class SFTConfig(BaseModelConfig):weight_decay: float = 0.0grad_clip: float = 1.0save_every: int = 500+ # LoRA (0 = full fine-tuning). The adapters are merged into the weights before saving,+ # so the checkpoint is a normal model every later stage can load.+ lora_rank: int = 0+ lora_alpha: float = 16.0+ lora_dropout: float = 0.0++ def __post_init__(self) -> None:+ super().__post_init__()+ _check(self.lora_rank >= 0, "lora_rank must be >= 0")@dataclassdiff --git a/configs/sft.json b/configs/sft.jsonindex 374a208..a29bf9e 100644--- a/configs/sft.json+++ b/configs/sft.json@@ -13,5 +13,8 @@"min_lr": 1e-06,"weight_decay": 0.0,"grad_clip": 1.0,- "save_every": 500+ "save_every": 500,+ "lora_rank": 0,+ "lora_alpha": 16.0,+ "lora_dropout": 0.0}diff --git a/scripts/train_sft.py b/scripts/train_sft.pyindex 4ec5c1d..ae7f825 100644--- a/scripts/train_sft.py+++ b/scripts/train_sft.py@@ -18,6 +18,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1])) # run from the repo without installingimport contextlib+import copyimport mathimport osimport time@@ -28,6 +29,7 @@ from config.post_training_config import SFTConfigfrom data_loader.sft_dataset import get_sft_batch_iteratorfrom src.post_training.cli import parse_config_with_jsonfrom src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar+from src.models.lora import apply_lora, lora_parameter_count, merge_lorafrom src.post_training.logging_utils import MetricsLoggerfrom src.post_training.optim import configure_optimizer, cosine_lr, set_lrfrom src.post_training.sft import sft_loss@@ -53,12 +55,25 @@ def eval_dev(model, cfg, ctx, dev_path: str, max_batches: int = 50) -> float:return total / max(1, n)+def model_to_save(model, use_lora: bool):+ """With LoRA, save a merged copy so the checkpoint is a plain model for the next stages."""+ plain = unwrap(model)+ return merge_lora(copy.deepcopy(plain)) if use_lora else plain++def main():cfg, _ = parse_config_with_json(SFTConfig, "configs/sft.json")ctx = ddp_setup(cfg.device)set_seed(cfg.seed + ctx.rank)model = load_backbone_from_ckpt(cfg, cfg.pretrained_ckpt, ctx.device)+ use_lora = cfg.lora_rank > 0+ if use_lora:+ wrapped = apply_lora(model, cfg.lora_rank, cfg.lora_alpha, cfg.lora_dropout)+ trainable, total = lora_parameter_count(model)+ if ctx.is_main:+ print(f"LoRA rank {cfg.lora_rank} on {len(wrapped)} layers: training {trainable:,} of "+ f"{total:,} parameters ({100 * trainable / total:.2f}%)")if cfg.compile:model = torch.compile(model)model = ddp_wrap(model, ctx)@@ -121,16 +136,16 @@ def main():logger.log(step, {"dev_loss": dev})if ctx.is_main and step > 0 and step % cfg.save_every == 0:- save_stage_ckpt(cfg.out_ckpt, model, optimizer, stage="sft", cfg=cfg, step=step,- metrics={"train_loss": loss.item()})+ save_stage_ckpt(cfg.out_ckpt, model_to_save(model, use_lora), None if use_lora else optimizer,+ stage="sft", cfg=cfg, step=step, metrics={"train_loss": loss.item()})if ctx.is_main:# Use the unwrapped model for the final eval: the other ranks have already reached# cleanup(), so calling the DDP-wrapped model here would launch a collective with no# peer and hang (NCCL timeout). The periodic eval above runs on all ranks, so it is fine.dev = eval_dev(unwrap(model), cfg, ctx, cfg.dev_path)- save_stage_ckpt(cfg.out_ckpt, model, optimizer, stage="sft", cfg=cfg, step=total_steps,- metrics={"dev_loss": dev})+ save_stage_ckpt(cfg.out_ckpt, model_to_save(model, use_lora), None if use_lora else optimizer,+ stage="sft", cfg=cfg, step=total_steps, metrics={"dev_loss": dev})print(f"Done SFT. dev_loss {dev:.4f} -> {cfg.out_ckpt}")if logger:logger.close()diff --git a/src/models/lora.py b/src/models/lora.pynew file mode 100644index 0000000..734be48--- /dev/null+++ b/src/models/lora.py@@ -0,0 +1,114 @@+"""+LoRA: low-rank adaptation (Hu et al. 2021), written from scratch.++Full fine-tuning updates every weight matrix ``W`` (``d_out x d_in`` numbers each). LoRA+freezes ``W`` and learns a low-rank correction instead:++ y = x W^T + (alpha / r) * x A^T B^T A: (r x d_in), B: (d_out x r)++With ``r = 8`` and ``d = 1024`` that is 16k trainable numbers per matrix instead of 1M.+``B`` starts at zero, so training starts exactly from the pretrained model, and after+training ``W + (alpha / r) B A`` can be folded back into one matrix (:func:`merge_lora`),+so inference costs nothing extra.++Why it works: fine-tuning changes turn out to be low-rank in practice, and the optimizer+state (Adam keeps two numbers per trainable weight) shrinks with the trainable count, so+LoRA fits on much smaller GPUs.+"""++from __future__ import annotations++import math+from collections.abc import Iterable++import torch+import torch.nn as nn+from jaxtyping import Float+from torch import Tensor++# Linear layers adapted by default: the attention projections of both architectures, and the+# MLP output projection of the classic model (it is also named "proj").+DEFAULT_TARGETS = frozenset({"query", "key", "value", "proj", "q_proj", "k_proj", "v_proj", "o_proj"})+++class LoRALinear(nn.Module):+ """A frozen ``nn.Linear`` plus a trainable low-rank update ``(alpha / r) * B @ A``."""++ def __init__(self, base: nn.Linear, rank: int, alpha: float = 16.0, dropout: float = 0.0) -> None:+ super().__init__()+ if rank <= 0:+ raise ValueError("LoRA rank must be positive")+ self.base = base+ for p in base.parameters():+ p.requires_grad_(False)+ self.rank, self.scaling = rank, alpha / rank+ w = base.weight+ self.lora_A = nn.Parameter(torch.empty(rank, base.in_features, device=w.device, dtype=w.dtype))+ self.lora_B = nn.Parameter(torch.zeros(base.out_features, rank, device=w.device, dtype=w.dtype))+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) # same init as nn.Linear+ self.dropout: nn.Module = nn.Dropout(dropout) if dropout > 0 else nn.Identity()++ @property+ def in_features(self) -> int:+ return self.base.in_features++ @property+ def out_features(self) -> int:+ return self.base.out_features++ def forward(self, x: Float[Tensor, "*batch d_in"]) -> Float[Tensor, "*batch d_out"]:+ update = (self.dropout(x) @ self.lora_A.T) @ self.lora_B.T+ return self.base(x) + update * self.scaling++ def merged(self) -> nn.Linear:+ """A plain ``nn.Linear`` with the update folded in: ``W + scaling * B @ A``."""+ out = nn.Linear(self.in_features, self.out_features, bias=self.base.bias is not None,+ device=self.base.weight.device, dtype=self.base.weight.dtype)+ with torch.no_grad():+ out.weight.copy_(self.base.weight + self.scaling * (self.lora_B @ self.lora_A))+ if self.base.bias is not None:+ out.bias.copy_(self.base.bias)+ return out+++def apply_lora(+ model: nn.Module,+ rank: int,+ alpha: float = 16.0,+ dropout: float = 0.0,+ targets: Iterable[str] = DEFAULT_TARGETS,+) -> list[str]:+ """+ Freeze ``model`` and wrap every ``nn.Linear`` whose attribute name is in ``targets`` with a+ :class:`LoRALinear`. Only the LoRA matrices stay trainable. Returns the wrapped names.+ """+ targets = set(targets)+ for p in model.parameters():+ p.requires_grad_(False)+ wrapped = []+ for parent_name, parent in list(model.named_modules()):+ for child_name, child in list(parent.named_children()):+ if child_name in targets and isinstance(child, nn.Linear):+ setattr(parent, child_name, LoRALinear(child, rank, alpha, dropout))+ wrapped.append(f"{parent_name}.{child_name}" if parent_name else child_name)+ if not wrapped:+ raise ValueError(f"no nn.Linear layer named one of {sorted(targets)} was found")+ return wrapped+++def merge_lora(model: nn.Module) -> nn.Module:+ """Fold every LoRA update into its base layer (in place) and make all weights trainable again."""+ for parent in list(model.modules()):+ for child_name, child in list(parent.named_children()):+ if isinstance(child, LoRALinear):+ setattr(parent, child_name, child.merged())+ for p in model.parameters():+ p.requires_grad_(True)+ return model+++def lora_parameter_count(model: nn.Module) -> tuple[int, int]:+ """``(trainable, total)`` parameter counts, to report how small the update is."""+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)+ total = sum(p.numel() for p in model.parameters())+ return trainable, totaldiff --git a/tests/test_lora.py b/tests/test_lora.pynew file mode 100644index 0000000..3df10ea--- /dev/null+++ b/tests/test_lora.py@@ -0,0 +1,66 @@+"""LoRA adapters on both architectures."""++from __future__ import annotations++import pytest+import torch++from src.models.lora import LoRALinear, apply_lora, lora_parameter_count, merge_lora+from src.models.modern import ModernConfig, ModernTransformer+from src.models.transformer import Transformer+++def _classic() -> Transformer:+ torch.manual_seed(0)+ return Transformer(n_head=4, n_embed=32, context_length=16, vocab_size=60, N_BLOCKS=2)+++def _modern() -> ModernTransformer:+ torch.manual_seed(0)+ return ModernTransformer(ModernConfig(vocab_size=60, context_length=16, n_embed=32, n_head=4, n_blocks=2, n_kv_head=2))++[email protected]("make", [_classic, _modern])+def test_lora_starts_as_the_identity_and_trains_few_params(make) -> None:+ model = make().eval()+ idx = torch.randint(0, 60, (2, 10))+ before = model(idx)[0]+ wrapped = apply_lora(model, rank=4, alpha=8)+ assert wrapped and all(isinstance(model.get_submodule(n), LoRALinear) for n in wrapped)+ assert torch.allclose(model(idx)[0], before) # B = 0 at init: same function as before+ trainable, total = lora_parameter_count(model)+ assert 0 < trainable < 0.2 * total+ assert all(("lora_" in n) == p.requires_grad for n, p in model.named_parameters())++[email protected]("make", [_classic, _modern])+def test_merge_gives_the_same_outputs(make) -> None:+ model = make().eval()+ apply_lora(model, rank=4, alpha=8)+ with torch.no_grad():+ for module in model.modules():+ if isinstance(module, LoRALinear):+ module.lora_B.normal_(std=0.1)+ idx = torch.randint(0, 60, (2, 10))+ adapted = model(idx)[0]+ merge_lora(model)+ assert not any(isinstance(m, LoRALinear) for m in model.modules())+ assert torch.allclose(model(idx)[0], adapted, atol=1e-5)+ assert all(p.requires_grad for p in model.parameters())+++def test_lora_learns_and_keeps_the_base_frozen() -> None:+ model = _classic()+ base_weight = model.attn_blocks[0].attn.heads[0].query.weight.detach().clone()+ apply_lora(model, rank=8, alpha=16)+ opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=1e-2)+ data = torch.randint(0, 60, (8, 11))+ first = None+ for _ in range(60):+ _, loss = model(data[:, :-1], data[:, 1:])+ first = first if first is not None else loss.item()+ opt.zero_grad()+ loss.backward()+ opt.step()+ assert loss.item() < 0.85 * first+ assert torch.equal(model.attn_blocks[0].attn.heads[0].query.base.weight, base_weight)