Publish TinyGPT checkpoint
Browse files- README.md +66 -0
- config.json +32 -0
- export_metadata.json +5 -0
- generation_config.json +10 -0
- model.safetensors +3 -0
- modeling_tiny_gpt.py +282 -0
- tiny_gpt_latest.pt +3 -0
- tokenization_tiny_gpt.py +85 -0
- tokenizer.model +3 -0
- tokenizer_config.json +49 -0
- training_config.yaml +30 -0
README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- pytorch
|
| 5 |
+
- gpt
|
| 6 |
+
- tiny-gpt
|
| 7 |
+
- causal-lm
|
| 8 |
+
---
|
| 9 |
+
# tiny-gpt-2-1m
|
| 10 |
+
|
| 11 |
+
This repository contains a pretrained TinyGPT checkpoint published for public use.
|
| 12 |
+
This checkpoint is provided for educational and experimentation purposes.
|
| 13 |
+
|
| 14 |
+
## Artifacts
|
| 15 |
+
|
| 16 |
+
- `tiny_gpt_latest.pt`: training checkpoint with model and optimizer state
|
| 17 |
+
- `tokenizer.model`: SentencePiece tokenizer used for training and generation
|
| 18 |
+
- `config.json`: model configuration serialized from the checkpoint
|
| 19 |
+
- `training_config.yaml`: training and MLflow settings used for the run
|
| 20 |
+
|
| 21 |
+
## How to use
|
| 22 |
+
|
| 23 |
+
Use with Transformers.
|
| 24 |
+
|
| 25 |
+
Starting with `transformers >= 4.43.0`, you can run conversational inference using the `pipeline` abstraction or by leveraging the `Auto` classes with `generate()`.
|
| 26 |
+
|
| 27 |
+
Make sure to update your Transformers installation via `pip install --upgrade transformers`.
|
| 28 |
+
|
| 29 |
+
```python
|
| 30 |
+
import torch
|
| 31 |
+
import transformers
|
| 32 |
+
|
| 33 |
+
model_id = "vjkhambe/tiny-gpt-2-1m"
|
| 34 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 35 |
+
dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
| 36 |
+
|
| 37 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 38 |
+
model_id,
|
| 39 |
+
trust_remote_code=True,
|
| 40 |
+
dtype=dtype,
|
| 41 |
+
)
|
| 42 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 43 |
+
model.generation_config.max_length = None
|
| 44 |
+
model.generation_config.max_new_tokens = 64
|
| 45 |
+
|
| 46 |
+
pipeline = transformers.pipeline(
|
| 47 |
+
"text-generation",
|
| 48 |
+
model=model,
|
| 49 |
+
tokenizer=tokenizer,
|
| 50 |
+
device=device,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
print(pipeline("Hey how are you doing today?"))
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Training details
|
| 57 |
+
|
| 58 |
+
- Base package: `tiny_gpt_pretrain`
|
| 59 |
+
- Model and training configuration are stored in the checkpoint and `training_config.yaml`
|
| 60 |
+
- The exported checkpoint includes optimizer state for continued fine-tuning or evaluation
|
| 61 |
+
|
| 62 |
+
## License
|
| 63 |
+
|
| 64 |
+
Released under the Apache-2.0 license.
|
| 65 |
+
|
| 66 |
+
Target repo: `vjkhambe/tiny-gpt-2-1m`
|
config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"TinyGPTForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "modeling_tiny_gpt.TinyGPTConfig",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_tiny_gpt.TinyGPTForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"bos_token_id": 1,
|
| 10 |
+
"context_length": 256,
|
| 11 |
+
"d_ff": 512,
|
| 12 |
+
"d_model": 128,
|
| 13 |
+
"dropout": 0.1,
|
| 14 |
+
"dtype": "float32",
|
| 15 |
+
"eos_token_id": 2,
|
| 16 |
+
"head_dim": 32,
|
| 17 |
+
"hidden_size": 128,
|
| 18 |
+
"intermediate_size": 512,
|
| 19 |
+
"is_decoder": true,
|
| 20 |
+
"max_position_embeddings": 256,
|
| 21 |
+
"model_type": "tiny_gpt",
|
| 22 |
+
"n_heads": 4,
|
| 23 |
+
"n_layers": 4,
|
| 24 |
+
"num_attention_heads": 4,
|
| 25 |
+
"num_hidden_layers": 4,
|
| 26 |
+
"pad_token_id": 3,
|
| 27 |
+
"tie_embeddings": false,
|
| 28 |
+
"tie_word_embeddings": false,
|
| 29 |
+
"transformers_version": "5.12.1",
|
| 30 |
+
"unk_token_id": 0,
|
| 31 |
+
"vocab_size": 2048
|
| 32 |
+
}
|
export_metadata.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_checkpoint": "checkpoints/tiny_gpt_latest.pt",
|
| 3 |
+
"source_tokenizer": "data/processed/tiny_bpe.model",
|
| 4 |
+
"transformers_compatible": true
|
| 5 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 3,
|
| 8 |
+
"transformers_version": "5.12.1",
|
| 9 |
+
"use_cache": false
|
| 10 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56fc1abc6dc067d4e46b323cff6a28ee4431300fbc223fd2612a35492df893bb
|
| 3 |
+
size 6456888
|
modeling_tiny_gpt.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from transformers import GenerationMixin, PreTrainedModel, PretrainedConfig
|
| 9 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TinyGPTConfig(PretrainedConfig):
|
| 13 |
+
model_type = "tiny_gpt"
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
vocab_size: int = 2048,
|
| 18 |
+
context_length: int = 256,
|
| 19 |
+
n_layers: int = 4,
|
| 20 |
+
n_heads: int = 4,
|
| 21 |
+
d_model: int = 128,
|
| 22 |
+
d_ff: int = 512,
|
| 23 |
+
dropout: float = 0.1,
|
| 24 |
+
tie_embeddings: bool = True,
|
| 25 |
+
bos_token_id: int = 1,
|
| 26 |
+
eos_token_id: int = 2,
|
| 27 |
+
pad_token_id: int = 3,
|
| 28 |
+
unk_token_id: int = 0,
|
| 29 |
+
use_cache: bool = False,
|
| 30 |
+
**kwargs,
|
| 31 |
+
) -> None:
|
| 32 |
+
is_decoder = kwargs.pop("is_decoder", True)
|
| 33 |
+
tie_word_embeddings = kwargs.pop("tie_word_embeddings", tie_embeddings)
|
| 34 |
+
use_cache = kwargs.pop("use_cache", use_cache)
|
| 35 |
+
super().__init__(
|
| 36 |
+
bos_token_id=bos_token_id,
|
| 37 |
+
eos_token_id=eos_token_id,
|
| 38 |
+
pad_token_id=pad_token_id,
|
| 39 |
+
unk_token_id=unk_token_id,
|
| 40 |
+
use_cache=use_cache,
|
| 41 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 42 |
+
is_decoder=is_decoder,
|
| 43 |
+
**kwargs,
|
| 44 |
+
)
|
| 45 |
+
self.vocab_size = vocab_size
|
| 46 |
+
self.context_length = context_length
|
| 47 |
+
self.n_layers = n_layers
|
| 48 |
+
self.n_heads = n_heads
|
| 49 |
+
self.d_model = d_model
|
| 50 |
+
self.d_ff = d_ff
|
| 51 |
+
self.dropout = dropout
|
| 52 |
+
self.tie_embeddings = tie_embeddings
|
| 53 |
+
|
| 54 |
+
# Standard Transformer aliases used by generation helpers.
|
| 55 |
+
self.hidden_size = d_model
|
| 56 |
+
self.intermediate_size = d_ff
|
| 57 |
+
self.num_attention_heads = n_heads
|
| 58 |
+
self.num_hidden_layers = n_layers
|
| 59 |
+
self.max_position_embeddings = context_length
|
| 60 |
+
self.head_dim = d_model // n_heads
|
| 61 |
+
|
| 62 |
+
if self.d_model % self.n_heads != 0:
|
| 63 |
+
raise ValueError("d_model must be divisible by n_heads")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class TokenEmbedding(nn.Module):
|
| 67 |
+
def __init__(self, config: TinyGPTConfig) -> None:
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.embedding = nn.Embedding(config.vocab_size, config.d_model)
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def weight(self) -> torch.Tensor:
|
| 73 |
+
return self.embedding.weight
|
| 74 |
+
|
| 75 |
+
def forward(self, idx: torch.Tensor) -> torch.Tensor:
|
| 76 |
+
return self.embedding(idx)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class PositionEmbedding(nn.Module):
|
| 80 |
+
def __init__(self, config: TinyGPTConfig) -> None:
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.embedding = nn.Embedding(config.context_length, config.d_model)
|
| 83 |
+
|
| 84 |
+
def forward(self, seq_len: int, device: torch.device) -> torch.Tensor:
|
| 85 |
+
positions = torch.arange(seq_len, device=device).unsqueeze(0)
|
| 86 |
+
return self.embedding(positions)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class CausalSelfAttention(nn.Module):
|
| 90 |
+
def __init__(self, config: TinyGPTConfig) -> None:
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.n_heads = config.n_heads
|
| 93 |
+
self.head_dim = config.d_model // config.n_heads
|
| 94 |
+
|
| 95 |
+
self.q_proj = nn.Linear(config.d_model, config.d_model)
|
| 96 |
+
self.k_proj = nn.Linear(config.d_model, config.d_model)
|
| 97 |
+
self.v_proj = nn.Linear(config.d_model, config.d_model)
|
| 98 |
+
self.out_proj = nn.Linear(config.d_model, config.d_model)
|
| 99 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
| 100 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
| 101 |
+
|
| 102 |
+
mask = torch.tril(torch.ones(config.context_length, config.context_length))
|
| 103 |
+
self.register_buffer(
|
| 104 |
+
"causal_mask",
|
| 105 |
+
mask.view(1, 1, config.context_length, config.context_length),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
batch_size, seq_len, d_model = x.shape
|
| 110 |
+
|
| 111 |
+
query = self._split_heads(self.q_proj(x), batch_size, seq_len)
|
| 112 |
+
key = self._split_heads(self.k_proj(x), batch_size, seq_len)
|
| 113 |
+
value = self._split_heads(self.v_proj(x), batch_size, seq_len)
|
| 114 |
+
|
| 115 |
+
scores = query @ key.transpose(-2, -1)
|
| 116 |
+
scores = scores / (self.head_dim**0.5)
|
| 117 |
+
scores = scores.masked_fill(
|
| 118 |
+
self.causal_mask[:, :, :seq_len, :seq_len] == 0,
|
| 119 |
+
float("-inf"),
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
attention_weights = F.softmax(scores, dim=-1)
|
| 123 |
+
attention_weights = self.attn_dropout(attention_weights)
|
| 124 |
+
|
| 125 |
+
out = attention_weights @ value
|
| 126 |
+
out = out.transpose(1, 2).contiguous().view(batch_size, seq_len, d_model)
|
| 127 |
+
out = self.out_proj(out)
|
| 128 |
+
return self.resid_dropout(out)
|
| 129 |
+
|
| 130 |
+
def _split_heads(self, x: torch.Tensor, batch_size: int, seq_len: int) -> torch.Tensor:
|
| 131 |
+
x = x.view(batch_size, seq_len, self.n_heads, self.head_dim)
|
| 132 |
+
return x.transpose(1, 2)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class FeedForward(nn.Module):
|
| 136 |
+
def __init__(self, config: TinyGPTConfig) -> None:
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.net = nn.Sequential(
|
| 139 |
+
nn.Linear(config.d_model, config.d_ff),
|
| 140 |
+
nn.GELU(),
|
| 141 |
+
nn.Linear(config.d_ff, config.d_model),
|
| 142 |
+
nn.Dropout(config.dropout),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 146 |
+
return self.net(x)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class TransformerBlock(nn.Module):
|
| 150 |
+
def __init__(self, config: TinyGPTConfig) -> None:
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.ln_1 = nn.LayerNorm(config.d_model)
|
| 153 |
+
self.attn = CausalSelfAttention(config)
|
| 154 |
+
self.ln_2 = nn.LayerNorm(config.d_model)
|
| 155 |
+
self.mlp = FeedForward(config)
|
| 156 |
+
|
| 157 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 158 |
+
x = x + self.attn(self.ln_1(x))
|
| 159 |
+
x = x + self.mlp(self.ln_2(x))
|
| 160 |
+
return x
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class TinyGPTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 164 |
+
config_class = TinyGPTConfig
|
| 165 |
+
base_model_prefix = "tiny_gpt"
|
| 166 |
+
main_input_name = "input_ids"
|
| 167 |
+
_tied_weights_keys = {"lm_head.weight": "token_embedding.embedding.weight"}
|
| 168 |
+
|
| 169 |
+
def __init__(self, config: TinyGPTConfig) -> None:
|
| 170 |
+
super().__init__(config)
|
| 171 |
+
|
| 172 |
+
self.token_embedding = TokenEmbedding(config)
|
| 173 |
+
self.position_embedding = PositionEmbedding(config)
|
| 174 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 175 |
+
self.blocks = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layers))
|
| 176 |
+
self.final_ln = nn.LayerNorm(config.d_model)
|
| 177 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 178 |
+
|
| 179 |
+
self.post_init()
|
| 180 |
+
self.tie_weights()
|
| 181 |
+
if getattr(self, "generation_config", None) is not None:
|
| 182 |
+
self.generation_config.use_cache = False
|
| 183 |
+
self.generation_config.cache_implementation = None
|
| 184 |
+
|
| 185 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 186 |
+
return self.token_embedding.embedding
|
| 187 |
+
|
| 188 |
+
def set_input_embeddings(self, value: nn.Module) -> None:
|
| 189 |
+
self.token_embedding.embedding = value
|
| 190 |
+
|
| 191 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 192 |
+
return self.lm_head
|
| 193 |
+
|
| 194 |
+
def set_output_embeddings(self, new_embeddings: nn.Module) -> None:
|
| 195 |
+
self.lm_head = new_embeddings
|
| 196 |
+
|
| 197 |
+
def tie_weights(self, *args, **kwargs) -> None:
|
| 198 |
+
del args, kwargs
|
| 199 |
+
if self.config.tie_embeddings:
|
| 200 |
+
self.lm_head.weight = self.token_embedding.weight
|
| 201 |
+
|
| 202 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 203 |
+
if isinstance(module, nn.Linear):
|
| 204 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 205 |
+
if module.bias is not None:
|
| 206 |
+
nn.init.zeros_(module.bias)
|
| 207 |
+
elif isinstance(module, nn.Embedding):
|
| 208 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 209 |
+
|
| 210 |
+
def forward(
|
| 211 |
+
self,
|
| 212 |
+
input_ids: torch.Tensor,
|
| 213 |
+
attention_mask: torch.Tensor | None = None,
|
| 214 |
+
labels: torch.Tensor | None = None,
|
| 215 |
+
past_key_values=None,
|
| 216 |
+
use_cache: bool | None = None,
|
| 217 |
+
return_dict: bool = True,
|
| 218 |
+
**kwargs,
|
| 219 |
+
) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]:
|
| 220 |
+
del attention_mask, past_key_values, use_cache, kwargs
|
| 221 |
+
|
| 222 |
+
batch_size, seq_len = input_ids.shape
|
| 223 |
+
if seq_len > self.config.context_length:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"Sequence length {seq_len} exceeds context length {self.config.context_length}"
|
| 226 |
+
)
|
| 227 |
+
if labels is not None and labels.shape != input_ids.shape:
|
| 228 |
+
raise ValueError(f"labels shape {labels.shape} must match input_ids shape {input_ids.shape}")
|
| 229 |
+
|
| 230 |
+
token_embeddings = self.token_embedding(input_ids)
|
| 231 |
+
position_embeddings = self.position_embedding(seq_len, input_ids.device)
|
| 232 |
+
x = token_embeddings + position_embeddings
|
| 233 |
+
x = self.dropout(x)
|
| 234 |
+
|
| 235 |
+
for block in self.blocks:
|
| 236 |
+
x = block(x)
|
| 237 |
+
|
| 238 |
+
x = self.final_ln(x)
|
| 239 |
+
logits = self.lm_head(x)
|
| 240 |
+
|
| 241 |
+
loss = None
|
| 242 |
+
if labels is not None:
|
| 243 |
+
if seq_len < 2:
|
| 244 |
+
raise ValueError("Need at least 2 tokens to compute causal LM loss")
|
| 245 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 246 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 247 |
+
loss = F.cross_entropy(
|
| 248 |
+
shift_logits.reshape(-1, self.config.vocab_size),
|
| 249 |
+
shift_labels.reshape(-1),
|
| 250 |
+
ignore_index=-100,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
if not return_dict:
|
| 254 |
+
output = (logits,)
|
| 255 |
+
if loss is not None:
|
| 256 |
+
output = (loss,) + output
|
| 257 |
+
return output
|
| 258 |
+
|
| 259 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None)
|
| 260 |
+
|
| 261 |
+
def prepare_inputs_for_generation(
|
| 262 |
+
self,
|
| 263 |
+
input_ids: torch.Tensor,
|
| 264 |
+
past_key_values=None,
|
| 265 |
+
attention_mask: torch.Tensor | None = None,
|
| 266 |
+
**kwargs,
|
| 267 |
+
) -> dict[str, torch.Tensor | None]:
|
| 268 |
+
del past_key_values
|
| 269 |
+
if input_ids.shape[1] > self.config.context_length:
|
| 270 |
+
input_ids = input_ids[:, -self.config.context_length :]
|
| 271 |
+
if attention_mask is not None:
|
| 272 |
+
attention_mask = attention_mask[:, -self.config.context_length :]
|
| 273 |
+
return {
|
| 274 |
+
"input_ids": input_ids,
|
| 275 |
+
"attention_mask": attention_mask,
|
| 276 |
+
"use_cache": False,
|
| 277 |
+
**kwargs,
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
TinyGPTConfig.register_for_auto_class()
|
| 282 |
+
TinyGPTForCausalLM.register_for_auto_class("AutoModelForCausalLM")
|
tiny_gpt_latest.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2fc5b95fc45d0b851f6b0d4590189187a92d60e58a27aeb030ad447196a929f9
|
| 3 |
+
size 14193447
|
tokenization_tiny_gpt.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import shutil
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import sentencepiece as spm
|
| 7 |
+
from transformers import PreTrainedTokenizer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TinyGPTTokenizer(PreTrainedTokenizer):
|
| 11 |
+
vocab_files_names = {"vocab_file": "tokenizer.model"}
|
| 12 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
vocab_file: str,
|
| 17 |
+
unk_token: str = "<unk>",
|
| 18 |
+
bos_token: str = "<s>",
|
| 19 |
+
eos_token: str = "</s>",
|
| 20 |
+
pad_token: str = "<pad>",
|
| 21 |
+
**kwargs,
|
| 22 |
+
) -> None:
|
| 23 |
+
self.vocab_file = vocab_file
|
| 24 |
+
self.sp_model = spm.SentencePieceProcessor(model_file=vocab_file)
|
| 25 |
+
super().__init__(
|
| 26 |
+
unk_token=unk_token,
|
| 27 |
+
bos_token=bos_token,
|
| 28 |
+
eos_token=eos_token,
|
| 29 |
+
pad_token=pad_token,
|
| 30 |
+
**kwargs,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def vocab_size(self) -> int:
|
| 35 |
+
return self.sp_model.get_piece_size()
|
| 36 |
+
|
| 37 |
+
def get_vocab(self) -> dict[str, int]:
|
| 38 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
| 39 |
+
vocab.update(self.added_tokens_encoder)
|
| 40 |
+
return vocab
|
| 41 |
+
|
| 42 |
+
def _tokenize(self, text: str) -> list[str]:
|
| 43 |
+
return list(self.sp_model.encode(text, out_type=str))
|
| 44 |
+
|
| 45 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 46 |
+
return int(self.sp_model.piece_to_id(token))
|
| 47 |
+
|
| 48 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 49 |
+
return self.sp_model.id_to_piece(int(index))
|
| 50 |
+
|
| 51 |
+
def convert_tokens_to_string(self, tokens: list[str]) -> str:
|
| 52 |
+
return self.sp_model.decode_pieces(tokens)
|
| 53 |
+
|
| 54 |
+
def build_inputs_with_special_tokens(
|
| 55 |
+
self,
|
| 56 |
+
token_ids_0: list[int],
|
| 57 |
+
token_ids_1: list[int] | None = None,
|
| 58 |
+
) -> list[int]:
|
| 59 |
+
if token_ids_1 is None:
|
| 60 |
+
return token_ids_0
|
| 61 |
+
return token_ids_0 + token_ids_1
|
| 62 |
+
|
| 63 |
+
def get_special_tokens_mask(
|
| 64 |
+
self,
|
| 65 |
+
token_ids_0: list[int],
|
| 66 |
+
token_ids_1: list[int] | None = None,
|
| 67 |
+
already_has_special_tokens: bool = False,
|
| 68 |
+
) -> list[int]:
|
| 69 |
+
if already_has_special_tokens:
|
| 70 |
+
return [0] * (len(token_ids_0) + (len(token_ids_1) if token_ids_1 else 0))
|
| 71 |
+
return [0] * (len(token_ids_0) + (len(token_ids_1) if token_ids_1 else 0))
|
| 72 |
+
|
| 73 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
|
| 74 |
+
if not self.vocab_file:
|
| 75 |
+
raise ValueError("No SentencePiece model file to save")
|
| 76 |
+
|
| 77 |
+
save_dir = Path(save_directory)
|
| 78 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
filename = "tokenizer.model"
|
| 80 |
+
out_path = save_dir / filename
|
| 81 |
+
shutil.copy2(self.vocab_file, out_path)
|
| 82 |
+
return (str(out_path),)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
TinyGPTTokenizer.register_for_auto_class()
|
tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:287ebd60f8f64703d0399f8b4c847852d62e6cb92e4d454b8114159ccf193b41
|
| 3 |
+
size 270227
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "<unk>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "<s>",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "</s>",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "<pad>",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"auto_map": {
|
| 37 |
+
"AutoTokenizer": [
|
| 38 |
+
"tokenization_tiny_gpt.TinyGPTTokenizer",
|
| 39 |
+
null
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
"backend": "custom",
|
| 43 |
+
"bos_token": "<s>",
|
| 44 |
+
"eos_token": "</s>",
|
| 45 |
+
"model_max_length": 1000000000,
|
| 46 |
+
"pad_token": "<pad>",
|
| 47 |
+
"tokenizer_class": "TinyGPTTokenizer",
|
| 48 |
+
"unk_token": "<unk>"
|
| 49 |
+
}
|
training_config.yaml
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
training:
|
| 2 |
+
input: data/raw/input.txt
|
| 3 |
+
tokenizer: data/processed/tiny_bpe.model
|
| 4 |
+
checkpoint_dir: checkpoints
|
| 5 |
+
checkpoint_prefix: tiny_gpt
|
| 6 |
+
batch_size: 64
|
| 7 |
+
max_steps: 5000
|
| 8 |
+
learning_rate: 3e-4
|
| 9 |
+
weight_decay: 0.1
|
| 10 |
+
grad_clip: 1.0
|
| 11 |
+
eval_interval: 250
|
| 12 |
+
eval_steps: 50
|
| 13 |
+
train_split: 0.9
|
| 14 |
+
seed: 1337
|
| 15 |
+
device: auto
|
| 16 |
+
generate_tokens: 160
|
| 17 |
+
keep_checkpoints: 5
|
| 18 |
+
show_sample: false
|
| 19 |
+
show_checkpoint: false
|
| 20 |
+
|
| 21 |
+
mlflow:
|
| 22 |
+
enabled: true
|
| 23 |
+
tracking_uri: sqlite:///mlflow.db
|
| 24 |
+
experiment_name: tiny-gpt-adoption
|
| 25 |
+
run_name: null
|
| 26 |
+
log_checkpoints: true
|
| 27 |
+
log_model_config: true
|
| 28 |
+
tags:
|
| 29 |
+
repo: tiny-gpt-adoption
|
| 30 |
+
purpose: pretrain-mlflow-hf
|