Fix CPU inference; add KV cache, FIM example, HumanEval results
Browse filesFiles changed (8)
- README.md+218-146
- config.json+41-31
- model/attention.py+61-24
- model/kv_cache.pyAdded+274
- model/pycraft_model.py+193-36
- model/sampling.pyAdded+146
- model/transformer.py+7-3
- requirements.txt+5-5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146---language:- enlicense: mittags:- code- python- causal-lm- from-scratch- gqa- rope- swiglu- fim- qk-normdatasets:- nampdn-ai/tiny-codes- ise-uiuc/Magicoder-OSS-Instruct-75K- iamtarun/python_code_instructions_18k_alpaca- bigcode/the-stack-smol- flytech/python-codes-25k- iamtarun/code_instructions_120k_alpaca---# PyCraft-1: A 55M Python Code LLM Trained From Scratch on Consumer Hardware## Model DescriptionPyCraft-1 is a 55.3M parameter decoder-only transformer trained**entirely from scratch** on Python code using a single NVIDIA RTX 3050laptop GPU (4GB VRAM). It demonstrates that a domain-specific code LLMcan be trained without cloud compute, following a quality-first datacurriculum inspired by the Phi-1 "Textbooks Are All You Need" approach.## Architecture| Component | Choice ||---|---|| Architecture | Decoder-only transformer || Parameters | 55.3M || Attention | Grouped Query Attention (8Q / 2KV heads) || Positional encoding | RoPE || QK-Norm | RMSNorm on Q and K (OLMo 2 / Qwen 3, 2025) || FFN | SwiGLU || Normalisation | RMSNorm pre-norm || Training objective | Causal LM + Fill-in-the-Middle (FIM, 50%) || Context window | 1024 tokens || Vocabulary | 32,000 (custom BPE, Python-tuned) |## Training**Pretraining:**- 309,221 curated Python examples from 6 open sources- Quality curriculum: scored on 5 heuristics, ordered best-first- 4,000 steps | 1.05B tokens | Loss 1.16 | PPL 3.2**Supervised Fine-Tuning:**- Magicoder-OSS-Instruct-75K (Python subset, 40k examples)- 400 steps | Loss 1.15 | PPL 3.15**Hardware:** NVIDIA RTX 3050 Laptop GPU 4GB, Ryzen 7 6000, 16GB RAM**Total training time:** ~22 hours## Novel Contributions1. **Quality-first data curriculum** — 309k Python examples scored andordered by educational value (docstrings, type hints, comments,naming conventions, length). Validates Phi-1 hypothesis at theresource-constrained regime.2. **QK-Norm** — RMSNorm applied to Q and K before RoPE, adopted fromOLMo 2 and Qwen 3 (2025), improving training stability in small models.3. **FIM pretraining on 4GB VRAM** — Fill-in-the-Middle objective usingPSM format trained on a consumer GPU via gradient checkpointing andBF16 mixed precision.4. **Full reproducibility** — complete open-source pipeline runnable onconsumer hardware in under one week.## Evaluation| Metric | Value ||---|---|| Pretraining loss | 1.16 || Pretraining PPL | 3.20 || SFT loss | 1.15 || SFT PPL | 3.15 || Held-out PPL (binary search) | 1.4 || Held-out PPL (Stack class) | 1.7 || Held-out PPL (average, 5 samples) | 2.16 |## Example Usage```python# Clone the repo and install dependencies first# pip install torch safetensors tokenizers datasetsimport torchfrom safetensors.torch import load_filefrom model.config import get_config_120mfrom model.pycraft_model import PyCraftModelfrom tokenizer.tokenizer_utils import PyCraftTokenizerdevice = "cuda" if torch.cuda.is_available() else "cpu"tokenizer = PyCraftTokenizer("tokenizer/vocab/tokenizer.json")cfg = get_config_120m()cfg.vocab_size = 32000cfg.dropout = 0.0model = PyCraftModel(cfg).to(device)model.load_state_dict(load_file("model.safetensors", device=device))model.eval()prompt = "def is_palindrome(s: str) -> bool:\n "ids = tokenizer.encode(prompt)inp = torch.tensor(ids, dtype=torch.long).unsqueeze(0).to(device)with torch.no_grad():out = model.generate(inp, max_new_tokens=80, temperature=0.7, top_k=40)print(tokenizer.decode(out[0].tolist()))```## Limitations- 55M parameters: generates plausible Python but may produce logical errors- Context window: 1024 tokens- Best on standard algorithms, data structures, and common library patterns- Not a conversational assistant## Citation```bibtex@misc{inamdar2026pycraft,title={PyCraft-1: Training a Python Code LLM From Scratch on Consumer Hardware},author={Inamdar, Rohan},year={2026},institution={University of Manchester, MSc Artificial Intelligence},}```## Links- GitHub: https://github.com/irohan0/pycraft-llm- Author: https://www.linkedin.com/in/rohan-inamdar-47aa4b251123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218---language:- enlicense: mittags:- code- python- causal-lm- from-scratch- gqa- rope- swiglu- fim- qk-normdatasets:- nampdn-ai/tiny-codes- ise-uiuc/Magicoder-OSS-Instruct-75K- iamtarun/python_code_instructions_18k_alpaca- bigcode/the-stack-smol- flytech/python-codes-25k- iamtarun/code_instructions_120k_alpaca---# PyCraft-1: A 55M Python Code LLM Trained From Scratch on Consumer Hardware## Model DescriptionPyCraft-1 is a 55.3M parameter decoder-only transformer trained**entirely from scratch** on Python code using a single NVIDIA RTX 3050laptop GPU (4GB VRAM). It demonstrates that a domain-specific code LLMcan be trained without cloud compute, following a quality-first datacurriculum inspired by the Phi-1 "Textbooks Are All You Need" approach.It runs comfortably on CPU — no GPU required for inference.## Architecture| Component | Choice ||---|---|| Architecture | Decoder-only transformer || Parameters | 55.3M || Attention | Grouped Query Attention (8Q / 2KV heads) || Positional encoding | RoPE || QK-Norm | RMSNorm on Q and K (OLMo 2 / Qwen 3, 2025) || FFN | SwiGLU || Normalisation | RMSNorm pre-norm || Training objective | Causal LM + Fill-in-the-Middle (FIM, 50%) || Context window | 1024 tokens || Vocabulary | 32,000 (custom BPE, Python-tuned) |## Training**Pretraining:**- 309,221 curated Python examples from 6 open sources- Quality curriculum: scored on 5 heuristics, ordered best-first- 4,000 steps | 1.05B tokens | Loss 1.16 | PPL 3.2**Supervised Fine-Tuning:**- Magicoder-OSS-Instruct-75K (Python subset, 40k examples)- 400 steps | Loss 1.15 | PPL 3.15**Hardware:** NVIDIA RTX 3050 Laptop GPU 4GB, Ryzen 7 6000, 16GB RAM**Total training time:** ~22 hours## Novel Contributions1. **Quality-first data curriculum** — 309k Python examples scored andordered by educational value (docstrings, type hints, comments,naming conventions, length). Validates Phi-1 hypothesis at theresource-constrained regime.2. **QK-Norm** — RMSNorm applied to Q and K before RoPE, adopted fromOLMo 2 and Qwen 3 (2025), improving training stability in small models.3. **FIM pretraining on 4GB VRAM** — Fill-in-the-Middle objective usingPSM format trained on a consumer GPU via gradient checkpointing andBF16 mixed precision.4. **Full reproducibility** — complete open-source pipeline runnable onconsumer hardware in under one week.## Evaluation| Metric | Value ||---|---|| Pretraining loss | 1.16 || Pretraining PPL | 3.20 || SFT loss | 1.15 || SFT PPL | 3.15 || Held-out PPL (binary search) | 1.4 || Held-out PPL (Stack class) | 1.7 || Held-out PPL (average, 5 samples) | 2.16 |### HumanEval| Model | Size | Training tokens | Hardware | Pass@1 ||---|---|---|---|---|| GPT-Neo | 125M | 300B | multi-GPU | 0.83% || **PyCraft-1** | **55M** | **1.05B** | **1× RTX 3050** | **3.66%** || CodeParrot | 110M | 50B | multi-GPU | 3.80% |**3.66% Pass@1 (6/164)** with greedy decoding, the conventional andreproducible setting for single-sample pass@1. Passing problems:`greatest_common_divisor`, `strlen`, `get_positive`, `is_prime`,`remove_vowels`, `add`.That is 4.4× GPT-Neo 125M on 0.35% of its training tokens, and close toCodeParrot 110M on 2% of its tokens, from a model roughly half their size.## Usage```bashpip install "torch>=2.1" safetensors tokenizers```Download this repository's `model.safetensors`, the `model/` package, and`tokenizer/tokenizer.json`, then:```pythonimport torchfrom safetensors.torch import load_filefrom model.config import get_config_120mfrom model.pycraft_model import PyCraftModelfrom tokenizer.tokenizer_utils import PyCraftTokenizerdevice = "cuda" if torch.cuda.is_available() else "cpu"tokenizer = PyCraftTokenizer("tokenizer/tokenizer.json")cfg = get_config_120m()cfg.vocab_size = 32000cfg.dropout = 0.0model = PyCraftModel(cfg).to(device)model.load_state_dict(load_file("model.safetensors", device=device))model.eval()prompt = "def is_palindrome(s: str) -> bool:\n "ids = tokenizer.encode(prompt)inp = torch.tensor(ids, dtype=torch.long).unsqueeze(0).to(device)with torch.no_grad():out = model.generate(inp,max_new_tokens=80,temperature=0.2, # 0.0 selects greedy decodingtop_k=20,repetition_penalty=1.1,)print(tokenizer.decode(out[0, len(ids):].tolist(), skip_special_tokens=True))````generate()` uses a KV cache, so cost per token stays flat instead ofgrowing with context. On CPU (8 threads) that is roughly 49–62 tokens/sdepending on context length, against 7–31 without it.Generation stops at `<|endoftext|>` by default. `stop_strings=[...]`(with `tokenizer=`) and `top_p` are also supported.### Fill in the MiddleHalf of pretraining used the FIM objective in PSM order, so infilling istrained behaviour rather than a prompting trick:```pythontok = tokenizerprefix = "def factorial(n):\n if n <= 1:\n return 1\n "suffix = "\n\nprint(factorial(5))\n"ids = ([tok.prefix_id] + tok.encode(prefix)+ [tok.suffix_id] + tok.encode(suffix)+ [tok.middle_id])inp = torch.tensor(ids, dtype=torch.long).unsqueeze(0).to(device)with torch.no_grad():out = model.generate(inp, max_new_tokens=40, temperature=0.2, top_k=20,eos_token_id=[tok.eot_id, tok.middle_id])print(tokenizer.decode(out[0, len(ids):].tolist(), skip_special_tokens=True))# -> return n * factorial(n-1)```### CLI and local REST APIThe GitHub repository ships an installable package with a CLI and aFastAPI server (completions with SSE streaming, plus a `/v1/fim` endpoint):```bashpip install -e ".[serve]"pycraft generate "def is_prime(n):"pycraft serve # http://127.0.0.1:8000/docs```## Limitations- 55M parameters: generates plausible Python but may produce logical errors- Context window: 1024 tokens, and it is a hard stop rather than a slidingwindow (the KV cache stores post-RoPE keys)- Best on standard algorithms, data structures, and common library patterns- The SFT data contained markdown code fences, so raw output often includesthem; strip them before executing- Not a conversational assistant## Citation```bibtex@misc{inamdar2026pycraft,title={PyCraft-1: Training a Python Code LLM From Scratch on Consumer Hardware},author={Inamdar, Rohan},year={2026},institution={University of Manchester, MSc Artificial Intelligence},}```## Links- GitHub: https://github.com/irohan0/pycraft-llm- Author: https://www.linkedin.com/in/rohan-inamdar-47aa4b251
12345678910111213141516171819202122232425262728293031{"model_type": "pycraft_decoder_only","vocab_size": 32000,"d_model": 512,"n_layers": 8,"n_heads": 8,"n_kv_heads": 2,"d_ff": 1408,"max_seq_len": 1024,"use_qk_norm": true,"rope_theta": 10000.0,"dropout": 0.0,"architecture_notes": {"attention": "Grouped Query Attention GQA 8Q/2KV","positional": "RoPE rotary embeddings","qk_norm": "RMSNorm on Q and K OLMo2 Qwen3 2025","ffn": "SwiGLU gated feedforward","norm": "RMSNorm pre-norm","objective": "Causal LM plus FIM 50 percent PSM format"},"training_summary": {"pretrain_steps": 4000,"pretrain_loss": 1.16,"pretrain_ppl": 3.2,"tokens_seen": "1.05B","sft_steps": 400,"sft_loss": 1.15,"sft_ppl": 3.15,"hardware": "NVIDIA RTX 3050 Laptop 4GB VRAM"}}1234567891011121314151617181920212223242526272829303132333435363738394041{"model_type": "pycraft_decoder_only","vocab_size": 32000,"d_model": 512,"n_layers": 8,"n_heads": 8,"n_kv_heads": 2,"d_ff": 1408,"max_seq_len": 1024,"use_qk_norm": true,"rope_theta": 10000.0,"dropout": 0.0,"architecture_notes": {"attention": "Grouped Query Attention GQA 8Q/2KV","positional": "RoPE rotary embeddings","qk_norm": "RMSNorm on Q and K OLMo2 Qwen3 2025","ffn": "SwiGLU gated feedforward","norm": "RMSNorm pre-norm","objective": "Causal LM plus FIM 50 percent PSM format"},"training_summary": {"pretrain_steps": 4000,"pretrain_loss": 1.16,"pretrain_ppl": 3.2,"tokens_seen": "1.05B","sft_steps": 400,"sft_loss": 1.15,"sft_ppl": 3.15,"hardware": "NVIDIA RTX 3050 Laptop 4GB VRAM","humaneval_pass_at_1": 3.66,"humaneval_passed": "6/164","humaneval_decoding": "greedy (temperature=0.0)"},"inference": {"kv_cache": true,"runs_on_cpu": true,"eos_token_id": 0,"fim_format": "PSM: <fim_prefix> prefix <fim_suffix> suffix <fim_middle>","context_window_is_hard_stop": true}}
1 unmodified line2345678910111213141553 unmodified lines697071727374757677787910 unmodified lines909192939495969738 unmodified lines13613713813914014114211 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841 unmodified line# Grouped-Query Attention with:# - Rotary Positional Embeddings (RoPE)# - QK-Norm (2025 technique from OLMo 2 / Qwen 3)# - PyTorch native SDPA (memory-efficient, no flash-attn dependency)# - No bias terms (standard in modern LLMs)import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.attention import sdpa_kernel, SDPBackendfrom model.config import PyCraftConfig53 unmodified linesself,q: torch.Tensor, # (batch, n_heads, seq_len, head_dim)k: torch.Tensor, # (batch, n_kv_heads, seq_len, head_dim)offset: int = 0, # for KV-cache offset during inference):seq_len = q.shape[2]cos = self.cos_cache[offset: offset + seq_len] # (seq_len, head_dim)sin = self.sin_cache[offset: offset + seq_len]# Reshape for broadcasting: (1, 1, seq_len, head_dim)cos = cos.unsqueeze(0).unsqueeze(0)10 unmodified lines# Reduces KV-cache size by 4x with negligible quality loss.# ------------------------------------------------------------------ #class GroupedQueryAttention(nn.Module):def __init__(self, config: PyCraftConfig):super().__init__()self.d_model = config.d_modelself.n_heads = config.n_headsself.n_kv_heads = config.n_kv_heads38 unmodified linesdef forward(self,x: torch.Tensor, # (batch, seq_len, d_model)attn_mask: torch.Tensor | None = None, # causal mask, pre-built) -> torch.Tensor:batch, seq_len, _ = x.shape11 unmodified linesself.head_dim).transpose(1, 2)# 3. QK-Norm (applied per-head, before RoPE)# Normalise each head vector independentlyif self.use_qk_norm:q = self.q_norm(q)k = self.k_norm(k)# 4. Apply RoPE to Q and Kq, k = self.rope(q, k)# 5. Expand K and V to match Q head count (GQA expansion)k = self._repeat_kv(k) # (batch, n_heads, seq, head_dim)v = self._repeat_kv(v)# 6. Scaled dot-product attention via PyTorch native SDPA# Uses memory-efficient attention automatically on Ampere GPUs.# is_causal=True applies the causal mask internally — no need to# pass an explicit mask during training (faster + less memory).with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):attn_out = F.scaled_dot_product_attention(q, k, v,attn_mask=None, # let is_causal handle itdropout_p=0.0,is_causal=True,)# 7. Merge heads and project back to d_model# (batch, n_heads, seq, head_dim) → (batch, seq, d_model)attn_out = attn_out.transpose(1, 2).contiguous().view(batch, seq_len, self.d_model)1 unmodified line2345678910111213141553 unmodified lines6970717273747576777879808182838485868788899091929310 unmodified lines10410510610710810911011111211338 unmodified lines15215315415515615715815916011 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202211 unmodified line# Grouped-Query Attention with:# - Rotary Positional Embeddings (RoPE)# - QK-Norm (2025 technique from OLMo 2 / Qwen 3)# - PyTorch native SDPA (backend auto-selected, no flash-attn dependency)# - Optional KV-cache for incremental decoding# - No bias terms (standard in modern LLMs)import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom model.config import PyCraftConfig53 unmodified linesself,q: torch.Tensor, # (batch, n_heads, seq_len, head_dim)k: torch.Tensor, # (batch, n_kv_heads, seq_len, head_dim)offset: int = 0, # absolute position of the first token):seq_len = q.shape[2]max_pos = self.cos_cache.shape[0]# Slicing past the end returns a SHORT tensor instead of raising,# which surfaces later as a confusing broadcast error — or worse, as# a plausible but positionally wrong result. Fail loudly instead.if offset < 0 or offset + seq_len > max_pos:raise ValueError(f"RoPE positions [{offset}, {offset + seq_len}) exceed the "f"precomputed table of {max_pos}. PyCraft-1 was trained with "f"max_seq_len={max_pos}; truncate the prompt or stop generating.")# .to() is a no-op when dtypes already match; _build_cache hardcodes# fp32, so this guards half/bf16 models.cos = self.cos_cache[offset: offset + seq_len].to(q.dtype)sin = self.sin_cache[offset: offset + seq_len].to(q.dtype)# Reshape for broadcasting: (1, 1, seq_len, head_dim)cos = cos.unsqueeze(0).unsqueeze(0)10 unmodified lines# Reduces KV-cache size by 4x with negligible quality loss.# ------------------------------------------------------------------ #class GroupedQueryAttention(nn.Module):def __init__(self, config: PyCraftConfig, layer_idx: int = 0):super().__init__()# Plain int — never enters state_dict, so checkpoints stay compatible.self.layer_idx = layer_idxself.d_model = config.d_modelself.n_heads = config.n_headsself.n_kv_heads = config.n_kv_heads38 unmodified linesdef forward(self,x: torch.Tensor, # (batch, seq_len, d_model)attn_mask: torch.Tensor | None = None, # (1|B, 1, T, S) bool, True = attendkv_cache=None, # KVCache, or None to disableposition_offset: int = 0, # cached positions before this call) -> torch.Tensor:batch, seq_len, _ = x.shape11 unmodified linesself.head_dim).transpose(1, 2)# 3. QK-Norm (applied per-head, before RoPE)# Normalise each head vector independently.# Cache-safe: RMSNorm reduces over the last dim only, so position t# depends on nothing but the vector at position t.if self.use_qk_norm:q = self.q_norm(q)k = self.k_norm(k)# 4. Apply RoPE at true absolute positionsq, k = self.rope(q, k, offset=position_offset)# 5. Append to the cache, read back everything written so far.# Stored PRE-expansion (n_kv_heads) — that 4x is the GQA memory win.# Keys are cached POST-RoPE; never re-rotate them.if kv_cache is not None:k, v = kv_cache.update(self.layer_idx, k, v)# 6. Expand K and V to match Q head count (GQA expansion)k = self._repeat_kv(k) # (batch, n_heads, kv_len, head_dim)v = self._repeat_kv(v)# 7. Scaled dot-product attention.# Backend is left to PyTorch: pinning one breaks CPU (the# memory-efficient kernel is CUDA-only) and blocks flash on GPU.## is_causal MUST be conditional. PyTorch builds it upper-left# aligned, so on a decode step (q_len=1, kv_len=N) it would mask# everything but the first prompt token — silently, with no error.# See build_attn_mask() in model/kv_cache.py.kv_len = k.shape[2]if attn_mask is None:# Square (offset == 0) -> upper-left causal is correct.# Single query (q_len == 1) -> may attend to all cached keys.is_causal = (seq_len == kv_len)else:is_causal = False # SDPA rejects mask + is_causal togetherattn_out = F.scaled_dot_product_attention(q, k, v,attn_mask=attn_mask,dropout_p=0.0,is_causal=is_causal,)# 8. Merge heads and project back to d_model# (batch, n_heads, seq, head_dim) → (batch, seq, d_model)attn_out = attn_out.transpose(1, 2).contiguous().view(batch, seq_len, self.d_model)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274# model/kv_cache.py
#
# KV-cache for PyCraft-1 incremental decoding.
#
# Without a cache, generating token N re-runs the full forward pass over all
# N-1 previous tokens — quadratic work for a linear amount of output.
# This module stores each layer's keys and values so every decode step only
# computes the single newest position.
#
# Two design choices matter and are easy to get wrong:
#
# 1. Storage is PRE-expansion — (B, n_kv_heads, ...) not (B, n_heads, ...).
# With GQA 8Q/2KV that is 4x less memory, which is the entire point of
# grouped-query attention. _repeat_kv re-expands on read.
#
# 2. Memory is PREALLOCATED, never torch.cat'd. Concatenating per step costs
# O(N) copy per step and O(N^2) overall — roughly 4.3 GB of pointless
# memcpy across one full-context generation.
#
# The cache holds POST-RoPE keys. RoPE is relative (q_m . k_n depends only on
# m - n), so a key rotated once at its true absolute position stays valid
# forever. Never re-apply RoPE to cached keys.
import torch
# ------------------------------------------------------------------ #
# KV cache
# ------------------------------------------------------------------ #
class KVCache:
"""
Pre-allocated per-layer key/value store for incremental decoding.
Per layer: k[i], v[i] : (batch, n_kv_heads, max_len, head_dim)
Live region: [:, :, :seq_len, :]
Typical use:
cache = KVCache.from_model(model, batch_size=1)
logits, _ = model(prompt_ids, past_key_values=cache) # prefill
logits, _ = model(next_id, past_key_values=cache) # decode
"""
def __init__(
self,
n_layers: int,
batch_size: int,
n_kv_heads: int,
head_dim: int,
max_len: int,
device,
dtype: torch.dtype = torch.float32,
):
self.n_layers = n_layers
self.batch_size = batch_size
self.n_kv_heads = n_kv_heads
self.head_dim = head_dim
self.max_len = max_len
self.device = device
self.dtype = dtype
self.seq_len = 0
shape = (batch_size, n_kv_heads, max_len, head_dim)
self.k = [torch.zeros(shape, device=device, dtype=dtype)
for _ in range(n_layers)]
self.v = [torch.zeros(shape, device=device, dtype=dtype)
for _ in range(n_layers)]
# -------------------------------------------------------------- #
# Called once per layer, per forward pass
# -------------------------------------------------------------- #
def update(
self,
layer_idx: int,
k_new: torch.Tensor, # (batch, n_kv_heads, T, head_dim)
v_new: torch.Tensor, # (batch, n_kv_heads, T, head_dim)
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Write this layer's new K/V into the cache and return views covering
everything written so far: (batch, n_kv_heads, seq_len + T, head_dim).
Deliberately does NOT advance seq_len. The model advances it once,
after all layers have written. Advancing here would make layer i see
the offset that only layer i+1 should see — a silent corruption that
produces plausible-looking garbage.
"""
batch, _, T, _ = k_new.shape
start = self.seq_len
if start + T > self.max_len:
raise ValueError(
f"KVCache overflow: {start} + {T} > max_len={self.max_len}. "
f"Allocate a larger cache or stop generating."
)
if batch != self.batch_size:
raise ValueError(
f"batch {batch} does not match cache batch {self.batch_size}"
)
if k_new.dtype != self.dtype:
# Silent casting here would quietly degrade precision every step.
raise TypeError(
f"cache dtype {self.dtype} != incoming dtype {k_new.dtype}"
)
self.k[layer_idx][:, :, start:start + T] = k_new
self.v[layer_idx][:, :, start:start + T] = v_new
# Narrowed views — the zero-padded tail is never visible, so reset()
# needs no memset.
return (
self.k[layer_idx][:, :, :start + T],
self.v[layer_idx][:, :, :start + T],
)
def advance(self, n: int):
"""Advance the write head. Called once per forward, by the model."""
self.seq_len += n
def reset(self):
"""Reuse this cache for a new sequence. No zeroing required."""
self.seq_len = 0
def __len__(self) -> int:
return self.seq_len
def __repr__(self) -> str:
return (
f"KVCache(layers={self.n_layers}, batch={self.batch_size}, "
f"kv_heads={self.n_kv_heads}, head_dim={self.head_dim}, "
f"seq_len={self.seq_len}/{self.max_len}, dtype={self.dtype})"
)
@property
def memory_bytes(self) -> int:
"""Total allocated cache size in bytes (K and V, all layers)."""
per = (self.batch_size * self.n_kv_heads
* self.max_len * self.head_dim)
return 2 * self.n_layers * per * torch.empty(
(), dtype=self.dtype).element_size()
# -------------------------------------------------------------- #
@classmethod
def from_model(
cls,
model,
batch_size: int = 1,
max_len: int | None = None,
device=None,
dtype: torch.dtype | None = None,
) -> "KVCache":
"""Build a cache matching a model's config, device, and dtype."""
cfg = model.config
# Read device/dtype from the embedding, not a Linear: dynamic
# quantization replaces nn.Linear with a module whose .weight is a
# method. Activations stay fp32 under dynamic quant either way.
ref = model.token_embedding.weight
return cls(
n_layers=cfg.n_layers,
batch_size=batch_size,
n_kv_heads=cfg.n_kv_heads,
head_dim=cfg.head_dim,
max_len=max_len or cfg.max_seq_len,
device=device if device is not None else ref.device,
dtype=dtype if dtype is not None else ref.dtype,
)
# ------------------------------------------------------------------ #
# Causal mask construction
# ------------------------------------------------------------------ #
def build_attn_mask(
q_len: int,
offset: int,
device,
) -> torch.Tensor | None:
"""
Build a bottom-right-aligned causal mask for cached attention.
Returns None for the two cases SDPA handles without an explicit mask:
offset == 0 caller passes is_causal=True (square, so PyTorch's
upper-left alignment is already correct)
q_len == 1 the single newest query may attend to every cached
key, so causality holds structurally — no mask needed
Otherwise returns (1, 1, q_len, offset + q_len) bool, True = "may attend":
mask[i, j] = (j <= offset + i)
WHY THIS EXISTS: PyTorch builds is_causal as torch.ones(L, S).tril() —
UPPER-LEFT aligned. With L=1, S=N that mask contains exactly one True
(column 0), so a cached decode step with is_causal=True would attend only
to the first prompt token, at every layer. No error, no NaN — just output
that ignores the prompt and collapses into repetition. Hence the explicit
dispatch rather than a blanket is_causal=True.
"""
if offset == 0 or q_len == 1:
return None
kv_len = offset + q_len
q_pos = torch.arange(offset, kv_len, device=device).unsqueeze(1) # (T, 1)
k_pos = torch.arange(0, kv_len, device=device).unsqueeze(0) # (1, S)
return (k_pos <= q_pos)[None, None, :, :] # (1,1,T,S)
# ------------------------------------------------------------------ #
# Quick self-test
# ------------------------------------------------------------------ #
if __name__ == "__main__":
print("Testing build_attn_mask...")
# Fast paths return None
assert build_attn_mask(4, 0, "cpu") is None, "offset=0 should return None"
assert build_attn_mask(1, 7, "cpu") is None, "q_len=1 should return None"
# Explicit mask matches a brute-force construction
for q_len, offset in [(4, 7), (3, 1), (2, 2)]:
got = build_attn_mask(q_len, offset, "cpu")
kv_len = offset + q_len
assert got.shape == (1, 1, q_len, kv_len), f"bad shape {got.shape}"
for i in range(q_len):
for j in range(kv_len):
expected = (j <= offset + i)
assert bool(got[0, 0, i, j]) == expected, (
f"mask[{i}][{j}] wrong for q_len={q_len}, offset={offset}"
)
print(" build_attn_mask: OK")
print("\nTesting KVCache...")
cache = KVCache(n_layers=2, batch_size=1, n_kv_heads=2,
head_dim=64, max_len=16, device="cpu")
print(f" {cache}")
print(f" allocated: {cache.memory_bytes / 1024:.1f} KiB")
# Prefill 4 positions across both layers
k = torch.randn(1, 2, 4, 64)
v = torch.randn(1, 2, 4, 64)
for layer in range(2):
kk, vv = cache.update(layer, k, v)
assert kk.shape == (1, 2, 4, 64), f"bad view shape {kk.shape}"
assert cache.seq_len == 0, "update() must not advance seq_len"
cache.advance(4)
assert len(cache) == 4
# One decode step
k1 = torch.randn(1, 2, 1, 64)
v1 = torch.randn(1, 2, 1, 64)
kk, vv = cache.update(0, k1, v1)
assert kk.shape == (1, 2, 5, 64), f"bad decode view {kk.shape}"
assert torch.equal(kk[:, :, :4], k), "prefill K was corrupted"
assert torch.equal(kk[:, :, 4:], k1), "decode K not written"
cache.advance(1)
print(" writes and views: OK")
# Guards
for bad, exc, label in [
(lambda: cache.update(0, torch.randn(1, 2, 99, 64),
torch.randn(1, 2, 99, 64)), ValueError, "overflow"),
(lambda: cache.update(0, torch.randn(1, 2, 1, 64).half(),
torch.randn(1, 2, 1, 64).half()), TypeError, "dtype"),
(lambda: cache.update(0, torch.randn(3, 2, 1, 64),
torch.randn(3, 2, 1, 64)), ValueError, "batch"),
]:
try:
bad()
raise AssertionError(f"{label} guard did not fire")
except exc:
pass
print(" guards: OK")
cache.reset()
assert len(cache) == 0
print(" reset: OK")
print("\nAll kv_cache tests PASSED.")17 unmodified lines1819202122236 unmodified lines3031323334353640 unmodified lines7778798081826 unmodified lines899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315441 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721817 unmodified linesfrom model.config import PyCraftConfig, get_config_120m, get_config_tinyfrom model.attention import RMSNormfrom model.transformer import TransformerBlockclass PyCraftModel(nn.Module):6 unmodified lines# Stack of transformer blocksself.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])# Final layer norm before output projection40 unmodified linesinput_ids: torch.Tensor, # (batch, seq_len)# (batch, seq_len) for trainingtargets: torch.Tensor | None = None,) -> tuple[torch.Tensor, torch.Tensor | None]:"""Args:6 unmodified lineslogits: (batch, seq_len, vocab_size)loss: scalar cross-entropy loss, or None if targets not given"""# 1. Embed tokensx = self.token_embedding(input_ids) # (batch, seq_len, d_model)# 2. Pass through transformer blocksfor block in self.blocks:x = block(x)# 3. Final normx = self.norm_final(x)# 4. Project to vocabulary logitslogits = self.lm_head(x) # (batch, seq_len, vocab_size)# 5. Compute loss if targets providedloss = Noneif targets is not None:# Flatten for cross-entropy:# logits: (batch * seq_len, vocab_size)# targets: (batch * seq_len,)loss = F.cross_entropy(logits.view(-1, self.config.vocab_size),targets.view(-1),ignore_index=-1, # -1 = padding token (masked from loss))return logits, loss@torch.no_grad()def generate(self,input_ids: torch.Tensor, # (1, prompt_len) — single sequence onlymax_new_tokens: int = 128,temperature: float = 0.8,top_k: int = 50,) -> torch.Tensor:"""Simple greedy / top-k generation for testing.Not for production — use a proper sampler later."""self.eval()for _ in range(max_new_tokens):# Crop context to max_seq_lencontext = input_ids[:, -self.config.max_seq_len:]logits, _ = self(context)# Take logits at last positionnext_logits = logits[:, -1, :] / temperature # (1, vocab_size)# Top-k filteringif top_k > 0:top_vals, _ = torch.topk(next_logits, top_k)threshold = top_vals[:, -1].unsqueeze(-1)next_logits = next_logits.masked_fill(next_logits < threshold, float('-inf'))probs = torch.softmax(next_logits, dim=-1)next_token = torch.multinomial(probs, num_samples=1) # (1, 1)input_ids = torch.cat([input_ids, next_token], dim=1)return input_idsdef param_count(self) -> dict:total = sum(p.numel() for p in self.parameters())41 unmodified linescounts = model.param_count()print(f" Params: {counts['total'] / 1e6:.2f}M total")# Memory checktorch.cuda.empty_cache()mem_before = torch.cuda.memory_allocated() / 1e6ids_full = torch.randint(0, cfg.vocab_size, (1, 256), device=device)tgt_full = torch.randint(0, cfg.vocab_size, (1, 256), device=device)logits_full, loss_full = model(ids_full, tgt_full)loss_full.backward()mem_after = torch.cuda.memory_allocated() / 1e6print(f" GPU memory used: {mem_after:.1f} MB")print(f" Loss: {loss_full.item():.4f}")print(f" Logits shape: {tuple(logits_full.shape)}")print("\n[3] Testing generation...")model.eval()torch.cuda.empty_cache()prompt = torch.randint(0, cfg.vocab_size, (1, 10), device=device)generated = model.generate(prompt, max_new_tokens=20, temperature=1.0, top_k=50)17 unmodified lines18192021222324256 unmodified lines323334353637383940 unmodified lines808182838485868788896 unmodified lines9697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730841 unmodified lines35035135235335435535635735835936036136236336436536636736836937037137237337437517 unmodified linesfrom model.config import PyCraftConfig, get_config_120m, get_config_tinyfrom model.attention import RMSNormfrom model.transformer import TransformerBlockfrom model.kv_cache import KVCache, build_attn_maskfrom model.sampling import sample_next_tokenclass PyCraftModel(nn.Module):6 unmodified lines# Stack of transformer blocksself.blocks = nn.ModuleList([TransformerBlock(config, layer_idx=i)for i in range(config.n_layers)])# Final layer norm before output projection40 unmodified linesinput_ids: torch.Tensor, # (batch, seq_len)# (batch, seq_len) for trainingtargets: torch.Tensor | None = None,past_key_values=None, # KVCache for incremental decodinguse_cache: bool | None = None, # None = auto (on iff a cache given)num_logits_to_keep: int = 0, # 0 = all positionsignore_index: int = -100, # label value excluded from loss) -> tuple[torch.Tensor, torch.Tensor | None]:"""Args:6 unmodified lineslogits: (batch, seq_len, vocab_size)loss: scalar cross-entropy loss, or None if targets not given"""batch, seq_len = input_ids.shapeusing_cache = ((past_key_values is not None)if use_cache is None else use_cache)if using_cache and past_key_values is None:raise ValueError("use_cache=True requires past_key_values; build one with ""KVCache.from_model(model, batch_size=...)")offset = past_key_values.seq_len if using_cache else 0if offset + seq_len > self.config.max_seq_len:raise ValueError(f"sequence {offset} + {seq_len} exceeds max_seq_len="f"{self.config.max_seq_len} (the RoPE tables end there)")# 1. Embed tokensx = self.token_embedding(input_ids) # (batch, seq_len, d_model)# 2. Build the causal mask ONCE and share it across all blocks.# Returns None on the two fast paths (offset 0, or single-token# decode) where SDPA needs no explicit mask.attn_mask = build_attn_mask(seq_len, offset, x.device)# 3. Pass through transformer blocksfor block in self.blocks:x = block(x, attn_mask=attn_mask,kv_cache=past_key_values if using_cache else None,position_offset=offset)# 4. Advance the cache exactly once, after every layer has written.if using_cache:past_key_values.advance(seq_len)# 5. Final normx = self.norm_final(x)# 6. Trim before the output projection when only the last positions# are wanted. lm_head is 16.4M of 55.3M params, so prefilling a# 200-token prompt otherwise computes 200x32000 logits for one row.if num_logits_to_keep > 0:if targets is not None:raise ValueError("num_logits_to_keep cannot be combined with targets")x = x[:, -num_logits_to_keep:, :]# 7. Project to vocabulary logitslogits = self.lm_head(x) # (batch, seq_len, vocab_size)# 8. Compute loss if targets providedloss = Noneif targets is not None:# Flatten for cross-entropy:# logits: (batch * seq_len, vocab_size)# targets: (batch * seq_len,)loss = F.cross_entropy(logits.view(-1, logits.size(-1)),targets.view(-1),ignore_index=ignore_index,)return logits, lossdef _prepare_prompt(self, input_ids: torch.Tensor, max_new_tokens: int):"""Clamp the prompt to the context window and work out how many tokensmay still be generated. Deterministic and idempotent, so stream() andgenerate() can both call it and agree."""batch, prompt_len = input_ids.shapeif batch != 1:raise NotImplementedError("batched generation needs left padding plus a key-padding ""mask; see build_attn_mask() in model/kv_cache.py")max_len = self.config.max_seq_lenif prompt_len >= max_len:# Truncate once, up front — not once per step.input_ids = input_ids[:, -(max_len - 1):]prompt_len = input_ids.shape[1]return input_ids, min(max_new_tokens, max_len - prompt_len)@torch.no_grad()def stream(self,input_ids: torch.Tensor, # (1, prompt_len) — single sequence onlymax_new_tokens: int = 128,temperature: float = 0.8,top_k: int = 50,top_p: float = 1.0,repetition_penalty: float = 1.0,eos_token_id: int | list[int] | None = 0, # 0 = <|endoftext|>stop_strings: list[str] | None = None,tokenizer=None, # required only when stop_strings is givenuse_cache: bool = True,past_key_values=None, # reuse an existing KVCache (it is reset)seed: int | None = None,):"""Yield generated token ids one at a time.This is the single decode implementation — generate() is a thinwrapper that collects what this yields. Incremental consumers (an SSEendpoint, a live terminal) can consume it directly.The prompt is processed in one prefill pass, then each new token costsa single-position forward instead of re-running the whole sequence.The context limit is a HARD STOP, not a sliding window: the cacheholds post-RoPE keys, so positions cannot be re-based withoutre-rotating every cached key. The uncached path (use_cache=False)keeps the old crop behaviour and exists as a reference for tests."""was_training = self.training # must not leave eval() set behindself.eval()try:device = input_ids.deviceif stop_strings and tokenizer is None:raise ValueError("stop_strings requires tokenizer=")input_ids, budget = self._prepare_prompt(input_ids, max_new_tokens)prompt_len = input_ids.shape[1]max_len = self.config.max_seq_leneos_ids = ([] if eos_token_id is Noneelse [eos_token_id] if isinstance(eos_token_id, int)else list(eos_token_id))generator = Noneif seed is not None:generator = torch.Generator(device=device)generator.manual_seed(seed)cache = Noneif use_cache:cache = past_key_values or KVCache.from_model(self, batch_size=1,max_len=prompt_len + budget,device=device,dtype=self.token_embedding.weight.dtype,)cache.reset()# ---- prefill: one pass over the whole prompt ----logits, _ = self(input_ids, past_key_values=cache,use_cache=use_cache, num_logits_to_keep=1)next_logits = logits[:, -1, :] # (1, vocab_size)out = input_idsnew_ids: list[int] = []for _ in range(budget):next_token = sample_next_token(next_logits, out, temperature, top_k, top_p,repetition_penalty, generator=generator,) # (1, 1)token = int(next_token.item())out = torch.cat([out, next_token], dim=1)new_ids.append(token)yield tokenif token in eos_ids:returnif stop_strings:# Decode the whole generated span, not the newest token:# byte-level BPE can render a suffix differently than the# full sequence. A stop string may still land mid-token,# so callers wanting exact truncation should cut the text.text = tokenizer.decode(new_ids, skip_special_tokens=False)if any(stop in text for stop in stop_strings):returnif len(new_ids) >= budget:returnstep_input = next_token if use_cache else out[:, -max_len:]logits, _ = self(step_input, past_key_values=cache,use_cache=use_cache, num_logits_to_keep=1)next_logits = logits[:, -1, :]finally:self.train(was_training)@torch.no_grad()def generate(self,input_ids: torch.Tensor, # (1, prompt_len) — single sequence onlymax_new_tokens: int = 128,temperature: float = 0.8,top_k: int = 50,**kwargs, # see stream() for the full set) -> torch.Tensor:"""Autoregressive generation with a KV cache.Returns (1, prompt_len + n_new) — the prompt plus what was generated,so callers can still slice with out[0, len(prompt_ids):]."""prepared, _ = self._prepare_prompt(input_ids, max_new_tokens)new_ids = list(self.stream(input_ids, max_new_tokens=max_new_tokens,temperature=temperature, top_k=top_k, **kwargs))if not new_ids:return preparedtail = torch.tensor([new_ids], dtype=prepared.dtype,device=prepared.device)return torch.cat([prepared, tail], dim=1)def param_count(self) -> dict:total = sum(p.numel() for p in self.parameters())41 unmodified linescounts = model.param_count()print(f" Params: {counts['total'] / 1e6:.2f}M total")# Memory check (CUDA only)if device == "cuda":torch.cuda.empty_cache()mem_before = torch.cuda.memory_allocated() / 1e6ids_full = torch.randint(0, cfg.vocab_size, (1, 256), device=device)tgt_full = torch.randint(0, cfg.vocab_size, (1, 256), device=device)logits_full, loss_full = model(ids_full, tgt_full)loss_full.backward()if device == "cuda":mem_after = torch.cuda.memory_allocated() / 1e6print(f" GPU memory used: {mem_after:.1f} MB")print(f" Loss: {loss_full.item():.4f}")print(f" Logits shape: {tuple(logits_full.shape)}")print("\n[3] Testing generation...")model.eval()if device == "cuda":torch.cuda.empty_cache()prompt = torch.randint(0, cfg.vocab_size, (1, 10), device=device)generated = model.generate(prompt, max_new_tokens=20, temperature=1.0, top_k=50)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# model/sampling.py
#
# Token sampling for PyCraft-1 generation.
#
# Kept in its own module so the cached and uncached decode paths provably
# share one RNG consumption pattern — that is what makes the cached-vs-
# uncached equivalence test meaningful. If the two paths drew randomness
# differently, an equivalence failure could not distinguish a cache bug from
# a sampling bug.
#
# Filter order is deliberate and matches HuggingFace:
#
# repetition penalty (on raw logits)
# -> temperature
# -> top-k
# -> top-p
# -> softmax
# -> multinomial
#
# Applying the penalty after temperature would change its effective strength;
# applying top-p before top-k would change the candidate set it sees.
import torch
# ------------------------------------------------------------------ #
# Individual filters
# ------------------------------------------------------------------ #
def apply_repetition_penalty(
logits: torch.Tensor, # (batch, vocab)
prev_ids: torch.Tensor, # (batch, n_prev)
penalty: float,
) -> torch.Tensor:
"""
Discourage tokens that have already appeared (CTRL / HuggingFace formula).
Positive logits are divided by the penalty and negative ones multiplied,
so both move toward -inf regardless of sign.
"""
if penalty == 1.0:
return logits
score = torch.gather(logits, 1, prev_ids)
score = torch.where(score < 0, score * penalty, score / penalty)
return logits.scatter(1, prev_ids, score)
def top_k_filter(logits: torch.Tensor, k: int | None) -> torch.Tensor:
"""Keep only the k highest-scoring tokens. k<=0 or k>=vocab disables it."""
if k is None or k <= 0 or k >= logits.size(-1):
return logits
kth = torch.topk(logits, k, dim=-1).values[..., -1, None]
return logits.masked_fill(logits < kth, float("-inf"))
def top_p_filter(logits: torch.Tensor, p: float | None) -> torch.Tensor:
"""
Nucleus sampling: keep the smallest set of tokens whose cumulative
probability reaches p. p>=1.0 disables it (and skips a 32k-element sort).
"""
if p is None or p >= 1.0:
return logits
srt, idx = torch.sort(logits, descending=True, dim=-1)
probs = srt.softmax(dim=-1)
# Subtracting probs shifts the cumulative sum one position right, which
# guarantees the top token is always kept even if it alone exceeds p.
remove = (probs.cumsum(dim=-1) - probs) > p
srt = srt.masked_fill(remove, float("-inf"))
return torch.full_like(logits, float("-inf")).scatter(-1, idx, srt)
# ------------------------------------------------------------------ #
# Combined sampler
# ------------------------------------------------------------------ #
def sample_next_token(
logits: torch.Tensor, # (batch, vocab) raw scores
prev_ids: torch.Tensor, # (batch, n_prev) tokens so far
temperature: float = 0.8, # <= 0.0 selects greedy decoding
top_k: int | None = 50,
top_p: float | None = 1.0,
repetition_penalty: float = 1.0,
generator: torch.Generator | None = None,
) -> torch.Tensor: # (batch, 1) int64
"""Pick the next token. temperature <= 0.0 means deterministic argmax."""
logits = apply_repetition_penalty(
logits.float(), prev_ids, repetition_penalty)
# Greedy. Handled before the division so temperature=0.0 cannot produce
# inf/NaN — the old code divided unconditionally and made greedy decoding
# impossible.
if temperature is None or temperature <= 0.0:
return logits.argmax(dim=-1, keepdim=True)
logits = logits / temperature
logits = top_k_filter(logits, top_k)
logits = top_p_filter(logits, top_p)
probs = torch.softmax(logits, dim=-1)
return torch.multinomial(probs, num_samples=1, generator=generator)
# ------------------------------------------------------------------ #
# Quick self-test
# ------------------------------------------------------------------ #
if __name__ == "__main__":
torch.manual_seed(0)
V = 100
logits = torch.randn(1, V)
prev = torch.tensor([[3, 7, 7]])
# Greedy is deterministic and matches a plain argmax
want = int(logits.argmax())
for temp in (0.0, -1.0, None):
got = sample_next_token(logits, prev, temperature=temp,
repetition_penalty=1.0)
assert int(got) == want, f"greedy failed at temperature={temp}"
print(" greedy decoding: OK")
# top-k restricts the support to exactly k tokens
filtered = top_k_filter(logits.clone(), 5)
assert int(torch.isfinite(filtered).sum()) == 5
assert torch.equal(top_k_filter(logits.clone(), 0), logits), "k=0 disables"
print(" top_k_filter: OK")
# top-p keeps at least one token and never more than the full vocab
for p in (0.01, 0.5, 0.9):
n = int(torch.isfinite(top_p_filter(logits.clone(), p)).sum())
assert 1 <= n <= V, f"top_p={p} kept {n} tokens"
assert torch.equal(top_p_filter(logits.clone(), 1.0), logits), "p=1 disables"
print(" top_p_filter: OK")
# Repetition penalty pushes seen tokens down, leaves others untouched
pen = apply_repetition_penalty(logits.clone(), prev, 2.0)
for t in (3, 7):
assert pen[0, t] < logits[0, t], f"token {t} not penalised"
untouched = [i for i in range(V) if i not in (3, 7)]
assert torch.equal(pen[0, untouched], logits[0, untouched])
print(" repetition_penalty: OK")
# A seeded generator reproduces the same draw
a = sample_next_token(logits, prev, 0.8, 50, 1.0, 1.0,
generator=torch.Generator().manual_seed(42))
b = sample_next_token(logits, prev, 0.8, 50, 1.0, 1.0,
generator=torch.Generator().manual_seed(42))
assert torch.equal(a, b), "seeded sampling is not reproducible"
print(" seeded reproducibility: OK")
print("\nAll sampling tests PASSED.")16 unmodified lines17181920212223242526273 unmodified lines31323334353637383916 unmodified linesclass TransformerBlock(nn.Module):def __init__(self, config: PyCraftConfig):super().__init__()# Pre-norm for attention sublayerself.norm1 = RMSNorm(config.d_model)self.attn = GroupedQueryAttention(config)# Pre-norm for FFN sublayerself.norm2 = RMSNorm(config.d_model)3 unmodified linesself,x: torch.Tensor, # (batch, seq_len, d_model)attn_mask: torch.Tensor | None = None,) -> torch.Tensor:# Attention sublayer with residualx = x + self.attn(self.norm1(x), attn_mask)# FFN sublayer with residualx = x + self.ffn(self.norm2(x))return x16 unmodified lines17181920212223242526273 unmodified lines3132333435363738394041424316 unmodified linesclass TransformerBlock(nn.Module):def __init__(self, config: PyCraftConfig, layer_idx: int = 0):super().__init__()# Pre-norm for attention sublayerself.norm1 = RMSNorm(config.d_model)self.attn = GroupedQueryAttention(config, layer_idx=layer_idx)# Pre-norm for FFN sublayerself.norm2 = RMSNorm(config.d_model)3 unmodified linesself,x: torch.Tensor, # (batch, seq_len, d_model)attn_mask: torch.Tensor | None = None,kv_cache=None, # KVCache, or None to disableposition_offset: int = 0, # cached positions before this call) -> torch.Tensor:# Attention sublayer with residualx = x + self.attn(self.norm1(x), attn_mask,kv_cache=kv_cache,position_offset=position_offset)# FFN sublayer with residualx = x + self.ffn(self.norm2(x))return x
12345torch>=2.3.0safetensors>=0.4.0tokenizers>=0.19.0datasets>=2.20.0huggingface_hub>=0.24.012345# torch 2.1 is the real floor: the only 2.3-specific API (a pinned SDPA# backend, which also broke CPU inference) has been removed.torch>=2.1safetensors>=0.4.0tokenizers>=0.19.0
README.md+218-146
config.json+41-31
model/attention.py+61-24
model/kv_cache.pyAdded+274
model/pycraft_model.py+193-36
model/sampling.pyAdded+146
model/transformer.py+7-3
requirements.txt+5-5