Upload folder using huggingface_hub
Browse files- config.json +20 -0
- model.py +296 -0
- model_configuration.py +33 -0
- modeling.py +384 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +8 -0
- tokenizer.json +0 -0
- tokenizer_config.json +16 -0
config.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling.StreamMixerConfig",
|
| 4 |
+
"AutoModel": "modeling.StreamMixerModel",
|
| 5 |
+
"AutoModelForCausalLM": "modeling.StreamMixerForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"hidden_size": 384,
|
| 8 |
+
"intermediate_size": 1024,
|
| 9 |
+
"max_sequence_length": 2048,
|
| 10 |
+
"model_type": "streammixer",
|
| 11 |
+
"n_embd": 384,
|
| 12 |
+
"n_layer": 14,
|
| 13 |
+
"n_read_heads": 4,
|
| 14 |
+
"n_streams": 32,
|
| 15 |
+
"num_attention_heads": 4,
|
| 16 |
+
"num_hidden_layers": 14,
|
| 17 |
+
"stream_dim": 64,
|
| 18 |
+
"transformers_version": "5.10.2",
|
| 19 |
+
"vocab_size": 16384
|
| 20 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stream Mixer GPT — model definition only. No side effects on import.
|
| 2 |
+
|
| 3 |
+
A linear-time, attention-free language model. Each layer mixes the sequence via
|
| 4 |
+
M parallel content-routed memory streams updated by a stable chunked parallel
|
| 5 |
+
scan. Multi-head sigmoid-gated reads with QK-norm. Strictly O(B·T·M·D) per layer.
|
| 6 |
+
|
| 7 |
+
Imported by both microgpt.py (training) and infer.py (sampling).
|
| 8 |
+
"""
|
| 9 |
+
import os
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
# ---------------------------------------------------------------------------
|
| 15 |
+
# BF16 mixed precision — explicit, no torch.amp.autocast.
|
| 16 |
+
# Master weights stay fp32 for optimizer precision; matmuls run in
|
| 17 |
+
# COMPUTE_DTYPE (bf16 on SM80+, fp32 fallback elsewhere).
|
| 18 |
+
# Override with: NANOCHAT_DTYPE=float32|bfloat16|float16
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
_DTYPE_MAP = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}
|
| 21 |
+
def _detect_compute_dtype():
|
| 22 |
+
env = os.environ.get("NANOCHAT_DTYPE")
|
| 23 |
+
if env is not None:
|
| 24 |
+
return _DTYPE_MAP[env]
|
| 25 |
+
if torch.cuda.is_available():
|
| 26 |
+
capability = torch.cuda.get_device_capability()
|
| 27 |
+
if capability >= (8, 0):
|
| 28 |
+
return torch.bfloat16
|
| 29 |
+
return torch.float32
|
| 30 |
+
return torch.float32
|
| 31 |
+
|
| 32 |
+
COMPUTE_DTYPE = _detect_compute_dtype()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Linear(nn.Linear):
|
| 36 |
+
"""nn.Linear that casts weights to match input dtype in forward.
|
| 37 |
+
Replaces autocast: master weights stay fp32 for optimizer precision,
|
| 38 |
+
but matmuls run in the activation dtype (typically bf16 from embeddings)."""
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
b = None if self.bias is None else self.bias.to(dtype=x.dtype)
|
| 41 |
+
return F.linear(x, self.weight.to(dtype=x.dtype), b)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class RMSNorm(nn.Module):
|
| 45 |
+
def __init__(self, dim):
|
| 46 |
+
super().__init__()
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
return F.rms_norm(x, (x.size(-1),))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class StreamMixer(nn.Module):
|
| 52 |
+
"""Recurrent sequence mixer over M parallel content-routed memory streams,
|
| 53 |
+
with H multi-head sigmoid-gated reads.
|
| 54 |
+
|
| 55 |
+
Per token t:
|
| 56 |
+
- write_value v[t] = W_v(x[t]) shape (D,)
|
| 57 |
+
- read_query q[t] = W_q(x[t]) shape (H, D) — H read heads
|
| 58 |
+
- write_route r[t] = softmax(W_r(x[t])) shape (M,)
|
| 59 |
+
- per-stream log-decay log_α[t] = −LOG_A_MAX_NEG·σ(W_α(x[t]) + wa.bias),
|
| 60 |
+
where wa.bias is a per-stream learnable vector initialized so that streams
|
| 61 |
+
span a wide range of timescales at init (see microgpt.py init).
|
| 62 |
+
Recurrence (per stream i):
|
| 63 |
+
s[t, i] = α[t, i] · s[t-1, i] + r[t, i] · v[t]
|
| 64 |
+
Read (per head h):
|
| 65 |
+
score[t, h, i] = (RMSNorm(q[t, h]) · RMSNorm(s[t, i])) / √D — QK-norm
|
| 66 |
+
out[t, h] = Σ_i σ(score[t, h, i]) · s[t, i]
|
| 67 |
+
Output:
|
| 68 |
+
Σ_out(out[t, :].flatten()) → (n_embd,)
|
| 69 |
+
|
| 70 |
+
Solved via chunked scan: within each chunk of length C,
|
| 71 |
+
Z_local[t] = Σ log_α[j] (j from chunk_start to t)
|
| 72 |
+
s[t] = exp(Z_local[t]) · (state_in + cumsum_in_chunk(exp(−Z_local) · write))
|
| 73 |
+
Cross-chunk: state_in propagates serially through n_chunks=T/C iterations
|
| 74 |
+
(each iteration is O(B·M·D); n_chunks≈8 for T=1024, C=128).
|
| 75 |
+
|
| 76 |
+
With LOG_A_MAX_NEG=0.5 and C=128, Z within a chunk ∈ (−64, 0) — exp(±64)
|
| 77 |
+
fits in float32 range, allowing α to span ~(0.61, 1.0) per step (half-lives
|
| 78 |
+
from ~1.4 steps to ∞). The old single-cumsum scan could only handle
|
| 79 |
+
LOG_A_MAX_NEG < ~0.086 for T=1024.
|
| 80 |
+
|
| 81 |
+
Causality is built into the recurrence; position is implicit (recency + the
|
| 82 |
+
diverse per-stream timescales encode coarse position information).
|
| 83 |
+
|
| 84 |
+
The output linear is named `wo_out` (not `wo`) so the training script's
|
| 85 |
+
residual-init pattern (which matches `wo.weight` / `w_out.weight` suffix)
|
| 86 |
+
misses it — the mixer needs a louder initial residual contribution than the
|
| 87 |
+
standard 1/√(2L) scaling provides.
|
| 88 |
+
"""
|
| 89 |
+
LOG_A_MAX_NEG = 0.5 # caps |log α| per step; α ∈ (exp(-0.5), 1.0) ≈ (0.61, 1.0)
|
| 90 |
+
CHUNK_SIZE = 128 # T must be a multiple of this; controls scan numerical range
|
| 91 |
+
|
| 92 |
+
def __init__(self, n_embd, n_streams, stream_dim, n_read_heads):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.M = n_streams
|
| 95 |
+
self.D = stream_dim
|
| 96 |
+
self.H = n_read_heads
|
| 97 |
+
self.wv = Linear(n_embd, stream_dim, bias=False)
|
| 98 |
+
self.wq = Linear(n_embd, n_read_heads * stream_dim, bias=False)
|
| 99 |
+
self.wr = Linear(n_embd, n_streams, bias=False)
|
| 100 |
+
# wa.bias is per-stream; initialized in microgpt.py to spread timescales.
|
| 101 |
+
self.wa = Linear(n_embd, n_streams, bias=True)
|
| 102 |
+
self.wo_out = Linear(n_read_heads * stream_dim, n_embd, bias=False)
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _rms_norm_last(x):
|
| 106 |
+
return F.rms_norm(x, (x.size(-1),))
|
| 107 |
+
|
| 108 |
+
def _read(self, q_flat, s):
|
| 109 |
+
"""Multi-head sigmoid-gated read with QK-norm.
|
| 110 |
+
q_flat: (..., H*D); s: (..., M, D); returns (..., H*D)."""
|
| 111 |
+
lead = q_flat.shape[:-1]
|
| 112 |
+
q = q_flat.view(*lead, self.H, self.D) # (..., H, D)
|
| 113 |
+
q_n = self._rms_norm_last(q) # (..., H, D)
|
| 114 |
+
s_n = self._rms_norm_last(s) # (..., M, D)
|
| 115 |
+
# score[..., h, i] = (q_n[..., h] · s_n[..., i]) / √D
|
| 116 |
+
scores = torch.einsum('...hd,...md->...hm', q_n, s_n) * (self.D ** -0.5)
|
| 117 |
+
weights = torch.sigmoid(scores) # (..., H, M)
|
| 118 |
+
read = torch.einsum('...hm,...md->...hd', weights, s) # (..., H, D)
|
| 119 |
+
return read.reshape(*lead, self.H * self.D)
|
| 120 |
+
|
| 121 |
+
def _scan(self, log_a, bv):
|
| 122 |
+
"""Chunked stable scan implementing s[t] = α[t]·s[t-1] + bv[t].
|
| 123 |
+
log_a: (B, T, M); bv: (B, T, M, D). Returns s: (B, T, M, D).
|
| 124 |
+
|
| 125 |
+
Within each chunk we use the closed-form cumsum identity. Across chunks
|
| 126 |
+
the incoming state propagates serially through `n_chunks` iterations —
|
| 127 |
+
cheap (B·M·D per step, ~8 steps total at T=1024). The chunking caps Z's
|
| 128 |
+
dynamic range to ±LOG_A_MAX_NEG·CHUNK_SIZE within any single exp() call,
|
| 129 |
+
keeping everything in float range even for fast-decay streams.
|
| 130 |
+
|
| 131 |
+
T need not be a multiple of CHUNK_SIZE: we right-pad the time dim with
|
| 132 |
+
log_a=0 (α=1, no decay) and bv=0 (no write), run the scan, and slice
|
| 133 |
+
back. Matters for prompt prefill where T can be smaller than C.
|
| 134 |
+
"""
|
| 135 |
+
B, T, M, D = bv.shape
|
| 136 |
+
C = self.CHUNK_SIZE
|
| 137 |
+
pad = (C - T % C) % C
|
| 138 |
+
if pad > 0:
|
| 139 |
+
log_a = F.pad(log_a, (0, 0, 0, pad)) # pad T dim only
|
| 140 |
+
bv = F.pad(bv, (0, 0, 0, 0, 0, pad)) # pad T dim only
|
| 141 |
+
Tp = T + pad
|
| 142 |
+
n_chunks = Tp // C
|
| 143 |
+
|
| 144 |
+
log_a_c = log_a.view(B, n_chunks, C, M)
|
| 145 |
+
bv_c = bv.view(B, n_chunks, C, M, D)
|
| 146 |
+
|
| 147 |
+
Z = log_a_c.cumsum(dim=2) # (B, n_c, C, M)
|
| 148 |
+
eZ = torch.exp(Z).unsqueeze(-1) # (B, n_c, C, M, 1)
|
| 149 |
+
inv_eZ = torch.exp(-Z).unsqueeze(-1) # (B, n_c, C, M, 1)
|
| 150 |
+
|
| 151 |
+
# Intra-chunk contribution assuming zero incoming state
|
| 152 |
+
s_intra = (bv_c * inv_eZ).cumsum(dim=2) * eZ # (B, n_c, C, M, D)
|
| 153 |
+
|
| 154 |
+
# Cross-chunk: serial propagation. chunk_decay[c] is the product of α's
|
| 155 |
+
# across the entire chunk (i.e. exp(Z_local[C-1])).
|
| 156 |
+
chunk_decay = eZ[:, :, -1] # (B, n_c, M, 1)
|
| 157 |
+
chunk_end_intra = s_intra[:, :, -1] # (B, n_c, M, D)
|
| 158 |
+
|
| 159 |
+
incomings = []
|
| 160 |
+
state = torch.zeros(B, M, D, device=bv.device, dtype=bv.dtype)
|
| 161 |
+
for c in range(n_chunks):
|
| 162 |
+
incomings.append(state)
|
| 163 |
+
state = chunk_decay[:, c] * state + chunk_end_intra[:, c]
|
| 164 |
+
incoming = torch.stack(incomings, dim=1) # (B, n_c, M, D)
|
| 165 |
+
|
| 166 |
+
# Add carryover: position t inside chunk c receives eZ[c, t] · incoming[c]
|
| 167 |
+
s = s_intra + eZ * incoming.unsqueeze(2) # (B, n_c, C, M, D)
|
| 168 |
+
return s.view(B, Tp, M, D)[:, :T] # slice off padding
|
| 169 |
+
|
| 170 |
+
def forward(self, x):
|
| 171 |
+
out, _ = self.forward_with_state(x)
|
| 172 |
+
return out
|
| 173 |
+
|
| 174 |
+
def forward_with_state(self, x):
|
| 175 |
+
"""Full parallel scan. Returns (output (B,T,C_embd), final_state (B,M,D))."""
|
| 176 |
+
v = self.wv(x) # (B, T, D)
|
| 177 |
+
q = self.wq(x) # (B, T, H*D)
|
| 178 |
+
r = F.softmax(self.wr(x), dim=-1) # (B, T, M)
|
| 179 |
+
log_a = -self.LOG_A_MAX_NEG * torch.sigmoid(self.wa(x)) # (B, T, M)
|
| 180 |
+
bv = r.unsqueeze(-1) * v.unsqueeze(2) # (B, T, M, D)
|
| 181 |
+
s = self._scan(log_a, bv) # (B, T, M, D)
|
| 182 |
+
read = self._read(q, s) # (B, T, H*D)
|
| 183 |
+
return self.wo_out(read), s[:, -1] # state @ last position
|
| 184 |
+
|
| 185 |
+
def step(self, x, state):
|
| 186 |
+
"""One token advance with explicit state. x:(B,1,C_embd), state:(B,M,D).
|
| 187 |
+
Returns (output (B,1,C_embd), new_state (B,M,D)). Cost O(M·D) per token."""
|
| 188 |
+
x_t = x.squeeze(1) # (B, C_embd)
|
| 189 |
+
v = self.wv(x_t) # (B, D)
|
| 190 |
+
q = self.wq(x_t) # (B, H*D)
|
| 191 |
+
r = F.softmax(self.wr(x_t), dim=-1) # (B, M)
|
| 192 |
+
log_a = -self.LOG_A_MAX_NEG * torch.sigmoid(self.wa(x_t)) # (B, M)
|
| 193 |
+
a = torch.exp(log_a) # (B, M)
|
| 194 |
+
write = r.unsqueeze(-1) * v.unsqueeze(1) # (B, M, D)
|
| 195 |
+
s = a.unsqueeze(-1) * state + write # (B, M, D)
|
| 196 |
+
read = self._read(q, s) # (B, H*D)
|
| 197 |
+
return self.wo_out(read).unsqueeze(1), s
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class MLP(nn.Module):
|
| 201 |
+
"""ReLU² MLP: ReLU(W_up x)² · W_down, then W_out. Hidden ≈ 8/3 * n_embd
|
| 202 |
+
keeps param count similar to a 4x GELU MLP."""
|
| 203 |
+
def __init__(self, n_embd):
|
| 204 |
+
super().__init__()
|
| 205 |
+
hidden = (int(8 * n_embd / 3) + 15) // 16 * 16
|
| 206 |
+
self.w_up = Linear(n_embd, hidden, bias=False)
|
| 207 |
+
self.w_down = Linear(n_embd, hidden, bias=False)
|
| 208 |
+
self.w_out = Linear(hidden, n_embd, bias=False)
|
| 209 |
+
def forward(self, x):
|
| 210 |
+
return self.w_out(F.relu(self.w_up(x)).square() * self.w_down(x))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class Block(nn.Module):
|
| 214 |
+
def __init__(self, n_embd, n_streams, stream_dim, n_read_heads):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.ln1 = RMSNorm(n_embd)
|
| 217 |
+
self.mix = StreamMixer(n_embd, n_streams, stream_dim, n_read_heads)
|
| 218 |
+
self.ln2 = RMSNorm(n_embd)
|
| 219 |
+
self.mlp = MLP(n_embd)
|
| 220 |
+
def forward(self, x):
|
| 221 |
+
x, _ = self.forward_with_state(x)
|
| 222 |
+
return x
|
| 223 |
+
def forward_with_state(self, x):
|
| 224 |
+
mix_out, state = self.mix.forward_with_state(self.ln1(x))
|
| 225 |
+
x = x + mix_out
|
| 226 |
+
x = x + self.mlp(self.ln2(x))
|
| 227 |
+
return x, state
|
| 228 |
+
def step(self, x, state):
|
| 229 |
+
mix_out, new_state = self.mix.step(self.ln1(x), state)
|
| 230 |
+
x = x + mix_out
|
| 231 |
+
x = x + self.mlp(self.ln2(x))
|
| 232 |
+
return x, new_state
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class GPT(nn.Module):
|
| 236 |
+
def __init__(self, vocab_size, n_embd, n_layer, n_streams, stream_dim, n_read_heads):
|
| 237 |
+
super().__init__()
|
| 238 |
+
# Pad vocab to multiple of 64 for tensor core efficiency
|
| 239 |
+
padded_vocab_size = ((vocab_size + 63) // 64) * 64
|
| 240 |
+
self.config = dict(
|
| 241 |
+
vocab_size=padded_vocab_size, n_embd=n_embd, n_layer=n_layer,
|
| 242 |
+
n_streams=n_streams, stream_dim=stream_dim, n_read_heads=n_read_heads,
|
| 243 |
+
)
|
| 244 |
+
self.wte = nn.Embedding(padded_vocab_size, n_embd, dtype=COMPUTE_DTYPE)
|
| 245 |
+
self.ln0 = RMSNorm(n_embd)
|
| 246 |
+
self.blocks = nn.ModuleList([
|
| 247 |
+
Block(n_embd, n_streams, stream_dim, n_read_heads) for _ in range(n_layer)
|
| 248 |
+
])
|
| 249 |
+
self.lm_head = Linear(n_embd, padded_vocab_size, bias=False)
|
| 250 |
+
self.lm_head.weight = self.wte.weight # weight tying
|
| 251 |
+
|
| 252 |
+
def forward(self, token_ids):
|
| 253 |
+
logits, _ = self.forward_with_states(token_ids)
|
| 254 |
+
return logits
|
| 255 |
+
|
| 256 |
+
def forward_with_states(self, token_ids):
|
| 257 |
+
"""Full forward; returns (logits, list of per-layer (B,M,D) final states).
|
| 258 |
+
Used to seed incremental generation from a prompt in one shot."""
|
| 259 |
+
x = self.ln0(self.wte(token_ids))
|
| 260 |
+
states = []
|
| 261 |
+
for block in self.blocks:
|
| 262 |
+
x, state = block.forward_with_state(x)
|
| 263 |
+
states.append(state)
|
| 264 |
+
return self.lm_head(x), states
|
| 265 |
+
|
| 266 |
+
def step(self, token_ids, states):
|
| 267 |
+
"""Advance one token using carried streams state. O(L·M·D) per token.
|
| 268 |
+
token_ids: (B, 1). states: list of (B, M, D). Returns (logits (B,1,V), new states)."""
|
| 269 |
+
x = self.ln0(self.wte(token_ids))
|
| 270 |
+
new_states = []
|
| 271 |
+
for block, state in zip(self.blocks, states):
|
| 272 |
+
x, new_state = block.step(x, state)
|
| 273 |
+
new_states.append(new_state)
|
| 274 |
+
return self.lm_head(x), new_states
|
| 275 |
+
|
| 276 |
+
def initial_states(self, batch_size, device, dtype=COMPUTE_DTYPE):
|
| 277 |
+
return [torch.zeros(batch_size, b.mix.M, b.mix.D, device=device, dtype=dtype)
|
| 278 |
+
for b in self.blocks]
|
| 279 |
+
|
| 280 |
+
def get_memory_footprint(self, return_buffers=True):
|
| 281 |
+
"""Total bytes used by parameters (+ buffers). Matches HF transformers' API."""
|
| 282 |
+
mem = sum(p.nelement() * p.element_size() for p in self.parameters())
|
| 283 |
+
if return_buffers:
|
| 284 |
+
mem += sum(b.nelement() * b.element_size() for b in self.buffers())
|
| 285 |
+
return mem
|
| 286 |
+
|
| 287 |
+
@classmethod
|
| 288 |
+
def from_config(cls, config):
|
| 289 |
+
return cls(**config)
|
| 290 |
+
|
| 291 |
+
def to_compute_dtype(self, dtype=None):
|
| 292 |
+
"""Cast all parameters and buffers to COMPUTE_DTYPE for inference.
|
| 293 |
+
Avoids per-call casting in Linear layers — one-time cost at load."""
|
| 294 |
+
dtype = dtype or COMPUTE_DTYPE
|
| 295 |
+
self.to(dtype)
|
| 296 |
+
return self
|
model_configuration.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class StreamMixerConfig(PretrainedConfig):
|
| 8 |
+
model_type = "streammixer"
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
vocab_size=32768,
|
| 13 |
+
n_embd=768,
|
| 14 |
+
n_layer=16,
|
| 15 |
+
n_streams=48,
|
| 16 |
+
stream_dim=96,
|
| 17 |
+
n_read_heads=6,
|
| 18 |
+
max_sequence_length=2048,
|
| 19 |
+
**kwargs,
|
| 20 |
+
):
|
| 21 |
+
super().__init__(**kwargs)
|
| 22 |
+
self.vocab_size = vocab_size
|
| 23 |
+
self.n_embd = n_embd
|
| 24 |
+
self.n_layer = n_layer
|
| 25 |
+
self.n_streams = n_streams
|
| 26 |
+
self.stream_dim = stream_dim
|
| 27 |
+
self.n_read_heads = n_read_heads
|
| 28 |
+
self.max_sequence_length = max_sequence_length
|
| 29 |
+
# Aliases expected by HF internals
|
| 30 |
+
self.hidden_size = n_embd
|
| 31 |
+
self.num_hidden_layers = n_layer
|
| 32 |
+
self.num_attention_heads = n_read_heads
|
| 33 |
+
self.intermediate_size = (int(8 * n_embd / 3) + 15) // 16 * 16
|
modeling.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import math
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 10 |
+
from transformers.generation import GenerationMixin
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutput, CausalLMOutput
|
| 12 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 13 |
+
|
| 14 |
+
from typing import Optional, Union
|
| 15 |
+
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
# Inlined config + model — fully self-contained for HF trust_remote_code.
|
| 18 |
+
# ---------------------------------------------------------------------------
|
| 19 |
+
|
| 20 |
+
class StreamMixerConfig(PretrainedConfig):
|
| 21 |
+
model_type = "streammixer"
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
vocab_size=32768,
|
| 26 |
+
n_embd=768,
|
| 27 |
+
n_layer=16,
|
| 28 |
+
n_streams=48,
|
| 29 |
+
stream_dim=96,
|
| 30 |
+
n_read_heads=6,
|
| 31 |
+
max_sequence_length=2048,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
super().__init__(**kwargs)
|
| 35 |
+
self.vocab_size = vocab_size
|
| 36 |
+
self.n_embd = n_embd
|
| 37 |
+
self.n_layer = n_layer
|
| 38 |
+
self.n_streams = n_streams
|
| 39 |
+
self.stream_dim = stream_dim
|
| 40 |
+
self.n_read_heads = n_read_heads
|
| 41 |
+
self.max_sequence_length = max_sequence_length
|
| 42 |
+
self.hidden_size = n_embd
|
| 43 |
+
self.num_hidden_layers = n_layer
|
| 44 |
+
self.num_attention_heads = n_read_heads
|
| 45 |
+
self.intermediate_size = (int(8 * n_embd / 3) + 15) // 16 * 16
|
| 46 |
+
|
| 47 |
+
# ---------------------------------------------------------------------------
|
| 48 |
+
# Inlined from model.py — keeps modeling.py self-contained for HF cache.
|
| 49 |
+
# ---------------------------------------------------------------------------
|
| 50 |
+
|
| 51 |
+
_DTYPE_MAP = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}
|
| 52 |
+
def _detect_compute_dtype():
|
| 53 |
+
env = os.environ.get("NANOCHAT_DTYPE")
|
| 54 |
+
if env is not None:
|
| 55 |
+
return _DTYPE_MAP[env]
|
| 56 |
+
if torch.cuda.is_available():
|
| 57 |
+
capability = torch.cuda.get_device_capability()
|
| 58 |
+
if capability >= (8, 0):
|
| 59 |
+
return torch.bfloat16
|
| 60 |
+
return torch.float32
|
| 61 |
+
return torch.float32
|
| 62 |
+
|
| 63 |
+
COMPUTE_DTYPE = _detect_compute_dtype()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Linear(nn.Linear):
|
| 67 |
+
def forward(self, x):
|
| 68 |
+
b = None if self.bias is None else self.bias.to(dtype=x.dtype)
|
| 69 |
+
return F.linear(x, self.weight.to(dtype=x.dtype), b)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class RMSNorm(nn.Module):
|
| 73 |
+
def __init__(self, dim):
|
| 74 |
+
super().__init__()
|
| 75 |
+
def forward(self, x):
|
| 76 |
+
return F.rms_norm(x, (x.size(-1),))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class StreamMixer(nn.Module):
|
| 80 |
+
LOG_A_MAX_NEG = 0.5
|
| 81 |
+
CHUNK_SIZE = 128
|
| 82 |
+
|
| 83 |
+
def __init__(self, n_embd, n_streams, stream_dim, n_read_heads):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.M = n_streams
|
| 86 |
+
self.D = stream_dim
|
| 87 |
+
self.H = n_read_heads
|
| 88 |
+
self.wv = Linear(n_embd, stream_dim, bias=False)
|
| 89 |
+
self.wq = Linear(n_embd, n_read_heads * stream_dim, bias=False)
|
| 90 |
+
self.wr = Linear(n_embd, n_streams, bias=False)
|
| 91 |
+
self.wa = Linear(n_embd, n_streams, bias=True)
|
| 92 |
+
self.wo_out = Linear(n_read_heads * stream_dim, n_embd, bias=False)
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def _rms_norm_last(x):
|
| 96 |
+
return F.rms_norm(x, (x.size(-1),))
|
| 97 |
+
|
| 98 |
+
def _read(self, q_flat, s):
|
| 99 |
+
lead = q_flat.shape[:-1]
|
| 100 |
+
q = q_flat.view(*lead, self.H, self.D)
|
| 101 |
+
q_n = self._rms_norm_last(q)
|
| 102 |
+
s_n = self._rms_norm_last(s)
|
| 103 |
+
scores = torch.einsum('...hd,...md->...hm', q_n, s_n) * (self.D ** -0.5)
|
| 104 |
+
weights = torch.sigmoid(scores)
|
| 105 |
+
read = torch.einsum('...hm,...md->...hd', weights, s)
|
| 106 |
+
return read.reshape(*lead, self.H * self.D)
|
| 107 |
+
|
| 108 |
+
def _scan(self, log_a, bv):
|
| 109 |
+
B, T, M, D = bv.shape
|
| 110 |
+
C = self.CHUNK_SIZE
|
| 111 |
+
pad = (C - T % C) % C
|
| 112 |
+
if pad > 0:
|
| 113 |
+
log_a = F.pad(log_a, (0, 0, 0, pad))
|
| 114 |
+
bv = F.pad(bv, (0, 0, 0, 0, 0, pad))
|
| 115 |
+
Tp = T + pad
|
| 116 |
+
n_chunks = Tp // C
|
| 117 |
+
|
| 118 |
+
log_a_c = log_a.view(B, n_chunks, C, M)
|
| 119 |
+
bv_c = bv.view(B, n_chunks, C, M, D)
|
| 120 |
+
|
| 121 |
+
Z = log_a_c.cumsum(dim=2)
|
| 122 |
+
eZ = torch.exp(Z).unsqueeze(-1)
|
| 123 |
+
inv_eZ = torch.exp(-Z).unsqueeze(-1)
|
| 124 |
+
|
| 125 |
+
s_intra = (bv_c * inv_eZ).cumsum(dim=2) * eZ
|
| 126 |
+
|
| 127 |
+
chunk_decay = eZ[:, :, -1]
|
| 128 |
+
chunk_end_intra = s_intra[:, :, -1]
|
| 129 |
+
|
| 130 |
+
incomings = []
|
| 131 |
+
state = torch.zeros(B, M, D, device=bv.device, dtype=bv.dtype)
|
| 132 |
+
for c in range(n_chunks):
|
| 133 |
+
incomings.append(state)
|
| 134 |
+
state = chunk_decay[:, c] * state + chunk_end_intra[:, c]
|
| 135 |
+
incoming = torch.stack(incomings, dim=1)
|
| 136 |
+
|
| 137 |
+
s = s_intra + eZ * incoming.unsqueeze(2)
|
| 138 |
+
return s.view(B, Tp, M, D)[:, :T]
|
| 139 |
+
|
| 140 |
+
def forward(self, x):
|
| 141 |
+
out, _ = self.forward_with_state(x)
|
| 142 |
+
return out
|
| 143 |
+
|
| 144 |
+
def forward_with_state(self, x):
|
| 145 |
+
v = self.wv(x)
|
| 146 |
+
q = self.wq(x)
|
| 147 |
+
r = F.softmax(self.wr(x), dim=-1)
|
| 148 |
+
log_a = -self.LOG_A_MAX_NEG * torch.sigmoid(self.wa(x))
|
| 149 |
+
bv = r.unsqueeze(-1) * v.unsqueeze(2)
|
| 150 |
+
s = self._scan(log_a, bv)
|
| 151 |
+
read = self._read(q, s)
|
| 152 |
+
return self.wo_out(read), s[:, -1]
|
| 153 |
+
|
| 154 |
+
def step(self, x, state):
|
| 155 |
+
x_t = x.squeeze(1)
|
| 156 |
+
v = self.wv(x_t)
|
| 157 |
+
q = self.wq(x_t)
|
| 158 |
+
r = F.softmax(self.wr(x_t), dim=-1)
|
| 159 |
+
log_a = -self.LOG_A_MAX_NEG * torch.sigmoid(self.wa(x_t))
|
| 160 |
+
a = torch.exp(log_a)
|
| 161 |
+
write = r.unsqueeze(-1) * v.unsqueeze(1)
|
| 162 |
+
s = a.unsqueeze(-1) * state + write
|
| 163 |
+
read = self._read(q, s)
|
| 164 |
+
return self.wo_out(read).unsqueeze(1), s
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class MLP(nn.Module):
|
| 168 |
+
def __init__(self, n_embd):
|
| 169 |
+
super().__init__()
|
| 170 |
+
hidden = (int(8 * n_embd / 3) + 15) // 16 * 16
|
| 171 |
+
self.w_up = Linear(n_embd, hidden, bias=False)
|
| 172 |
+
self.w_down = Linear(n_embd, hidden, bias=False)
|
| 173 |
+
self.w_out = Linear(hidden, n_embd, bias=False)
|
| 174 |
+
def forward(self, x):
|
| 175 |
+
return self.w_out(F.relu(self.w_up(x)).square() * self.w_down(x))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class Block(nn.Module):
|
| 179 |
+
def __init__(self, n_embd, n_streams, stream_dim, n_read_heads):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = RMSNorm(n_embd)
|
| 182 |
+
self.mix = StreamMixer(n_embd, n_streams, stream_dim, n_read_heads)
|
| 183 |
+
self.ln2 = RMSNorm(n_embd)
|
| 184 |
+
self.mlp = MLP(n_embd)
|
| 185 |
+
def forward(self, x):
|
| 186 |
+
x, _ = self.forward_with_state(x)
|
| 187 |
+
return x
|
| 188 |
+
def forward_with_state(self, x):
|
| 189 |
+
mix_out, state = self.mix.forward_with_state(self.ln1(x))
|
| 190 |
+
x = x + mix_out
|
| 191 |
+
x = x + self.mlp(self.ln2(x))
|
| 192 |
+
return x, state
|
| 193 |
+
def step(self, x, state):
|
| 194 |
+
mix_out, new_state = self.mix.step(self.ln1(x), state)
|
| 195 |
+
x = x + mix_out
|
| 196 |
+
x = x + self.mlp(self.ln2(x))
|
| 197 |
+
return x, new_state
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class GPT(nn.Module):
|
| 201 |
+
def __init__(self, vocab_size, n_embd, n_layer, n_streams, stream_dim, n_read_heads):
|
| 202 |
+
super().__init__()
|
| 203 |
+
padded_vocab_size = ((vocab_size + 63) // 64) * 64
|
| 204 |
+
self.config = dict(
|
| 205 |
+
vocab_size=padded_vocab_size, n_embd=n_embd, n_layer=n_layer,
|
| 206 |
+
n_streams=n_streams, stream_dim=stream_dim, n_read_heads=n_read_heads,
|
| 207 |
+
)
|
| 208 |
+
self.wte = nn.Embedding(padded_vocab_size, n_embd, dtype=COMPUTE_DTYPE)
|
| 209 |
+
self.ln0 = RMSNorm(n_embd)
|
| 210 |
+
self.blocks = nn.ModuleList([
|
| 211 |
+
Block(n_embd, n_streams, stream_dim, n_read_heads) for _ in range(n_layer)
|
| 212 |
+
])
|
| 213 |
+
self.lm_head = Linear(n_embd, padded_vocab_size, bias=False)
|
| 214 |
+
self.lm_head.weight = self.wte.weight
|
| 215 |
+
|
| 216 |
+
def forward(self, token_ids):
|
| 217 |
+
logits, _ = self.forward_with_states(token_ids)
|
| 218 |
+
return logits
|
| 219 |
+
|
| 220 |
+
def forward_with_states(self, token_ids):
|
| 221 |
+
x = self.ln0(self.wte(token_ids))
|
| 222 |
+
states = []
|
| 223 |
+
for block in self.blocks:
|
| 224 |
+
x, state = block.forward_with_state(x)
|
| 225 |
+
states.append(state)
|
| 226 |
+
return self.lm_head(x), states
|
| 227 |
+
|
| 228 |
+
def step(self, token_ids, states):
|
| 229 |
+
x = self.ln0(self.wte(token_ids))
|
| 230 |
+
new_states = []
|
| 231 |
+
for block, state in zip(self.blocks, states):
|
| 232 |
+
x, new_state = block.step(x, state)
|
| 233 |
+
new_states.append(new_state)
|
| 234 |
+
return self.lm_head(x), new_states
|
| 235 |
+
|
| 236 |
+
def initial_states(self, batch_size, device, dtype=COMPUTE_DTYPE):
|
| 237 |
+
return [torch.zeros(batch_size, b.mix.M, b.mix.D, device=device, dtype=dtype)
|
| 238 |
+
for b in self.blocks]
|
| 239 |
+
|
| 240 |
+
def get_memory_footprint(self, return_buffers=True):
|
| 241 |
+
mem = sum(p.nelement() * p.element_size() for p in self.parameters())
|
| 242 |
+
if return_buffers:
|
| 243 |
+
mem += sum(b.nelement() * b.element_size() for b in self.buffers())
|
| 244 |
+
return mem
|
| 245 |
+
|
| 246 |
+
@classmethod
|
| 247 |
+
def from_config(cls, config):
|
| 248 |
+
return cls(**config)
|
| 249 |
+
|
| 250 |
+
def to_compute_dtype(self, dtype=None):
|
| 251 |
+
dtype = dtype or COMPUTE_DTYPE
|
| 252 |
+
self.to(dtype)
|
| 253 |
+
return self
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# ---------------------------------------------------------------------------
|
| 257 |
+
# HF Model wrappers
|
| 258 |
+
# ---------------------------------------------------------------------------
|
| 259 |
+
|
| 260 |
+
class StreamMixerPreTrainedModel(PreTrainedModel):
|
| 261 |
+
config_class = StreamMixerConfig
|
| 262 |
+
supports_gradient_checkpointing = False
|
| 263 |
+
base_model_prefix = "model"
|
| 264 |
+
|
| 265 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 266 |
+
raise NotImplementedError("Gradient checkpointing is not supported")
|
| 267 |
+
|
| 268 |
+
def _init_weights(self, module):
|
| 269 |
+
pass
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class StreamMixerModel(StreamMixerPreTrainedModel):
|
| 273 |
+
def __init__(self, config: StreamMixerConfig, **kwargs):
|
| 274 |
+
super().__init__(config, **kwargs)
|
| 275 |
+
self.config = config
|
| 276 |
+
inner_cfg = {
|
| 277 |
+
'vocab_size': config.vocab_size,
|
| 278 |
+
'n_embd': config.n_embd,
|
| 279 |
+
'n_layer': config.n_layer,
|
| 280 |
+
'n_streams': config.n_streams,
|
| 281 |
+
'stream_dim': config.stream_dim,
|
| 282 |
+
'n_read_heads': config.n_read_heads,
|
| 283 |
+
}
|
| 284 |
+
self.inner = GPT.from_config(inner_cfg)
|
| 285 |
+
self.inner.to(COMPUTE_DTYPE)
|
| 286 |
+
|
| 287 |
+
def get_input_embeddings(self):
|
| 288 |
+
return self.inner.wte
|
| 289 |
+
|
| 290 |
+
def set_input_embeddings(self, value):
|
| 291 |
+
self.inner.wte = value
|
| 292 |
+
|
| 293 |
+
def get_output_embeddings(self):
|
| 294 |
+
return self.inner.lm_head
|
| 295 |
+
|
| 296 |
+
def set_output_embeddings(self, value):
|
| 297 |
+
self.inner.lm_head = value
|
| 298 |
+
|
| 299 |
+
def _get_hidden_states(self, input_ids):
|
| 300 |
+
x = self.inner.ln0(self.inner.wte(input_ids))
|
| 301 |
+
for block in self.inner.blocks:
|
| 302 |
+
x = block(x)
|
| 303 |
+
return x
|
| 304 |
+
|
| 305 |
+
def forward(
|
| 306 |
+
self,
|
| 307 |
+
input_ids: torch.Tensor,
|
| 308 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 309 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 310 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 311 |
+
output_hidden_states: Optional[bool] = None,
|
| 312 |
+
output_attentions: Optional[bool] = None,
|
| 313 |
+
return_dict: Optional[bool] = None,
|
| 314 |
+
**kwargs,
|
| 315 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 316 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 317 |
+
hidden_states = self._get_hidden_states(input_ids)
|
| 318 |
+
if not return_dict:
|
| 319 |
+
return (hidden_states,)
|
| 320 |
+
return BaseModelOutput(last_hidden_state=hidden_states)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class StreamMixerForCausalLM(GenerationMixin, StreamMixerPreTrainedModel):
|
| 324 |
+
_keys_to_ignore_on_load_unexpected = set()
|
| 325 |
+
|
| 326 |
+
def __init__(self, config: StreamMixerConfig, **kwargs):
|
| 327 |
+
super().__init__(config, **kwargs)
|
| 328 |
+
self.model = StreamMixerModel(config, **kwargs)
|
| 329 |
+
self.vocab_size = config.vocab_size
|
| 330 |
+
self.config = config
|
| 331 |
+
|
| 332 |
+
def __getattr__(self, name):
|
| 333 |
+
if name == "all_tied_weights_keys":
|
| 334 |
+
return {}
|
| 335 |
+
return super().__getattr__(name)
|
| 336 |
+
|
| 337 |
+
def get_input_embeddings(self):
|
| 338 |
+
return self.model.inner.wte
|
| 339 |
+
|
| 340 |
+
def set_input_embeddings(self, value):
|
| 341 |
+
self.model.inner.wte = value
|
| 342 |
+
|
| 343 |
+
def get_output_embeddings(self):
|
| 344 |
+
return self.model.inner.lm_head
|
| 345 |
+
|
| 346 |
+
def set_output_embeddings(self, value):
|
| 347 |
+
self.model.inner.lm_head = value
|
| 348 |
+
|
| 349 |
+
def can_generate(self):
|
| 350 |
+
return True
|
| 351 |
+
|
| 352 |
+
def forward(
|
| 353 |
+
self,
|
| 354 |
+
input_ids: torch.Tensor,
|
| 355 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 356 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 357 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 358 |
+
output_hidden_states: Optional[bool] = None,
|
| 359 |
+
output_attentions: Optional[bool] = None,
|
| 360 |
+
return_dict: Optional[bool] = None,
|
| 361 |
+
labels: Optional[torch.LongTensor] = None,
|
| 362 |
+
**kwargs,
|
| 363 |
+
) -> Union[tuple, CausalLMOutput]:
|
| 364 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 365 |
+
hidden_states = self.model._get_hidden_states(input_ids)
|
| 366 |
+
logits = self.model.inner.lm_head(hidden_states)
|
| 367 |
+
|
| 368 |
+
loss = None
|
| 369 |
+
if labels is not None:
|
| 370 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 371 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 372 |
+
loss = F.cross_entropy(
|
| 373 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 374 |
+
shift_labels.view(-1),
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
if not return_dict:
|
| 378 |
+
output = (logits,)
|
| 379 |
+
return ((loss,) + output) if loss is not None else output
|
| 380 |
+
|
| 381 |
+
return CausalLMOutput(
|
| 382 |
+
loss=loss,
|
| 383 |
+
logits=logits,
|
| 384 |
+
)
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ea53044d5dfe2a6cf2005e1e84fea3d18844b5620b973aac965e664824c690a4
|
| 3 |
+
size 92448927
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "<|bos|>",
|
| 3 |
+
"eos_token": "<|bos|>",
|
| 4 |
+
"pad_token": "<|bos|>",
|
| 5 |
+
"additional_special_tokens": [
|
| 6 |
+
"<|bos|>"
|
| 7 |
+
]
|
| 8 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"model_max_length": 1024,
|
| 4 |
+
"bos_token": "<|bos|>",
|
| 5 |
+
"eos_token": "<|bos|>",
|
| 6 |
+
"pad_token": "<|bos|>",
|
| 7 |
+
"added_tokens_decoder": {
|
| 8 |
+
"0": {
|
| 9 |
+
"content": "<|bos|>",
|
| 10 |
+
"lstrip": false,
|
| 11 |
+
"rstrip": false,
|
| 12 |
+
"single_word": false,
|
| 13 |
+
"special": true
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
}
|