Text Generation
Transformers
Safetensors
English
gpt-s2.5
tiny
tiny-lm
tiny-model
slm
small-language-model
from-scratch
gpt
gqa
swiglu
rope
rmsnorm
cpu-trained
Run this model with HF Jobs
Run Compactbot/compacttest-5m on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/Compactbot/compacttest-5m. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Compactbot/compacttest-5m on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/Compactbot/compacttest-5m. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/Compactbot/compacttest-5m. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use Compactbot/compacttest-5m with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Compactbot/compacttest-5m with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Compactbot/compacttest-5m")# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Compactbot/compacttest-5m", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Compactbot/compacttest-5m with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Compactbot/compacttest-5m" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Compactbot/compacttest-5m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Compactbot/compacttest-5m
- SGLang
How to use Compactbot/compacttest-5m with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Compactbot/compacttest-5m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Compactbot/compacttest-5m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Compactbot/compacttest-5m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Compactbot/compacttest-5m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Compactbot/compacttest-5m with Docker Model Runner:
docker model run hf.co/Compactbot/compacttest-5m
Commit ·
9014085
1
Parent(s): 412797e
Add tokenizer_config.json, model.py, .gitattributes and README (renamed copy of gpt-s2.5-5m) (#5)
Browse files- Add tokenizer_config.json, model.py, .gitattributes and README (renamed copy of gpt-s2.5-5m) (5f887f58204606d8b75b7ec31aa10be11510f5de)
Files changed (3)
- README.mdAdded+85
- model.pyAdded+153
- tokenizer_config.jsonAdded+7
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485---license: apache-2.0pipeline_tag: text-generationlanguage: entags: - tiny - tiny-lm - tiny-model - slm - small-language-model - from-scratch - gpt - gqa - swiglu - rope - rmsnorm - cpu-trainedlibrary_name: transformersmetrics: - accuracymodel-index: - name: HellaSwag type: text-generation results: []---
# compacttest-5m
**5.11M-parameter subword language model, trained from scratch on CPU.**
> This repo is a **renamed copy** of [`Compactbot/gpt-s2.5-5m`](https://huggingface.co/Compactbot/gpt-s2.5-5m),> renamed at the request of @Datdanboi25 (see `Compactbot/model-requests` #2).> Weights, config and architecture are **identical** to the original.
## What it is
A small but genuine from-scratch causal LM in the GPT-X2.5 style:
- **Architecture:** GQA (8 query / 2 key-value heads) + SwiGLU FFN + RoPE + RMSNorm, pre-norm, no biases, **weight-tied** input/output embeddings (the embedding matrix doubles as the LM head — no separate `lm_head` tensor).- **Params:** 5,114,112 (verified against the checkpoint).- **Tokenizer:** 8,192-vocab byte-level BPE (custom, not a standard HF tokenizer).- **Trained:** on CPU, ~94M TinyStories tokens, cosine LR schedule with warmup.
## How to load
This is a self-contained `nn.Module`, not a transformers-native architecture.
```pythonimport torchfrom model import Model
m = Model()from safetensors.torch import load_filesd = load_file("model.safetensors")m.load_state_dict(sd)m.eval()
# greedy generationwith torch.no_grad(): x = torch.tensor([[1]]) for _ in range(60): logits = m(x[:, -512:])[:, -1, :] x = torch.cat([x, logits.argmax(-1, keepdim=True)], dim=1)```
## Honest scope
- **Greedy-coherent, sampling-fragile.** At 5M params the model produces readable prose under greedy decoding but degrades noticeably under sampling. That is the expected behaviour at this scale, not a bug.- **Intelligence index:** 0.032 (see the original card for the full eval breakdown).- It is a reference build demonstrating that a 5M-param from-scratch subword LM is trainable and coherent on CPU. It is not a chat model.
## Files
| File | Purpose ||---|---|| `config.json` | Architecture config (matches `model.py` exactly) || `model.py` | Self-contained architecture definition || `model.safetensors` | Weights (5,114,112 params, F32) || `tokenizer.json` | 8192-vocab BPE tokenizer || `tokenizer_config.json` | Tokenizer metadata |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""GPT-S2.5 — 5.11M-param subword language model (from scratch).Custom GPT-2-style architecture: GQA + SwiGLU + RoPE + RMSNorm, weight-tied head.
This is NOT a transformers-native architecture. It is a self-containednn.Module you can load directly:
import torch from model import Model m = Model() sd = torch.load("best.pt", map_location="cpu")["model"] # or load safetensors m.load_state_dict(sd); m.eval()
# generate (greedy): with torch.no_grad(): x = torch.tensor([[1]]) for _ in range(60): logits = m(x[:, -512:])[:, -1, :] x = torch.cat([x, logits.argmax(-1, keepdim=True)], dim=1)
Architecture (matches config.json exactly): vocab 8192 (BPE), n_embd 256, 4 layers, 8 q-heads / 2 kv-heads (GQA 4:1), head_dim 32, SwiGLU FFN intermediate 768, RoPE (base 10000), RMSNorm (eps 1e-6), pre-norm, no biases, weight-tied head (tok.weight reused as lm_head). Total: 5,114,112 parameters."""import mathimport torchimport torch.nn as nnimport torch.nn.functional as F
VOCAB = 8192N_EMBD = 256N_LAYERS = 4N_Q_HEADS = 8N_KV_HEADS = 2HEAD_DIM = 32INTER = 768MAX_SEQ = 512ROPE_BASE = 10000.0
Q_DIM = N_Q_HEADS * HEAD_DIM # 256KV_DIM = N_KV_HEADS * HEAD_DIM # 64assert Q_DIM == N_EMBDassert N_Q_HEADS % N_KV_HEADS == 0
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
def precompute_rope(head_dim, max_seq, base): freqs = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim)) t = torch.arange(max_seq, dtype=torch.float) ang = torch.outer(t, freqs) return ang.cos(), ang.sin() # [T, head_dim/2]
def apply_rope(x, cos, sin): # x: [B, H, T, D] T = x.size(2) cos = cos[:T].view(1, 1, T, -1) sin = sin[:T].view(1, 1, T, -1) x1, x2 = x[..., 0::2], x[..., 1::2] out = torch.empty_like(x) out[..., 0::2] = x1 * cos - x2 * sin out[..., 1::2] = x2 * cos + x1 * sin return out
class Attention(nn.Module): def __init__(self): super().__init__() self.wq = nn.Linear(N_EMBD, Q_DIM, bias=False) self.wk = nn.Linear(N_EMBD, KV_DIM, bias=False) self.wv = nn.Linear(N_EMBD, KV_DIM, bias=False) self.wo = nn.Linear(Q_DIM, N_EMBD, bias=False)
def forward(self, x, cos, sin): B, T, _ = x.shape q = self.wq(x).view(B, T, N_Q_HEADS, HEAD_DIM).transpose(1, 2) k = self.wk(x).view(B, T, N_KV_HEADS, HEAD_DIM).transpose(1, 2) v = self.wv(x).view(B, T, N_KV_HEADS, HEAD_DIM).transpose(1, 2) q = apply_rope(q, cos, sin) k = apply_rope(k, cos, sin) # GQA: repeat kv heads to match q heads rep = N_Q_HEADS // N_KV_HEADS k = k.repeat_interleave(rep, dim=1) v = v.repeat_interleave(rep, dim=1) y = F.scaled_dot_product_attention(q, k, v, is_causal=True) y = y.transpose(1, 2).contiguous().view(B, T, Q_DIM) return self.wo(y)
class MLP(nn.Module): def __init__(self): super().__init__() self.wgate = nn.Linear(N_EMBD, INTER, bias=False) self.wup = nn.Linear(N_EMBD, INTER, bias=False) self.wdown = nn.Linear(INTER, N_EMBD, bias=False)
def forward(self, x): return self.wdown(F.silu(self.wgate(x)) * self.wup(x))
class Block(nn.Module): def __init__(self): super().__init__() self.ln1 = RMSNorm(N_EMBD) self.attn = Attention() self.ln2 = RMSNorm(N_EMBD) self.mlp = MLP()
def forward(self, x, cos, sin): x = x + self.attn(self.ln1(x), cos, sin) x = x + self.mlp(self.ln2(x)) return x
class Model(nn.Module): def __init__(self): super().__init__() self.tok = nn.Embedding(VOCAB, N_EMBD) self.blocks = nn.ModuleList([Block() for _ in range(N_LAYERS)]) self.ln_f = RMSNorm(N_EMBD) self.cos, self.sin = precompute_rope(HEAD_DIM, MAX_SEQ, ROPE_BASE)
def forward(self, idx, targets=None): B, T = idx.shape h = self.tok(idx) cos, sin = self.cos, self.sin for blk in self.blocks: h = blk(h, cos, sin) h = self.ln_f(h) logits = F.linear(h, self.tok.weight) # weight-tied head if targets is not None: loss = F.cross_entropy(logits.view(-1, VOCAB), targets.view(-1)) return loss return logits
if __name__ == "__main__": m = Model() total = sum(p.numel() for p in m.parameters()) print(f"params = {total} (expected 5114112)") assert total == 5114112, "param count mismatch" print("OK")1234567{ "tokenizer_class": "GPTS25BPE", "model_type": "gpt-s2.5", "vocab_size": 8192, "add_prefix_space": false, "note": "8192-vocab BPE (byte-level). This is a custom BPE, not a standard HF tokenizer; load bpe_8k.json / tokenizer.json directly."}README.mdAdded+85
model.pyAdded+153
tokenizer_config.jsonAdded+7