README.md DELETED
@@ -1,318 +0,0 @@
1
- ---
2
- license: mit
3
- language:
4
- - en
5
- library_name: transformers
6
- pipeline_tag: text-generation
7
- tags:
8
- - tinyllm
9
- - transformer
10
- - causal-lm
11
- - tinystories
12
- - storytelling
13
- - pytorch
14
- - small-language-model
15
- - from-scratch
16
- datasets:
17
- - roneneldan/TinyStories
18
- ---
19
-
20
- # TinyStories-17M
21
-
22
- **TinyStories-17M** is a **17.2 million parameter** decoder-only Transformer trained **entirely from scratch** for children's story generation.
23
-
24
- The project explores how far a modern Small Language Model (SLM) can be pushed using high-quality synthetic data, an efficient Transformer architecture, and careful training. Despite its compact size, the model is capable of generating coherent, grammatically correct, multi-paragraph children's stories while following a wide variety of prompts.
25
-
26
- ---
27
- ## References
28
-
29
- This project is inspired by the TinyStories paper:
30
-
31
- **TinyStories: How Small Can Language Models Be and Still Speak Coherent English?**
32
-
33
- Ronen Eldan, Yuanzhi Li (2023)
34
-
35
- Paper: https://arxiv.org/abs/2305.07759
36
-
37
- Dataset: https://huggingface.co/datasets/roneneldan/TinyStories
38
-
39
- # Highlights
40
-
41
- - Trained **from scratch**
42
- - **17.2M parameters**
43
- - Trained on **2.1 million** TinyStories-style synthetic stories
44
- - Modern LLaMA-style architecture
45
- - Rotary Position Embeddings (RoPE)
46
- - RMSNorm
47
- - SwiGLU Feed Forward Network
48
- - PyTorch Scaled Dot Product Attention (Flash Attention compatible)
49
- - Tied Input & Output Embeddings
50
- - Fully compatible with Hugging Face Transformers
51
-
52
- ---
53
-
54
- # Model Architecture
55
-
56
- | Property | Value |
57
- |-----------|------:|
58
- | Architecture | Decoder-only Transformer |
59
- | Parameters | **17,234,304** |
60
- | Layers | 8 |
61
- | Hidden Size | 384 |
62
- | Attention Heads | 6 |
63
- | Feed Forward Size | 1024 |
64
- | Context Length | 512 |
65
- | Vocabulary Size | 8000 |
66
- | Positional Encoding | Rotary Embeddings (RoPE) |
67
- | Activation | SwiGLU |
68
- | Normalization | RMSNorm |
69
- | Weight Tying | Yes |
70
-
71
- ---
72
-
73
- # Training
74
-
75
- The model was trained **from scratch** using next-token prediction on a synthetic TinyStories-style dataset.
76
-
77
- ### Training Configuration
78
-
79
- | Setting | Value |
80
- |---------|------:|
81
- | Optimizer | AdamW |
82
- | Precision | BF16 Mixed Precision |
83
- | Learning Rate | 3e-4 |
84
- | Weight Decay | 0.1 |
85
- | Epochs | 8 |
86
- | Batch Size | 70 |
87
- | Context Length | 512 |
88
- | Vocabulary | 8000 |
89
-
90
- Training was performed using PyTorch with Automatic Mixed Precision (AMP) and a cosine learning rate schedule.
91
-
92
- ---
93
-
94
- # Dataset
95
-
96
- The model was trained on approximately **2.1 million** synthetic English children's stories inspired by the TinyStories dataset.
97
-
98
- The dataset focuses on:
99
-
100
- - Simple English
101
- - Short coherent narratives
102
- - Moral lessons
103
- - Everyday situations
104
- - Dialogues
105
- - Fantasy adventures
106
- - Animal stories
107
- - Child-friendly vocabulary
108
-
109
- ---
110
-
111
- # Intended Use
112
-
113
- TinyStories-17M is intended for:
114
-
115
- - Story generation
116
- - Small Language Model research
117
- - Educational projects
118
- - Transformer architecture experiments
119
- - Learning how decoder-only LLMs work
120
- - Efficient inference research
121
-
122
- ---
123
-
124
- # Evaluation
125
-
126
- The model was evaluated using a combination of:
127
-
128
- - Validation loss during training
129
- - Manual inspection of generated stories
130
- - LLM-assisted qualitative evaluation using ChatGPT-5
131
-
132
- Evaluation focused on:
133
-
134
- - Grammar
135
- - Story coherence
136
- - Prompt following
137
- - Creativity
138
- - Character consistency
139
- - Repetition
140
- - Overall story quality
141
-
142
- ## Qualitative Assessment
143
-
144
- | Category | Score |
145
- |-----------|------:|
146
- | Grammar | **9.7 / 10** |
147
- | Story Coherence | **8.7 / 10** |
148
- | Character Consistency | **8.6 / 10** |
149
- | Creativity | **8.1 / 10** |
150
- | Repetition Resistance | **8.0 / 10** |
151
- | Overall Story Quality | **8.62 / 10** |
152
-
153
- > **Note:** These scores are qualitative assessments based on manual inspection and LLM-assisted evaluation. They are intended to provide an approximate indication of the model's strengths and limitations rather than standardized benchmark results.
154
-
155
- ---
156
-
157
- # Generation Examples
158
-
159
- The following examples are **actual generations** produced by TinyStories-17M.
160
-
161
- ---
162
-
163
- ## Example 1
164
-
165
- ### Prompt
166
-
167
- ```text
168
- Once upon a time
169
- ```
170
-
171
- ### Generation
172
-
173
- ```text
174
- there was a little girl who was very curious. One day she decided to
175
- explore the woods and take a look around. As she walked, the little
176
- girl heard some strange noises coming from behind some trees.She
177
- stopped and looked around but couldn't see anything. Suddenly, a
178
- voice said, "Help me!" The little girl was scared but she asked,
179
- "Who are you?" The voice replied, "I am a giant. I need to tell you
180
- that you must leave these woods and not come back." The little girl
181
- knew she had to do something...
182
- ```
183
-
184
- ---
185
-
186
- ## Example 2
187
-
188
- ### Prompt
189
-
190
- ```text
191
- Ben discovered an old compass hidden inside his grandfather's attic.
192
- ```
193
-
194
- ### Generation
195
-
196
- ```text
197
- He decided to explore the attic, but it was very dark and scary. He was
198
- scared, but he was determined to find out what was behind the boxes. He
199
- opened one of the boxes and found a heavy chest. He tried to lift it,
200
- but it was too heavy. He wondered what could be inside. Suddenly, he
201
- heard a mysterious voice introducing itself as the spirit of the attic,
202
- encouraging Ben to continue exploring and discover new adventures...
203
- ```
204
-
205
- ---
206
-
207
- ## Example 3
208
-
209
- ### Prompt
210
-
211
- ```text
212
- A lonely dragon met a tiny mouse for the first time.
213
- ```
214
-
215
- ### Generation
216
-
217
- ```text
218
- The dragon wanted to play with the mouse, but the mouse was scared and ran
219
- away. Hoping to become friends, the dragon searched for the tiny mouse
220
- throughout the forest. Soon a misunderstanding turned into an exciting
221
- chase, and both of them learned that first impressions are not always true...
222
- ```
223
-
224
- ---
225
-
226
- > **Note:** The examples above are intentionally truncated for brevity. The model continues generating complete children's stories beyond these excerpts.
227
-
228
- ---
229
-
230
- # Usage
231
-
232
- ```python
233
- from transformers import AutoTokenizer, AutoModelForCausalLM
234
-
235
- tokenizer = AutoTokenizer.from_pretrained(
236
- "kaushik-harsh-99/TinyStories-17M",
237
- trust_remote_code=True,
238
- )
239
-
240
- model = AutoModelForCausalLM.from_pretrained(
241
- "kaushik-harsh-99/TinyStories-17M",
242
- trust_remote_code=True,
243
- )
244
-
245
- prompt = "Once upon a time"
246
-
247
- inputs = tokenizer(prompt, return_tensors="pt")
248
-
249
- outputs = model.generate(
250
- **inputs,
251
- max_new_tokens=200,
252
- temperature=0.8,
253
- top_p=0.95,
254
- do_sample=True,
255
- )
256
-
257
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
258
- ```
259
-
260
- ---
261
-
262
- # Repository Structure
263
-
264
- ```text
265
- model.safetensors
266
- config.json
267
- generation_config.json
268
-
269
- configuration_tiny.py
270
- modeling_tiny.py
271
- __init__.py
272
-
273
- tokenizer.json
274
- tokenizer.model
275
- tokenizer_config.json
276
- special_tokens_map.json
277
-
278
- README.md
279
- LICENSE
280
- ```
281
-
282
- ---
283
-
284
- # Known Limitations
285
-
286
- As a **17M parameter** language model, TinyStories-17M has several limitations:
287
-
288
- - May become repetitive during long generations.
289
- - Limited world knowledge.
290
- - Occasionally produces repetitive dialogue.
291
- - Sometimes struggles with uncommon names or complex entities.
292
- - Optimized specifically for children's storytelling rather than general-purpose language tasks.
293
-
294
- ---
295
-
296
- # Future Work
297
-
298
- The next version of this project focuses on improving both the dataset and training methodology.
299
-
300
- Planned improvements include:
301
-
302
- - Training on approximately **3.7 million** curated stories.
303
- - Greater diversity of character names and story settings.
304
- - Continued pretraining from the current checkpoint.
305
- - Larger effective batch size using gradient accumulation.
306
- - Longer training schedules.
307
- - Improved tokenizer.
308
- - Architecture and efficiency experiments.
309
-
310
- ---
311
-
312
- # Acknowledgements
313
-
314
- This project was inspired by:
315
-
316
- - TinyStories
317
-
318
- Special thanks to the open-source AI community for making efficient language model research accessible.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
__init__.py DELETED
@@ -1,2 +0,0 @@
1
- from .configuration_tiny import TinyConfig
2
- from .modeling_tiny import TinyModel, TinyForCausalLM
 
 
 
config.json DELETED
@@ -1,25 +0,0 @@
1
- {
2
- "architectures": [
3
- "TinyForCausalLM"
4
- ],
5
- "model_type": "tiny",
6
- "auto_map": {
7
- "AutoConfig": "configuration_tiny.TinyConfig",
8
- "AutoModel": "modeling_tiny.TinyModel",
9
- "AutoModelForCausalLM": "modeling_tiny.TinyForCausalLM"
10
- },
11
- "vocab_size": 8000,
12
- "hidden_size": 384,
13
- "intermediate_size": 1024,
14
- "num_hidden_layers": 8,
15
- "num_attention_heads": 6,
16
- "max_position_embeddings": 512,
17
- "rms_norm_eps": 1e-05,
18
- "rope_theta": 10000.0,
19
- "tie_word_embeddings": true,
20
- "bos_token_id": 2,
21
- "eos_token_id": 3,
22
- "pad_token_id": 0,
23
- "torch_dtype": "float32",
24
- "transformers_version": "4.57.0"
25
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
configuration_tiny.py DELETED
@@ -1,62 +0,0 @@
1
- from transformers.configuration_utils import PretrainedConfig
2
-
3
-
4
- class TinyConfig(PretrainedConfig):
5
- """
6
- Configuration class for TinyStories Transformer.
7
- """
8
-
9
- model_type = "tiny"
10
-
11
- def __init__(
12
- self,
13
- vocab_size=8000,
14
- hidden_size=384,
15
- intermediate_size=1024,
16
- num_hidden_layers=8,
17
- num_attention_heads=6,
18
- max_position_embeddings=512,
19
- rms_norm_eps=1e-5,
20
- rope_theta=10000.0,
21
- tie_word_embeddings=True,
22
- bos_token_id=2,
23
- eos_token_id=3,
24
- pad_token_id=0,
25
- initializer_range=0.02,
26
- hidden_dropout=0.0,
27
- attention_dropout=0.0,
28
- **kwargs,
29
- ):
30
- super().__init__(
31
- bos_token_id=bos_token_id,
32
- eos_token_id=eos_token_id,
33
- pad_token_id=pad_token_id,
34
- tie_word_embeddings=tie_word_embeddings,
35
- **kwargs,
36
- )
37
-
38
- self.vocab_size = vocab_size
39
-
40
- self.hidden_size = hidden_size
41
-
42
- self.intermediate_size = intermediate_size
43
-
44
- self.num_hidden_layers = num_hidden_layers
45
-
46
- self.num_attention_heads = num_attention_heads
47
-
48
- self.max_position_embeddings = max_position_embeddings
49
-
50
- self.rms_norm_eps = rms_norm_eps
51
-
52
- self.rope_theta = rope_theta
53
-
54
- self.initializer_range = initializer_range
55
-
56
- self.hidden_dropout = hidden_dropout
57
-
58
- self.attention_dropout = attention_dropout
59
-
60
- @property
61
- def head_dim(self):
62
- return self.hidden_size // self.num_attention_heads
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
generation_config.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "bos_token_id": 2,
3
- "eos_token_id": 3,
4
- "pad_token_id": 0,
5
- "do_sample": true,
6
- "temperature": 0.8,
7
- "top_p": 0.95,
8
- "top_k": 50
9
- }
 
 
 
 
 
 
 
 
 
 
model.safetensors DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:fced437532fcc4308c7904b1951a60d9043cf66d5afc14c91941ad2df13520db
3
- size 68944576
 
 
 
 
modeling_tiny.py DELETED
@@ -1,446 +0,0 @@
1
- import math
2
- import sys
3
- from typing import Optional, Tuple, Union
4
-
5
- # Monkeypatch safetensors to handle None/missing metadata which crashes transformers
6
- try:
7
- import safetensors
8
- original_safe_open = safetensors.safe_open
9
-
10
- class SafeOpenWrapper:
11
- def __init__(self, original_obj):
12
- self.original_obj = original_obj
13
-
14
- def __enter__(self):
15
- self.original_obj.__enter__()
16
- return self
17
-
18
- def __exit__(self, exc_type, exc_val, exc_tb):
19
- return self.original_obj.__exit__(exc_type, exc_val, exc_tb)
20
-
21
- def metadata(self):
22
- meta = self.original_obj.metadata()
23
- if meta is None:
24
- return {"format": "pt"}
25
- return meta
26
-
27
- def __getattr__(self, name):
28
- return getattr(self.original_obj, name)
29
-
30
- def patched_safe_open(*args, **kwargs):
31
- f = original_safe_open(*args, **kwargs)
32
- return SafeOpenWrapper(f)
33
-
34
- safetensors.safe_open = patched_safe_open
35
-
36
- if "transformers.modeling_utils" in sys.modules:
37
- import transformers.modeling_utils
38
- transformers.modeling_utils.safe_open = patched_safe_open
39
- except Exception:
40
- pass
41
-
42
-
43
- import torch
44
- import torch.nn as nn
45
- import torch.nn.functional as F
46
-
47
- from transformers import PreTrainedModel
48
- from transformers.modeling_outputs import (
49
- BaseModelOutputWithPast,
50
- CausalLMOutputWithPast,
51
- )
52
-
53
- from .configuration_tiny import TinyConfig
54
-
55
-
56
- def rotate_half(x: torch.Tensor) -> torch.Tensor:
57
- x1 = x[..., :x.shape[-1] // 2]
58
- x2 = x[..., x.shape[-1] // 2:]
59
- return torch.cat((-x2, x1), dim=-1)
60
-
61
-
62
- def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
63
- assert dim % 2 == 0
64
- freqs = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
65
- t = torch.arange(end)
66
- freqs = torch.outer(t, freqs).float()
67
- cos = torch.cos(freqs)
68
- sin = torch.sin(freqs)
69
- cos = torch.cat([cos, cos], dim=-1)
70
- sin = torch.cat([sin, sin], dim=-1)
71
- return cos, sin
72
-
73
-
74
- def apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
75
- T = x.shape[2]
76
- cos_t = cos[:T, :].unsqueeze(0).unsqueeze(1)
77
- sin_t = sin[:T, :].unsqueeze(0).unsqueeze(1)
78
- return (x * cos_t) + (rotate_half(x) * sin_t)
79
-
80
-
81
- class RMSNorm(nn.Module):
82
- def __init__(self, dim: int, eps: float = 1e-5):
83
- super().__init__()
84
- self.eps = eps
85
- self.weight = nn.Parameter(torch.ones(dim))
86
-
87
- def forward(self, x: torch.Tensor) -> torch.Tensor:
88
- variance = x.pow(2).mean(-1, keepdim=True)
89
- return x * torch.rsqrt(variance + self.eps) * self.weight
90
-
91
-
92
- class FeedForward(nn.Module):
93
- def __init__(self, config: TinyConfig):
94
- super().__init__()
95
- self.w1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
96
- self.w2 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
97
- self.w3 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
98
- self.dropout = nn.Dropout(config.hidden_dropout) if config.hidden_dropout > 0.0 else None
99
-
100
- def forward(self, x: torch.Tensor) -> torch.Tensor:
101
- out = F.silu(self.w1(x)) * self.w2(x)
102
- out = self.w3(out)
103
- if self.dropout is not None:
104
- out = self.dropout(out)
105
- return out
106
-
107
-
108
- class Attention(nn.Module):
109
- def __init__(self, config: TinyConfig):
110
- super().__init__()
111
- self.n_heads = config.num_attention_heads
112
- self.hidden_size = config.hidden_size
113
- self.head_dim = config.hidden_size // config.num_attention_heads
114
-
115
- assert self.n_heads * self.head_dim == self.hidden_size
116
-
117
- self.wq = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
118
- self.wk = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
119
- self.wv = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
120
- self.wo = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
121
- self.dropout_p = config.attention_dropout
122
-
123
- def forward(
124
- self,
125
- x: torch.Tensor,
126
- cos: torch.Tensor,
127
- sin: torch.Tensor,
128
- attention_mask: Optional[torch.Tensor] = None,
129
- ) -> torch.Tensor:
130
- B, T, C = x.shape
131
- q = self.wq(x)
132
- k = self.wk(x)
133
- v = self.wv(x)
134
-
135
- q = q.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
136
- k = k.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
137
- v = v.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
138
-
139
- q = apply_rotary_emb(q, cos, sin)
140
- k = apply_rotary_emb(k, cos, sin)
141
-
142
- dropout_p = self.dropout_p if self.training else 0.0
143
-
144
- if attention_mask is not None:
145
- if torch.all(attention_mask == 1):
146
- attn_mask = None
147
- is_causal = True
148
- else:
149
- causal_mask = torch.tril(torch.ones((T, T), dtype=torch.bool, device=x.device))
150
- padding_mask = attention_mask.to(torch.bool).unsqueeze(1).unsqueeze(2) # shape: (B, 1, 1, T)
151
- attn_mask = causal_mask.unsqueeze(0).unsqueeze(1) & padding_mask # shape: (B, 1, T, T)
152
- is_causal = False
153
- else:
154
- attn_mask = None
155
- is_causal = True
156
-
157
- out = F.scaled_dot_product_attention(
158
- q, k, v,
159
- attn_mask=attn_mask,
160
- dropout_p=dropout_p,
161
- is_causal=is_causal
162
- )
163
-
164
- out = out.transpose(1, 2).contiguous().view(B, T, C)
165
- return self.wo(out)
166
-
167
-
168
- class TransformerBlock(nn.Module):
169
- def __init__(self, config: TinyConfig):
170
- super().__init__()
171
- self.attention = Attention(config)
172
- self.feed_forward = FeedForward(config)
173
- self.attention_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
174
- self.ffn_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
175
-
176
- def forward(
177
- self,
178
- x: torch.Tensor,
179
- cos: torch.Tensor,
180
- sin: torch.Tensor,
181
- attention_mask: Optional[torch.Tensor] = None,
182
- ) -> torch.Tensor:
183
- x = x + self.attention(self.attention_norm(x), cos, sin, attention_mask)
184
- x = x + self.feed_forward(self.ffn_norm(x))
185
- return x
186
-
187
-
188
- class TinyPreTrainedModel(PreTrainedModel):
189
- config_class = TinyConfig
190
- base_model_prefix = "model"
191
- supports_gradient_checkpointing = True
192
- _no_split_modules = ["TransformerBlock"]
193
-
194
- def _init_weights(self, module):
195
- if isinstance(module, nn.Linear):
196
- nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
197
- if module.bias is not None:
198
- nn.init.zeros_(module.bias)
199
- elif isinstance(module, nn.Embedding):
200
- nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
201
-
202
- def _set_gradient_checkpointing(self, module, value=False):
203
- if isinstance(module, (TinyModel, TinyForCausalLM)):
204
- module.gradient_checkpointing = value
205
-
206
-
207
- class TinyModel(TinyPreTrainedModel):
208
- def __init__(self, config: TinyConfig):
209
- super().__init__(config)
210
- self.padding_idx = config.pad_token_id
211
- self.tok_embeddings = nn.Embedding(
212
- config.vocab_size, config.hidden_size, self.padding_idx
213
- )
214
- self.layers = nn.ModuleList(
215
- [TransformerBlock(config) for _ in range(config.num_hidden_layers)]
216
- )
217
- self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
218
-
219
- cos, sin = precompute_freqs_cis(
220
- dim=config.hidden_size // config.num_attention_heads,
221
- end=config.max_position_embeddings * 2,
222
- theta=config.rope_theta,
223
- )
224
- self.register_buffer("cos", cos, persistent=False)
225
- self.register_buffer("sin", sin, persistent=False)
226
-
227
- self.gradient_checkpointing = False
228
- self.post_init()
229
-
230
- def get_input_embeddings(self):
231
- return self.tok_embeddings
232
-
233
- def set_input_embeddings(self, value):
234
- self.tok_embeddings = value
235
-
236
- def forward(
237
- self,
238
- input_ids: Optional[torch.LongTensor] = None,
239
- attention_mask: Optional[torch.Tensor] = None,
240
- position_ids: Optional[torch.LongTensor] = None,
241
- past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
242
- inputs_embeds: Optional[torch.FloatTensor] = None,
243
- use_cache: Optional[bool] = None,
244
- output_attentions: Optional[bool] = None,
245
- output_hidden_states: Optional[bool] = None,
246
- return_dict: Optional[bool] = None,
247
- ) -> Union[Tuple, BaseModelOutputWithPast]:
248
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
249
- output_hidden_states = (
250
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
251
- )
252
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
253
-
254
- if input_ids is not None and inputs_embeds is not None:
255
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
256
- elif input_ids is not None:
257
- hidden_states = self.tok_embeddings(input_ids)
258
- elif inputs_embeds is not None:
259
- hidden_states = inputs_embeds
260
- else:
261
- raise ValueError("You must specify either input_ids or inputs_embeds")
262
-
263
- T = hidden_states.shape[1]
264
- cos = self.cos[:T]
265
- sin = self.sin[:T]
266
-
267
- all_hidden_states = () if output_hidden_states else None
268
-
269
- for layer in self.layers:
270
- if output_hidden_states:
271
- all_hidden_states += (hidden_states,)
272
-
273
- if self.gradient_checkpointing and self.training:
274
- hidden_states = self._gradient_checkpointing_func(
275
- layer.__call__,
276
- hidden_states,
277
- cos,
278
- sin,
279
- attention_mask,
280
- )
281
- else:
282
- hidden_states = layer(
283
- hidden_states,
284
- cos,
285
- sin,
286
- attention_mask,
287
- )
288
-
289
- hidden_states = self.norm(hidden_states)
290
-
291
- if output_hidden_states:
292
- all_hidden_states += (hidden_states,)
293
-
294
- if not return_dict:
295
- return (hidden_states,)
296
-
297
- return BaseModelOutputWithPast(
298
- last_hidden_state=hidden_states,
299
- hidden_states=all_hidden_states,
300
- past_key_values=None,
301
- )
302
-
303
-
304
- class TinyForCausalLM(TinyPreTrainedModel):
305
- _tied_weights_keys = ["tok_embeddings.weight"]
306
-
307
- def __init__(self, config: TinyConfig):
308
- super().__init__(config)
309
- self.padding_idx = config.pad_token_id
310
- self.tok_embeddings = nn.Embedding(
311
- config.vocab_size, config.hidden_size, self.padding_idx
312
- )
313
- self.layers = nn.ModuleList(
314
- [TransformerBlock(config) for _ in range(config.num_hidden_layers)]
315
- )
316
- self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
317
-
318
- self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
319
-
320
- cos, sin = precompute_freqs_cis(
321
- dim=config.hidden_size // config.num_attention_heads,
322
- end=config.max_position_embeddings * 2,
323
- theta=config.rope_theta,
324
- )
325
- self.register_buffer("cos", cos, persistent=False)
326
- self.register_buffer("sin", sin, persistent=False)
327
-
328
- if config.tie_word_embeddings:
329
- self.output.weight = self.tok_embeddings.weight
330
-
331
- self.gradient_checkpointing = False
332
- self.post_init()
333
-
334
- def get_input_embeddings(self):
335
- return self.tok_embeddings
336
-
337
- def set_input_embeddings(self, value):
338
- self.tok_embeddings = value
339
- if self.config.tie_word_embeddings:
340
- self.output.weight = value.weight
341
-
342
- def get_output_embeddings(self):
343
- return self.output
344
-
345
- def set_output_embeddings(self, new_embeddings):
346
- self.output = new_embeddings
347
-
348
- def tie_weights(self):
349
- if self.config.tie_word_embeddings:
350
- self.tok_embeddings.weight = self.output.weight
351
-
352
- def forward(
353
- self,
354
- input_ids: Optional[torch.LongTensor] = None,
355
- attention_mask: Optional[torch.Tensor] = None,
356
- position_ids: Optional[torch.LongTensor] = None,
357
- past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
358
- inputs_embeds: Optional[torch.FloatTensor] = None,
359
- labels: Optional[torch.LongTensor] = None,
360
- use_cache: Optional[bool] = None,
361
- output_attentions: Optional[bool] = None,
362
- output_hidden_states: Optional[bool] = None,
363
- return_dict: Optional[bool] = None,
364
- **kwargs,
365
- ) -> Union[Tuple, CausalLMOutputWithPast]:
366
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
367
- output_hidden_states = (
368
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
369
- )
370
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
371
-
372
- if input_ids is not None and inputs_embeds is not None:
373
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
374
- elif input_ids is not None:
375
- hidden_states = self.tok_embeddings(input_ids)
376
- elif inputs_embeds is not None:
377
- hidden_states = inputs_embeds
378
- else:
379
- raise ValueError("You must specify either input_ids or inputs_embeds")
380
-
381
- T = hidden_states.shape[1]
382
- cos = self.cos[:T]
383
- sin = self.sin[:T]
384
-
385
- all_hidden_states = () if output_hidden_states else None
386
-
387
- for layer in self.layers:
388
- if output_hidden_states:
389
- all_hidden_states += (hidden_states,)
390
-
391
- if self.gradient_checkpointing and self.training:
392
- hidden_states = self._gradient_checkpointing_func(
393
- layer.__call__,
394
- hidden_states,
395
- cos,
396
- sin,
397
- attention_mask,
398
- )
399
- else:
400
- hidden_states = layer(
401
- hidden_states,
402
- cos,
403
- sin,
404
- attention_mask,
405
- )
406
-
407
- hidden_states = self.norm(hidden_states)
408
- logits = self.output(hidden_states)
409
-
410
- loss = None
411
- if labels is not None:
412
- shift_logits = logits[..., :-1, :].contiguous()
413
- shift_labels = labels[..., 1:].contiguous()
414
- loss_fct = nn.CrossEntropyLoss()
415
- loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
416
-
417
- if not return_dict:
418
- output = (logits,)
419
- if output_hidden_states:
420
- output = output + (all_hidden_states,)
421
- return (loss,) + output if loss is not None else output
422
-
423
- return CausalLMOutputWithPast(
424
- loss=loss,
425
- logits=logits,
426
- past_key_values=None,
427
- hidden_states=all_hidden_states,
428
- attentions=None,
429
- )
430
-
431
- def prepare_inputs_for_generation(
432
- self,
433
- input_ids: torch.LongTensor,
434
- past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
435
- attention_mask: Optional[torch.Tensor] = None,
436
- inputs_embeds: Optional[torch.FloatTensor] = None,
437
- **kwargs,
438
- ) -> dict:
439
- if inputs_embeds is not None and past_key_values is None:
440
- model_inputs = {"inputs_embeds": inputs_embeds}
441
- else:
442
- model_inputs = {"input_ids": input_ids}
443
-
444
- model_inputs["attention_mask"] = attention_mask
445
- model_inputs["past_key_values"] = past_key_values
446
- return model_inputs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
special_tokens_map.json DELETED
@@ -1,30 +0,0 @@
1
- {
2
- "bos_token": {
3
- "content": "<s>",
4
- "lstrip": false,
5
- "normalized": false,
6
- "rstrip": false,
7
- "single_word": false
8
- },
9
- "eos_token": {
10
- "content": "</s>",
11
- "lstrip": false,
12
- "normalized": false,
13
- "rstrip": false,
14
- "single_word": false
15
- },
16
- "pad_token": {
17
- "content": "<pad>",
18
- "lstrip": false,
19
- "normalized": false,
20
- "rstrip": false,
21
- "single_word": false
22
- },
23
- "unk_token": {
24
- "content": "<unk>",
25
- "lstrip": false,
26
- "normalized": false,
27
- "rstrip": false,
28
- "single_word": false
29
- }
30
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tokenizer.json DELETED
The diff for this file is too large to render. See raw diff
 
tokenizer.model DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4cffac9db68a0db7daf412a3811d5731bef8c323414e638ba0480d9980128453
3
- size 370810
 
 
 
 
tokenizer_config.json DELETED
@@ -1,50 +0,0 @@
1
- {
2
- "add_bos_token": true,
3
- "add_eos_token": false,
4
- "add_prefix_space": null,
5
- "added_tokens_decoder": {
6
- "0": {
7
- "content": "<pad>",
8
- "lstrip": false,
9
- "normalized": false,
10
- "rstrip": false,
11
- "single_word": false,
12
- "special": true
13
- },
14
- "1": {
15
- "content": "<unk>",
16
- "lstrip": false,
17
- "normalized": false,
18
- "rstrip": false,
19
- "single_word": false,
20
- "special": true
21
- },
22
- "2": {
23
- "content": "<s>",
24
- "lstrip": false,
25
- "normalized": false,
26
- "rstrip": false,
27
- "single_word": false,
28
- "special": true
29
- },
30
- "3": {
31
- "content": "</s>",
32
- "lstrip": false,
33
- "normalized": false,
34
- "rstrip": false,
35
- "single_word": false,
36
- "special": true
37
- }
38
- },
39
- "bos_token": "<s>",
40
- "clean_up_tokenization_spaces": false,
41
- "eos_token": "</s>",
42
- "legacy": true,
43
- "model_max_length": 1000000000000000019884624838656,
44
- "pad_token": "<pad>",
45
- "sp_model_kwargs": {},
46
- "spaces_between_special_tokens": false,
47
- "tokenizer_class": "LlamaTokenizer",
48
- "unk_token": "<unk>",
49
- "use_default_system_prompt": false
50
- }