Upload folder using huggingface_hub
Browse files- README.md +82 -0
- config.json +39 -0
- model.py +148 -0
- weights.pt +3 -0
README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- conversational
|
| 7 |
+
- text-generation
|
| 8 |
+
- character-level
|
| 9 |
+
- transformer
|
| 10 |
+
- gpt
|
| 11 |
+
library_name: pytorch
|
| 12 |
+
pipeline_tag: text-generation
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# Fourth GPT
|
| 16 |
+
|
| 17 |
+
A tiny (344K parameter) character-level GPT trained for casual conversation.
|
| 18 |
+
|
| 19 |
+
## Model Details
|
| 20 |
+
|
| 21 |
+
| Property | Value |
|
| 22 |
+
|----------|-------|
|
| 23 |
+
| Parameters | 344,256 |
|
| 24 |
+
| Architecture | Decoder-only Transformer |
|
| 25 |
+
| Layers | 3 |
|
| 26 |
+
| Embedding Dim | 96 |
|
| 27 |
+
| Attention Heads | 6 |
|
| 28 |
+
| Context Window | 64 characters |
|
| 29 |
+
| Vocabulary | 29 (a-z, space, pipe, BOS) |
|
| 30 |
+
| Tokenization | Character-level |
|
| 31 |
+
| Framework | PyTorch |
|
| 32 |
+
|
| 33 |
+
## Architecture
|
| 34 |
+
|
| 35 |
+
- 3 Transformer blocks with RMS normalization
|
| 36 |
+
- Multi-head causal self-attention (6 heads, 16-dim each)
|
| 37 |
+
- MLP with ReLU activation (4x expansion)
|
| 38 |
+
- Learned positional embeddings
|
| 39 |
+
- Weight tying not used
|
| 40 |
+
|
| 41 |
+
## Training
|
| 42 |
+
|
| 43 |
+
- **Data**: ~3,500 conversational prompt-response pairs
|
| 44 |
+
- **Format**: `prompt|response` with `|` as turn separator
|
| 45 |
+
- **Optimizer**: Adam with linear LR decay
|
| 46 |
+
- **Learning Rate**: 1e-3
|
| 47 |
+
- **Steps**: 18,000
|
| 48 |
+
- **Batch Size**: 16
|
| 49 |
+
- **Hardware**: Apple M1 GPU via MLX (converted to PyTorch for serving)
|
| 50 |
+
|
| 51 |
+
## Usage
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
import torch
|
| 55 |
+
from model import FourthModel
|
| 56 |
+
|
| 57 |
+
model = FourthModel()
|
| 58 |
+
model.load()
|
| 59 |
+
response = model.generate("hello")
|
| 60 |
+
print(response) # "hi there friend"
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## API
|
| 64 |
+
|
| 65 |
+
An OpenAI-compatible API is available as a Hugging Face Space:
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
curl https://ajaxdavis-fourth-gpt-api.hf.space/v1/chat/completions \
|
| 69 |
+
-H "Content-Type: application/json" \
|
| 70 |
+
-d '{"model":"fourth-gpt","messages":[{"role":"user","content":"hello"}]}'
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
## Limitations
|
| 74 |
+
|
| 75 |
+
- Character-level tokenization limits vocabulary to lowercase English
|
| 76 |
+
- 64-character context window constrains response length
|
| 77 |
+
- Small model size means memorization of training data rather than broad generalization
|
| 78 |
+
- Best on seen prompt patterns (greetings, jokes, wisdom, recommendations)
|
| 79 |
+
|
| 80 |
+
## License
|
| 81 |
+
|
| 82 |
+
MIT
|
config.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"n_layer": 3,
|
| 3 |
+
"n_embd": 96,
|
| 4 |
+
"block_size": 64,
|
| 5 |
+
"n_head": 6,
|
| 6 |
+
"vocab_size": 29,
|
| 7 |
+
"bos": 28,
|
| 8 |
+
"stoi": {
|
| 9 |
+
" ": 0,
|
| 10 |
+
"a": 1,
|
| 11 |
+
"b": 2,
|
| 12 |
+
"c": 3,
|
| 13 |
+
"d": 4,
|
| 14 |
+
"e": 5,
|
| 15 |
+
"f": 6,
|
| 16 |
+
"g": 7,
|
| 17 |
+
"h": 8,
|
| 18 |
+
"i": 9,
|
| 19 |
+
"j": 10,
|
| 20 |
+
"k": 11,
|
| 21 |
+
"l": 12,
|
| 22 |
+
"m": 13,
|
| 23 |
+
"n": 14,
|
| 24 |
+
"o": 15,
|
| 25 |
+
"p": 16,
|
| 26 |
+
"q": 17,
|
| 27 |
+
"r": 18,
|
| 28 |
+
"s": 19,
|
| 29 |
+
"t": 20,
|
| 30 |
+
"u": 21,
|
| 31 |
+
"v": 22,
|
| 32 |
+
"w": 23,
|
| 33 |
+
"x": 24,
|
| 34 |
+
"y": 25,
|
| 35 |
+
"z": 26,
|
| 36 |
+
"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3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
import math
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class RMSNorm(nn.Module):
|
| 13 |
+
def __init__(self, dim, eps=1e-6):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 16 |
+
self.eps = eps
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 20 |
+
return x * norm * self.weight
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TransformerBlock(nn.Module):
|
| 24 |
+
def __init__(self, n_embd, n_head):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.n_head = n_head
|
| 27 |
+
self.head_dim = n_embd // n_head
|
| 28 |
+
self.norm1 = RMSNorm(n_embd)
|
| 29 |
+
self.wq = nn.Linear(n_embd, n_embd, bias=False)
|
| 30 |
+
self.wk = nn.Linear(n_embd, n_embd, bias=False)
|
| 31 |
+
self.wv = nn.Linear(n_embd, n_embd, bias=False)
|
| 32 |
+
self.wo = nn.Linear(n_embd, n_embd, bias=False)
|
| 33 |
+
self.norm2 = RMSNorm(n_embd)
|
| 34 |
+
self.mlp_fc1 = nn.Linear(n_embd, 4 * n_embd, bias=False)
|
| 35 |
+
self.mlp_fc2 = nn.Linear(4 * n_embd, n_embd, bias=False)
|
| 36 |
+
|
| 37 |
+
def forward(self, x, mask):
|
| 38 |
+
B, T, _ = x.shape
|
| 39 |
+
xn = self.norm1(x)
|
| 40 |
+
q = self.wq(xn).reshape(B, T, self.n_head, self.head_dim).transpose(1, 2)
|
| 41 |
+
k = self.wk(xn).reshape(B, T, self.n_head, self.head_dim).transpose(1, 2)
|
| 42 |
+
v = self.wv(xn).reshape(B, T, self.n_head, self.head_dim).transpose(1, 2)
|
| 43 |
+
att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 44 |
+
att = att + mask
|
| 45 |
+
att = F.softmax(att, dim=-1)
|
| 46 |
+
out = (att @ v).transpose(1, 2).reshape(B, T, -1)
|
| 47 |
+
x = x + self.wo(out)
|
| 48 |
+
xn2 = self.norm2(x)
|
| 49 |
+
h = F.relu(self.mlp_fc1(xn2))
|
| 50 |
+
x = x + self.mlp_fc2(h)
|
| 51 |
+
return x
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class GPT(nn.Module):
|
| 55 |
+
def __init__(self, vocab_size, n_layer, n_embd, block_size, n_head):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.block_size = block_size
|
| 58 |
+
self.wte = nn.Embedding(vocab_size, n_embd)
|
| 59 |
+
self.wpe = nn.Embedding(block_size, n_embd)
|
| 60 |
+
self.ln_pre = RMSNorm(n_embd)
|
| 61 |
+
self.layers = nn.ModuleList([TransformerBlock(n_embd, n_head) for _ in range(n_layer)])
|
| 62 |
+
self.ln_post = RMSNorm(n_embd)
|
| 63 |
+
self.lm_head = nn.Linear(n_embd, vocab_size, bias=False)
|
| 64 |
+
|
| 65 |
+
def forward(self, tokens):
|
| 66 |
+
B, T = tokens.shape
|
| 67 |
+
x = self.wte(tokens) + self.wpe(torch.arange(T, device=tokens.device))
|
| 68 |
+
x = self.ln_pre(x)
|
| 69 |
+
mask = torch.triu(torch.full((T, T), -1e9, device=tokens.device), diagonal=1)
|
| 70 |
+
for layer in self.layers:
|
| 71 |
+
x = layer(x, mask)
|
| 72 |
+
x = self.ln_post(x)
|
| 73 |
+
return self.lm_head(x)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class FourthModel:
|
| 77 |
+
"""Wraps the GPT model with tokenizer and generation logic."""
|
| 78 |
+
|
| 79 |
+
def __init__(self, checkpoint_dir=None):
|
| 80 |
+
if checkpoint_dir is None:
|
| 81 |
+
checkpoint_dir = os.path.join(os.path.dirname(__file__) or ".", "model_weights")
|
| 82 |
+
self.checkpoint_dir = checkpoint_dir
|
| 83 |
+
self.model = None
|
| 84 |
+
self.stoi = None
|
| 85 |
+
self.itos = None
|
| 86 |
+
self.bos = None
|
| 87 |
+
self.config = None
|
| 88 |
+
|
| 89 |
+
def load(self):
|
| 90 |
+
config_path = os.path.join(self.checkpoint_dir, "config.json")
|
| 91 |
+
with open(config_path) as f:
|
| 92 |
+
self.config = json.load(f)
|
| 93 |
+
|
| 94 |
+
self.stoi = self.config["stoi"]
|
| 95 |
+
self.bos = self.config["bos"]
|
| 96 |
+
self.itos = {int(i): c for c, i in self.stoi.items()}
|
| 97 |
+
self.itos[self.bos] = ""
|
| 98 |
+
|
| 99 |
+
self.model = GPT(
|
| 100 |
+
vocab_size=self.config["vocab_size"],
|
| 101 |
+
n_layer=self.config["n_layer"],
|
| 102 |
+
n_embd=self.config["n_embd"],
|
| 103 |
+
block_size=self.config["block_size"],
|
| 104 |
+
n_head=self.config["n_head"],
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Load weights — try PyTorch format first, fall back to npz
|
| 108 |
+
pt_path = os.path.join(self.checkpoint_dir, "weights.pt")
|
| 109 |
+
npz_path = os.path.join(self.checkpoint_dir, "weights.npz")
|
| 110 |
+
|
| 111 |
+
if os.path.exists(pt_path):
|
| 112 |
+
state_dict = torch.load(pt_path, map_location="cpu", weights_only=True)
|
| 113 |
+
else:
|
| 114 |
+
import numpy as np
|
| 115 |
+
npz = np.load(npz_path)
|
| 116 |
+
state_dict = {k: torch.tensor(npz[k]) for k in npz.files}
|
| 117 |
+
|
| 118 |
+
self.model.load_state_dict(state_dict)
|
| 119 |
+
self.model.eval()
|
| 120 |
+
|
| 121 |
+
nparams = sum(p.numel() for p in self.model.parameters())
|
| 122 |
+
print(f"Loaded model: {nparams} params, vocab={self.config['vocab_size']}")
|
| 123 |
+
|
| 124 |
+
@torch.no_grad()
|
| 125 |
+
def generate(self, prompt: str, max_tokens: int = 128, temperature: float = 0.7) -> str:
|
| 126 |
+
"""Generate a response to a prompt."""
|
| 127 |
+
clean = re.sub(r'[^a-z |]', '', prompt.lower().strip())
|
| 128 |
+
clean = re.sub(r' +', ' ', clean).strip()
|
| 129 |
+
|
| 130 |
+
if not clean.endswith("|"):
|
| 131 |
+
clean += "|"
|
| 132 |
+
|
| 133 |
+
block_size = self.config["block_size"]
|
| 134 |
+
tokens = [self.bos] + [self.stoi.get(c, self.bos) for c in clean]
|
| 135 |
+
|
| 136 |
+
for _ in range(min(max_tokens, block_size - len(tokens))):
|
| 137 |
+
x = torch.tensor([tokens[-block_size:]], dtype=torch.long)
|
| 138 |
+
logits = self.model(x)
|
| 139 |
+
logits = logits[0, -1] / temperature
|
| 140 |
+
probs = F.softmax(logits, dim=-1)
|
| 141 |
+
tok = torch.multinomial(probs, 1).item()
|
| 142 |
+
if tok == self.bos:
|
| 143 |
+
break
|
| 144 |
+
tokens.append(tok)
|
| 145 |
+
|
| 146 |
+
full = "".join(self.itos.get(t, "?") for t in tokens[1:])
|
| 147 |
+
parts = full.split("|", 1)
|
| 148 |
+
return parts[1] if len(parts) > 1 else full
|
weights.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:33de338e658afe29547afb62f9920848ce78d9301cd2bea78196d68b1482b080
|
| 3 |
+
size 1385548
|