anlp-assignment2 / src /part1 /config.py
sahoosk's picture
Upload folder using huggingface_hub
5407bdc verified
Raw History Blame Contribute Delete
6.15 kB
"""Configuration for the decoder-only transformer and its five FFN variants.
The parameter budget is the whole point of this task, so the arithmetic that
sizes each variant lives here rather than being scattered through the model.
Every FFN variant is built from the same 2-layer MLP primitive with hidden
width ``d_ff``. One such MLP costs ``2 * d_model * d_ff`` weight parameters
(no biases). Writing E for the number of experts and k for the number that
are active on a given token:
total FFN params = E * 2 * d_model * d_ff_expert
active FFN params = k * 2 * d_model * d_ff_expert
The dense baseline is E = k = 1 with ``d_ff_expert = d_ff``. Variants 2-4
hold *total* params fixed by shrinking each expert to ``d_ff / E``; variant 5
holds *active* params fixed by shrinking each expert to ``d_ff / k`` instead,
which doubles the total.
"""
from dataclasses import dataclass, asdict
from typing import Optional
@dataclass
class TransformerConfig:
# --- shape -------------------------------------------------------------
d_model: int = 512 # Dimension of the model
n_ctx: int = 256 # Number of context tokens
n_layers: int = 6
n_heads: int = 8
n_kv_heads: Optional[int] = None # None -> plain MHA
vocab_size: int = 16000
d_ff: int = 2048 # dense-baseline FFN hidden width
dropout: float = 0.0
tie_embeddings: bool = True
rope_base: float = 10000.0
# --- feed-forward variant ---------------------------------------------
use_moe: bool = False
n_experts: int = 4 # routed experts (excludes the shared one)
n_active: int = 2 # routed experts active per token (top-k)
n_shared: int = 0 # always-on experts
# How each expert's hidden width is derived from ``d_ff``:
# "total" -> d_ff // (n_experts + n_shared) [total params preserved]
# "active" -> d_ff // (n_active + n_shared) [active params preserved]
expert_budget: str = "total"
router_aux_coef: float = 0.01 # load-balancing loss weight
router_z_coef: float = 1e-3 # router logit z-loss weight
router_noise: float = 0.0 # std of train-time noise on router logits
# --- bookkeeping -------------------------------------------------------
name: str = "c1_dense"
@property
def d_head(self) -> int:
return self.d_model // self.n_heads
@property
def d_ff_expert(self) -> int:
"""Hidden width of a single expert under the chosen budget rule."""
if not self.use_moe:
return self.d_ff
if self.expert_budget == "total":
denom = self.n_experts + self.n_shared
elif self.expert_budget == "active":
denom = self.n_active + self.n_shared
else:
raise ValueError(f"unknown expert_budget {self.expert_budget!r}")
assert self.d_ff % denom == 0, (
f"d_ff={self.d_ff} not divisible by {denom} for budget "
f"{self.expert_budget!r}"
)
return self.d_ff // denom
# --- parameter accounting ---------------------------------------------
def ffn_params(self):
"""(total, active) FFN weight params in ONE layer, routers included."""
per_expert = 2 * self.d_model * self.d_ff_expert
if not self.use_moe:
return per_expert, per_expert
n_all = self.n_experts + self.n_shared
router = self.d_model * self.n_experts
total = n_all * per_expert + router
active = (self.n_active + self.n_shared) * per_expert + router
return total, active
def param_counts(self):
"""Analytic (total, active) parameter counts for the whole model."""
emb = self.vocab_size * self.d_model
head = 0 if self.tie_embeddings else self.vocab_size * self.d_model
kv = self.n_kv_heads or self.n_heads
attn = (2 * self.d_model * self.d_model # Wq, Wo
+ 2 * self.d_model * kv * self.d_head) # Wk, Wv
norms = 2 * self.d_model # two RMSNorms
ffn_total, ffn_active = self.ffn_params()
per_layer_total = attn + norms + ffn_total
per_layer_active = attn + norms + ffn_active
base = emb + head + self.d_model # + final norm
return (base + self.n_layers * per_layer_total,
base + self.n_layers * per_layer_active)
def to_dict(self):
return asdict(self)
# ---------------------------------------------------------------------------
# The five deliverable configurations.
# ---------------------------------------------------------------------------
def build_configs(**overrides) -> dict:
"""Return the five FFN ablations, all sharing the same trunk."""
base = dict(d_model=512, n_ctx=256, n_layers=6, n_heads=8,
vocab_size=16000, d_ff=2048)
base.update(overrides)
cfgs = {
# 1. standard 2-layer MLP -- the dense baseline
"c1_dense": TransformerConfig(
**base, use_moe=False, name="c1_dense"),
# 2. 4 experts, top-1 (total params held at the dense budget)
"c2_moe_4e1a": TransformerConfig(
**base, use_moe=True, n_experts=4, n_active=1, n_shared=0,
expert_budget="total", name="c2_moe_4e1a"),
# 3. 4 experts, top-2 (total params held at the dense budget)
"c3_moe_4e2a": TransformerConfig(
**base, use_moe=True, n_experts=4, n_active=2, n_shared=0,
expert_budget="total", name="c3_moe_4e2a"),
# 4. 1 shared + 3 routed, top-1 routed (2 of 4 active)
"c4_moe_shared": TransformerConfig(
**base, use_moe=True, n_experts=3, n_active=1, n_shared=1,
expert_budget="total", name="c4_moe_shared"),
# 5. 4 experts, top-2, ACTIVE params matched to the dense baseline
"c5_moe_4e2a_wide": TransformerConfig(
**base, use_moe=True, n_experts=4, n_active=2, n_shared=0,
expert_budget="active", name="c5_moe_4e2a_wide"),
}
return cfgs