Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

feat(models): build either architecture from one config

FareedKhan-devad9aaeb5d8b6
diff --git a/config/post_training_config.py b/config/post_training_config.py
index 93c5897..100813b 100644
--- a/config/post_training_config.py
+++ b/config/post_training_config.py
@@ -24,6 +24,8 @@ from typing import Literal, TypeVar
from config.paths import CKPT_DIR, DATA_DIR, LOG_DIR
+Arch = Literal["classic", "modern"]
+AttentionKind = Literal["gqa", "mla"]
AmpDtype = Literal["bf16", "fp16"]
PreferenceLoss = Literal["dpo", "orpo", "kto"]
RewardSource = Literal["verifier", "rm"]
@@ -41,12 +43,26 @@ def _check(cond: bool, message: str) -> None:
@dataclass
class BaseModelConfig:
# --- model architecture (must match across all stages + the pretrained ckpt) ---
+ arch: Arch = "classic" # "classic" = the original Transformer, "modern" = Llama-style
vocab_size: int = 50304
context_length: int = 1024
n_embed: int = 1024
n_head: int = 16
n_blocks: int = 24
+ # --- modern architecture only (ignored when arch="classic"), see src/models/modern ---
+ n_kv_head: int | None = None # grouped-query attention; None = one KV head per query head
+ attention: AttentionKind = "gqa" # "mla" = DeepSeek multi-head latent attention
+ kv_latent_dim: int | None = None # MLA latent size; None = n_embed // 4
+ rope_theta: float = 10_000.0
+ qk_norm: bool = True
+ attn_gate: bool = False
+ sliding_window: int | None = None
+ tie_embeddings: bool = True
+ n_experts: int = 0 # > 0 = Mixture of Experts
+ moe_top_k: int = 2
+ n_shared_experts: int = 0
+
# --- runtime ---
device: str = "auto" # auto | cuda | mps | cpu
amp_dtype: AmpDtype | None = "bf16" # None | "bf16" | "fp16"; ignored on CPU
@@ -62,6 +78,12 @@ class BaseModelConfig:
_check(getattr(self, name) > 0, f"{name} must be positive, got {getattr(self, name)}")
_check(self.n_embed % self.n_head == 0,
f"n_embed ({self.n_embed}) must be divisible by n_head ({self.n_head})")
+ if self.n_kv_head is not None:
+ _check(self.n_kv_head > 0 and self.n_head % self.n_kv_head == 0,
+ f"n_head ({self.n_head}) must be divisible by n_kv_head ({self.n_kv_head})")
+ _check(self.n_experts >= 0, "n_experts must be >= 0")
+ if self.n_experts:
+ _check(1 <= self.moe_top_k <= self.n_experts, "moe_top_k must be between 1 and n_experts")
@dataclass
diff --git a/configs/base.json b/configs/base.json
index 1aeadd0..b1468f2 100644
--- a/configs/base.json
+++ b/configs/base.json
@@ -1,9 +1,21 @@
{
+ "arch": "classic",
"vocab_size": 50304,
"context_length": 1024,
"n_embed": 1024,
"n_head": 16,
"n_blocks": 24,
+ "n_kv_head": null,
+ "attention": "gqa",
+ "kv_latent_dim": null,
+ "rope_theta": 10000.0,
+ "qk_norm": true,
+ "attn_gate": false,
+ "sliding_window": null,
+ "tie_embeddings": true,
+ "n_experts": 0,
+ "moe_top_k": 2,
+ "n_shared_experts": 0,
"device": "auto",
"amp_dtype": "bf16",
"seed": 1337,
diff --git a/configs/smoke/base.json b/configs/smoke/base.json
index 8303146..e11ee11 100644
--- a/configs/smoke/base.json
+++ b/configs/smoke/base.json
@@ -1,4 +1,5 @@
{
+ "arch": "classic",
"vocab_size": 50304,
"context_length": 256,
"n_embed": 128,
diff --git a/src/models/factory.py b/src/models/factory.py
new file mode 100644
index 0000000..9f02df3
--- /dev/null
+++ b/src/models/factory.py
@@ -0,0 +1,56 @@
+"""
+Build a model from any config: a post-training dataclass, the legacy ``default_config`` dict,
+or the ``cfg`` stored inside a checkpoint.
+
+``arch`` picks the architecture:
+
+- ``"classic"`` (default): the original 2017-style Transformer in ``src/models/transformer.py``.
+- ``"modern"``: the Llama/Qwen-style decoder in ``src/models/modern`` (RoPE, RMSNorm, SwiGLU,
+ GQA or MLA, optional MoE). Its extra settings (``n_kv_head``, ``n_experts``, ...) are read
+ from the same config when present.
+
+Checkpoints written before ``arch`` existed have no such key, so they load as ``"classic"``.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import asdict, is_dataclass
+from typing import Any
+
+import torch.nn as nn
+
+from src.models.modern import ModernConfig, ModernTransformer
+from src.models.transformer import Transformer
+
+ARCHITECTURES = ("classic", "modern")
+
+
+def config_as_dict(cfg: Any) -> dict[str, Any]:
+ """A plain dict view of a dataclass instance, a mapping, or a namespace."""
+ if isinstance(cfg, Mapping):
+ return dict(cfg)
+ if is_dataclass(cfg) and not isinstance(cfg, type):
+ return asdict(cfg)
+ return dict(vars(cfg))
+
+
+def build_model(cfg: Any) -> nn.Module:
+ """Construct a fresh, randomly initialized model described by ``cfg``."""
+ values = config_as_dict(cfg)
+ arch = values.get("arch") or "classic"
+ if arch == "classic":
+ return Transformer(
+ n_head=values["n_head"],
+ n_embed=values["n_embed"],
+ context_length=values["context_length"],
+ vocab_size=values["vocab_size"],
+ N_BLOCKS=values["n_blocks"],
+ )
+ if arch == "modern":
+ return ModernTransformer(ModernConfig.from_mapping(values))
+ raise ValueError(f"unknown arch {arch!r}; expected one of {ARCHITECTURES}")
+
+
+def count_parameters(model: nn.Module) -> int:
+ return sum(p.numel() for p in model.parameters())
diff --git a/src/post_training/inference.py b/src/post_training/inference.py
index a30bf7c..6e13f25 100644
--- a/src/post_training/inference.py
+++ b/src/post_training/inference.py
@@ -17,6 +17,7 @@ from src.checkpoint import (
model_config_from_checkpoint,
model_state_from_checkpoint,
)
+from src.models.factory import build_model
from src.models.transformer import Transformer
from src.post_training.chat_template import encode_prompt, get_tokenizer
from src.post_training.evaluation import batched_generate
@@ -32,12 +33,9 @@ def load_model_from_ckpt(ckpt_path: str, device: str, overrides: dict | None = N
too, so a model trained with ``--compile true`` loads correctly (issue #36).
"""
ck = load_checkpoint(ckpt_path, map_location="cpu")
- cfg = {**model_config_from_checkpoint(ck), **(overrides or {})}
- model = Transformer(
- n_head=cfg.get("n_head", 16), n_embed=cfg.get("n_embed", 1024),
- context_length=cfg.get("context_length", 1024), vocab_size=cfg.get("vocab_size", 50304),
- N_BLOCKS=cfg.get("n_blocks", 24),
- )
+ defaults = {"n_head": 16, "n_embed": 1024, "context_length": 1024, "vocab_size": 50304, "n_blocks": 24}
+ cfg = {**defaults, **model_config_from_checkpoint(ck), **(overrides or {})}
+ model = build_model(cfg)
state = model_state_from_checkpoint(ck, extra_prefixes=("transformer.",))
load_model_weights(model, state, source=ckpt_path)
return model.to(device).eval()
diff --git a/src/post_training/utils.py b/src/post_training/utils.py
index ead4a01..f6bf4e8 100644
--- a/src/post_training/utils.py
+++ b/src/post_training/utils.py
@@ -24,6 +24,7 @@ from src.checkpoint import (
strip_wrapper_prefixes,
unwrap_model,
)
+from src.models.factory import build_model
from src.models.transformer import Transformer
@@ -58,17 +59,12 @@ def _cfg_get(cfg: Any, key: str) -> Any:
def build_model_from_config(cfg: Any) -> Transformer:
"""
- Construct a fresh :class:`Transformer` from a config carrying the standard keys
- ``n_head, n_embed, context_length, vocab_size, n_blocks``. Works with the new
- post-training dataclasses and with the legacy ``default_config`` dict.
+ Construct a fresh model from a config carrying the standard keys
+ ``n_head, n_embed, context_length, vocab_size, n_blocks`` (plus ``arch`` and the modern
+ model's settings, when present). Works with the post-training dataclasses and with the
+ legacy ``default_config`` dict.
"""
- return Transformer(
- n_head=_cfg_get(cfg, "n_head"),
- n_embed=_cfg_get(cfg, "n_embed"),
- context_length=_cfg_get(cfg, "context_length"),
- vocab_size=_cfg_get(cfg, "vocab_size"),
- N_BLOCKS=_cfg_get(cfg, "n_blocks"),
- )
+ return build_model(cfg) # type: ignore[return-value] # either architecture fits the interface
# Kept for code that imported the old private name; it now also strips torch.compile's
diff --git a/tests/test_factory.py b/tests/test_factory.py
new file mode 100644
index 0000000..58a19ac
--- /dev/null
+++ b/tests/test_factory.py
@@ -0,0 +1,47 @@
+"""One factory builds either architecture, and checkpoints remember which one they hold."""
+
+from __future__ import annotations
+
+import os
+from dataclasses import replace
+
+import pytest
+import torch
+
+from config.loader import load_config
+from config.post_training_config import SFTConfig, smoke
+from src.models.factory import build_model
+from src.models.modern import ModernTransformer
+from src.models.transformer import Transformer
+from src.post_training.inference import load_model_from_ckpt
+from src.post_training.utils import load_backbone_from_ckpt, save_stage_ckpt
+
+DIMS = {"n_head": 4, "n_embed": 32, "context_length": 16, "vocab_size": 64, "n_blocks": 2}
+
+
+def test_build_model_picks_the_architecture() -> None:
+ assert isinstance(build_model(DIMS), Transformer) # no arch key: classic, like old checkpoints
+ assert isinstance(build_model({**DIMS, "arch": "classic"}), Transformer)
+ modern = build_model({**DIMS, "arch": "modern", "n_kv_head": 2, "lr": 1e-3}) # unrelated keys ignored
+ assert isinstance(modern, ModernTransformer) and modern.config.kv_heads == 2
+ with pytest.raises(ValueError, match="unknown arch"):
+ build_model({**DIMS, "arch": "mamba"})
+
+
+def test_cli_style_overrides_build_a_modern_model() -> None:
+ cfg = load_config(SFTConfig, "configs/smoke/sft.json", {"arch": "modern", "n_kv_head": "2", "n_experts": "4"})
+ model = build_model(cfg)
+ assert isinstance(model, ModernTransformer)
+ assert model.config.kv_heads == 2 and model.config.n_experts == 4
+
+
+def test_modern_checkpoints_round_trip(tmp_path: str) -> None:
+ cfg = replace(smoke(SFTConfig), arch="modern", n_kv_head=2)
+ torch.manual_seed(0)
+ model = build_model(cfg)
+ path = os.path.join(tmp_path, "modern.pt")
+ save_stage_ckpt(path, model, None, stage="sft", cfg=cfg, step=1)
+ for loaded in (load_model_from_ckpt(path, "cpu"), load_backbone_from_ckpt(cfg, path, "cpu")):
+ assert isinstance(loaded, ModernTransformer)
+ for (k, a), b in zip(model.state_dict().items(), loaded.state_dict().values()):
+ assert torch.equal(a, b), k