""" Standalone PyTorch + Hugging Face implementation of GStack v4.1 (VoidOSS Second Comeback Model — 9.41M params, 67% O(n) Linear, 1/3 KV Cache) Architecture: - Shift-Invariant Token Embedding + Multi-Scale Causal Char-Glue (k=3 + k=7) - Layers [0, 1, 3, 4] (67% O(n) Linear): * Neural Context: 5 power-of-2 linear memory horizons (128, 256, 512, 1024, 2048) * Associative Neural Attention: 4 self-cleaning working-memory concept slots with soft eviction * Per-Layer Gweight (Galaxyweights): Dedicated SwiGLU Core + 4 Neural-Attention-dialed Orbits - Layers [2, 5] (33% Sniper Recall): * Compressed UltraFlashAttention (QK-RMSNorm + RoPE) + Per-Layer Gweight Usage: from modeling_gstack import GStackModel model = GStackModel.from_pretrained("VoidOSS/GStack-v4.1-PythonCode") print(model.generate("def parse_config(filepath, default_timeout=30):\n ")) """ import json import math from pathlib import Path 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: return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight def precompute_rope(max_len: int, head_dim: int, device: torch.device): inv_freq = 1.0 / (10000.0 ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim)) t = torch.arange(max_len, device=device, dtype=torch.float32) freqs = torch.outer(t, inv_freq) cos = freqs.cos()[None, None, :, :] sin = freqs.sin()[None, None, :, :] return cos, sin 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[..., 0::2], x[..., 1::2] out1 = x1 * c - x2 * s out2 = x1 * s + x2 * c return torch.stack([out1, out2], dim=-1).flatten(-2) class UltraFlashAttentionF(nn.Module): def __init__(self, d_model: int, n_heads: int = 6, 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.q_norm = RMSNorm(self.head_dim) self.k_norm = RMSNorm(self.head_dim) 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 = self.q_norm(q.view(B, M, self.n_heads, self.head_dim)).transpose(1, 2) k = self.k_norm(k.view(B, M, self.n_heads, self.head_dim)).transpose(1, 2) q = apply_rope(q, cos, sin) k = apply_rope(k, 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 FastNeuralContext(nn.Module): """5 power-of-2 linear memory horizons (128, 256, 512, 1024, 2048).""" def __init__(self, d_model: int, stride: int = 1, raw_horizons=(128, 256, 512, 1024, 2048), chunk_size: int = 64): super().__init__() self.n_horizons = len(raw_horizons) self.chunk_size = chunk_size self.d_h = max(32, (d_model // self.n_horizons // 16) * 16) self.total_h = self.n_horizons * self.d_h self.in_proj = nn.Linear(d_model, self.total_h, bias=False) self.read_gate = nn.Linear(d_model, self.n_horizons, bias=True) self.norm_out = RMSNorm(self.d_h) self.out_proj = nn.Linear(self.d_h, d_model, bias=False) base_logits = [] for rh in raw_horizons: void_h = max(2.0, rh / float(stride)) alpha = math.exp(-math.log(2.0) / void_h) base_logits.append(math.log(alpha / (1.0 - alpha))) self.register_buffer("base_decay_logits", torch.tensor(base_logits, dtype=torch.float32)) self.decay_delta = nn.Parameter(torch.zeros(self.n_horizons)) def forward(self, x: torch.Tensor) -> torch.Tensor: B, M, D = x.shape H = self.n_horizons u = self.in_proj(x).view(B, M, H, self.d_h) C = min(self.chunk_size, M) pad = (C - (M % C)) % C if pad > 0: u = F.pad(u, (0, 0, 0, 0, 0, pad)) Mp = u.shape[1] Nc = Mp // C alpha = torch.sigmoid(self.base_decay_logits + 0.5 * torch.tanh(self.decay_delta)) idx = torch.arange(C, device=x.device, dtype=torch.float32) diff = idx.unsqueeze(1) - idx.unsqueeze(0) mask = (diff >= 0).float() a_h = alpha.view(H, 1, 1) L = ((1.0 - a_h) * torch.pow(a_h, diff.clamp(min=0.0).unsqueeze(0)) * mask.unsqueeze(0)).to(u.dtype) u_c = u.view(B, Nc, C, H, self.d_h) intra = torch.einsum("hij,bnjhd->bnihd", L, u_c) if Nc > 1: a_chunk = torch.pow(alpha, float(C)) c_idx = torch.arange(Nc, device=x.device, dtype=torch.float32) c_diff = c_idx.unsqueeze(1) - c_idx.unsqueeze(0) - 1.0 c_mask = (c_diff >= 0).float() M_c = (torch.pow(a_chunk.view(H, 1, 1), c_diff.clamp(min=0.0).unsqueeze(0)) * c_mask.unsqueeze(0)).to(u.dtype) prev = torch.einsum("hcj,bjhd->bchd", M_c, intra[:, :, -1]) pow_in = torch.pow(alpha.view(1, 1, 1, H, 1), (idx + 1.0).view(1, 1, C, 1, 1)).to(u.dtype) mem = intra + pow_in * prev.unsqueeze(2) else: mem = intra mem = mem.reshape(B, Mp, H, self.d_h)[:, :M] w = F.softmax(self.read_gate(x), dim=-1).unsqueeze(-1) mixed = self.norm_out((mem * w).sum(dim=2)) return self.out_proj(mixed) class FastAssociativeNeuralAttention(nn.Module): """4 self-cleaning active working-memory concept slots with soft eviction.""" def __init__(self, d_model: int, n_slots: int = 4, d_k: int = 24, d_v: int = 48, chunk_size: int = 64): super().__init__() self.n_slots = n_slots self.d_k = d_k self.d_v = d_v self.chunk_size = chunk_size self.q_proj = nn.Linear(d_model, n_slots * d_k, bias=False) self.k_proj = nn.Linear(d_model, n_slots * d_k, bias=False) self.v_proj = nn.Linear(d_model, n_slots * d_v, bias=False) self.q_norm = RMSNorm(d_k) self.k_norm = RMSNorm(d_k) self.pull_route = nn.Linear(d_model, n_slots, bias=True) self.pull_strength = nn.Linear(d_model, n_slots, bias=True) self.focus_gate = nn.Linear(d_model, n_slots, bias=True) self.slot_base_decay = nn.Parameter(torch.tensor([2.0, 3.0, 4.0, 5.0], dtype=torch.float32)[:n_slots]) self.norm_out = RMSNorm(n_slots * d_v) self.out_proj = nn.Linear(n_slots * d_v, 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): B, M, D = x.shape H, dk, dv = self.n_slots, self.d_k, self.d_v C = min(self.chunk_size, M) pad = (C - (M % C)) % C scale = 1.0 / math.sqrt(float(dk)) q = self.q_norm(self.q_proj(x).view(B, M, H, dk)) * scale k = self.k_norm(self.k_proj(x).view(B, M, H, dk)) v = self.v_proj(x).view(B, M, H, dv) route = F.softmax(self.pull_route(x), dim=-1) strength = torch.sigmoid(self.pull_strength(x)) pull_in = (route * strength).float() base_decay = torch.sigmoid(self.slot_base_decay).view(1, 1, H) fade = ((1.0 - 0.5 * pull_in) * base_decay).clamp(min=1e-4, max=0.9999) log_fade = torch.log(fade) if pad > 0: q = F.pad(q, (0, 0, 0, 0, 0, pad)) k = F.pad(k, (0, 0, 0, 0, 0, pad)) v = F.pad(v, (0, 0, 0, 0, 0, pad)) pull_in = F.pad(pull_in, (0, 0, 0, pad)) log_fade = F.pad(log_fade, (0, 0, 0, pad)) Mp = q.shape[1] Nc = Mp // C q_c = q.view(B, Nc, C, H, dk).transpose(2, 3) k_c = k.view(B, Nc, C, H, dk).transpose(2, 3) v_c = v.view(B, Nc, C, H, dv).transpose(2, 3) p_c = pull_in.view(B, Nc, C, H).transpose(2, 3) lf_c = log_fade.view(B, Nc, C, H).transpose(2, 3) G = torch.cumsum(lf_c, dim=-1) tril = torch.tril(torch.ones(C, C, device=x.device, dtype=torch.bool)) G_diff = (G.unsqueeze(-1) - G.unsqueeze(-2)).masked_fill(~tril, -1e9) D_intra = torch.exp(G_diff) * tril.float() k_weighted = k_c * p_c.to(k_c.dtype).unsqueeze(-1) attn_intra = torch.matmul(q_c, k_weighted.transpose(-1, -2)) * D_intra.to(q_c.dtype) out_intra = torch.matmul(attn_intra, v_c) if Nc > 1: decay_to_end = torch.exp((G[..., -1:] - G).clamp(max=0.0)) * p_c k_end = k_c * decay_to_end.to(k_c.dtype).unsqueeze(-1) S_chunk = torch.matmul(k_end.transpose(-1, -2), v_c) A_chunk = torch.exp(G[..., -1]).to(q_c.dtype).unsqueeze(-1).unsqueeze(-1) prev_S = [] S = torch.zeros(B, H, dk, dv, device=x.device, dtype=q_c.dtype) for c in range(Nc): prev_S.append(S) S = A_chunk[:, c] * S + S_chunk[:, c] S_prev = torch.stack(prev_S, dim=1) decay_from_start = torch.exp(G.clamp(max=0.0)).to(q_c.dtype).unsqueeze(-1) out_cross = decay_from_start * torch.matmul(q_c, S_prev) out = out_intra + out_cross else: out = out_intra out = out.transpose(2, 3).reshape(B, Mp, H, dv)[:, :M] focus = F.softmax(self.focus_gate(x), dim=-1) focused = self.norm_out((out * (1.0 + focus.unsqueeze(-1))).reshape(B, M, H * dv)) x_local = self.local_conv(F.pad(x.transpose(1, 2), (2, 0))).transpose(1, 2) return self.out_proj(focused) + self.local_gate * x_local, focus class PerLayerGweight(nn.Module): """Per-Layer Galaxyweight (Gweight): Dedicated SwiGLU Core + 4 Neural-Attention-dialed Orbits.""" def __init__(self, d_model: int, hidden: int, n_orbits: int = 4, orbit_rank: int = 32): super().__init__() self.n_orbits = n_orbits self.orbit_rank = orbit_rank self.w_gu = nn.Linear(d_model, 2 * hidden, bias=False) self.w_down = nn.Linear(hidden, d_model, bias=False) self.orbit_down = nn.Linear(d_model, n_orbits * orbit_rank, bias=False) self.orbit_up = nn.Linear(n_orbits * orbit_rank, d_model, bias=False) def forward(self, x: torch.Tensor, orbit_dial: torch.Tensor) -> torch.Tensor: B, M, D = x.shape g, u = self.w_gu(x).chunk(2, dim=-1) core_out = self.w_down(F.silu(g) * u) o = F.silu(self.orbit_down(x)).view(B, M, self.n_orbits, self.orbit_rank) o = (o * orbit_dial.unsqueeze(-1)).reshape(B, M, self.n_orbits * self.orbit_rank) return core_out + self.orbit_up(o) class GStackLinearBlock(nn.Module): def __init__(self, d_model: int, hidden: int, orbit_rank: int = 32): super().__init__() self.ln_mem = RMSNorm(d_model) self.neural_ctx = FastNeuralContext(d_model, stride=1, chunk_size=64) self.neural_attn = FastAssociativeNeuralAttention(d_model, n_slots=4, d_k=24, d_v=48, chunk_size=64) self.ln_gw = RMSNorm(d_model) self.gweight = PerLayerGweight(d_model, hidden, n_orbits=4, orbit_rank=orbit_rank) def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: h = self.ln_mem(x) ctx_out = self.neural_ctx(h) attn_out, orbit_dial = self.neural_attn(h) x = x + ctx_out + attn_out x = x + self.gweight(self.ln_gw(x), orbit_dial) return x class GStackRecallBlock(nn.Module): def __init__(self, d_model: int, hidden: int, n_heads: int = 6, orbit_rank: int = 32): super().__init__() self.ln_mem = RMSNorm(d_model) self.attn = UltraFlashAttentionF(d_model, n_heads=n_heads, compress=2) self.orbit_router = nn.Linear(d_model, 4, bias=True) self.ln_gw = RMSNorm(d_model) self.gweight = PerLayerGweight(d_model, hidden, n_orbits=4, orbit_rank=orbit_rank) def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: h = self.ln_mem(x) x = x + self.attn(h, cos, sin) dial = F.softmax(self.orbit_router(h), dim=-1) x = x + self.gweight(self.ln_gw(x), dial) return x class GStackModel(nn.Module): def __init__(self, config: dict): super().__init__() self.config = config vocab_size = config["vocab_size"] d_model = config.get("d_model", 384) n_layers = config.get("n_layers", 6) n_heads = config.get("n_heads", 6) hidden = config.get("hidden", 960) orbit_rank = config.get("orbit_rank", 32) self.max_len = config.get("max_len", 2048) self.itos = config.get("itos", []) self.stoi = {c: i for i, c in enumerate(self.itos)} self.tok_emb = nn.Embedding(vocab_size, d_model) self.emb_conv3 = nn.Conv1d(d_model, d_model, kernel_size=3, padding=0, groups=d_model, bias=False) self.emb_conv7 = nn.Conv1d(d_model, d_model, kernel_size=7, padding=0, groups=d_model, bias=False) recall_indices = set(config.get("recall_layers", [2, 5])) blocks = [] for i in range(n_layers): if i in recall_indices: blocks.append(GStackRecallBlock(d_model, hidden, n_heads=n_heads, orbit_rank=orbit_rank)) else: blocks.append(GStackLinearBlock(d_model, hidden, orbit_rank=orbit_rank)) self.blocks = nn.ModuleList(blocks) self.ln_f = RMSNorm(d_model) self.lm_head = nn.Linear(d_model, vocab_size, bias=False) self.head_dim = self.blocks[min(recall_indices)].attn.head_dim self._rope_cache = None resid_std = 0.02 / math.sqrt(2.0 * n_layers) for name, mod in self.named_modules(): if isinstance(mod, nn.Linear): std = resid_std if ( name.endswith("out_proj") or name.endswith("w_down") or name.endswith("orbit_up") ) else 0.02 nn.init.normal_(mod.weight, mean=0.0, std=std) if mod.bias is not None: nn.init.zeros_(mod.bias) elif isinstance(mod, nn.Embedding): nn.init.normal_(mod.weight, mean=0.0, std=0.02) def _get_rope(self, T: int, device: torch.device): if self._rope_cache is None or self._rope_cache[0].shape[2] < T or self._rope_cache[0].device != device: self._rope_cache = precompute_rope(max(T, self.max_len), self.head_dim, device) return self._rope_cache def forward(self, idx: torch.Tensor) -> torch.Tensor: B, T = idx.shape x = self.tok_emb(idx) xt = x.transpose(1, 2) c3 = self.emb_conv3(F.pad(xt, (2, 0))).transpose(1, 2) c7 = self.emb_conv7(F.pad(xt, (6, 0))).transpose(1, 2) x = x + 0.3 * c3 + 0.2 * c7 cos, sin = self._get_rope(T, idx.device) for blk in self.blocks: x = blk(x, cos, sin) return self.lm_head(self.ln_f(x)) @classmethod def from_pretrained(cls, repo_or_dir: str, device: str | None = None): p = Path(repo_or_dir) if p.is_dir(): cfg_path = p / "config.json" w_path = p / "model.safetensors" else: from huggingface_hub import hf_hub_download cfg_path = Path(hf_hub_download(repo_id=repo_or_dir, filename="config.json")) w_path = Path(hf_hub_download(repo_id=repo_or_dir, filename="model.safetensors")) config = json.loads(cfg_path.read_text(encoding="utf-8")) model = cls(config) model.load_state_dict(load_file(str(w_path)), strict=True) dev = device or ("cuda" if torch.cuda.is_available() else "cpu") return model.to(dev).eval() @torch.no_grad() def generate(self, prompt: str, max_chars: int = 280, temperature: float = 0.65, seed: int = 42) -> str: device = next(self.parameters()).device ids = [self.stoi[c] for c in prompt if c in self.stoi] if not ids: ids = [0] gen = torch.Generator(device=device).manual_seed(seed) for _ in range(max_chars): ctx = ids[-self.max_len:] x = torch.tensor([ctx], dtype=torch.long, device=device) with torch.amp.autocast(device.type, dtype=torch.bfloat16, enabled=(device.type == "cuda")): logits = self(x)[0, -1].float() / max(temperature, 1e-4) probs = F.softmax(logits, dim=-1) ids.append(torch.multinomial(probs, 1, generator=gen).item()) return "".join(self.itos[i] for i in ids)