File size: 10,590 Bytes
9788a47 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | """
VoidNet v3 — Standalone Reference Implementation & Inference Wrapper
Architecture: English -> Void Packer + UltraFlashAttention Void Core (RoPE + SwiGLU)
+ Separate 2-Layer FiLM Void-to-English Translator + V_endText Instant Halt.
Usage:
from modeling_voidnet import VoidNetModel
model = VoidNetModel.from_pretrained("VoidOSS/VoidNet-25M-TinyStories")
print(model.generate("Once upon a time, a little dog named Max "))
"""
import json
from pathlib import Path
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
norm = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
return (x.float() * norm).to(x.dtype) * self.weight
def precompute_rope(seq_len: int, head_dim: int, device: torch.device, base: float = 10000.0):
inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
t = torch.arange(seq_len, device=device).float()
freqs = torch.outer(t, inv_freq)
return torch.cos(freqs)[None, None, :, :], torch.sin(freqs)[None, None, :, :]
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
T = x.shape[2]
c = cos[:, :, :T, :].to(x.dtype)
s = sin[:, :, :T, :].to(x.dtype)
x1, x2 = x[..., ::2], x[..., 1::2]
return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1).flatten(-2)
class UltraFlashAttentionV3(nn.Module):
def __init__(self, d_model: int, n_heads: int = 4, compress: int = 2):
super().__init__()
self.n_heads = n_heads
self.attn_dim = (d_model // compress // n_heads) * n_heads
self.head_dim = self.attn_dim // n_heads
self.qkv_proj = nn.Linear(d_model, 3 * self.attn_dim, bias=False)
self.out_proj = nn.Linear(self.attn_dim, d_model, bias=False)
self.local_conv = nn.Conv1d(d_model, d_model, kernel_size=3, padding=0, groups=d_model, bias=False)
self.local_gate = nn.Parameter(torch.tensor(0.25))
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
B, M, D = x.shape
q, k, v = self.qkv_proj(x).chunk(3, dim=-1)
q = apply_rope(q.view(B, M, self.n_heads, self.head_dim).transpose(1, 2), cos, sin)
k = apply_rope(k.view(B, M, self.n_heads, self.head_dim).transpose(1, 2), cos, sin)
v = v.view(B, M, self.n_heads, self.head_dim).transpose(1, 2)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
out = self.out_proj(out.transpose(1, 2).contiguous().view(B, M, self.attn_dim))
x_local = self.local_conv(F.pad(x.transpose(1, 2), (2, 0))).transpose(1, 2)
return out + self.local_gate * x_local
class VoidCoreBlockV3(nn.Module):
def __init__(self, d_model: int, n_heads: int = 4):
super().__init__()
self.ln1 = RMSNorm(d_model)
self.attn = UltraFlashAttentionV3(d_model, n_heads=n_heads, compress=2)
self.ln2 = RMSNorm(d_model)
hidden = (int(d_model * 8 / 3) // 64) * 64
self.w_gu = nn.Linear(d_model, 2 * hidden, bias=False)
self.w_down = nn.Linear(hidden, d_model, bias=False)
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
x = x + self.attn(self.ln1(x), cos, sin)
g, u = self.w_gu(self.ln2(x)).chunk(2, dim=-1)
return x + self.w_down(F.silu(g) * u)
class VoidToEnglishTranslatorV3(nn.Module):
def __init__(self, vocab_size: int, d_void: int, d_trans: int = 256, stride: int = 4):
super().__init__()
self.stride = stride
self.char_emb = nn.Embedding(vocab_size, d_trans)
self.char_conv = nn.Conv1d(d_trans, d_trans, kernel_size=5, padding=0, groups=d_trans, bias=False)
self.sub_pos_emb = nn.Embedding(stride, d_trans)
self.void_film = nn.Linear(d_void, 2 * d_trans, bias=True)
self.layers = nn.ModuleList([
nn.ModuleDict({
"ln1": RMSNorm(d_trans),
"qkv": nn.Linear(d_trans, 3 * d_trans, bias=False),
"out": nn.Linear(d_trans, d_trans, bias=False),
"ln2": RMSNorm(d_trans),
"w_gu": nn.Linear(d_trans, 4 * d_trans, bias=False),
"w_down": nn.Linear(2 * d_trans, d_trans, bias=False),
})
for _ in range(2)
])
self.ln_f = RMSNorm(d_trans)
self.out_head = nn.Linear(d_trans, vocab_size, bias=False)
def forward(self, void_state: torch.Tensor, raw_chars: torch.Tensor) -> torch.Tensor:
B, T = raw_chars.shape
S = self.stride
M = T // S
c = self.char_emb(raw_chars)
c_local = self.char_conv(F.pad(c.transpose(1, 2), (4, 0))).transpose(1, 2)
h = (c + c_local).view(B, M, S, -1)
pos = torch.arange(S, device=raw_chars.device)
gamma, beta = self.void_film(void_state).chunk(2, dim=-1)
h = (h + self.sub_pos_emb(pos)) * (1.0 + 0.5 * torch.tanh(gamma).unsqueeze(2)) + beta.unsqueeze(2)
h_flat = h.reshape(B * M, S, -1)
for lyr in self.layers:
q, k, v = lyr["qkv"](lyr["ln1"](h_flat)).chunk(3, dim=-1)
attn_out = F.scaled_dot_product_attention(
q.unsqueeze(1), k.unsqueeze(1), v.unsqueeze(1), is_causal=True
).squeeze(1)
h_flat = h_flat + lyr["out"](attn_out)
g, u = lyr["w_gu"](lyr["ln2"](h_flat)).chunk(2, dim=-1)
h_flat = h_flat + lyr["w_down"](F.silu(g) * u)
return self.out_head(self.ln_f(h_flat)).view(B, T, -1)
class VoidNetV3LM(nn.Module):
def __init__(
self,
vocab_size: int,
d_void: int = 512,
n_layers: int = 9,
n_heads: int = 4,
d_trans: int = 256,
stride: int = 4,
max_len: int = 2048,
):
super().__init__()
self.stride = stride
self.max_void_len = max_len // stride
self.pack_emb = nn.Embedding(vocab_size, d_void // stride)
self.pack_proj = nn.Linear(d_void, d_void, bias=False)
self.void_start = nn.Parameter(torch.zeros(1, 1, d_void))
self.void_blocks = nn.ModuleList([VoidCoreBlockV3(d_void, n_heads=n_heads) for _ in range(n_layers)])
self.void_ln = RMSNorm(d_void)
self.void_head_dim = self.void_blocks[0].attn.head_dim
self._rope_cache = None
self.translator = VoidToEnglishTranslatorV3(vocab_size, d_void=d_void, d_trans=d_trans, stride=stride)
def _get_rope(self, M: int, device: torch.device):
if self._rope_cache is None or self._rope_cache[0].shape[2] < M or self._rope_cache[0].device != device:
self._rope_cache = precompute_rope(max(M, self.max_void_len), self.void_head_dim, device)
return self._rope_cache
def forward(self, idx: torch.Tensor) -> torch.Tensor:
B, T = idx.shape
S = self.stride
assert T % S == 0, f"Input length {T} must be divisible by stride {S}"
M = T // S
chunks = idx.view(B, M, S)
void_tokens = self.pack_proj(self.pack_emb(chunks).reshape(B, M, -1))
void_in = torch.cat([self.void_start.expand(B, 1, -1), void_tokens[:, :-1, :]], dim=1)
cos, sin = self._get_rope(M, idx.device)
v = void_in
for blk in self.void_blocks:
v = blk(v, cos, sin)
return self.translator(self.void_ln(v), idx)
class VoidNetModel:
"""High-level loader & generator with V_endText instant halt."""
def __init__(self, model: VoidNetV3LM, config: dict, device: torch.device):
self.model = model.to(device).eval()
self.config = config
self.device = device
self.chars = config["chars"]
self.stoi = {c: i for i, c in enumerate(self.chars)}
self.itos = {i: c for i, c in enumerate(self.chars)}
self.v_endtext_id = config["v_endtext_id"]
self.v_pad_id = config["v_pad_id"]
self.stride = config["stride"]
@classmethod
def from_pretrained(cls, repo_or_dir: str, device: Optional[str] = None) -> "VoidNetModel":
dev = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
p = Path(repo_or_dir)
if p.exists():
cfg_path = p / "config.json"
wt_path = p / "model.safetensors"
else:
from huggingface_hub import hf_hub_download
cfg_path = Path(hf_hub_download(repo_or_dir, "config.json"))
wt_path = Path(hf_hub_download(repo_or_dir, "model.safetensors"))
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
net = VoidNetV3LM(
vocab_size=cfg["vocab_size"],
d_void=cfg["d_void"],
n_layers=cfg["n_layers"],
n_heads=cfg["n_heads"],
d_trans=cfg["d_trans"],
stride=cfg["stride"],
max_len=cfg["max_len"],
)
net.load_state_dict(load_file(str(wt_path)))
return cls(net, cfg, dev)
@torch.no_grad()
def generate(self, prompt: str, max_chars: int = 700, temperature: float = 0.72, top_p: float = 0.9, seed: Optional[int] = None) -> str:
ids = [self.stoi.get(c, self.stoi[" "]) for c in prompt]
gen = torch.Generator(device=self.device)
if seed is not None:
gen.manual_seed(seed)
out = []
for _ in range(max_chars):
cur = ids[-(self.config["max_len"] - self.stride):]
real_len = len(cur)
rem = real_len % self.stride
cur_padded = cur + [self.v_pad_id] * (self.stride - rem) if rem != 0 else cur
x = torch.tensor([cur_padded], dtype=torch.long, device=self.device)
logits = self.model(x)[0, real_len - 1].float() / max(temperature, 1e-4)
logits[self.v_pad_id] = float("-inf")
sorted_logits, sorted_idx = torch.sort(logits, descending=True)
probs = F.softmax(sorted_logits, dim=-1)
sorted_logits[torch.cumsum(probs, dim=-1) - probs > top_p] = float("-inf")
probs = F.softmax(sorted_logits, dim=-1)
nxt = sorted_idx[torch.multinomial(probs, 1, generator=gen)].item()
if nxt == self.v_endtext_id:
break
ids.append(nxt)
out.append(self.itos[nxt])
return prompt + "".join(out)
|