Text Generation
Transformers
Safetensors
PyTorch
English
tiny
tinyllm
transformer
causal-lm
tinystories
storytelling
small-language-model
from-scratch
custom_code
Instructions to use Krishna0812/Tiny_Stories with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Krishna0812/Tiny_Stories with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Krishna0812/Tiny_Stories", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Krishna0812/Tiny_Stories", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Krishna0812/Tiny_Stories with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Krishna0812/Tiny_Stories" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Krishna0812/Tiny_Stories", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Krishna0812/Tiny_Stories
- SGLang
How to use Krishna0812/Tiny_Stories 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 "Krishna0812/Tiny_Stories" \ --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": "Krishna0812/Tiny_Stories", "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 "Krishna0812/Tiny_Stories" \ --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": "Krishna0812/Tiny_Stories", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Krishna0812/Tiny_Stories with Docker Model Runner:
docker model run hf.co/Krishna0812/Tiny_Stories
Upload 10 files
Browse filesWhole setup of model
- __init__.py +2 -0
- config.json +25 -0
- configuration_tiny.py +62 -0
- generation_config.json +9 -0
- model.safetensors +3 -0
- modeling_tiny.py +446 -0
- special_tokens_map.json +30 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +50 -0
__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .configuration_tiny import TinyConfig
|
| 2 |
+
from .modeling_tiny import TinyModel, TinyForCausalLM
|
config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4cffac9db68a0db7daf412a3811d5731bef8c323414e638ba0480d9980128453
|
| 3 |
+
size 370810
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
}
|