Instructions to use coderian/TinyGPT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use coderian/TinyGPT with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="coderian/TinyGPT", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("coderian/TinyGPT", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use coderian/TinyGPT with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "coderian/TinyGPT" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "coderian/TinyGPT", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/coderian/TinyGPT
- SGLang
How to use coderian/TinyGPT 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 "coderian/TinyGPT" \ --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": "coderian/TinyGPT", "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 "coderian/TinyGPT" \ --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": "coderian/TinyGPT", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use coderian/TinyGPT with Docker Model Runner:
docker model run hf.co/coderian/TinyGPT
Upload folder using huggingface_hub
Browse files- README.md +259 -0
- config.json +17 -0
- config.py +23 -0
- generation_config.json +6 -0
- model.safetensors +3 -0
- models/__init__.py +0 -0
- models/attention.py +54 -0
- models/config.py +23 -0
- models/tinygpt.py +91 -0
- models/transformer_block.py +42 -0
- tinygpt.py +91 -0
- tokenizer.json +0 -0
- tokenizer_config.json +13 -0
README.md
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- text-generation
|
| 7 |
+
- causal-lm
|
| 8 |
+
- gpt
|
| 9 |
+
- tinygpt
|
| 10 |
+
- transformer
|
| 11 |
+
library_name: transformers
|
| 12 |
+
pipeline_tag: text-generation
|
| 13 |
+
base_model: gpt2
|
| 14 |
+
widget:
|
| 15 |
+
- text: "Once upon a time, a little boy named Sam"
|
| 16 |
+
example_title: "Story start"
|
| 17 |
+
- text: "The cat and the dog decided to"
|
| 18 |
+
example_title: "Animals"
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
# TinyGPT
|
| 22 |
+
|
| 23 |
+
A small-scale, **trained-from-scratch** GPT language model. Based on the GPT-2 architecture and fully compatible with `transformers`; downloadable via the Hub, with model source code included in this repo.
|
| 24 |
+
|
| 25 |
+
- **Architecture:** Decoder-only Transformer (custom, Chapter-1 style)
|
| 26 |
+
- **Parameters:** ~29M (`28,974,161`)
|
| 27 |
+
- **Context length (`max_seq_len`):** 128 tokens
|
| 28 |
+
- **Tokenizer:** GPT-2 (vocab size = 50,257, BPE)
|
| 29 |
+
- **Training data:** First 50,000 stories from [TinyStories](https://huggingface.co/datasets/roneneldan/TinyStories)
|
| 30 |
+
- **Inference memory (fp32 weights):** ~116MB -- runs comfortably on a single GPU or even CPU
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Installation
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
pip install transformers torch
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## Usage (with transformers)
|
| 43 |
+
|
| 44 |
+
TinyGPT uses a custom architecture, so the model code is loaded from this repo at runtime. This requires the **`trust_remote_code=True`** flag.
|
| 45 |
+
|
| 46 |
+
### 1) Simplest approach: Auto classes
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 50 |
+
|
| 51 |
+
repo = "coderian/TinyGPT"
|
| 52 |
+
|
| 53 |
+
tokenizer = AutoTokenizer.from_pretrained(repo)
|
| 54 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 55 |
+
repo,
|
| 56 |
+
trust_remote_code=True, # loads custom architecture code from repo
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
model.eval()
|
| 60 |
+
|
| 61 |
+
# Generation (sampling)
|
| 62 |
+
prompt = "Once upon a time, a little girl named Lily found"
|
| 63 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 64 |
+
|
| 65 |
+
output = model.generate(
|
| 66 |
+
**inputs,
|
| 67 |
+
max_new_tokens=50,
|
| 68 |
+
do_sample=True,
|
| 69 |
+
temperature=0.8,
|
| 70 |
+
top_k=50,
|
| 71 |
+
top_p=0.95,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
text = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 75 |
+
print(text)
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### 2) Direct class (code-based usage)
|
| 79 |
+
|
| 80 |
+
If you copied the source code into your own project, `trust_remote_code` is not needed:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
from models.tinygpt import TinyGPT
|
| 84 |
+
|
| 85 |
+
model = TinyGPT.from_pretrained("coderian/TinyGPT", device="cpu")
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
### 3) GPU placement and half-precision
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 92 |
+
repo,
|
| 93 |
+
trust_remote_code=True,
|
| 94 |
+
torch_dtype="auto", # uses config dtype (fp32)
|
| 95 |
+
device_map="auto", # places model on GPU if available
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# Lower memory usage with bf16/fp16:
|
| 99 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 100 |
+
repo,
|
| 101 |
+
trust_remote_code=True,
|
| 102 |
+
torch_dtype="bf16", # or "float16"
|
| 103 |
+
device_map="auto",
|
| 104 |
+
)
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
### 4) Simple greedy chat loop
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
def reply(prompt, max_new_tokens=40):
|
| 111 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 112 |
+
out = model.generate(**inputs, max_new_tokens=max_new_tokens)
|
| 113 |
+
return tokenizer.decode(out[0], skip_special_tokens=True)
|
| 114 |
+
|
| 115 |
+
print(reply("One rainy day, Ben and his dog Rex decided to"))
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
> **Note:** The model was trained exclusively on **English** TinyStories data. It works best with simple English story openings.
|
| 119 |
+
|
| 120 |
+
---
|
| 121 |
+
|
| 122 |
+
## Repo contents
|
| 123 |
+
|
| 124 |
+
| File | Description |
|
| 125 |
+
|---|---|
|
| 126 |
+
| `model.safetensors` | Trained weights (~116MB, fp32) |
|
| 127 |
+
| `config.json` | Model configuration (`TinyGPTConfig`) |
|
| 128 |
+
| `generation_config.json` | Default `generate()` parameters |
|
| 129 |
+
| `tokenizer.json`, `tokenizer_config.json` | GPT-2 tokenizer |
|
| 130 |
+
| `models/` | Open-source model code (config, tinygpt, transformer_block, attention) |
|
| 131 |
+
|
| 132 |
+
---
|
| 133 |
+
|
| 134 |
+
## Architecture
|
| 135 |
+
|
| 136 |
+
TinyGPT is a **decoder-only Transformer**. Input tokens pass through `token + position embedding`, are processed by `num_layers` Transformer blocks, and finally a LayerNorm + linear head produces logits over the vocabulary.
|
| 137 |
+
|
| 138 |
+
```
|
| 139 |
+
Input tokens (B, T)
|
| 140 |
+
|
|
| 141 |
+
v
|
| 142 |
+
+-----------------------------------+
|
| 143 |
+
| token_embedding (50,257 -> d) | nn.Embedding
|
| 144 |
+
| position_embedding (T -> d) | nn.Embedding
|
| 145 |
+
| x = token_emb + pos_emb |
|
| 146 |
+
+------------------+-----------------+
|
| 147 |
+
v
|
| 148 |
+
+-----------------------------+ x num_layers (4)
|
| 149 |
+
| LN1 -> CausalSelfAttn | Pre-LN, residual
|
| 150 |
+
| + |
|
| 151 |
+
| LN2 -> FFN (x4) | GELU activation
|
| 152 |
+
| + |
|
| 153 |
+
+-----------------------------+
|
| 154 |
+
v
|
| 155 |
+
ln_f (LayerNorm)
|
| 156 |
+
v
|
| 157 |
+
lm_head (d -> 50,257) --> logits (B, T, V)
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
### 1) Embedding layers
|
| 161 |
+
|
| 162 |
+
- **`token_embedding`**: maps each token ID to a `d=256` dimensional vector. `W_e` in R^(50257 x 256)
|
| 163 |
+
- **`position_embedding`**: adds positional information. Consecutive positions use the same learned embedding; `W_p` in R^(128 x 256)
|
| 164 |
+
|
| 165 |
+
Input vector: `x = W_e[input_ids] + W_p[positions]`
|
| 166 |
+
|
| 167 |
+
### 2) Causal Self-Attention (masked scaled dot-product)
|
| 168 |
+
|
| 169 |
+
Each position can only attend to **previous** tokens (causal mask).
|
| 170 |
+
|
| 171 |
+
```
|
| 172 |
+
Q = x W_q , K = x W_k , V = x W_v W in R^(256x256)
|
| 173 |
+
|
| 174 |
+
scores = (Q K^T) / sqrt(d) d = 256
|
| 175 |
+
scores = masked_fill(upper_triangle, -inf) <- blocks future tokens
|
| 176 |
+
attn = softmax(scores, dim=-1)
|
| 177 |
+
output = attn @ V , then output W_o
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
- Scaling by `1/sqrt(d)`: keeps dot-product variance stable at high dimensions,
|
| 181 |
+
preventing softmax saturation.
|
| 182 |
+
- `nn.Embedding` and `nn.Linear` weights are initialized from `N(0, 0.02)`.
|
| 183 |
+
|
| 184 |
+
### 3) Residual connections and Pre-LayerNorm
|
| 185 |
+
|
| 186 |
+
LayerNorm is applied before each sublayer, followed by a residual add:
|
| 187 |
+
|
| 188 |
+
```
|
| 189 |
+
x = x + attention(ln1(x))
|
| 190 |
+
x = x + ffn(ln2(x))
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
Pre-LN keeps training stable in deeper models.
|
| 194 |
+
|
| 195 |
+
### 4) FFN (Feed-Forward Network)
|
| 196 |
+
|
| 197 |
+
```
|
| 198 |
+
FFN(x) = W2 * GELU(W1 * x + b1) + b2
|
| 199 |
+
|
| 200 |
+
W1: 256 -> 1024 (expansion x4)
|
| 201 |
+
GELU: activation
|
| 202 |
+
W2: 1024 -> 256 (contraction)
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
### 5) Output
|
| 206 |
+
|
| 207 |
+
```
|
| 208 |
+
logits = lm_head(ln_f(x)) ln_f: LayerNorm(256)
|
| 209 |
+
lm_head: Linear(256 -> 50,257)
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
During training, `CrossEntropyLoss(logits, shift_right(y))` is used for the language modeling objective.
|
| 213 |
+
During inference, the `lm_head` logits directly represent the next-token distribution.
|
| 214 |
+
|
| 215 |
+
### Parameter breakdown
|
| 216 |
+
|
| 217 |
+
| Component | Parameters | Notes |
|
| 218 |
+
|---|---|---|
|
| 219 |
+
| `token_embedding` | 12,865,792 | 50,257 x 256 |
|
| 220 |
+
| `position_embedding` | 32,768 | 128 x 256 |
|
| 221 |
+
| 1 Transformer block | 789,760 | LN + attn + FFN |
|
| 222 |
+
| 4 Transformer blocks | 3,159,040 | total body |
|
| 223 |
+
| `ln_f` + `lm_head` | 12,916,561 | language head |
|
| 224 |
+
|
| 225 |
+
**Total: ~28.97M.** Most parameters reside in the embedding/head due to the large vocabulary; the actual reasoning capacity (transformer body) is ~3.1M.
|
| 226 |
+
|
| 227 |
+
---
|
| 228 |
+
|
| 229 |
+
## Training details
|
| 230 |
+
|
| 231 |
+
| Metric | Value |
|
| 232 |
+
|---|---|
|
| 233 |
+
| Data | TinyStories (first 50,000 stories, ~11.1M tokens) |
|
| 234 |
+
| Training samples | 86,636 blocks x 128 tokens |
|
| 235 |
+
| `embed_dim` | 256 |
|
| 236 |
+
| `num_layers` | 4 |
|
| 237 |
+
| `max_seq_len` | 128 |
|
| 238 |
+
| Optimizer | AdamW, lr `3e-4` |
|
| 239 |
+
| Batch size | 24 |
|
| 240 |
+
| Epochs | 2 |
|
| 241 |
+
| Duration | Short training run on CPU |
|
| 242 |
+
|
| 243 |
+
---
|
| 244 |
+
|
| 245 |
+
## Limitations & Notes
|
| 246 |
+
|
| 247 |
+
- English only; produces nonsensical output for non-English input.
|
| 248 |
+
- 128-token context window; insufficient for tasks requiring long-range context.
|
| 249 |
+
- Due to its small size, the model does not perform logic, recall factual knowledge, or produce coherent long-form text.
|
| 250 |
+
- Requires `trust_remote_code=True` to run; the code is open for inspection in this repo's `models/` directory.
|
| 251 |
+
- No weight decay or other regularization was applied during training.
|
| 252 |
+
|
| 253 |
+
---
|
| 254 |
+
|
| 255 |
+
## License
|
| 256 |
+
|
| 257 |
+
MIT -- model weights and code are freely usable.
|
| 258 |
+
|
| 259 |
+
**HF Hub:** [huggingface.co/coderian/TinyGPT](https://huggingface.co/coderian/TinyGPT)
|
config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"TinyGPT"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "config.TinyGPTConfig",
|
| 7 |
+
"AutoModelForCausalLM": "tinygpt.TinyGPT"
|
| 8 |
+
},
|
| 9 |
+
"dtype": "float32",
|
| 10 |
+
"embed_dim": 256,
|
| 11 |
+
"max_seq_len": 128,
|
| 12 |
+
"model_type": "tinygpt",
|
| 13 |
+
"num_hidden_layers": 4,
|
| 14 |
+
"num_layers": 4,
|
| 15 |
+
"transformers_version": "5.17.0",
|
| 16 |
+
"vocab_size": 50257
|
| 17 |
+
}
|
config.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TinyGPTConfig(PretrainedConfig):
|
| 5 |
+
model_type = "tinygpt"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
vocab_size=50257,
|
| 10 |
+
embed_dim=256,
|
| 11 |
+
max_seq_len=128,
|
| 12 |
+
num_layers=4,
|
| 13 |
+
**kwargs,
|
| 14 |
+
):
|
| 15 |
+
super().__init__(**kwargs)
|
| 16 |
+
self.vocab_size = vocab_size
|
| 17 |
+
self.embed_dim = embed_dim
|
| 18 |
+
self.max_seq_len = max_seq_len
|
| 19 |
+
self.num_layers = num_layers
|
| 20 |
+
self.num_hidden_layers = num_layers
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
TinyGPTConfig.register_for_auto_class("AutoConfig")
|
generation_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"output_attentions": false,
|
| 4 |
+
"output_hidden_states": false,
|
| 5 |
+
"transformers_version": "5.17.0"
|
| 6 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:583e7a4409a4bb4d73798ecaef5ea474eec7eb5da19818b40b833949c55f0d2e
|
| 3 |
+
size 115904092
|
models/__init__.py
ADDED
|
File without changes
|
models/attention.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class CausalSelfAttention(nn.Module):
|
| 5 |
+
def __init__(self, embed_dim):
|
| 6 |
+
super().__init__()
|
| 7 |
+
|
| 8 |
+
self.embed_dim = embed_dim
|
| 9 |
+
|
| 10 |
+
# Query | Key | Value
|
| 11 |
+
self.query = nn.Linear(
|
| 12 |
+
embed_dim,
|
| 13 |
+
embed_dim
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
self.key = nn.Linear(
|
| 17 |
+
embed_dim,
|
| 18 |
+
embed_dim
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
self.value = nn.Linear(
|
| 22 |
+
embed_dim,
|
| 23 |
+
embed_dim
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
self.out = nn.Linear(embed_dim, embed_dim)
|
| 27 |
+
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
batch_size, seq_len, embed_dim = x.shape
|
| 30 |
+
|
| 31 |
+
Q = self.query(x)
|
| 32 |
+
K = self.key(x)
|
| 33 |
+
V = self.value(x)
|
| 34 |
+
|
| 35 |
+
scores = Q @ K.transpose(-2, -1)
|
| 36 |
+
|
| 37 |
+
scores = scores / (embed_dim ** 0.5)
|
| 38 |
+
|
| 39 |
+
# Causal Mask
|
| 40 |
+
mask = torch.triu(
|
| 41 |
+
torch.ones(seq_len, seq_len, device=x.device),
|
| 42 |
+
diagonal=1
|
| 43 |
+
).bool()
|
| 44 |
+
|
| 45 |
+
scores = scores.masked_fill(mask, float("-inf"))
|
| 46 |
+
|
| 47 |
+
attention_weight = torch.softmax(scores, dim=-1)
|
| 48 |
+
|
| 49 |
+
output = attention_weight @ V
|
| 50 |
+
|
| 51 |
+
output = self.out(output)
|
| 52 |
+
|
| 53 |
+
return output
|
| 54 |
+
|
models/config.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TinyGPTConfig(PretrainedConfig):
|
| 5 |
+
model_type = "tinygpt"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
vocab_size=50257,
|
| 10 |
+
embed_dim=256,
|
| 11 |
+
max_seq_len=128,
|
| 12 |
+
num_layers=4,
|
| 13 |
+
**kwargs,
|
| 14 |
+
):
|
| 15 |
+
super().__init__(**kwargs)
|
| 16 |
+
self.vocab_size = vocab_size
|
| 17 |
+
self.embed_dim = embed_dim
|
| 18 |
+
self.max_seq_len = max_seq_len
|
| 19 |
+
self.num_layers = num_layers
|
| 20 |
+
self.num_hidden_layers = num_layers
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
TinyGPTConfig.register_for_auto_class("AutoConfig")
|
models/tinygpt.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import PreTrainedModel, GenerationMixin
|
| 4 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 5 |
+
|
| 6 |
+
from models.config import TinyGPTConfig
|
| 7 |
+
from models.transformer_block import TransformerBlock
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TinyGPT(PreTrainedModel, GenerationMixin):
|
| 11 |
+
config_class = TinyGPTConfig
|
| 12 |
+
|
| 13 |
+
def __init__(self, config):
|
| 14 |
+
super().__init__(config)
|
| 15 |
+
self.config = config
|
| 16 |
+
|
| 17 |
+
self.token_embedding = nn.Embedding(
|
| 18 |
+
config.vocab_size,
|
| 19 |
+
config.embed_dim,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
self.position_embedding = nn.Embedding(
|
| 23 |
+
config.max_seq_len,
|
| 24 |
+
config.embed_dim,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
self.transformer_blocks = nn.ModuleList([
|
| 28 |
+
TransformerBlock(
|
| 29 |
+
config.embed_dim
|
| 30 |
+
)
|
| 31 |
+
for _ in range(config.num_layers)
|
| 32 |
+
])
|
| 33 |
+
|
| 34 |
+
self.ln_f = nn.LayerNorm(
|
| 35 |
+
config.embed_dim
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
self.lm_head = nn.Linear(
|
| 39 |
+
config.embed_dim,
|
| 40 |
+
config.vocab_size,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
self.post_init()
|
| 44 |
+
|
| 45 |
+
def forward(self, input_ids, **kwargs):
|
| 46 |
+
batch_size, seq_len = input_ids.shape
|
| 47 |
+
|
| 48 |
+
positions = torch.arange(
|
| 49 |
+
seq_len,
|
| 50 |
+
device=input_ids.device
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
token_emb = self.token_embedding(
|
| 54 |
+
input_ids
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
pos_emb = self.position_embedding(
|
| 58 |
+
positions
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
x = token_emb + pos_emb
|
| 62 |
+
|
| 63 |
+
for block in self.transformer_blocks:
|
| 64 |
+
x = block(x)
|
| 65 |
+
|
| 66 |
+
x = self.ln_f(x)
|
| 67 |
+
|
| 68 |
+
logits = self.lm_head(x)
|
| 69 |
+
|
| 70 |
+
return CausalLMOutput(logits=logits)
|
| 71 |
+
|
| 72 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 73 |
+
return {"input_ids": input_ids}
|
| 74 |
+
|
| 75 |
+
def _init_weights(self, module):
|
| 76 |
+
std = 0.02
|
| 77 |
+
|
| 78 |
+
if isinstance(module, nn.Linear):
|
| 79 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 80 |
+
if module.bias is not None:
|
| 81 |
+
module.bias.data.zero_()
|
| 82 |
+
|
| 83 |
+
elif isinstance(module, nn.Embedding):
|
| 84 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 85 |
+
|
| 86 |
+
elif isinstance(module, nn.LayerNorm):
|
| 87 |
+
module.bias.data.zero_()
|
| 88 |
+
module.weight.data.fill_(1.0)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
TinyGPT.register_for_auto_class("AutoModelForCausalLM")
|
models/transformer_block.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from models.attention import CausalSelfAttention
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
class TransformerBlock(nn.Module):
|
| 6 |
+
def __init__(self, embed_dim):
|
| 7 |
+
super().__init__()
|
| 8 |
+
|
| 9 |
+
self.ln1 = nn.LayerNorm(embed_dim)
|
| 10 |
+
|
| 11 |
+
self.attention = CausalSelfAttention(
|
| 12 |
+
embed_dim
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
self.ln2 = nn.LayerNorm(embed_dim)
|
| 16 |
+
|
| 17 |
+
# FFN
|
| 18 |
+
self.ffn = nn.Sequential(
|
| 19 |
+
nn.Linear(
|
| 20 |
+
in_features=embed_dim,
|
| 21 |
+
out_features=4*embed_dim
|
| 22 |
+
),
|
| 23 |
+
|
| 24 |
+
nn.GELU(),
|
| 25 |
+
|
| 26 |
+
nn.Linear(
|
| 27 |
+
in_features=4*embed_dim,
|
| 28 |
+
out_features=embed_dim
|
| 29 |
+
)
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def forward(self, x):
|
| 33 |
+
x = x + self.attention(
|
| 34 |
+
self.ln1(x)
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
x = x + self.ffn(
|
| 38 |
+
self.ln2(x)
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
return x
|
| 42 |
+
|
tinygpt.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import PreTrainedModel, GenerationMixin
|
| 4 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 5 |
+
|
| 6 |
+
from models.config import TinyGPTConfig
|
| 7 |
+
from models.transformer_block import TransformerBlock
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TinyGPT(PreTrainedModel, GenerationMixin):
|
| 11 |
+
config_class = TinyGPTConfig
|
| 12 |
+
|
| 13 |
+
def __init__(self, config):
|
| 14 |
+
super().__init__(config)
|
| 15 |
+
self.config = config
|
| 16 |
+
|
| 17 |
+
self.token_embedding = nn.Embedding(
|
| 18 |
+
config.vocab_size,
|
| 19 |
+
config.embed_dim,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
self.position_embedding = nn.Embedding(
|
| 23 |
+
config.max_seq_len,
|
| 24 |
+
config.embed_dim,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
self.transformer_blocks = nn.ModuleList([
|
| 28 |
+
TransformerBlock(
|
| 29 |
+
config.embed_dim
|
| 30 |
+
)
|
| 31 |
+
for _ in range(config.num_layers)
|
| 32 |
+
])
|
| 33 |
+
|
| 34 |
+
self.ln_f = nn.LayerNorm(
|
| 35 |
+
config.embed_dim
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
self.lm_head = nn.Linear(
|
| 39 |
+
config.embed_dim,
|
| 40 |
+
config.vocab_size,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
self.post_init()
|
| 44 |
+
|
| 45 |
+
def forward(self, input_ids, **kwargs):
|
| 46 |
+
batch_size, seq_len = input_ids.shape
|
| 47 |
+
|
| 48 |
+
positions = torch.arange(
|
| 49 |
+
seq_len,
|
| 50 |
+
device=input_ids.device
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
token_emb = self.token_embedding(
|
| 54 |
+
input_ids
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
pos_emb = self.position_embedding(
|
| 58 |
+
positions
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
x = token_emb + pos_emb
|
| 62 |
+
|
| 63 |
+
for block in self.transformer_blocks:
|
| 64 |
+
x = block(x)
|
| 65 |
+
|
| 66 |
+
x = self.ln_f(x)
|
| 67 |
+
|
| 68 |
+
logits = self.lm_head(x)
|
| 69 |
+
|
| 70 |
+
return CausalLMOutput(logits=logits)
|
| 71 |
+
|
| 72 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 73 |
+
return {"input_ids": input_ids}
|
| 74 |
+
|
| 75 |
+
def _init_weights(self, module):
|
| 76 |
+
std = 0.02
|
| 77 |
+
|
| 78 |
+
if isinstance(module, nn.Linear):
|
| 79 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 80 |
+
if module.bias is not None:
|
| 81 |
+
module.bias.data.zero_()
|
| 82 |
+
|
| 83 |
+
elif isinstance(module, nn.Embedding):
|
| 84 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 85 |
+
|
| 86 |
+
elif isinstance(module, nn.LayerNorm):
|
| 87 |
+
module.bias.data.zero_()
|
| 88 |
+
module.weight.data.fill_(1.0)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
TinyGPT.register_for_auto_class("AutoModelForCausalLM")
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": "<|endoftext|>",
|
| 5 |
+
"eos_token": "<|endoftext|>",
|
| 6 |
+
"errors": "replace",
|
| 7 |
+
"is_local": false,
|
| 8 |
+
"local_files_only": false,
|
| 9 |
+
"model_max_length": 1024,
|
| 10 |
+
"pad_token": null,
|
| 11 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 12 |
+
"unk_token": "<|endoftext|>"
|
| 13 |
+
}
|