Download model/model.py from Atharva31/indicslm-from-scratch: direct link, hf CLI and curl.
- Browser
- Download file 6.45 kB
-
https://huggingface.co/Atharva31/indicslm-from-scratch/resolve/main/model/model.py
- Command line
-
hf download hf://Atharva31/indicslm-from-scratch/model/model.py
-
curl -L -o model.py https://huggingface.co/Atharva31/indicslm-from-scratch/resolve/main/model/model.py
6.45 kB
| """ | |
| Full decoder-only transformer: tied embedding -> N transformer blocks -> | |
| final RMSNorm -> tied output head. Positions come entirely from RoPE | |
| (applied inside attention) — there is no learned/absolute positional | |
| embedding table. | |
| Design decisions: | |
| - Weight tying (input embedding == output projection weight) per | |
| config.tie_embeddings: at vocab_size=16k / d_model=384 the embedding is | |
| a large fraction of total params, so untying would nearly double | |
| embedding-related params for no expected quality gain at this scale. | |
| - forward(input_ids, kv_cache=None): when kv_cache is None, positions = | |
| arange(seq_len) (full-sequence training/prefill path). When kv_cache is | |
| given, positions = arange(kv_cache.seq_len, kv_cache.seq_len + seq_len) | |
| — "wherever the cache says we've generated up to" — so the caller can | |
| pass a full prompt for prefill or one token at a time for decoding, and | |
| the model always uses correct absolute positions for RoPE/masking. | |
| - kv_cache.step(seq_len) is called exactly once per forward pass, after | |
| all layers have written into the cache — a per-layer bump would desync | |
| layers if step() were called inside the block/attention loop instead. | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| from model.config import ModelConfig | |
| from model.rope import precompute_rope_freqs | |
| from model.rmsnorm import RMSNorm | |
| from model.transformer import TransformerBlock | |
| class IndicSLM(nn.Module): | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.config = config | |
| self.token_embedding = nn.Embedding(config.vocab_size, config.d_model) | |
| self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)]) | |
| self.final_norm = RMSNorm(config.d_model, eps = config.rms_eps) | |
| # Declared as a Linear so the forward path is uniform whether tied | |
| # or not; in the tied case we overwrite .weight to be the SAME | |
| # tensor object as the embedding (not a copy), so gradients from | |
| # both "uses" accumulate into one shared parameter. | |
| self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) | |
| if config.tie_embeddings: | |
| self.lm_head.weight = self.token_embedding.weight | |
| # Fixed function of position/config, not a learned weight — not a | |
| # Parameter, and not saved in checkpoints (persistent=False). | |
| rope_angles = precompute_rope_freqs(config.head_dim, config.max_seq_len, config.rope_theta) | |
| self.register_buffer("rope_angles", rope_angles, persistent=False) | |
| # Weight init: PyTorch's defaults (nn.Embedding ~ N(0,1), | |
| # nn.Linear ~ Kaiming-uniform) produced ~340-350 nats initial loss | |
| # and exploding gradients in a real-data smoke test -- verified | |
| # root cause: tied embeddings make each logit a dot product of two | |
| # ~sqrt(d_model)-norm random vectors when Embedding's default | |
| # std=1 gives each 384-dim embedding a norm of ~19.6. Fixed with | |
| # the GPT-2/nanoGPT reference scheme below. | |
| self.apply(self._init_weights) | |
| self._scale_residual_projections() | |
| def _init_weights(self, module: nn.Module) -> None: | |
| """ | |
| N(0, 0.02) for every Linear/Embedding weight. 0.02 is the | |
| GPT-2/GPT-NeoX/LLaMA reference value: small enough that initial | |
| logits/activations stay in a well-behaved range (avoiding the | |
| ~340-nat blowup measured with std=1), but not so small that early | |
| gradients vanish. No bias init needed -- every Linear in this | |
| model is bias=False (see model/config.py's no-bias decision). | |
| """ | |
| if isinstance(module, (nn.Linear, nn.Embedding)): | |
| nn.init.normal_(module.weight, mean=0.0, std=0.02) | |
| def _scale_residual_projections(self) -> None: | |
| """ | |
| Extra 1/sqrt(2 * n_layers) scaling on top of the 0.02 std, applied | |
| ONLY to the two projections whose output gets added directly into | |
| the residual stream (attention's out_proj, SwiGLU's down_proj). | |
| Every other projection (q/k/v, SwiGLU's gate/up) feeds into a norm | |
| or activation before its output is used, so its output scale gets | |
| re-normalized downstream -- but a residual add has no norm in | |
| between, so without this dampening, the residual stream's | |
| variance compounds additively across all n_layers layers (a | |
| second, independent instability from the one the smoke test | |
| caught). This is the same fix GPT-2 uses for its c_proj/c_fc | |
| output weights. | |
| """ | |
| residual_std = 0.02 / (2 * self.config.n_layers) ** 0.5 | |
| for name, module in self.named_modules(): | |
| if name.endswith("attn.out_proj") or name.endswith("ffn.down_proj"): | |
| nn.init.normal_(module.weight, mean=0.0, std=residual_std) | |
| def forward(self, input_ids: torch.Tensor, kv_cache = None): | |
| """ | |
| Input_ids: (batch, seq_len) | |
| Returns logits: (batch, seq_len, vocab_size) | |
| """ | |
| batch, seq_len = input_ids.shape | |
| device = input_ids.device | |
| if kv_cache is None: | |
| positions = torch.arange(seq_len, device = device) | |
| else: | |
| start = kv_cache.seq_len | |
| positions = torch.arange(start, start + seq_len, device = device) | |
| x = self.token_embedding(input_ids) | |
| for layer_idx, block in enumerate(self.blocks): | |
| x = block(x, self.rope_angles, positions, kv_cache = kv_cache, layer_idx = layer_idx) | |
| if kv_cache is not None: | |
| kv_cache.step(seq_len) | |
| x = self.final_norm(x) | |
| logits = self.lm_head(x) | |
| return logits | |
| if __name__ == "__main__": | |
| config = ModelConfig() | |
| model = IndicSLM(config) | |
| total_params = sum(p.numel() for p in model.parameters()) | |
| print(f"Config: {config}") | |
| print(f"Total parameters: {total_params:,}") | |
| print(f"Hand estimate was ~22M (tied embedding ~6.14M + ~1.57M/layer * 10 layers)") | |
| batch, seq_len = 2, config.max_seq_len | |
| dummy_ids = torch.randint(0, config.vocab_size, (batch, seq_len)) | |
| logits = model(dummy_ids) | |
| print(f"forward() output shape: {tuple(logits.shape)} (expected ({batch}, {seq_len}, {config.vocab_size}))") |