Text Generation
Transformers
Safetensors
English
tiny_transformer
custom-code
causal-lm
from-scratch
custom_code
Instructions to use Mayuresh231/tiny-transformer-29m with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Mayuresh231/tiny-transformer-29m with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Mayuresh231/tiny-transformer-29m", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Mayuresh231/tiny-transformer-29m", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Mayuresh231/tiny-transformer-29m with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Mayuresh231/tiny-transformer-29m" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Mayuresh231/tiny-transformer-29m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Mayuresh231/tiny-transformer-29m
- SGLang
How to use Mayuresh231/tiny-transformer-29m 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 "Mayuresh231/tiny-transformer-29m" \ --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": "Mayuresh231/tiny-transformer-29m", "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 "Mayuresh231/tiny-transformer-29m" \ --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": "Mayuresh231/tiny-transformer-29m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Mayuresh231/tiny-transformer-29m with Docker Model Runner:
docker model run hf.co/Mayuresh231/tiny-transformer-29m
Upload folder using huggingface_hub
Browse files- LICENSE +21 -0
- README.md +88 -0
- config.json +32 -0
- configuration_tiny_transformer.py +65 -0
- export_manifest.json +11 -0
- generation_config.json +17 -0
- model.safetensors +3 -0
- modeling_tiny_transformer.py +202 -0
- samples/generation_config.json +25 -0
- samples/sample_01.txt +5 -0
- samples/sample_02.txt +5 -0
- samples/sample_03.txt +9 -0
- samples/sample_04.txt +5 -0
- samples/sample_05.txt +5 -0
- tokenizer.json +0 -0
- tokenizer_config.json +10 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Project contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
library_name: transformers
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
datasets:
|
| 8 |
+
- roneneldan/TinyStories
|
| 9 |
+
tags:
|
| 10 |
+
- custom-code
|
| 11 |
+
- causal-lm
|
| 12 |
+
- from-scratch
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# Tiny Transformer 29M — TinyStories
|
| 16 |
+
|
| 17 |
+
A 29,545,472-parameter decoder-only Transformer trained from scratch on 600,000
|
| 18 |
+
unique TinyStories examples. It uses a custom 4,096-token lowercase ByteLevel
|
| 19 |
+
BPE tokenizer and a 256-token context window.
|
| 20 |
+
|
| 21 |
+
## Load and generate
|
| 22 |
+
|
| 23 |
+
This repository contains custom model code. Review it, then opt in with
|
| 24 |
+
`trust_remote_code=True`:
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
import torch
|
| 28 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 29 |
+
|
| 30 |
+
model_id = "YOUR_USERNAME/tiny-transformer-29m"
|
| 31 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 32 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 33 |
+
model_id,
|
| 34 |
+
trust_remote_code=True,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
inputs = tokenizer("Once upon a time", return_tensors="pt")
|
| 38 |
+
torch.manual_seed(100)
|
| 39 |
+
output = model.generate(
|
| 40 |
+
**inputs,
|
| 41 |
+
max_new_tokens=200,
|
| 42 |
+
do_sample=True,
|
| 43 |
+
temperature=0.7,
|
| 44 |
+
top_k=50,
|
| 45 |
+
top_p=0.9,
|
| 46 |
+
repetition_penalty=1.08,
|
| 47 |
+
no_repeat_ngram_size=3,
|
| 48 |
+
)
|
| 49 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Architecture
|
| 53 |
+
|
| 54 |
+
| Setting | Value |
|
| 55 |
+
|---|---:|
|
| 56 |
+
| Parameters | 29,545,472 |
|
| 57 |
+
| Vocabulary | 4,096 ByteLevel BPE tokens |
|
| 58 |
+
| Context | 256 tokens |
|
| 59 |
+
| Hidden size | 512 |
|
| 60 |
+
| Layers | 8 |
|
| 61 |
+
| Attention heads | 8 × 64 dimensions |
|
| 62 |
+
| Feed-forward size | 2,048 |
|
| 63 |
+
| Dropout | 0.1 |
|
| 64 |
+
|
| 65 |
+
The output projection is not tied to the token embedding. The implementation
|
| 66 |
+
uses PyTorch scaled dot-product causal attention. Generation is compatible with
|
| 67 |
+
the Transformers API but does not use a KV cache, so it recomputes the active
|
| 68 |
+
context window for every new token.
|
| 69 |
+
|
| 70 |
+
## Training results
|
| 71 |
+
|
| 72 |
+
| Epoch | Train loss | Validation loss | Perplexity |
|
| 73 |
+
|---:|---:|---:|---:|
|
| 74 |
+
| 1 | 2.1191 | 1.7118 | 5.54 |
|
| 75 |
+
| 2 | 1.6595 | 1.5911 | 4.91 |
|
| 76 |
+
| 3 | 1.5568 | 1.5243 | 4.59 |
|
| 77 |
+
| 4 | **1.4971** | **1.4977** | **4.47** |
|
| 78 |
+
|
| 79 |
+
Training processed 547,749,888 token positions on an NVIDIA RTX 3050 Laptop GPU
|
| 80 |
+
with 6 GB VRAM. The completed epochs took 3h 9m 25s.
|
| 81 |
+
|
| 82 |
+
## Intended use and limitations
|
| 83 |
+
|
| 84 |
+
This is an educational small language model for studying tokenization,
|
| 85 |
+
attention, optimization, checkpointing, and generation. It is not an assistant
|
| 86 |
+
or a factual knowledge model. Outputs may be repetitive, contradictory, or
|
| 87 |
+
inherit encoding noise and other biases from TinyStories. Do not use it for
|
| 88 |
+
high-stakes decisions.
|
config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"TinyTransformerForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_probs_dropout_prob": 0.1,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_tiny_transformer.TinyTransformerConfig",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_tiny_transformer.TinyTransformerForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 2,
|
| 11 |
+
"context": 256,
|
| 12 |
+
"dim": 512,
|
| 13 |
+
"dropout": 0.1,
|
| 14 |
+
"dtype": "float32",
|
| 15 |
+
"eos_token_id": 3,
|
| 16 |
+
"ff_dim": 2048,
|
| 17 |
+
"heads": 8,
|
| 18 |
+
"hidden_dropout_prob": 0.1,
|
| 19 |
+
"hidden_size": 512,
|
| 20 |
+
"intermediate_size": 2048,
|
| 21 |
+
"layers": 8,
|
| 22 |
+
"max_position_embeddings": 256,
|
| 23 |
+
"model_type": "tiny_transformer",
|
| 24 |
+
"num_attention_heads": 8,
|
| 25 |
+
"num_hidden_layers": 8,
|
| 26 |
+
"pad_token_id": 0,
|
| 27 |
+
"tie_word_embeddings": false,
|
| 28 |
+
"transformers_version": "5.16.1",
|
| 29 |
+
"unk_token_id": 1,
|
| 30 |
+
"use_cache": false,
|
| 31 |
+
"vocab_size": 4096
|
| 32 |
+
}
|
configuration_tiny_transformer.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from transformers import PretrainedConfig
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TinyTransformerConfig(PretrainedConfig):
|
| 7 |
+
"""Hugging Face configuration for the 29.5M TinyStories Transformer."""
|
| 8 |
+
|
| 9 |
+
model_type = "tiny_transformer"
|
| 10 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 11 |
+
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
vocab_size: int = 4_096,
|
| 15 |
+
context: int = 256,
|
| 16 |
+
dim: int = 512,
|
| 17 |
+
heads: int = 8,
|
| 18 |
+
layers: int = 8,
|
| 19 |
+
ff_dim: int = 2_048,
|
| 20 |
+
dropout: float = 0.1,
|
| 21 |
+
bos_token_id: int = 2,
|
| 22 |
+
eos_token_id: int = 3,
|
| 23 |
+
pad_token_id: int = 0,
|
| 24 |
+
unk_token_id: int = 1,
|
| 25 |
+
tie_word_embeddings: bool = False,
|
| 26 |
+
use_cache: bool = False,
|
| 27 |
+
**kwargs,
|
| 28 |
+
) -> None:
|
| 29 |
+
if vocab_size < 300:
|
| 30 |
+
raise ValueError("vocab_size must leave room for the byte alphabet")
|
| 31 |
+
if context < 2:
|
| 32 |
+
raise ValueError("context must be at least 2")
|
| 33 |
+
if dim % heads:
|
| 34 |
+
raise ValueError("dim must be divisible by heads")
|
| 35 |
+
if layers < 1 or ff_dim < dim:
|
| 36 |
+
raise ValueError("layers and ff_dim are invalid")
|
| 37 |
+
if not 0.0 <= dropout < 1.0:
|
| 38 |
+
raise ValueError("dropout must be in [0, 1)")
|
| 39 |
+
|
| 40 |
+
self.vocab_size = vocab_size
|
| 41 |
+
self.context = context
|
| 42 |
+
self.dim = dim
|
| 43 |
+
self.heads = heads
|
| 44 |
+
self.layers = layers
|
| 45 |
+
self.ff_dim = ff_dim
|
| 46 |
+
self.dropout = dropout
|
| 47 |
+
|
| 48 |
+
# Standard aliases let generic Hugging Face tooling inspect the model.
|
| 49 |
+
self.max_position_embeddings = context
|
| 50 |
+
self.hidden_size = dim
|
| 51 |
+
self.num_attention_heads = heads
|
| 52 |
+
self.num_hidden_layers = layers
|
| 53 |
+
self.intermediate_size = ff_dim
|
| 54 |
+
self.hidden_dropout_prob = dropout
|
| 55 |
+
self.attention_probs_dropout_prob = dropout
|
| 56 |
+
self.use_cache = use_cache
|
| 57 |
+
|
| 58 |
+
super().__init__(
|
| 59 |
+
bos_token_id=bos_token_id,
|
| 60 |
+
eos_token_id=eos_token_id,
|
| 61 |
+
pad_token_id=pad_token_id,
|
| 62 |
+
unk_token_id=unk_token_id,
|
| 63 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 64 |
+
**kwargs,
|
| 65 |
+
)
|
export_manifest.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_id": "YOUR_USERNAME/tiny-transformer-29m",
|
| 3 |
+
"parameter_count": 29545472,
|
| 4 |
+
"source_checkpoint": "artifacts\\tinystories_600k\\checkpoint_best.pt",
|
| 5 |
+
"source_checkpoint_sha256": "3e93365868f2a63d627396b14053b445defafc0e1bab7d92ad1197c628010ae0",
|
| 6 |
+
"source_epoch": 4,
|
| 7 |
+
"source_validation_loss": 1.4976564651141033,
|
| 8 |
+
"tokenizer_sha256": "1552a7af0ee1f40908c0ff49b0726526fc1cc2c0f775bbd36946725d33b6e141",
|
| 9 |
+
"weights_file": "model.safetensors",
|
| 10 |
+
"weights_sha256": "a27ee52b876b5a89ba6620d438415fc6b94f43273e064cccb62b82594a857d91"
|
| 11 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 2,
|
| 4 |
+
"do_sample": true,
|
| 5 |
+
"eos_token_id": 3,
|
| 6 |
+
"max_new_tokens": 300,
|
| 7 |
+
"no_repeat_ngram_size": 3,
|
| 8 |
+
"output_attentions": false,
|
| 9 |
+
"output_hidden_states": false,
|
| 10 |
+
"pad_token_id": 0,
|
| 11 |
+
"repetition_penalty": 1.08,
|
| 12 |
+
"temperature": 0.7,
|
| 13 |
+
"top_k": 50,
|
| 14 |
+
"top_p": 0.9,
|
| 15 |
+
"transformers_version": "5.16.1",
|
| 16 |
+
"use_cache": false
|
| 17 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a27ee52b876b5a89ba6620d438415fc6b94f43273e064cccb62b82594a857d91
|
| 3 |
+
size 118192048
|
modeling_tiny_transformer.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from transformers import PreTrainedModel
|
| 10 |
+
from transformers.generation import GenerationMixin
|
| 11 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 12 |
+
|
| 13 |
+
from .configuration_tiny_transformer import TinyTransformerConfig
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CausalSelfAttention(nn.Module):
|
| 17 |
+
def __init__(self, config: TinyTransformerConfig):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.heads = config.heads
|
| 20 |
+
self.head_dim = config.dim // config.heads
|
| 21 |
+
self.dropout = config.dropout
|
| 22 |
+
self.qkv = nn.Linear(config.dim, 3 * config.dim)
|
| 23 |
+
self.output = nn.Linear(config.dim, config.dim)
|
| 24 |
+
self.residual_dropout = nn.Dropout(config.dropout)
|
| 25 |
+
|
| 26 |
+
def forward(self, x: Tensor, attention_mask: Tensor | None = None) -> Tensor:
|
| 27 |
+
batch, steps, width = x.shape
|
| 28 |
+
qkv = self.qkv(x).view(batch, steps, 3, self.heads, self.head_dim)
|
| 29 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0)
|
| 30 |
+
|
| 31 |
+
if attention_mask is None:
|
| 32 |
+
attended = F.scaled_dot_product_attention(
|
| 33 |
+
q,
|
| 34 |
+
k,
|
| 35 |
+
v,
|
| 36 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 37 |
+
is_causal=True,
|
| 38 |
+
)
|
| 39 |
+
else:
|
| 40 |
+
causal = torch.ones(
|
| 41 |
+
(steps, steps), dtype=torch.bool, device=x.device
|
| 42 |
+
).tril()
|
| 43 |
+
valid_keys = attention_mask[:, None, None, :].to(torch.bool)
|
| 44 |
+
combined_mask = causal[None, None, :, :] & valid_keys
|
| 45 |
+
attended = F.scaled_dot_product_attention(
|
| 46 |
+
q,
|
| 47 |
+
k,
|
| 48 |
+
v,
|
| 49 |
+
attn_mask=combined_mask,
|
| 50 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 51 |
+
is_causal=False,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
attended = attended.transpose(1, 2).contiguous().view(batch, steps, width)
|
| 55 |
+
return self.residual_dropout(self.output(attended))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class FeedForward(nn.Module):
|
| 59 |
+
def __init__(self, config: TinyTransformerConfig):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.input = nn.Linear(config.dim, config.ff_dim)
|
| 62 |
+
self.output = nn.Linear(config.ff_dim, config.dim)
|
| 63 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 64 |
+
|
| 65 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 66 |
+
return self.dropout(self.output(F.gelu(self.input(x))))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class TransformerBlock(nn.Module):
|
| 70 |
+
def __init__(self, config: TinyTransformerConfig):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.attention_norm = nn.LayerNorm(config.dim)
|
| 73 |
+
self.attention = CausalSelfAttention(config)
|
| 74 |
+
self.feed_forward_norm = nn.LayerNorm(config.dim)
|
| 75 |
+
self.feed_forward = FeedForward(config)
|
| 76 |
+
|
| 77 |
+
def forward(self, x: Tensor, attention_mask: Tensor | None = None) -> Tensor:
|
| 78 |
+
x = x + self.attention(self.attention_norm(x), attention_mask)
|
| 79 |
+
return x + self.feed_forward(self.feed_forward_norm(x))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class TinyTransformerForCausalLM(PreTrainedModel, GenerationMixin):
|
| 83 |
+
"""Decoder-only TinyStories model compatible with AutoModelForCausalLM."""
|
| 84 |
+
|
| 85 |
+
config_class = TinyTransformerConfig
|
| 86 |
+
model_type = "tiny_transformer"
|
| 87 |
+
base_model_prefix = "tiny_transformer"
|
| 88 |
+
main_input_name = "input_ids"
|
| 89 |
+
_no_split_modules = ["TransformerBlock"]
|
| 90 |
+
_supports_sdpa = True
|
| 91 |
+
|
| 92 |
+
def __init__(self, config: TinyTransformerConfig):
|
| 93 |
+
super().__init__(config)
|
| 94 |
+
self.token_embedding = nn.Embedding(config.vocab_size, config.dim)
|
| 95 |
+
self.position_embedding = nn.Embedding(config.context, config.dim)
|
| 96 |
+
self.embedding_dropout = nn.Dropout(config.dropout)
|
| 97 |
+
self.blocks = nn.ModuleList(
|
| 98 |
+
[TransformerBlock(config) for _ in range(config.layers)]
|
| 99 |
+
)
|
| 100 |
+
self.final_norm = nn.LayerNorm(config.dim)
|
| 101 |
+
self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False)
|
| 102 |
+
self.post_init()
|
| 103 |
+
|
| 104 |
+
residual_std = 0.02 / math.sqrt(2 * config.layers)
|
| 105 |
+
for block in self.blocks:
|
| 106 |
+
nn.init.normal_(block.attention.output.weight, mean=0.0, std=residual_std)
|
| 107 |
+
nn.init.normal_(block.feed_forward.output.weight, mean=0.0, std=residual_std)
|
| 108 |
+
|
| 109 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 110 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 111 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 112 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 113 |
+
nn.init.zeros_(module.bias)
|
| 114 |
+
|
| 115 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 116 |
+
return self.token_embedding
|
| 117 |
+
|
| 118 |
+
def set_input_embeddings(self, value: nn.Embedding) -> None:
|
| 119 |
+
self.token_embedding = value
|
| 120 |
+
|
| 121 |
+
def get_output_embeddings(self) -> nn.Linear:
|
| 122 |
+
return self.lm_head
|
| 123 |
+
|
| 124 |
+
def set_output_embeddings(self, value: nn.Linear) -> None:
|
| 125 |
+
self.lm_head = value
|
| 126 |
+
|
| 127 |
+
def forward(
|
| 128 |
+
self,
|
| 129 |
+
input_ids: Tensor,
|
| 130 |
+
attention_mask: Tensor | None = None,
|
| 131 |
+
position_ids: Tensor | None = None,
|
| 132 |
+
labels: Tensor | None = None,
|
| 133 |
+
output_hidden_states: bool | None = None,
|
| 134 |
+
return_dict: bool | None = None,
|
| 135 |
+
**_: Any,
|
| 136 |
+
) -> CausalLMOutput | tuple[Tensor, ...]:
|
| 137 |
+
_, steps = input_ids.shape
|
| 138 |
+
if steps > self.config.context:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
f"sequence has {steps} tokens; context limit is {self.config.context}"
|
| 141 |
+
)
|
| 142 |
+
if position_ids is None:
|
| 143 |
+
if attention_mask is None:
|
| 144 |
+
position_ids = torch.arange(steps, device=input_ids.device)[None, :]
|
| 145 |
+
else:
|
| 146 |
+
position_ids = attention_mask.long().cumsum(dim=-1) - 1
|
| 147 |
+
position_ids.masked_fill_(attention_mask == 0, 0)
|
| 148 |
+
|
| 149 |
+
x = self.embedding_dropout(
|
| 150 |
+
self.token_embedding(input_ids) + self.position_embedding(position_ids)
|
| 151 |
+
)
|
| 152 |
+
collect_hidden = bool(
|
| 153 |
+
output_hidden_states
|
| 154 |
+
if output_hidden_states is not None
|
| 155 |
+
else self.config.output_hidden_states
|
| 156 |
+
)
|
| 157 |
+
hidden_states: list[Tensor] | None = [x] if collect_hidden else None
|
| 158 |
+
for block in self.blocks:
|
| 159 |
+
x = block(x, attention_mask)
|
| 160 |
+
if hidden_states is not None:
|
| 161 |
+
hidden_states.append(x)
|
| 162 |
+
logits = self.lm_head(self.final_norm(x))
|
| 163 |
+
|
| 164 |
+
loss = None
|
| 165 |
+
if labels is not None:
|
| 166 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 167 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 168 |
+
loss = F.cross_entropy(
|
| 169 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 170 |
+
shift_labels.view(-1),
|
| 171 |
+
ignore_index=-100,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
use_return_dict = (
|
| 175 |
+
return_dict if return_dict is not None else self.config.return_dict
|
| 176 |
+
)
|
| 177 |
+
if not use_return_dict:
|
| 178 |
+
result: tuple[Tensor, ...] = (logits,)
|
| 179 |
+
if hidden_states is not None:
|
| 180 |
+
result += (tuple(hidden_states),) # type: ignore[assignment]
|
| 181 |
+
return ((loss,) + result) if loss is not None else result
|
| 182 |
+
return CausalLMOutput(
|
| 183 |
+
loss=loss,
|
| 184 |
+
logits=logits,
|
| 185 |
+
hidden_states=tuple(hidden_states) if hidden_states is not None else None,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def prepare_inputs_for_generation(
|
| 189 |
+
self,
|
| 190 |
+
input_ids: Tensor,
|
| 191 |
+
attention_mask: Tensor | None = None,
|
| 192 |
+
**_: Any,
|
| 193 |
+
) -> dict[str, Tensor | bool | None]:
|
| 194 |
+
if input_ids.size(1) > self.config.context:
|
| 195 |
+
input_ids = input_ids[:, -self.config.context :]
|
| 196 |
+
if attention_mask is not None:
|
| 197 |
+
attention_mask = attention_mask[:, -self.config.context :]
|
| 198 |
+
return {
|
| 199 |
+
"input_ids": input_ids,
|
| 200 |
+
"attention_mask": attention_mask,
|
| 201 |
+
"use_cache": False,
|
| 202 |
+
}
|
samples/generation_config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": "artifacts\\tinystories_600k\\checkpoint_best.pt",
|
| 3 |
+
"checkpoint_epoch": 4,
|
| 4 |
+
"prompt": "Once upon a time",
|
| 5 |
+
"count": 5,
|
| 6 |
+
"accepted_seeds": [
|
| 7 |
+
100,
|
| 8 |
+
103,
|
| 9 |
+
104,
|
| 10 |
+
106,
|
| 11 |
+
107
|
| 12 |
+
],
|
| 13 |
+
"rejected_non_ascii_seeds": [
|
| 14 |
+
101,
|
| 15 |
+
102,
|
| 16 |
+
105
|
| 17 |
+
],
|
| 18 |
+
"selection_rule": "first five seeds whose decoded output is ASCII",
|
| 19 |
+
"max_new_tokens": 300,
|
| 20 |
+
"temperature": 0.7,
|
| 21 |
+
"top_k": 50,
|
| 22 |
+
"top_p": 0.9,
|
| 23 |
+
"repetition_penalty": 1.08,
|
| 24 |
+
"no_repeat_ngram": 3
|
| 25 |
+
}
|
samples/sample_01.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
once upon a time, there was a little girl named lily. she loved to play outside in the sun. one day, she saw a big tree with lots of leaves. she wanted to climb it, but her mom said no because it was too dangerous.
|
| 2 |
+
|
| 3 |
+
lily didn't listen and climbed the tree anyway. she felt very happy and proud of herself for climbing so high. suddenly, she heard a loud noise and saw a bird flying towards her. she got scared and started to cry.
|
| 4 |
+
|
| 5 |
+
her mom came outside and asked what happened. lily told her about the bird and how she climbed the big tree. her mom hugged her and said it was okay. she reminded her that it's important to listen to your parents and not climb things that can hurt you.
|
samples/sample_02.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
once upon a time, there was a little boy named timmy. timmy loved to play outside in the rain. he would jump and splash around with his toys. one day, timmy's mom told him they were going on a trip to the beach. timmy was so excited!
|
| 2 |
+
|
| 3 |
+
when they got to the hotel, timmy saw a man who looked sad. timmy asked the man why he was sad. the man said he lost his favorite toy car. timmy wanted to help the man find it.
|
| 4 |
+
|
| 5 |
+
they searched and searched until they found the toy car under a tree. the boy was so happy and thanked timmy for helping him. timmy felt proud that he could help someone in need.
|
samples/sample_03.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
once upon a time, there was a little girl named lily. she loved to play outside and run around in the grass. one day, she found a shiny penny on the ground. she picked it up and showed it to her mom.
|
| 2 |
+
|
| 3 |
+
"mommy, look what i found!" said lily.
|
| 4 |
+
|
| 5 |
+
her mom looked at the penny and said, "that's a lucky penny, lily. but be careful not to lose it."
|
| 6 |
+
|
| 7 |
+
lily nodded and continued to play with her friends. she had so much fun playing tag and hide-and-seek with her new lucky penny.
|
| 8 |
+
|
| 9 |
+
when it was time for dinner, lily went inside and told her mom about her lucky penny and how she found it. her mom smiled and said it was a lucky day for lily to find something special.
|
samples/sample_04.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
once upon a time, there was a boy named timmy. timmy loved to play with his toy cars and trucks. one day, timmy's mom asked him to help her clean up the house. timmy didn't want to do it because he thought he wanted to play. but then, his mom said, "if you clean up, you can play with your trucks again later."
|
| 2 |
+
|
| 3 |
+
timmy was sad because he really wanted to go outside and play with trucks. but his mom explained that if he cleaned up, he could have a new toy truck. timmy started to clean up his toys and put them away. when he was done, he felt proud of himself for doing a good job.
|
| 4 |
+
|
| 5 |
+
from that day on, timmy made sure to always keep his room tidy so he wouldn't get bored again. and every time he played with his trucks, he remembered how much fun he had playing with his toys.
|
samples/sample_05.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
once upon a time, there was a boy named timmy. he loved to play outside and look at the sky. one day, he saw a big, scary monster in his backyard. he was so scared that he ran inside to tell his mom.
|
| 2 |
+
|
| 3 |
+
his mom asked him what was wrong and he said he saw the monster in the backyard. his mom told him not to worry and that they would find the monster together. they went outside and looked for the monster. after a while, they found it hiding behind a bush.
|
| 4 |
+
|
| 5 |
+
timmy was so happy to have his monster back and he hugged it tightly. but then, he accidentally stepped on a sharp rock and it hurt his foot. he cried and cried until his mom came to help him. she took his hand and they went inside to get some ice cream. timmy learned that sometimes things can be scary, but they can be fixed.
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<bos>",
|
| 4 |
+
"eos_token": "<eos>",
|
| 5 |
+
"model_max_length": 256,
|
| 6 |
+
"pad_token": "<pad>",
|
| 7 |
+
"padding_side": "left",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "<unk>"
|
| 10 |
+
}
|