Delete model.py
Browse files
model.py
DELETED
|
@@ -1,189 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import math
|
| 4 |
-
|
| 5 |
-
from .optimized_diffattn import MultiheadDiffAttn
|
| 6 |
-
|
| 7 |
-
# --- Tokenizer Definition ---
|
| 8 |
-
# Vocabulary: 256 bytes + IM_START_TOKEN + IM_END_TOKEN + <pad>
|
| 9 |
-
IM_START_TOKEN = "<|im_start|>"
|
| 10 |
-
IM_END_TOKEN = "<|im_end|>"
|
| 11 |
-
PAD_TOKEN = "<pad>"
|
| 12 |
-
|
| 13 |
-
SPECIAL_TOKENS = [IM_START_TOKEN, IM_END_TOKEN, PAD_TOKEN]
|
| 14 |
-
VOCAB_SIZE = 256 + len(SPECIAL_TOKENS)
|
| 15 |
-
|
| 16 |
-
# Create token to id mapping
|
| 17 |
-
token_to_id = {}
|
| 18 |
-
id_to_token = {}
|
| 19 |
-
|
| 20 |
-
for i in range(256):
|
| 21 |
-
token_to_id[bytes([i])] = i
|
| 22 |
-
id_to_token[i] = bytes([i])
|
| 23 |
-
|
| 24 |
-
for i, token_str in enumerate(SPECIAL_TOKENS):
|
| 25 |
-
token_id = 256 + i
|
| 26 |
-
token_to_id[token_str] = token_id
|
| 27 |
-
id_to_token[token_id] = token_str
|
| 28 |
-
|
| 29 |
-
PAD_ID = token_to_id[PAD_TOKEN]
|
| 30 |
-
IM_START_ID = token_to_id[IM_START_TOKEN]
|
| 31 |
-
IM_END_ID = token_to_id[IM_END_TOKEN]
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
class ByteTokenizer:
|
| 35 |
-
def __init__(self):
|
| 36 |
-
self.token_to_id = token_to_id
|
| 37 |
-
self.id_to_token = id_to_token
|
| 38 |
-
self.vocab_size = VOCAB_SIZE
|
| 39 |
-
self.pad_id = PAD_ID
|
| 40 |
-
self.im_start_id = IM_START_ID
|
| 41 |
-
self.im_end_id = IM_END_ID
|
| 42 |
-
|
| 43 |
-
def encode(self, text_bytes: bytes, add_special_tokens=True):
|
| 44 |
-
ids = [self.token_to_id[bytes([b])] for b in text_bytes]
|
| 45 |
-
if add_special_tokens:
|
| 46 |
-
return [self.im_start_id] + ids + [self.im_end_id]
|
| 47 |
-
return ids
|
| 48 |
-
|
| 49 |
-
def decode(self, ids: list[int]):
|
| 50 |
-
tokens = []
|
| 51 |
-
for i in ids:
|
| 52 |
-
token = self.id_to_token.get(i)
|
| 53 |
-
if token is None:
|
| 54 |
-
# Handle unknown token ID if necessary, or raise error
|
| 55 |
-
tokens.append(b"?") # Placeholder for unknown
|
| 56 |
-
elif isinstance(token, bytes):
|
| 57 |
-
tokens.append(token)
|
| 58 |
-
# Ignore special tokens for decoding to raw text, or handle as needed
|
| 59 |
-
return b"".join(tokens)
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
# --- RoPE Embeddings --- (Reused from previous script)
|
| 63 |
-
def get_rotary_embeddings(seq_len, dim_model, theta=10000.0):
|
| 64 |
-
if dim_model % 2 != 0:
|
| 65 |
-
raise ValueError(f"dim_model must be even, got {dim_model}")
|
| 66 |
-
position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1)
|
| 67 |
-
div_term = torch.exp(
|
| 68 |
-
torch.arange(0, dim_model, 2).float() * -(math.log(theta) / dim_model)
|
| 69 |
-
)
|
| 70 |
-
angles = position * div_term
|
| 71 |
-
cos_emb = torch.cos(angles)
|
| 72 |
-
sin_emb = torch.sin(angles)
|
| 73 |
-
return cos_emb, sin_emb
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# --- Model Definition ---
|
| 77 |
-
class FeedForward(nn.Module):
|
| 78 |
-
def __init__(self, embed_dim, hidden_dim, dropout=0.1):
|
| 79 |
-
super().__init__()
|
| 80 |
-
self.fc1 = nn.Linear(embed_dim, hidden_dim)
|
| 81 |
-
self.fc2 = nn.Linear(hidden_dim, embed_dim)
|
| 82 |
-
self.dropout = nn.Dropout(dropout)
|
| 83 |
-
self.act = nn.GELU()
|
| 84 |
-
|
| 85 |
-
def forward(self, x):
|
| 86 |
-
return self.fc2(self.dropout(self.act(self.fc1(x))))
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
class DiffTransformerBlock(nn.Module):
|
| 90 |
-
def __init__(self, embed_dim, num_heads, depth, ffn_hidden_dim, dropout=0.1):
|
| 91 |
-
super().__init__()
|
| 92 |
-
self.attn = MultiheadDiffAttn(embed_dim, depth, num_heads, dropout=dropout)
|
| 93 |
-
self.ffn = FeedForward(embed_dim, ffn_hidden_dim, dropout)
|
| 94 |
-
self.norm1 = nn.LayerNorm(embed_dim)
|
| 95 |
-
self.norm2 = nn.LayerNorm(embed_dim)
|
| 96 |
-
self.dropout = nn.Dropout(dropout)
|
| 97 |
-
|
| 98 |
-
def forward(self, x, rel_pos, attn_mask=None):
|
| 99 |
-
# Pre-norm
|
| 100 |
-
attn_out = self.attn(self.norm1(x), rel_pos, attn_mask)
|
| 101 |
-
x = x + self.dropout(attn_out)
|
| 102 |
-
ffn_out = self.ffn(self.norm2(x))
|
| 103 |
-
x = x + self.dropout(ffn_out)
|
| 104 |
-
return x
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
class DiffTransformerLLM(nn.Module):
|
| 108 |
-
def __init__(
|
| 109 |
-
self,
|
| 110 |
-
vocab_size,
|
| 111 |
-
embed_dim,
|
| 112 |
-
num_layers,
|
| 113 |
-
num_heads,
|
| 114 |
-
ffn_hidden_dim,
|
| 115 |
-
max_seq_len,
|
| 116 |
-
dropout=0.1,
|
| 117 |
-
):
|
| 118 |
-
super().__init__()
|
| 119 |
-
self.embed_dim = embed_dim
|
| 120 |
-
self.max_seq_len = max_seq_len
|
| 121 |
-
|
| 122 |
-
self.token_embeddings = nn.Embedding(vocab_size, embed_dim)
|
| 123 |
-
# Positional embeddings are handled by RoPE, so no separate nn.Embedding for positions
|
| 124 |
-
self.dropout = nn.Dropout(dropout)
|
| 125 |
-
|
| 126 |
-
self.layers = nn.ModuleList(
|
| 127 |
-
[
|
| 128 |
-
DiffTransformerBlock(
|
| 129 |
-
embed_dim, num_heads, depth, ffn_hidden_dim, dropout
|
| 130 |
-
)
|
| 131 |
-
for depth in range(num_layers)
|
| 132 |
-
]
|
| 133 |
-
)
|
| 134 |
-
self.norm_out = nn.LayerNorm(embed_dim)
|
| 135 |
-
self.lm_head = nn.Linear(embed_dim, vocab_size, bias=False)
|
| 136 |
-
|
| 137 |
-
# Tie weights
|
| 138 |
-
self.token_embeddings.weight = self.lm_head.weight
|
| 139 |
-
|
| 140 |
-
# RoPE precomputation
|
| 141 |
-
# The head_dim for MultiheadDiffAttn is embed_dim // num_heads // 2
|
| 142 |
-
self.rope_head_dim = embed_dim // num_heads // 2
|
| 143 |
-
cos_emb, sin_emb = get_rotary_embeddings(max_seq_len, self.rope_head_dim)
|
| 144 |
-
self.register_buffer("cos_emb", cos_emb, persistent=False)
|
| 145 |
-
self.register_buffer("sin_emb", sin_emb, persistent=False)
|
| 146 |
-
|
| 147 |
-
def forward(self, input_ids, attn_mask=None):
|
| 148 |
-
batch_size, seq_len = input_ids.shape
|
| 149 |
-
|
| 150 |
-
x = self.token_embeddings(input_ids) * math.sqrt(self.embed_dim)
|
| 151 |
-
x = self.dropout(x)
|
| 152 |
-
|
| 153 |
-
# Ensure RoPE embeddings are on the same device *and* dtype as activations
|
| 154 |
-
rel_pos = (
|
| 155 |
-
self.cos_emb[:seq_len, :].to(x.device, dtype=x.dtype),
|
| 156 |
-
self.sin_emb[:seq_len, :].to(x.device, dtype=x.dtype),
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
# Create causal attention mask if not provided
|
| 160 |
-
if attn_mask is None:
|
| 161 |
-
# Standard causal mask for autoregressive decoding
|
| 162 |
-
# MultiheadDiffAttn expects a mask where -inf indicates masked positions
|
| 163 |
-
causal_mask = torch.triu(
|
| 164 |
-
torch.ones(seq_len, seq_len, device=x.device) * float("-inf"),
|
| 165 |
-
diagonal=1,
|
| 166 |
-
)
|
| 167 |
-
else:
|
| 168 |
-
# If a custom mask is provided (e.g., for padding), ensure it's correctly formatted
|
| 169 |
-
# For MultiheadDiffAttn, 0 means attend, -inf means mask.
|
| 170 |
-
# Assuming input attn_mask is 1 for attend, 0 for mask (like Hugging Face)
|
| 171 |
-
# We need to convert it: (1 - attn_mask) * -inf
|
| 172 |
-
# However, MultiheadDiffAttn's internal mask logic might be sufficient if it handles padding.
|
| 173 |
-
# For simplicity, let's assume the provided attn_mask is already in the correct format if not None.
|
| 174 |
-
# If it's a padding mask (1 for real tokens, 0 for pad), we need to adapt it.
|
| 175 |
-
# Let's stick to causal mask for now, padding handled by loss_fn ignore_index.
|
| 176 |
-
causal_mask = torch.triu(
|
| 177 |
-
torch.ones(seq_len, seq_len, device=x.device) * float("-inf"),
|
| 178 |
-
diagonal=1,
|
| 179 |
-
)
|
| 180 |
-
|
| 181 |
-
for layer in self.layers:
|
| 182 |
-
x = layer(x, rel_pos, attn_mask=causal_mask)
|
| 183 |
-
|
| 184 |
-
x = self.norm_out(x)
|
| 185 |
-
logits = self.lm_head(x)
|
| 186 |
-
return logits
|
| 187 |
-
|
| 188 |
-
def count_parameters(self):
|
| 189 |
-
return sum(p.numel() for p in self.parameters() if p.requires_grad)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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