Devdan Schretlen Claude Opus 4.8 commited on
Commit
8b12a0a
·
1 Parent(s): 02ec25d

Add MicroGPT chat demo: FastAPI + React app, Dockerfile, gpt3.1 model

Browse files

Brings the GPTs chatbot into the Space: server/ (FastAPI SSE backend),
models/, common.py, and the prebuilt web/dist frontend, served on a single
origin via Docker (CPU PyTorch, uvicorn on port 7860).

The gpt3.1_chat.pth checkpoint is stored in bf16 (~0.6 GB) via Git LFS so it
fits the free Space's 1 GB storage limit; it is upcast to fp32 at load time
for CPU inference.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

.dockerignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Keep the build context small and the image clean.
2
+ .git
3
+ .gitattributes
4
+ **/__pycache__
5
+ *.pyc
6
+ *.pyo
7
+ .venv
8
+ .venv-1
9
+ .understand-anything
10
+ .claude
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Python caches and virtual environments — never the model weights (*.pth go to LFS).
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ .venv/
6
+ .venv-1/
Dockerfile ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MicroGPT chat demo for Hugging Face Spaces (Docker SDK).
2
+ # A FastAPI backend serves the fine-tuned GPT-3-style model and the prebuilt
3
+ # React frontend (web/dist) on a single origin.
4
+ FROM python:3.12-slim
5
+
6
+ # Run as the non-root "user" account Hugging Face Spaces expects (uid 1000).
7
+ RUN useradd -m -u 1000 user
8
+ USER user
9
+ ENV HOME=/home/user \
10
+ PATH=/home/user/.local/bin:$PATH \
11
+ PYTHONUNBUFFERED=1 \
12
+ TIKTOKEN_CACHE_DIR=/home/user/.cache/tiktoken
13
+
14
+ # Keep the app under the user's home so it owns the directory tree.
15
+ WORKDIR /home/user/app
16
+
17
+ # Install dependencies first so this layer caches across code/model changes.
18
+ # torch comes from the CPU-only wheel index (matches the locally tested build).
19
+ COPY --chown=user:user requirements.txt ./
20
+ RUN pip install --user --no-cache-dir --upgrade pip \
21
+ && pip install --user --no-cache-dir torch==2.12.0 --index-url https://download.pytorch.org/whl/cpu \
22
+ && pip install --user --no-cache-dir -r requirements.txt
23
+
24
+ # Copy the application: model weights, server/, models/, common.py, web/dist/.
25
+ COPY --chown=user:user . .
26
+
27
+ # Bake the GPT-2 BPE vocab into the image so the first request needs no network.
28
+ RUN mkdir -p "$TIKTOKEN_CACHE_DIR" \
29
+ && python -c "import tiktoken; tiktoken.get_encoding('gpt2')"
30
+
31
+ # Hugging Face Spaces routes external traffic to port 7860.
32
+ EXPOSE 7860
33
+ CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -4,7 +4,30 @@ emoji: 📈
4
  colorFrom: purple
5
  colorTo: purple
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  colorFrom: purple
5
  colorTo: purple
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # MicroGPT chat
12
+
13
+ A live demo of a ~254M-parameter, GPT-3-style language model trained from
14
+ scratch in PyTorch and fine-tuned into a chat model. A FastAPI backend streams
15
+ the assistant's reply token-by-token over Server-Sent Events, and a prebuilt
16
+ React frontend renders the conversation — all served on a single origin.
17
+
18
+ The model (`gpt3.1_chat.pth`) runs on **CPU**, so replies are generated slowly:
19
+ allow a few moments per message, and use the settings bar to lower *max new
20
+ tokens* for snappier (shorter) answers.
21
+
22
+ ## How it works
23
+
24
+ - `server/` — FastAPI app (`/api/chat` SSE stream, `/api/models`) that loads the
25
+ `*_chat.pth` checkpoint and serves the built frontend.
26
+ - `models/` — GPT-3-style model definition and the chat tokenizer.
27
+ - `web/dist/` — prebuilt React + Vite single-page chat UI.
28
+ - `Dockerfile` — installs CPU PyTorch + deps and launches uvicorn on port 7860.
29
+
30
+ It's a small model, so expect modest, sometimes quirky answers — that's the fun
31
+ of chatting with something trained end-to-end on a single GPU's worth of data.
32
+
33
+ Configuration reference: https://huggingface.co/docs/hub/spaces-config-reference
common.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared helpers for the entry-point scripts (train.py, sample.py,
3
+ sample_chat.py, eval_hellaswag.py) and the web backend.
4
+
5
+ Holds the two bits of glue every runnable script needs -- mapping an
6
+ architecture name to a fresh model, and picking the best available device --
7
+ so the logic lives in exactly one place instead of being copied per script.
8
+ """
9
+
10
+ import torch
11
+
12
+ from models import GPT, GPT3, GPTConfig, GPT3Config
13
+
14
+
15
+ def build_model(arch):
16
+ """Instantiate a fresh model for the given architecture name."""
17
+ if arch == "gpt2":
18
+ return GPT(GPTConfig())
19
+ if arch == "gpt3":
20
+ return GPT3(GPT3Config())
21
+ raise ValueError(f"unknown arch: {arch}")
22
+
23
+
24
+ def get_device():
25
+ """Pick the best available device: cuda > mps > cpu."""
26
+ if torch.cuda.is_available():
27
+ return "cuda"
28
+ if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
29
+ return "mps"
30
+ return "cpu"
gpt3.1_chat.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6eb745bbad058a69d89f1808c36307e673edf172439f364e7649faef74354851
3
+ size 611977592
models/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model architectures and the chat tokenizer.
3
+
4
+ Re-exports the public surface so callers can write `from models import GPT,
5
+ GPT3, get_encoding, ...` without reaching into the individual submodules:
6
+
7
+ * gpt2.py -- GPT-2 (124M): GPT / GPTConfig
8
+ * gpt3.py -- GPT-3-style (254M): GPT3 / GPT3Config
9
+ * tokenizer.py -- GPT-2 tiktoken encoding extended with chat special tokens
10
+ """
11
+
12
+ from .gpt2 import GPT, GPTConfig
13
+ from .gpt3 import GPT3, GPT3Config
14
+ from .tokenizer import SPECIAL_TOKENS, get_encoding
15
+
16
+ __all__ = [
17
+ "GPT",
18
+ "GPTConfig",
19
+ "GPT3",
20
+ "GPT3Config",
21
+ "SPECIAL_TOKENS",
22
+ "get_encoding",
23
+ ]
models/gpt2.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GPT-2 model definition.
3
+
4
+ Holds everything specific to the GPT-2 architecture: the transformer blocks,
5
+ the config, and the GPT module. The driver scripts (train.py, sample.py) import
6
+ the model from here. To train/sample a different architecture of similar design,
7
+ write another module like this one exposing a comparable GPT/GPTConfig and point
8
+ the scripts at it.
9
+ """
10
+
11
+ import inspect
12
+ from dataclasses import dataclass
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ from torch.nn import functional as F
17
+ from torch.nn.functional import scaled_dot_product_attention
18
+
19
+ # -----------------------------------------------------------------------------
20
+
21
+
22
+ class CausalSelfAttention(nn.Module):
23
+ """Multi-head causal self-attention using PyTorch's fused SDPA kernel."""
24
+
25
+ def __init__(self, config):
26
+ super().__init__()
27
+ assert config.n_embd % config.n_head == 0
28
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
29
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
30
+ self.c_proj.NANOGPT_SCALE_INIT = 1
31
+ self.n_head = config.n_head
32
+ self.n_embd = config.n_embd
33
+ # named 'bias' to match OpenAI/HF weight naming conventions
34
+ self.register_buffer(
35
+ "bias",
36
+ torch.tril(torch.ones(config.block_size, config.block_size))
37
+ .view(1, 1, config.block_size, config.block_size),
38
+ )
39
+
40
+ def forward(self, x):
41
+ B, T, C = x.size() # batch, sequence length, embedding dim
42
+ # nh = number of heads, hs = head size; C = nh * hs (e.g. 12 * 64 = 768)
43
+ qkv = self.c_attn(x)
44
+ q, k, v = qkv.split(self.n_embd, dim=2)
45
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
46
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
47
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
48
+ y = scaled_dot_product_attention(q, k, v, is_causal=True)
49
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
50
+ y = self.c_proj(y)
51
+ return y
52
+
53
+
54
+ class MLP(nn.Module):
55
+ """Position-wise feed-forward network with GELU activation."""
56
+
57
+ def __init__(self, config):
58
+ super().__init__()
59
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
60
+ self.gelu = nn.GELU(approximate='tanh')
61
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
62
+ self.c_proj.NANOGPT_SCALE_INIT = 1
63
+
64
+ def forward(self, x):
65
+ x = self.c_fc(x)
66
+ x = self.gelu(x)
67
+ x = self.c_proj(x)
68
+ return x
69
+
70
+
71
+ class Block(nn.Module):
72
+ """Single transformer block: pre-norm causal attention then pre-norm MLP."""
73
+
74
+ def __init__(self, config):
75
+ super().__init__()
76
+ self.ln_1 = nn.LayerNorm(config.n_embd)
77
+ self.attn = CausalSelfAttention(config)
78
+ self.ln_2 = nn.LayerNorm(config.n_embd)
79
+ self.mlp = MLP(config)
80
+
81
+ def forward(self, x):
82
+ x = x + self.attn(self.ln_1(x))
83
+ x = x + self.mlp(self.ln_2(x))
84
+ return x
85
+
86
+
87
+ @dataclass
88
+ class GPTConfig:
89
+ """Hyperparameters for the GPT-2 124M model."""
90
+ block_size: int = 1024 # maximum sequence length
91
+ vocab_size: int = 50304 # 50,257 real tokens, padded to a multiple of 64 for efficiency
92
+ n_layer: int = 12 # number of transformer blocks
93
+ n_head: int = 12 # number of attention heads
94
+ n_embd: int = 768 # embedding / hidden dimension
95
+
96
+
97
+ class GPT(nn.Module):
98
+ """GPT-2 language model."""
99
+
100
+ def __init__(self, config):
101
+ super().__init__()
102
+ self.config = config
103
+ self.transformer = nn.ModuleDict(dict(
104
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
105
+ wpe = nn.Embedding(config.block_size, config.n_embd),
106
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
107
+ ln_f = nn.LayerNorm(config.n_embd),
108
+ ))
109
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
110
+ # tie input and output embeddings to reduce parameter count
111
+ self.transformer.wte.weight = self.lm_head.weight
112
+
113
+ def _init_weights(self, module):
114
+ if isinstance(module, nn.Linear):
115
+ std = 0.02
116
+ if hasattr(module, 'NANOGPT_SCALE_INIT'):
117
+ std *= (2 * self.config.n_layer) ** -0.5
118
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
119
+ if module.bias is not None:
120
+ torch.nn.init.zeros_(module.bias)
121
+ elif isinstance(module, nn.Embedding):
122
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
123
+
124
+ def forward(self, idx, targets=None):
125
+ """Forward pass; returns (logits, loss). Loss is None when targets is None."""
126
+ _, T = idx.size()
127
+ assert T <= self.config.block_size, (
128
+ f"Cannot forward sequence of length {T}, block size is {self.config.block_size}"
129
+ )
130
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
131
+ x = self.transformer.wte(idx) + self.transformer.wpe(pos)
132
+ for block in self.transformer.h:
133
+ x = block(x)
134
+ x = self.transformer.ln_f(x)
135
+ logits = self.lm_head(x)
136
+ loss = None
137
+ if targets is not None:
138
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
139
+ return logits, loss
140
+
141
+ def configure_optimizers(self, weight_decay, learning_rate, device_type):
142
+ """Build AdamW with weight decay applied only to 2-D parameters (weights, not biases/norms)."""
143
+ decay_params, no_decay_params = [], []
144
+ for _, p in self.named_parameters():
145
+ if p.requires_grad:
146
+ (decay_params if p.dim() >= 2 else no_decay_params).append(p)
147
+ optim_groups = [
148
+ {'params': decay_params, 'weight_decay': weight_decay},
149
+ {'params': no_decay_params, 'weight_decay': 0.0},
150
+ ]
151
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
152
+ use_fused = fused_available and device_type == 'cuda'
153
+ return torch.optim.AdamW(
154
+ optim_groups, lr=learning_rate, betas=(0.9, 0.95), eps=1e-8, fused=use_fused,
155
+ )
models/gpt3.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GPT-3-style model definition (~254M parameters).
3
+
4
+ A modernized decoder-only transformer that keeps GPT-2's overall shape but
5
+ adopts well-established post-GPT-2 improvements. Sized (~250M params) to train
6
+ well on the ~10B-token FineWeb-Edu sample -- roughly 40 tokens/parameter, ~2x
7
+ past the Chinchilla compute-optimal point, which gives a solid, well-converged
8
+ small model rather than a data-starved one:
9
+
10
+ * 18 layers, n_embd 1024 (head_dim 64)
11
+ * GQA (grouped-query attention): 16 query heads, 4 key/value heads --
12
+ smaller KV projection + KV cache, so a larger batch fits for better GPU use
13
+ * RoPE (rotary position embeddings) instead of a learned position table
14
+ * RMSNorm instead of LayerNorm, and no biases anywhere
15
+ * SwiGLU feed-forward instead of a GELU MLP
16
+ * QK-normalization for stable from-scratch training (esp. with bf16)
17
+ * tied input/output embeddings (kept from GPT-2)
18
+
19
+ It deliberately mirrors gpt2.py's public surface -- GPT3Config / GPT3 with a
20
+ `forward(idx, targets=None) -> (logits, loss)` contract, a `configure_optimizers`
21
+ method, and a `config.block_size` attribute -- so train.py and sample.py can
22
+ drive it through the exact same loops. block_size and vocab_size match gpt2 so
23
+ the existing tokenized FineWeb-Edu shards work unchanged.
24
+ """
25
+
26
+ import inspect
27
+ from dataclasses import dataclass
28
+
29
+ import torch
30
+ import torch.nn as nn
31
+ from torch.nn import functional as F
32
+ from torch.nn.functional import scaled_dot_product_attention
33
+
34
+ # -----------------------------------------------------------------------------
35
+
36
+
37
+ @dataclass
38
+ class GPT3Config:
39
+ """Hyperparameters for the ~254M speed-tuned GPT-3-style model."""
40
+ block_size: int = 1024 # maximum sequence length the model supports
41
+ vocab_size: int = 50304 # 50,257 real tokens, padded to a multiple of 64
42
+ n_layer: int = 18 # transformer blocks (~254M params total)
43
+ n_head: int = 16 # query heads (head_dim = n_embd // n_head = 64)
44
+ n_kv_head: int = 4 # GQA key/value heads (must divide n_head)
45
+ n_embd: int = 1024 # embedding / hidden dimension
46
+ d_ff: int = 2816 # SwiGLU inner dim (~8/3 * n_embd, rounded to mult of 256)
47
+ rope_theta: float = 10000.0 # RoPE base frequency
48
+ norm_eps: float = 1e-5 # RMSNorm epsilon
49
+
50
+
51
+ # -----------------------------------------------------------------------------
52
+
53
+
54
+ class RMSNorm(nn.Module):
55
+ """Root-mean-square layer normalization (no mean subtraction, no bias)."""
56
+
57
+ def __init__(self, dim, eps=1e-5):
58
+ super().__init__()
59
+ self.eps = eps
60
+ self.weight = nn.Parameter(torch.ones(dim))
61
+
62
+ def forward(self, x):
63
+ # normalize in float32 for stability, then cast back
64
+ dtype = x.dtype
65
+ x = x.float()
66
+ x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
67
+ return (x.type_as(self.weight) * self.weight).to(dtype)
68
+
69
+
70
+ # -----------------------------------------------------------------------------
71
+ # Rotary position embeddings (RoPE)
72
+ # -----------------------------------------------------------------------------
73
+
74
+
75
+ def build_rope_cache(block_size, head_dim, theta, device=None):
76
+ """Precompute (cos, sin) tables of shape (block_size, head_dim) for RoPE."""
77
+ # inverse frequencies for each pair of dimensions
78
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) / head_dim))
79
+ positions = torch.arange(block_size, dtype=torch.float32, device=device)
80
+ freqs = torch.outer(positions, inv_freq) # (block_size, head_dim/2)
81
+ emb = torch.cat((freqs, freqs), dim=-1) # (block_size, head_dim)
82
+ return emb.cos(), emb.sin()
83
+
84
+
85
+ def _rotate_half(x):
86
+ """Rotate the two halves of the last dimension: (-x2, x1)."""
87
+ x1, x2 = x.chunk(2, dim=-1)
88
+ return torch.cat((-x2, x1), dim=-1)
89
+
90
+
91
+ def apply_rope(q, k, cos, sin):
92
+ """Apply rotary embeddings to q and k, each shaped (B, n_head, T, head_dim)."""
93
+ T = q.size(-2)
94
+ cos = cos[:T].view(1, 1, T, -1) # (1, 1, T, head_dim)
95
+ sin = sin[:T].view(1, 1, T, -1)
96
+ q = (q * cos) + (_rotate_half(q) * sin)
97
+ k = (k * cos) + (_rotate_half(k) * sin)
98
+ return q, k
99
+
100
+
101
+ # -----------------------------------------------------------------------------
102
+
103
+
104
+ class CausalSelfAttention(nn.Module):
105
+ """Grouped-query causal self-attention with RoPE and QK-norm, via fused SDPA.
106
+
107
+ Queries use n_head heads; keys/values use n_kv_head <= n_head heads (GQA),
108
+ which shrinks the KV projection and KV-cache so a larger batch fits -- the
109
+ main win on a big GPU. No biases; q and k are RMS-normalized per head before
110
+ the rotary embedding, which stabilizes from-scratch training in bf16.
111
+ """
112
+
113
+ def __init__(self, config):
114
+ super().__init__()
115
+ assert config.n_embd % config.n_head == 0
116
+ assert config.n_head % config.n_kv_head == 0
117
+ self.n_head = config.n_head
118
+ self.n_kv_head = config.n_kv_head
119
+ self.head_dim = config.n_embd // config.n_head
120
+ self.q_dim = self.n_head * self.head_dim # = n_embd
121
+ self.kv_dim = self.n_kv_head * self.head_dim
122
+
123
+ # one projection producing q (full) and k, v (reduced for GQA)
124
+ self.c_attn = nn.Linear(config.n_embd, self.q_dim + 2 * self.kv_dim, bias=False)
125
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
126
+ self.c_proj.NANOGPT_SCALE_INIT = 1 # residual projection: scaled init
127
+
128
+ # QK-norm: per-head RMSNorm over head_dim
129
+ self.q_norm = RMSNorm(self.head_dim, eps=config.norm_eps)
130
+ self.k_norm = RMSNorm(self.head_dim, eps=config.norm_eps)
131
+
132
+ def forward(self, x, cos, sin):
133
+ B, T, C = x.size() # batch, sequence length, embedding dim
134
+ qkv = self.c_attn(x)
135
+ q, k, v = qkv.split([self.q_dim, self.kv_dim, self.kv_dim], dim=2)
136
+ q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2) # (B, nh, T, hd)
137
+ k = k.view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2) # (B, nkv, T, hd)
138
+ v = v.view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2) # (B, nkv, T, hd)
139
+
140
+ q = self.q_norm(q)
141
+ k = self.k_norm(k)
142
+ q, k = apply_rope(q, k, cos, sin)
143
+
144
+ # SDPA repeats the n_kv_head k/v across query groups when enable_gqa=True
145
+ y = scaled_dot_product_attention(
146
+ q, k, v, is_causal=True, enable_gqa=self.n_kv_head != self.n_head,
147
+ )
148
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
149
+ y = self.c_proj(y)
150
+ return y
151
+
152
+
153
+ # -----------------------------------------------------------------------------
154
+
155
+
156
+ class SwiGLU(nn.Module):
157
+ """Gated feed-forward network: (SiLU(x W_gate) * x W_up) W_down, no biases."""
158
+
159
+ def __init__(self, config):
160
+ super().__init__()
161
+ self.w_gate = nn.Linear(config.n_embd, config.d_ff, bias=False)
162
+ self.w_up = nn.Linear(config.n_embd, config.d_ff, bias=False)
163
+ self.w_down = nn.Linear(config.d_ff, config.n_embd, bias=False)
164
+ self.w_down.NANOGPT_SCALE_INIT = 1 # residual projection: scaled init
165
+
166
+ def forward(self, x):
167
+ return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
168
+
169
+
170
+ # -----------------------------------------------------------------------------
171
+
172
+
173
+ class Block(nn.Module):
174
+ """Pre-norm transformer block with RMSNorm, RoPE attention, and SwiGLU."""
175
+
176
+ def __init__(self, config):
177
+ super().__init__()
178
+ self.ln_1 = RMSNorm(config.n_embd, eps=config.norm_eps)
179
+ self.attn = CausalSelfAttention(config)
180
+ self.ln_2 = RMSNorm(config.n_embd, eps=config.norm_eps)
181
+ self.mlp = SwiGLU(config)
182
+
183
+ def forward(self, x, cos, sin):
184
+ x = x + self.attn(self.ln_1(x), cos, sin)
185
+ x = x + self.mlp(self.ln_2(x))
186
+ return x
187
+
188
+
189
+ # -----------------------------------------------------------------------------
190
+
191
+
192
+ class GPT3(nn.Module):
193
+ """GPT-3-style decoder-only language model."""
194
+
195
+ def __init__(self, config):
196
+ super().__init__()
197
+ self.config = config
198
+ self.transformer = nn.ModuleDict(dict(
199
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
200
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
201
+ ln_f = RMSNorm(config.n_embd, eps=config.norm_eps),
202
+ ))
203
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
204
+ # tie input and output embeddings to reduce parameter count
205
+ self.transformer.wte.weight = self.lm_head.weight
206
+
207
+ # RoPE tables: not persisted in the checkpoint (recomputed on build)
208
+ head_dim = config.n_embd // config.n_head
209
+ cos, sin = build_rope_cache(config.block_size, head_dim, config.rope_theta)
210
+ self.register_buffer("rope_cos", cos, persistent=False)
211
+ self.register_buffer("rope_sin", sin, persistent=False)
212
+
213
+ # initialize all weights (gpt2.py defined _init_weights but never applied it)
214
+ self.apply(self._init_weights)
215
+
216
+ def _init_weights(self, module):
217
+ if isinstance(module, nn.Linear):
218
+ std = 0.02
219
+ if hasattr(module, 'NANOGPT_SCALE_INIT'):
220
+ std *= (2 * self.config.n_layer) ** -0.5
221
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
222
+ if module.bias is not None:
223
+ torch.nn.init.zeros_(module.bias)
224
+ elif isinstance(module, nn.Embedding):
225
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
226
+
227
+ def forward(self, idx, targets=None):
228
+ """Forward pass; returns (logits, loss). Loss is None when targets is None."""
229
+ _, T = idx.size()
230
+ assert T <= self.config.block_size, (
231
+ f"Cannot forward sequence of length {T}, block size is {self.config.block_size}"
232
+ )
233
+ cos = self.rope_cos.to(idx.device)
234
+ sin = self.rope_sin.to(idx.device)
235
+
236
+ x = self.transformer.wte(idx)
237
+ for block in self.transformer.h:
238
+ x = block(x, cos, sin)
239
+ x = self.transformer.ln_f(x)
240
+ logits = self.lm_head(x)
241
+ loss = None
242
+ if targets is not None:
243
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
244
+ return logits, loss
245
+
246
+ def configure_optimizers(self, weight_decay, learning_rate, device_type):
247
+ """Build AdamW with weight decay applied only to 2-D parameters (weights, not norms)."""
248
+ decay_params, no_decay_params = [], []
249
+ for _, p in self.named_parameters():
250
+ if p.requires_grad:
251
+ (decay_params if p.dim() >= 2 else no_decay_params).append(p)
252
+ optim_groups = [
253
+ {'params': decay_params, 'weight_decay': weight_decay},
254
+ {'params': no_decay_params, 'weight_decay': 0.0},
255
+ ]
256
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
257
+ use_fused = fused_available and device_type == 'cuda'
258
+ return torch.optim.AdamW(
259
+ optim_groups, lr=learning_rate, betas=(0.9, 0.95), eps=1e-8, fused=use_fused,
260
+ )
models/tokenizer.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tiktoken
2
+
3
+ SPECIAL_TOKENS = {
4
+ "<|bos|>": 50257,
5
+ "<|user_start|>": 50258,
6
+ "<|user_end|>": 50259,
7
+ "<|assistant_start|>": 50260,
8
+ "<|assistant_end|>": 50261,
9
+ "<|system_start|>": 50262,
10
+ "<|system_end|>": 50263,
11
+ }
12
+
13
+
14
+ def get_encoding():
15
+ """Return a gpt2 tiktoken encoding extended with the chat special tokens."""
16
+ base = tiktoken.get_encoding("gpt2")
17
+ return tiktoken.Encoding(
18
+ name="gpt2_chat",
19
+ pat_str=base._pat_str,
20
+ mergeable_ranks=base._mergeable_ranks,
21
+ special_tokens={**base._special_tokens, **SPECIAL_TOKENS},
22
+ )
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Web backend + model runtime deps for the Hugging Face Space.
2
+ # torch is installed separately in the Dockerfile from the CPU wheel index
3
+ # (https://download.pytorch.org/whl/cpu) to keep the image small.
4
+ fastapi==0.137.0
5
+ uvicorn[standard]==0.49.0
6
+ tiktoken==0.13.0
7
+ pydantic==2.13.4
server/__init__.py ADDED
File without changes
server/app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI backend that serves the chat model to the web frontend.
3
+
4
+ Discovers the available *_chat.pth checkpoints, loads each one lazily (and only
5
+ once), and exposes:
6
+ GET /api/models -> which chat models are available
7
+ POST /api/chat -> stream an assistant reply as Server-Sent Events
8
+ It also serves the built frontend (web/dist) when that directory exists.
9
+ """
10
+
11
+ import json
12
+ from pathlib import Path
13
+
14
+ from fastapi import FastAPI
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ from fastapi.responses import StreamingResponse
17
+ from fastapi.staticfiles import StaticFiles
18
+ from pydantic import BaseModel
19
+
20
+ from server.inference import ChatModel
21
+
22
+ ROOT = Path(__file__).resolve().parent.parent
23
+ SUFFIX = "_chat.pth"
24
+
25
+
26
+ def discover_checkpoints():
27
+ """Map arch name -> checkpoint path for every *_chat.pth in the project root."""
28
+ found = {}
29
+ for path in sorted(ROOT.glob(f"*{SUFFIX}")):
30
+ arch = path.name[: -len(SUFFIX)]
31
+ if arch in ("gpt2", "gpt3", "gpt3.1"):
32
+ found[arch] = path
33
+ return found
34
+
35
+
36
+ _checkpoints = discover_checkpoints()
37
+ _models = {} # arch -> ChatModel, loaded on first use
38
+
39
+
40
+ def get_model(arch):
41
+ if arch not in _models:
42
+ _models[arch] = ChatModel("gpt3", str(_checkpoints[arch]))
43
+ return _models[arch]
44
+
45
+
46
+ app = FastAPI(title="GPT Chat")
47
+ app.add_middleware(
48
+ CORSMiddleware,
49
+ allow_origins=["*"],
50
+ allow_methods=["*"],
51
+ allow_headers=["*"],
52
+ )
53
+
54
+
55
+ class Message(BaseModel):
56
+ role: str
57
+ content: str
58
+
59
+
60
+ class ChatRequest(BaseModel):
61
+ messages: list[Message]
62
+ model: str | None = None
63
+ max_new_tokens: int = 200
64
+ top_k: int = 50
65
+
66
+
67
+ @app.get("/api/models")
68
+ def list_models():
69
+ return {"models": list(_checkpoints.keys())}
70
+
71
+
72
+ @app.post("/api/chat")
73
+ def chat(req: ChatRequest):
74
+ arch = req.model or (next(iter(_checkpoints), None))
75
+
76
+ def sse(obj):
77
+ return f"data: {json.dumps(obj)}\n\n"
78
+
79
+ if arch not in _checkpoints:
80
+ return StreamingResponse(
81
+ iter([sse({"error": f"unknown model: {arch}"})]),
82
+ media_type="text/event-stream",
83
+ )
84
+
85
+ model = get_model(arch)
86
+ messages = [m.model_dump() for m in req.messages]
87
+ max_new_tokens = max(1, min(req.max_new_tokens, 1000))
88
+ top_k = max(1, min(req.top_k, 200))
89
+
90
+ def event_stream():
91
+ try:
92
+ for delta in model.generate_stream(messages, max_new_tokens, top_k):
93
+ yield sse({"delta": delta})
94
+ yield sse({"done": True})
95
+ except Exception as e: # surface generation errors to the client
96
+ yield sse({"error": str(e)})
97
+
98
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
99
+
100
+
101
+ # Serve the built frontend if present (production single-origin deploy).
102
+ # Mounted last so it does not shadow the /api routes above.
103
+ _dist = ROOT / "web" / "dist"
104
+ if _dist.is_dir():
105
+ app.mount("/", StaticFiles(directory=str(_dist), html=True), name="static")
server/inference.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference wrapper around the fine-tuned chat model for the web backend.
3
+
4
+ Reuses the same model construction and chat template as the sample_chat.py CLI
5
+ so the web server generates replies exactly the way the CLI does, but keeps the
6
+ model loaded across requests and streams tokens out as they are produced.
7
+ """
8
+
9
+ import threading
10
+
11
+ import torch
12
+ from torch.nn import functional as F
13
+
14
+ from common import build_model, get_device
15
+ from models import SPECIAL_TOKENS, get_encoding
16
+
17
+ # Real GPT-2 vocab is 0..50256; 50257+ are the chat special tokens (and padding
18
+ # up to the model's padded vocab_size), which have no printable byte form.
19
+ FIRST_SPECIAL_TOKEN = 50257
20
+
21
+
22
+ class ChatModel:
23
+ """A loaded chat model that builds prompts from history and streams replies."""
24
+
25
+ def __init__(self, arch, checkpoint, device=None):
26
+ self.device = device or get_device()
27
+ self.model = build_model(arch).to(self.device)
28
+ state = torch.load(checkpoint, map_location=self.device)
29
+ state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
30
+ self.model.load_state_dict(state)
31
+ self.model.eval()
32
+
33
+ self.enc = get_encoding()
34
+ self.bos = SPECIAL_TOKENS["<|bos|>"]
35
+ self.user_start = SPECIAL_TOKENS["<|user_start|>"]
36
+ self.user_end = SPECIAL_TOKENS["<|user_end|>"]
37
+ self.asst_start = SPECIAL_TOKENS["<|assistant_start|>"]
38
+ self.asst_end = SPECIAL_TOKENS["<|assistant_end|>"]
39
+ self.block_size = self.model.config.block_size
40
+
41
+ # one model on one device can't run two generations at once
42
+ self._lock = threading.Lock()
43
+
44
+ def _encode_turn(self, role, content):
45
+ body = self.enc.encode_ordinary(content)
46
+ if role == "user":
47
+ return [self.user_start, *body, self.user_end]
48
+ return [self.asst_start, *body, self.asst_end]
49
+
50
+ def build_prompt(self, messages, max_new_tokens):
51
+ """Tokenize the conversation, dropping oldest whole turns to fit the window."""
52
+ # leave room for the leading <|bos|> and the trailing <|assistant_start|>
53
+ budget = self.block_size - max_new_tokens - 2
54
+ turns = [self._encode_turn(m["role"], m["content"]) for m in messages]
55
+
56
+ kept, total = [], 0
57
+ for turn in reversed(turns): # keep the most recent turns that fit
58
+ if total + len(turn) > budget:
59
+ break
60
+ kept.append(turn)
61
+ total += len(turn)
62
+ kept.reverse()
63
+
64
+ ids = [self.bos]
65
+ for turn in kept:
66
+ ids.extend(turn)
67
+ ids.append(self.asst_start) # hand the floor to the assistant
68
+ return ids
69
+
70
+ def generate_stream(self, messages, max_new_tokens=200, top_k=50):
71
+ """Yield decoded text chunks of the assistant's reply as tokens are sampled."""
72
+ with self._lock:
73
+ ids = self.build_prompt(messages, max_new_tokens)
74
+ x = torch.tensor(ids, dtype=torch.long, device=self.device).unsqueeze(0)
75
+
76
+ byte_buf = b"" # holds bytes of an in-progress multibyte character
77
+ for _ in range(max_new_tokens):
78
+ with torch.no_grad():
79
+ idx_cond = x[:, -self.block_size:]
80
+ logits, _ = self.model(idx_cond)
81
+ logits = logits[:, -1, :]
82
+ probs = F.softmax(logits, dim=-1)
83
+ topk_probs, topk_indices = torch.topk(probs, top_k, dim=-1)
84
+ ix = torch.multinomial(topk_probs, 1)
85
+ next_id = torch.gather(topk_indices, -1, ix)
86
+
87
+ tok = next_id.item()
88
+ if tok >= FIRST_SPECIAL_TOKEN: # <|assistant_end|> or any special token: stop
89
+ break
90
+ x = torch.cat((x, next_id), dim=1)
91
+
92
+ # decode safely: only emit once we have complete UTF-8 characters
93
+ byte_buf += self.enc.decode_single_token_bytes(tok)
94
+ try:
95
+ text = byte_buf.decode("utf-8")
96
+ except UnicodeDecodeError:
97
+ continue # wait for the rest of a multibyte character
98
+ byte_buf = b""
99
+ if text:
100
+ yield text
101
+
102
+ if byte_buf: # flush any trailing bytes, ignoring an incomplete tail
103
+ tail = byte_buf.decode("utf-8", errors="ignore")
104
+ if tail:
105
+ yield tail
web/dist/assets/index-Dh532deN.css ADDED
@@ -0,0 +1 @@
 
 
1
+ :root{--bg: #ffffff;--panel: #f7f7f8;--border: #e5e5e7;--accent: #2563eb;--user-text: #ffffff;--asst: #f1f1f3;--asst-text: #111111;--muted: #8a8a8f}*{box-sizing:border-box}html,body,#root{height:100%;margin:0}body{font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;color:#111;background:var(--bg)}.app{display:flex;flex-direction:column;height:100%;max-width:820px;margin:0 auto;border-left:1px solid var(--border);border-right:1px solid var(--border)}.settings{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 16px;border-bottom:1px solid var(--border);background:var(--panel);flex-wrap:wrap}.brand{font-weight:600}.controls{display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap}.controls label{display:flex;flex-direction:column;gap:2px;font-size:11px;color:var(--muted)}.controls select,.controls input{font-size:13px;padding:4px 6px;border:1px solid var(--border);border-radius:6px}.controls input[type=number]{width:72px}.newchat{padding:6px 12px;border:1px solid var(--border);background:#fff;border-radius:6px;cursor:pointer}.newchat:hover{background:#efefef}.messages{flex:1;overflow-y:auto;padding:20px 16px;display:flex;flex-direction:column;gap:12px}.empty{margin:auto;color:var(--muted)}.bubble-row{display:flex}.bubble-row.user{justify-content:flex-end}.bubble-row.assistant{justify-content:flex-start}.bubble{max-width:75%;padding:10px 14px;border-radius:14px;white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.5}.bubble.user{background:var(--accent);color:var(--user-text);border-bottom-right-radius:4px}.bubble.assistant{background:var(--asst);color:var(--asst-text);border-bottom-left-radius:4px}.typing{letter-spacing:2px;color:var(--muted);animation:blink 1.2s infinite}@keyframes blink{0%,to{opacity:.3}50%{opacity:1}}.composer{display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);background:var(--panel)}.composer textarea{flex:1;resize:none;font:inherit;padding:10px 12px;border:1px solid var(--border);border-radius:10px;min-height:42px;max-height:160px}.composer button{padding:0 18px;border:none;background:var(--accent);color:#fff;border-radius:10px;cursor:pointer;font-weight:600}.composer button:disabled{opacity:.5;cursor:not-allowed}
web/dist/assets/index-lK4BG3Ty.js ADDED
The diff for this file is too large to render. See raw diff
 
web/dist/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>GPT Chat</title>
7
+ <script type="module" crossorigin src="/assets/index-lK4BG3Ty.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-Dh532deN.css">
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ </body>
13
+ </html>