Upload Thirty-30M-Instruct (Original BF16 + FP16/INT8/INT4 quantized safetensors + CLI/evals)
9a03799 verified Download model.py from respinosamena/Thirty-30M-Instruct: direct link, hf CLI and curl.
- Browser
- Download file 24.8 kB
-
https://huggingface.co/respinosamena/Thirty-30M-Instruct/resolve/main/model.py
- Command line
-
hf download hf://respinosamena/Thirty-30M-Instruct/model.py
-
curl -L -o model.py https://huggingface.co/respinosamena/Thirty-30M-Instruct/resolve/main/model.py
24.8 kB
| """Standalone TurboSynthesis-30M dense language model (zero external repo dependencies). | |
| Winner of the strix-30m-lab architecture and tokenizer tournament (30,119,281 params, | |
| 8,192+ token context, 0.99554 weighted BPB, 88.9% multi-depth passkey retrieval, | |
| 43.8k tok/s @ 1k and 21.2k tok/s @ 8k on AMD Strix Halo gfx1151). | |
| Features: | |
| - Factorized tied embeddings (vocab=32,768, embed_rank=192 -> d_model=384) | |
| - Zero-FLOP hashed bigram Engram residual table (4,096 x 32) | |
| - Input-dependent causal bigram smear gate | |
| - NanoRes-ReLU2 trunk (parameter-free RMSNorm, x0 skip highway, mid-layer backout, | |
| first-layer v0 value residual, squared ReLU 4d MLP, softcapped logits) | |
| - Zero-overhead 4-tap shifted-slice Canon-Lite local token mixer per block | |
| - Separate Q/K/V GQA projections (6 Q heads / 2 KV heads) + QK-Norm + dynamic RoPE | |
| with log-length attention scaling beyond 1,024 tokens for >=8,192 context | |
| - Exact step-level KV-cache preserving engram, smear, Canon-Lite shift, and v0 parity | |
| """ | |
| from __future__ import annotations | |
| import os | |
| # Activate AMD ROCm AOTriton Flash/Mem-Efficient SDPA on gfx1151 when available | |
| os.environ.setdefault("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL", "1") | |
| import argparse | |
| from dataclasses import asdict, dataclass | |
| import json | |
| from pathlib import Path | |
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch.utils.checkpoint import checkpoint | |
| class ModelConfig: | |
| vocab_size: int = 32768 | |
| seq_len: int = 8192 | |
| d_model: int = 384 | |
| n_layer: int = 15 | |
| n_head: int = 6 | |
| n_kv_head: int = 2 | |
| mlp_mult: int = 4 | |
| window_size: int = 1024 | |
| global_every: int = 4 | |
| engram_buckets: int = 4096 | |
| engram_dim: int = 32 | |
| rope_theta: float = 500000.0 | |
| logit_softcap: float = 15.0 | |
| tie_embeddings: bool = True | |
| embed_rank: int = 192 | |
| log_scale_base: int = 1024 | |
| ce_chunk_size: int = 0 | |
| TurboSynthesisConfig = ModelConfig | |
| def build_rope_cache( | |
| seq_len: int, | |
| head_dim: int, | |
| base: float, | |
| device: Optional[torch.device] = None, | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) / head_dim)) | |
| t = torch.arange(seq_len, dtype=torch.float32, device=device) | |
| freqs = torch.outer(t, inv_freq) | |
| return freqs.cos()[None, None, :, :], freqs.sin()[None, None, :, :] | |
| def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: | |
| d = x.shape[-1] // 2 | |
| x1, x2 = x[..., :d], x[..., d:] | |
| return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1) | |
| def _rms_norm(x: torch.Tensor) -> torch.Tensor: | |
| return F.rms_norm(x, (x.size(-1),)) | |
| class KVCache: | |
| """Exact stateful inference cache for TurboSynthesis (Engram + Smear + Canon-Lite + GQA).""" | |
| def __init__(self, n_layer: int): | |
| self.pos: int = 0 | |
| self.prev_token: Optional[torch.Tensor] = None | |
| self.prev_x_pre_smear: Optional[torch.Tensor] = None | |
| self.h_hist: list[Optional[torch.Tensor]] = [None] * n_layer | |
| self.k_cache: list[Optional[torch.Tensor]] = [None] * n_layer | |
| self.v_cache: list[Optional[torch.Tensor]] = [None] * n_layer | |
| class TurboBlock(nn.Module): | |
| def __init__(self, cfg: ModelConfig, layer_idx: int): | |
| super().__init__() | |
| assert cfg.d_model % cfg.n_head == 0 and cfg.n_head % cfg.n_kv_head == 0 | |
| self.layer_idx = layer_idx | |
| self.is_global = ((layer_idx + 1) % cfg.global_every == 0) or (layer_idx == cfg.n_layer - 1) | |
| self.n_head = cfg.n_head | |
| self.n_kv_head = cfg.n_kv_head | |
| self.head_dim = cfg.d_model // cfg.n_head | |
| self.window_size = cfg.window_size | |
| self.log_scale_base = cfg.log_scale_base | |
| # 4-tap shifted-slice Canon-Lite local token mixer: taps t, t-1, t-2, t-4 | |
| self.shift_w = nn.Parameter(torch.zeros(3, cfg.d_model)) | |
| # Separate Q, K, V projections for independent Muon orthogonalization during training | |
| q_dim = self.n_head * self.head_dim | |
| kv_dim = self.n_kv_head * self.head_dim | |
| self.c_q = nn.Linear(cfg.d_model, q_dim, bias=False) | |
| self.c_k = nn.Linear(cfg.d_model, kv_dim, bias=False) | |
| self.c_v = nn.Linear(cfg.d_model, kv_dim, bias=False) | |
| self.c_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) | |
| self.v_res_gate = nn.Linear(16, self.n_kv_head, bias=False) if layer_idx > 0 else None | |
| hidden = cfg.mlp_mult * cfg.d_model | |
| self.c_fc = nn.Linear(cfg.d_model, hidden, bias=False) | |
| self.c_mlp_proj = nn.Linear(hidden, cfg.d_model, bias=False) | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| cos: torch.Tensor, | |
| sin: torch.Tensor, | |
| v0: Optional[torch.Tensor] = None, | |
| kv_cache: Optional[KVCache] = None, | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| B, T, C = x.shape | |
| h = _rms_norm(x) | |
| if kv_cache is not None: | |
| hist = kv_cache.h_hist[self.layer_idx] | |
| if hist is None: | |
| hist = h.new_zeros(B, 4, C) | |
| buf = torch.cat([hist, h], dim=1) | |
| sw = self.shift_w.to(h.dtype) | |
| h_attn = h + sw[0] * buf[:, 3 : T + 3, :] + sw[1] * buf[:, 2 : T + 2, :] + sw[2] * buf[:, :T, :] | |
| kv_cache.h_hist[self.layer_idx] = buf[:, -4:] | |
| elif T > 1: | |
| hp = F.pad(h, (0, 0, 4, 0)) | |
| sw = self.shift_w.to(h.dtype) | |
| h_attn = h + sw[0] * hp[:, 3 : T + 3, :] + sw[1] * hp[:, 2 : T + 2, :] + sw[2] * hp[:, :T, :] | |
| else: | |
| h_attn = h | |
| q = self.c_q(h_attn).view(B, T, self.n_head, self.head_dim).transpose(1, 2) | |
| k = self.c_k(h_attn).view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2) | |
| v = self.c_v(h_attn).view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2) | |
| if self.layer_idx == 0: | |
| v_first = v | |
| else: | |
| v_first = v0 | |
| if v0 is not None and self.v_res_gate is not None: | |
| gate = torch.sigmoid(self.v_res_gate(h[..., :16])).transpose(1, 2).unsqueeze(-1) | |
| v = (1.0 - gate) * v + gate * v0 | |
| q = _rms_norm(apply_rope(q, cos, sin)) * 1.15 | |
| k = _rms_norm(apply_rope(k, cos, sin)) * 1.15 | |
| pos_offset = kv_cache.pos if kv_cache is not None else 0 | |
| total_pos = pos_offset + T | |
| if self.log_scale_base > 0 and total_pos > self.log_scale_base: | |
| pos_ids = torch.arange(pos_offset + 1, total_pos + 1, device=x.device, dtype=torch.float32) | |
| scale = (1.0 + 0.15 * torch.log(torch.clamp(pos_ids / float(self.log_scale_base), min=1.0))).to(q.dtype) | |
| q = q * scale[None, None, :, None] | |
| enable_gqa = self.n_kv_head != self.n_head | |
| if kv_cache is not None: | |
| k_prev = kv_cache.k_cache[self.layer_idx] | |
| v_prev = kv_cache.v_cache[self.layer_idx] | |
| k_full = torch.cat([k_prev, k], dim=2) if k_prev is not None else k | |
| v_full = torch.cat([v_prev, v], dim=2) if v_prev is not None else v | |
| kv_cache.k_cache[self.layer_idx] = k_full | |
| kv_cache.v_cache[self.layer_idx] = v_full | |
| if pos_offset == 0: | |
| y = F.scaled_dot_product_attention(q, k_full, v_full, is_causal=True, enable_gqa=enable_gqa) | |
| elif T == 1: | |
| y = F.scaled_dot_product_attention(q, k_full, v_full, is_causal=False, enable_gqa=enable_gqa) | |
| else: | |
| q_pos = torch.arange(pos_offset, total_pos, device=x.device).unsqueeze(1) | |
| k_pos = torch.arange(total_pos, device=x.device).unsqueeze(0) | |
| y = F.scaled_dot_product_attention( | |
| q, k_full, v_full, attn_mask=(k_pos <= q_pos), enable_gqa=enable_gqa | |
| ) | |
| else: | |
| y = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=enable_gqa) | |
| x = x + self.c_proj(y.transpose(1, 2).contiguous().view(B, T, C)) | |
| x = x + self.c_mlp_proj(F.relu(self.c_fc(_rms_norm(x))).square()) | |
| return x, v_first | |
| def _load_any_state_dict(ckpt_path: Path) -> dict[str, torch.Tensor]: | |
| """Load standard Safetensors, block-32 INT8/INT4 Safetensors, or GGUF v3 weights.""" | |
| if ckpt_path.suffix.lower() == ".gguf": | |
| import gguf | |
| reader = gguf.GGUFReader(str(ckpt_path)) | |
| return { | |
| t.name: torch.from_numpy(gguf.quants.dequantize(t.data, t.tensor_type).copy()) | |
| for t in reader.tensors | |
| } | |
| from safetensors.torch import load_file | |
| raw = load_file(str(ckpt_path), device="cpu") | |
| out: dict[str, torch.Tensor] = {} | |
| handled: set[str] = set() | |
| for key in list(raw.keys()): | |
| if key.endswith(".__q8"): | |
| base = key[: -len(".__q8")] | |
| q8 = raw[key].float() | |
| sc = raw[f"{base}.__scale"].float() | |
| rows = q8.shape[0] | |
| out[base] = (q8 * sc).reshape(rows, -1).contiguous() | |
| handled.update((key, f"{base}.__scale")) | |
| elif key.endswith(".__q4"): | |
| base = key[: -len(".__q4")] | |
| packed = raw[key] | |
| sc = raw[f"{base}.__scale"].float() | |
| mn = raw[f"{base}.__min"].float() | |
| lo = packed & 0x0F | |
| hi = (packed >> 4) & 0x0F | |
| q4 = torch.cat([lo, hi], dim=-1).float() | |
| rows = q4.shape[0] | |
| out[base] = (q4 * sc + mn).reshape(rows, -1).contiguous() | |
| handled.update((key, f"{base}.__scale", f"{base}.__min")) | |
| for key, val in raw.items(): | |
| if key not in handled and not key.endswith((".__scale", ".__min")): | |
| out[key] = val | |
| return out | |
| class TurboSynthesis(nn.Module): | |
| def __init__(self, cfg: ModelConfig): | |
| super().__init__() | |
| self.cfg = cfg | |
| if cfg.embed_rank > 0: | |
| self.wte = nn.Embedding(cfg.vocab_size, cfg.embed_rank) | |
| self.embed_proj = nn.Linear(cfg.embed_rank, cfg.d_model, bias=False) | |
| self.lm_head = None | |
| else: | |
| self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model) | |
| self.embed_proj = None | |
| self.lm_head = None if cfg.tie_embeddings else nn.Linear(cfg.d_model, cfg.vocab_size, bias=False) | |
| if cfg.engram_buckets > 0 and cfg.engram_dim > 0: | |
| self.engram_wte = nn.Embedding(cfg.engram_buckets, cfg.engram_dim) | |
| self.engram_proj = nn.Linear(cfg.engram_dim, cfg.d_model, bias=False) | |
| self.engram_lambda = nn.Parameter(torch.zeros(1)) | |
| else: | |
| self.engram_wte = None | |
| self.engram_proj = None | |
| self.engram_lambda = None | |
| self.blocks = nn.ModuleList([TurboBlock(cfg, i) for i in range(cfg.n_layer)]) | |
| self.resid_lambdas = nn.Parameter(torch.linspace(1.12, 1.02, cfg.n_layer)) | |
| self.x0_lambdas = nn.Parameter(torch.linspace(0.20, 0.05, cfg.n_layer)) | |
| self.smear_gate = nn.Linear(16, 1, bias=False) | |
| self.smear_lambda = nn.Parameter(torch.zeros(1)) | |
| self.backout_lambda = nn.Parameter(torch.tensor([0.15])) | |
| cos, sin = build_rope_cache(cfg.seq_len, cfg.d_model // cfg.n_head, cfg.rope_theta) | |
| self.register_buffer("cos", cos, persistent=False) | |
| self.register_buffer("sin", sin, persistent=False) | |
| self._init_weights() | |
| def set_rope_theta(self, new_theta: float, seq_len: Optional[int] = None) -> None: | |
| self.cfg.rope_theta = float(new_theta) | |
| target_len = seq_len if seq_len is not None else self.cos.size(2) | |
| cos, sin = build_rope_cache( | |
| target_len, self.cfg.d_model // self.cfg.n_head, new_theta, device=self.wte.weight.device | |
| ) | |
| self.register_buffer("cos", cos, persistent=False) | |
| self.register_buffer("sin", sin, persistent=False) | |
| def set_log_scale_base(self, base_len: int) -> None: | |
| self.cfg.log_scale_base = int(base_len) | |
| for blk in self.blocks: | |
| blk.log_scale_base = int(base_len) | |
| def _init_weights(self) -> None: | |
| d = self.cfg.d_model | |
| nn.init.normal_(self.wte.weight, mean=0.0, std=0.5 * (d ** -0.5) if self.embed_proj is None else 0.02) | |
| if self.embed_proj is not None: | |
| nn.init.normal_(self.embed_proj.weight, mean=0.0, std=(self.cfg.embed_rank ** -0.5)) | |
| if self.lm_head is not None: | |
| nn.init.normal_(self.lm_head.weight, mean=0.0, std=0.001) | |
| if self.engram_wte is not None: | |
| nn.init.normal_(self.engram_wte.weight, mean=0.0, std=0.02) | |
| nn.init.normal_(self.engram_proj.weight, mean=0.0, std=(self.cfg.engram_dim ** -0.5)) | |
| s = (3.0 ** 0.5) * (d ** -0.5) | |
| for blk in self.blocks: | |
| nn.init.uniform_(blk.c_q.weight, -s, s) | |
| nn.init.uniform_(blk.c_k.weight, -s, s) | |
| nn.init.uniform_(blk.c_v.weight, -s, s) | |
| nn.init.zeros_(blk.c_proj.weight) | |
| if blk.v_res_gate is not None: | |
| nn.init.uniform_(blk.v_res_gate.weight, 0.0, 0.02) | |
| nn.init.uniform_(blk.c_fc.weight, -0.45 * s, 0.45 * s) | |
| nn.init.zeros_(blk.c_mlp_proj.weight) | |
| nn.init.uniform_(self.smear_gate.weight, 0.0, 0.02) | |
| def _compute_logits(self, x_flat: torch.Tensor) -> torch.Tensor: | |
| if self.embed_proj is not None: | |
| h_rank = F.linear(x_flat, self.embed_proj.weight.t()) | |
| logits = F.linear(h_rank, self.wte.weight) | |
| elif self.lm_head is not None: | |
| logits = self.lm_head(x_flat) | |
| else: | |
| logits = F.linear(x_flat, self.wte.weight) | |
| logits = logits.float() | |
| cap = self.cfg.logit_softcap | |
| return cap * torch.tanh(logits / cap) | |
| def _chunk_ce_loss(self, x_chunk: torch.Tensor, y_chunk: torch.Tensor) -> torch.Tensor: | |
| logits = self._compute_logits(x_chunk) | |
| return F.cross_entropy(logits, y_chunk, ignore_index=-1, reduction="sum") | |
| def forward( | |
| self, | |
| idx: torch.Tensor, | |
| targets: Optional[torch.Tensor] = None, | |
| kv_cache: Optional[KVCache] = None, | |
| last_only: bool = False, | |
| ) -> torch.Tensor: | |
| B, T = idx.shape | |
| pos = kv_cache.pos if kv_cache is not None else 0 | |
| need_len = pos + T | |
| if need_len > self.cos.size(2): | |
| self.set_rope_theta(self.cfg.rope_theta, seq_len=max(need_len, self.cos.size(2) * 2)) | |
| x = self.wte(idx) | |
| if self.embed_proj is not None: | |
| x = self.embed_proj(x) | |
| x = _rms_norm(x) | |
| if self.engram_wte is not None: | |
| if kv_cache is not None and kv_cache.prev_token is not None: | |
| prev_idx = torch.cat([kv_cache.prev_token, idx[:, :-1]], dim=1) | |
| else: | |
| prev_idx = F.pad(idx[:, :-1], (1, 0), value=0) | |
| if kv_cache is not None: | |
| kv_cache.prev_token = idx[:, -1:].to(torch.int64) | |
| bh = ((prev_idx.to(torch.int64) * 2654435761) ^ idx.to(torch.int64)) & (self.cfg.engram_buckets - 1) | |
| x = x + self.engram_lambda.to(x.dtype) * self.engram_proj(self.engram_wte(bh)) | |
| x_pre_smear = x | |
| if kv_cache is not None: | |
| if kv_cache.prev_x_pre_smear is not None: | |
| x_prev = torch.cat([kv_cache.prev_x_pre_smear, x_pre_smear[:, :-1]], dim=1) | |
| gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x_pre_smear[:, :, :16])) | |
| x = x_pre_smear + gate * x_prev | |
| elif T > 1: | |
| gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x_pre_smear[:, 1:, :16])) | |
| x = torch.cat([x_pre_smear[:, :1], x_pre_smear[:, 1:] + gate * x_pre_smear[:, :-1]], dim=1) | |
| kv_cache.prev_x_pre_smear = x_pre_smear[:, -1:] | |
| elif T > 1: | |
| gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, 1:, :16])) | |
| x = torch.cat([x[:, :1], x[:, 1:] + gate * x[:, :-1]], dim=1) | |
| cos = self.cos[:, :, pos : pos + T, :].to(x.dtype) | |
| sin = self.sin[:, :, pos : pos + T, :].to(x.dtype) | |
| x0 = x | |
| v0 = None | |
| x_mid = None | |
| mid_idx = self.cfg.n_layer // 2 | |
| for i, blk in enumerate(self.blocks): | |
| x = self.resid_lambdas[i].to(x.dtype) * x + self.x0_lambdas[i].to(x.dtype) * x0 | |
| x, v_first = blk(x, cos, sin, v0, kv_cache=kv_cache) | |
| if i == 0: | |
| v0 = v_first | |
| if i == mid_idx: | |
| x_mid = x | |
| if kv_cache is not None: | |
| kv_cache.pos = need_len | |
| if x_mid is not None: | |
| x = x - self.backout_lambda.to(x.dtype) * x_mid | |
| x = _rms_norm(x) | |
| if targets is None: | |
| if last_only: | |
| logits_last = self._compute_logits(x[:, -1, :]) | |
| return logits_last.unsqueeze(1) | |
| return self._compute_logits(x.view(-1, x.size(-1))).view(B, T, -1) | |
| x_flat = x.reshape(-1, x.size(-1)) | |
| y_flat = targets.reshape(-1) | |
| cs = self.cfg.ce_chunk_size | |
| if cs <= 0 or cs >= x_flat.size(0): | |
| return F.cross_entropy(self._compute_logits(x_flat), y_flat, ignore_index=-1) | |
| n_tok = x_flat.size(0) | |
| total_loss = x_flat.new_zeros((), dtype=torch.float32) | |
| for start in range(0, n_tok, cs): | |
| xc = x_flat[start : start + cs] | |
| yc = y_flat[start : start + cs] | |
| if torch.is_grad_enabled() and xc.requires_grad: | |
| total_loss = total_loss + checkpoint(self._chunk_ce_loss, xc, yc, use_reentrant=False) | |
| else: | |
| total_loss = total_loss + self._chunk_ce_loss(xc, yc) | |
| valid_count = (y_flat != -1).sum().clamp(min=1).to(torch.float32) | |
| return total_loss / valid_count | |
| def generate( | |
| self, | |
| idx: torch.Tensor, | |
| max_new_tokens: int = 128, | |
| temperature: float = 0.65, | |
| top_k: int = 40, | |
| top_p: float = 1.0, | |
| repetition_penalty: float = 1.12, | |
| eos_token_id: Optional[int] = None, | |
| use_cache: bool = True, | |
| ) -> torch.Tensor: | |
| self.eval() | |
| out = idx | |
| kv = KVCache(self.cfg.n_layer) if use_cache else None | |
| if use_cache: | |
| logits = self.forward(out, kv_cache=kv, last_only=True)[:, -1, :] | |
| else: | |
| logits = self.forward(out, last_only=True)[:, -1, :] | |
| for step in range(max_new_tokens): | |
| if step > 0: | |
| if use_cache: | |
| logits = self.forward(out[:, -1:], kv_cache=kv, last_only=True)[:, -1, :] | |
| else: | |
| logits = self.forward(out, last_only=True)[:, -1, :] | |
| next_logits = logits.float() | |
| if repetition_penalty != 1.0: | |
| for b in range(out.size(0)): | |
| seen = torch.unique(out[b]) | |
| vals = next_logits[b, seen] | |
| next_logits[b, seen] = torch.where(vals < 0, vals * repetition_penalty, vals / repetition_penalty) | |
| if temperature <= 0.0: | |
| next_tok = next_logits.argmax(dim=-1, keepdim=True) | |
| else: | |
| scaled = next_logits / temperature | |
| if 0 < top_k < scaled.size(-1): | |
| v, _ = torch.topk(scaled, top_k) | |
| scaled = scaled.masked_fill(scaled < v[:, [-1]], float("-inf")) | |
| if 0.0 < top_p < 1.0: | |
| sorted_logits, sorted_idx = torch.sort(scaled, descending=True) | |
| cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) | |
| drop_mask = cum_probs > top_p | |
| drop_mask[:, 1:] = drop_mask[:, :-1].clone() | |
| drop_mask[:, 0] = False | |
| scaled = scaled.scatter(1, sorted_idx, sorted_logits.masked_fill(drop_mask, float("-inf"))) | |
| probs = F.softmax(scaled, dim=-1) | |
| next_tok = torch.multinomial(probs, num_samples=1) | |
| out = torch.cat([out, next_tok], dim=1) | |
| if eos_token_id is not None and (next_tok == eos_token_id).all(): | |
| break | |
| return out | |
| def from_pretrained( | |
| cls, | |
| path: str | Path, | |
| config_path: Optional[str | Path] = None, | |
| device: str | torch.device = "auto", | |
| dtype: torch.dtype = torch.bfloat16, | |
| ) -> "TurboSynthesis": | |
| p = Path(path) | |
| ckpt_path = p / "model.safetensors" if p.is_dir() else p | |
| if config_path is not None: | |
| cfg_file = Path(config_path) | |
| elif (ckpt_path.parent / "config.json").exists(): | |
| cfg_file = ckpt_path.parent / "config.json" | |
| else: | |
| cfg_file = ckpt_path.parent.parent / "config.json" | |
| if cfg_file.exists(): | |
| raw = json.loads(cfg_file.read_text()) | |
| cfg_dict = raw.get("config", raw) | |
| valid = {f for f in ModelConfig.__dataclass_fields__} | |
| cfg = ModelConfig(**{k: v for k, v in cfg_dict.items() if k in valid}) | |
| else: | |
| cfg = ModelConfig() | |
| if device == "auto": | |
| target_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") | |
| else: | |
| target_device = torch.device(device) | |
| model = cls(cfg) | |
| sd = _load_any_state_dict(ckpt_path) | |
| model.load_state_dict(sd, strict=True) | |
| model = model.to(device=target_device, dtype=dtype) | |
| model.set_rope_theta(cfg.rope_theta, seq_len=cfg.seq_len) | |
| model.set_log_scale_base(cfg.log_scale_base) | |
| model.eval() | |
| return model | |
| Strix30M = TurboSynthesis | |
| def load_pretrained( | |
| export_dir: str | Path, | |
| device: str | torch.device = "auto", | |
| dtype: torch.dtype = torch.bfloat16, | |
| ) -> TurboSynthesis: | |
| return TurboSynthesis.from_pretrained(export_dir, device=device, dtype=dtype) | |
| def _run_self_test(export_dir: Path) -> None: | |
| dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") | |
| print(f"[Self-Test] device={dev} | export_dir={export_dir}") | |
| model = load_pretrained(export_dir, device=dev, dtype=torch.bfloat16) | |
| n_params = sum(p.numel() for p in model.parameters()) | |
| print(f"[Self-Test] loaded strict=True | params={n_params:,}") | |
| assert n_params == 30_119_281, f"Unexpected param count: {n_params}" | |
| # Verify exact float32 KV-cache parity including crossing log_scale_base=1024 boundary | |
| f32_model = load_pretrained(export_dir, device=dev, dtype=torch.float32) | |
| for start_len in (16, 1020): | |
| prompt = torch.randint(4, 2000, (1, start_len), device=dev, dtype=torch.long) | |
| out_cached = f32_model.generate(prompt, max_new_tokens=16, temperature=0.0, repetition_penalty=1.0, use_cache=True) | |
| out_full = f32_model.generate(prompt, max_new_tokens=16, temperature=0.0, repetition_penalty=1.0, use_cache=False) | |
| assert torch.equal(out_cached, out_full), f"KV-cache parity failed at start_len={start_len}" | |
| print(f"[Self-Test] KV-cache greedy parity OK (prompt_len={start_len}, 16 tokens)") | |
| # Verify 8,192-token forward pass | |
| with torch.inference_mode(), torch.amp.autocast(dev.type, dtype=torch.bfloat16, enabled=(dev.type == "cuda")): | |
| x8k = torch.randint(4, 2000, (1, 8192), device=dev, dtype=torch.long) | |
| logits = model(x8k, last_only=True) | |
| assert logits.shape == (1, 1, model.cfg.vocab_size) and torch.isfinite(logits).all() | |
| loss = model(x8k[:, :-1], targets=x8k[:, 1:]) | |
| assert torch.isfinite(loss) | |
| print(f"[Self-Test] 8,192-token forward & CE pass OK (random loss={float(loss):.4f})") | |
| if __name__ == "__main__": | |
| default_dir = Path(__file__).resolve().parent | |
| parser = argparse.ArgumentParser(description="Standalone TurboSynthesis-30M inference & self-test") | |
| parser.add_argument("--dir", type=Path, default=default_dir, help="Directory with model.safetensors, config.json, tokenizer.json") | |
| parser.add_argument("--prompt", type=str, default=None, help="Prompt string to complete") | |
| parser.add_argument("--max-new-tokens", type=int, default=128) | |
| parser.add_argument("--temperature", type=float, default=0.65) | |
| parser.add_argument("--self-test", action="store_true") | |
| args = parser.parse_args() | |
| if args.self_test or args.prompt is None: | |
| _run_self_test(args.dir) | |
| if args.prompt is not None: | |
| from tokenizers import Tokenizer | |
| tok = Tokenizer.from_file(str(args.dir / "tokenizer.json")) | |
| model = load_pretrained(args.dir) | |
| dev = next(model.parameters()).device | |
| bos = tok.token_to_id("<|bos|>") | |
| ids = ([] if bos is None else [bos]) + tok.encode(args.prompt).ids | |
| x = torch.tensor([ids], dtype=torch.long, device=dev) | |
| y = model.generate(x, max_new_tokens=args.max_new_tokens, temperature=args.temperature, top_k=40, repetition_penalty=1.12) | |
| print(tok.decode(y[0].tolist(), skip_special_tokens=True)) | |