#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" code_layer0_vllm.py =================== 100% Standalone CPU **BPE-Free Sībawayh Code Layer-0 + 24-D Orthographic/Acronym/AST Descriptor** for `vLLM 0.34.0` FP8 (`enable_prompt_embeds=True`) AND PyTorch QLoRA Training (Stage 18.1). Architecture: - Uses our Stage 18.0 Sībawayh Factored Code Manifold (`stage18_0_code_layer0_istighna_27b.pt`, `121 MB`: `12,288` productive code stems × `10` casing *Awzān* × `6` leading delimiters). - For every multi-BPE code identifier span `[s, e)` in the prompt: 1. Decomposes the full identifier into `(delim, wazn, stems)` via `split_identifier_into_sibawayh_tuple`. 2. Computes the **24-D Orthographic / Acronym / Delimiter Descriptor**: - Leading `_` count (0, 1, 2+), trailing `_` count (0, 1, 2+), dunder flag - Acronym-run count (`HTTPResponse` -> `HTTP` run), digit-letter transitions (`200OK`), morpheme count, uppercase ratio, digit ratio, span BPE length, camel/Pascal/snake/UPPER/kebab flags 3. Detects its **Basran *ʿĀmil / Maʿmūl* AST Role** (`FUNC_DEF_AMIL`, `CLASS_DEF_AMIL`, `CALL_AMIL`, `ATTR_METHOD`, `PARAM_OR_TYPE_MAMUL`, `CONST_BINDING`, `GENERIC_IDENT`). 4. Fuses norm-matched Sībawayh stem+wazn vector + span-mean + optional trained `ortho_24d` & `ast_role` projections via per-channel `channel_gate [5120]` (`0.00 GB` GPU VRAM during `vLLM` serving!). """ from __future__ import annotations import re import sys from collections import Counter from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from tokenizers import Tokenizer as FastTokenizer ROOT = Path("/workspace/rootstar") if Path("/workspace/rootstar").exists() else Path(__file__).resolve().parent.parent OUT_CODE_LAYER0_ISTIGHNA_PT = ROOT / "checkpoints" / "stage18_0" / "stage18_0_code_layer0_istighna_27b.pt" CODE_AST_ROLES = [ "GENERIC_IDENT", "FUNC_DEF_AMIL", "CLASS_DEF_AMIL", "CALL_AMIL", "PARAM_OR_TYPE_MAMUL", "ATTR_METHOD", "CONST_BINDING", ] _CAMEL_BOUNDARY_RE = re.compile( r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])" ) _VALID_CODE_PIECE_RE = re.compile(r"^[ \t._]{0,2}[A-Za-z_][A-Za-z0-9_]*$") def split_identifier_into_sibawayh_tuple(raw_piece: str) -> Optional[Tuple[str, str, List[str], str]]: """Standalone Sībawayhian identifier morpheme & casing (*Wazn*) splitter (`0` external deps).""" if not raw_piece or len(raw_piece) > 48 or not _VALID_CODE_PIECE_RE.match(raw_piece): return None s = raw_piece delim = "" if s.startswith((" ", "\t", ".")): delim = s[0] s = s[1:] if not s: return None if s.startswith("__") and s.endswith("__") and len(s) > 4 and s[2:-2].replace("_", "").isalnum(): stems = [p.lower() for seg in s[2:-2].split("_") if seg for p in _CAMEL_BOUNDARY_RE.split(seg) if p] return (delim, "dunder", stems, "+".join(stems) + "@dunder") if stems else None if s.startswith("__") and len(s) > 2: delim = "__" if delim == "" else delim s = s[2:] elif s.startswith("_") and len(s) > 1: delim = "_" if delim == "" else delim s = s[1:] if not s or not s.replace("_", "").isalnum() or s[0].isdigit(): return None alpha_chars = [c for c in s if c.isalpha()] if not alpha_chars: return None has_digit = any(c.isdigit() for c in s) if "_" in s: raw_parts = [p for p in s.split("_") if p] if not raw_parts: return None wazn = "UPPER_SNAKE" if all(c.isupper() for c in alpha_chars) else ("snake_case" if all(c.islower() for c in alpha_chars) else "Mixed_Snake") stems = [sp.lower() for rp in raw_parts for sp in _CAMEL_BOUNDARY_RE.split(rp) if sp] else: parts = [p for p in _CAMEL_BOUNDARY_RE.split(s) if p] stems = [p.lower() for p in parts if p] if len(parts) >= 2: if all(c.isupper() for c in alpha_chars): wazn = "UPPER" elif s[0].islower() and any(c.isupper() for c in s[1:]): wazn = "camelCase" elif s[0].isupper() and any(c.islower() for c in s): wazn = "PascalCase" else: wazn = "alnum_ident" else: if all(c.isupper() for c in alpha_chars): wazn = "UPPER" elif s[0].isupper() and all(c.islower() for c in alpha_chars[1:]): wazn = "TitleAtom" elif all(c.islower() for c in alpha_chars): wazn = "lower_atom" if not has_digit else "alnum_ident" else: wazn = "alnum_ident" return (delim, wazn, stems, "+".join(stems)) if stems else None ROLE_TO_ID: Dict[str, int] = {r: i for i, r in enumerate(CODE_AST_ROLES)} _IDENT_HEAD_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _IDENT_CONT_RE = re.compile(r"^[A-Za-z0-9_]+$") _ACRONYM_RUN_RE = re.compile(r"[A-Z]{2,}") _ALNUM_BOUND_RE = re.compile(r"(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])") def compute_code_ortho_24d(ident: str, span_bpe_len: int, wazn: str, n_stems: int) -> List[float]: """24-D character-structure descriptor eliminating BPE character-blindness on acronyms/underscores.""" L = max(1, len(ident)) lead_u = len(ident) - len(ident.lstrip("_")) trail_u = len(ident) - len(ident.rstrip("_")) is_dunder = 1.0 if (L > 4 and ident.startswith("__") and ident.endswith("__")) else 0.0 n_upper = sum(1 for c in ident if c.isupper()) n_lower = sum(1 for c in ident if c.islower()) n_digit = sum(1 for c in ident if c.isdigit()) n_us = ident.count("_") n_acronyms = len(_ACRONYM_RUN_RE.findall(ident)) n_alnum_tr = len(_ALNUM_BOUND_RE.findall(ident)) vec = [ min(lead_u, 3) / 3.0, 1.0 if lead_u == 1 else 0.0, 1.0 if lead_u >= 2 else 0.0, min(trail_u, 3) / 3.0, is_dunder, min(n_acronyms, 4) / 4.0, 1.0 if n_acronyms >= 1 else 0.0, min(n_alnum_tr, 4) / 4.0, 1.0 if n_digit > 0 else 0.0, n_upper / L, n_lower / L, n_digit / L, n_us / L, min(n_stems, 8) / 8.0, min(span_bpe_len, 8) / 8.0, min(L, 40) / 40.0, 1.0 if wazn == "snake_case" else 0.0, 1.0 if wazn == "camelCase" else 0.0, 1.0 if wazn == "PascalCase" else 0.0, 1.0 if wazn == "UPPER_SNAKE" else 0.0, 1.0 if wazn == "UPPER" else 0.0, 1.0 if wazn == "dunder" else 0.0, 1.0 if wazn == "Mixed_Snake" else 0.0, 1.0 if ident[0].isupper() else 0.0, ] return vec class SibawayhCodeLayer0V18_1(nn.Module): """ Trainable & vLLM-ready BPE-Free Sībawayh Code Layer-0 Adapter. In zero-shot mode (`use_trained_residuals=False`), uses exact norm-matched Sībawayh stem+wazn fusion. In trained Stage 18.1 mode, activates learned `channel_gate`, `ortho_24d_proj`, and `ast_role_embed`! """ def __init__( self, base_embed: nn.Embedding, code_manifold_path: Path = OUT_CODE_LAYER0_ISTIGHNA_PT, alpha_code_span: float = 0.03, d_model: int = 5120, device: torch.device = torch.device("cpu"), ) -> None: super().__init__() self.base_embed = base_embed self.alpha_code_span = alpha_code_span self.d_model = d_model self._active_plan: Optional[Dict[str, Any]] = None ck = torch.load(code_manifold_path, map_location="cpu", weights_only=False) self.register_buffer("code_P", ck["P_in"].to(device=device, dtype=torch.float32), persistent=False) self.register_buffer("code_W", ck["W_in"].to(device=device, dtype=torch.float32), persistent=False) self.register_buffer("code_R", ck["R_in"].to(device=device, dtype=torch.float32), persistent=False) self.stem_to_id: Dict[str, int] = {s: i for i, s in enumerate(ck["stems_vocab"])} self.delim_to_id: Dict[str, int] = {d: i for i, d in enumerate(ck["code_delims"])} self.wazn_to_id: Dict[str, int] = {w: i for i, w in enumerate(ck["code_awzan"])} # Trainable Stage 18.1 components (zero-initialized residual so untrained == exact zero-shot Sībawayh!) self.channel_gate = nn.Parameter(torch.full((d_model,), float(alpha_code_span), dtype=torch.float32, device=device)) self.ortho_proj = nn.Sequential( nn.Linear(24, 128, dtype=torch.float32, device=device), nn.SiLU(), nn.Linear(128, d_model, dtype=torch.float32, device=device), ) nn.init.zeros_(self.ortho_proj[2].weight) nn.init.zeros_(self.ortho_proj[2].bias) self.ast_role_embed = nn.Embedding(len(CODE_AST_ROLES), d_model, dtype=torch.float32, device=device) nn.init.zeros_(self.ast_role_embed.weight) self.use_learned_gate = False def load_trained_state(self, state: Dict[str, Any], device: torch.device = torch.device("cpu")) -> None: self.channel_gate.data.copy_(state["channel_gate"].to(device=device, dtype=torch.float32)) self.ortho_proj.load_state_dict({k: v.to(device=device, dtype=torch.float32) for k, v in state["ortho_proj"].items()}) self.ast_role_embed.load_state_dict({k: v.to(device=device, dtype=torch.float32) for k, v in state["ast_role_embed"].items()}) self.use_learned_gate = True def export_trained_state(self) -> Dict[str, Any]: return { "channel_gate": self.channel_gate.detach().cpu().float(), "ortho_proj": {k: v.detach().cpu().float() for k, v in self.ortho_proj.state_dict().items()}, "ast_role_embed": {k: v.detach().cpu().float() for k, v in self.ast_role_embed.state_dict().items()}, } def clear_plan(self) -> None: self._active_plan = None @staticmethod def _detect_ast_role(pieces: List[str], s_idx: int, e_idx: int, ident: str) -> str: prev_ctx = "".join(pieces[max(0, s_idx - 3) : s_idx]).strip() next_ctx = "".join(pieces[e_idx : min(len(pieces), e_idx + 2)]).lstrip() if prev_ctx.endswith("def"): return "FUNC_DEF_AMIL" if prev_ctx.endswith("class"): return "CLASS_DEF_AMIL" if prev_ctx.endswith("."): return "ATTR_METHOD" if next_ctx.startswith("("): return "CALL_AMIL" if next_ctx.startswith(":") or prev_ctx.endswith("->"): return "PARAM_OR_TYPE_MAMUL" if ident.isupper() and "_" in ident: return "CONST_BINDING" return "GENERIC_IDENT" @torch.no_grad() def build_code_plan( self, input_ids_1d: List[int], raw_tok: FastTokenizer, min_tok_idx: int = 0, ) -> Dict[str, Any]: T = len(input_ids_1d) pieces = [raw_tok.decode([tid]) for tid in input_ids_1d] spans: List[Dict[str, Any]] = [] i = max(0, min_tok_idx) in_quote: Optional[str] = None while i < T: pc = pieces[i] # Track simple single/double quote literal state so we NEVER blur exact literal strings! for ch in pc: if ch in ("'", '"'): if in_quote is None: in_quote = ch elif in_quote == ch: in_quote = None if in_quote is not None or pc.lstrip().startswith(("'", '"')): i += 1 continue lead_char = " " if pc.startswith(" ") else ("." if pc.startswith(".") else "") pc_s = pc.lstrip(" \n\t`.([{: ") if pc_s and _IDENT_HEAD_RE.match(pc_s): j = i + 1 combined = pc_s while j < T: nxt = pieces[j] if nxt and not nxt[0].isspace() and _IDENT_CONT_RE.match(nxt): combined += nxt j += 1 else: break span_len = j - i # Ground multi-BPE identifiers (`_`, camelCase, acronyms, or length >= 7) if span_len >= 2 and ("_" in combined or any(c.isupper() for c in combined[1:]) or len(combined) >= 7): role = self._detect_ast_role(pieces, i, j, combined) parsed = split_identifier_into_sibawayh_tuple(lead_char + combined) wazn = "alnum_ident" sib_vec: Optional[torch.Tensor] = None n_stems = 1 if parsed is not None: delim, wazn, stems, _ = parsed n_stems = len(stems) st_ids = [self.stem_to_id[st] for st in stems if st in self.stem_to_id] if st_ids: r_mean = self.code_R[st_ids].mean(dim=0) p_vec = self.code_P[self.delim_to_id.get(delim, 0)] w_vec = self.code_W[self.wazn_to_id.get(wazn, 0)] sib_vec = p_vec + w_vec + r_mean ortho_24 = compute_code_ortho_24d(combined, span_len, wazn, n_stems) spans.append({ "start": i, "end": j, "ident": combined, "role_id": ROLE_TO_ID[role], "sib_vec": sib_vec, "ortho_24": ortho_24, }) i = j else: i += 1 plan = {"seq_len": T, "spans": spans, "num_spans": len(spans)} self._active_plan = plan return plan def forward(self, input_ids: torch.Tensor) -> torch.Tensor: base = self.base_embed(input_ids) # [B, T, D] plan = self._active_plan if not plan or not plan["spans"] or input_ids.size(0) != 1 or input_ids.size(1) != plan["seq_len"]: if self.training and self.channel_gate.requires_grad: return base + (self.channel_gate.sum() * 0.0).to(base.dtype) return base dev = base.device out_dtype = base.dtype base_f = base.float() gate = torch.clamp(self.channel_gate.to(dev), 0.0, 0.35) if self.use_learned_gate else torch.full( (self.d_model,), float(self.alpha_code_span), dtype=torch.float32, device=dev ) spans = plan["spans"] ortho_t = torch.tensor([sp["ortho_24"] for sp in spans], dtype=torch.float32, device=dev) role_t = torch.tensor([sp["role_id"] for sp in spans], dtype=torch.long, device=dev) ortho_deltas = self.ortho_proj(ortho_t) + self.ast_role_embed(role_t) # [M, D] # Strictly out-of-place residual accumulation (ZERO inplace view mutation -> 100% autograd-safe!) pos_chunks: List[torch.Tensor] = [] diff_chunks: List[torch.Tensor] = [] for idx, sp in enumerate(spans): s, e = sp["start"], sp["end"] seg = base_f[0, s:e, :].detach() # frozen base embedding slice [L, D] seg_mean = seg.mean(dim=0) target_norm = seg.norm(dim=-1, keepdim=True).mean().clamp(min=1e-4) if sp["sib_vec"] is not None: sv = sp["sib_vec"].to(dev) sv_norm = sv * (target_norm / sv.norm().clamp(min=1e-4)) fused = 0.55 * seg_mean + 0.45 * sv_norm else: fused = seg_mean fused_nm = fused * (target_norm / fused.norm().clamp(min=1e-4)) # Delta = blended - seg = gate * (fused_nm - seg) + ortho_delta delta_seg = gate * (fused_nm.unsqueeze(0) - seg) + ortho_deltas[idx].unsqueeze(0) pos_chunks.append(torch.arange(s, e, device=dev, dtype=torch.long)) diff_chunks.append(delta_seg) all_pos = torch.cat(pos_chunks, dim=0) all_diff = torch.cat(diff_chunks, dim=0) delta_full = torch.zeros_like(base_f[0]).index_add(0, all_pos, all_diff) out = base_f + delta_full.unsqueeze(0) return out.to(out_dtype) @torch.inference_mode() def compute_prompt_embeds_cpu( self, ids: List[int], raw_tok: FastTokenizer, min_tok_idx: int = 0, ) -> torch.Tensor: self.build_code_plan(ids, raw_tok, min_tok_idx=min_tok_idx) inp = torch.tensor([ids], dtype=torch.long, device=self.base_embed.weight.device) emb = self.forward(inp)[0].to(torch.bfloat16).contiguous() self.clear_plan() return emb def _self_test() -> None: tok_p = ROOT / "checkpoints" / "qwen3_8_27b_4bit" / "tokenizer.json" if not tok_p.exists(): # Fallback: search any tokenizer.json in stage15.2 cands = list(ROOT.rglob("tokenizer.json")) tok_p = cands[0] if cands else tok_p raw_tok = FastTokenizer.from_file(str(tok_p)) # Tiny mock embedding table on CPU to verify shapes & zero-drift init in <1s! emb = nn.Embedding(raw_tok.get_vocab_size(), 5120) nn.init.normal_(emb.weight, std=0.02) l0 = SibawayhCodeLayer0V18_1(base_embed=emb, alpha_code_span=0.12) sample = "def _parseHTTPResponse200OK(vault_key: str) -> dict:\n return transform_payload_keys(vault_key, 'camelCase')" ids = raw_tok.encode(sample).ids plan = l0.build_code_plan(ids, raw_tok, min_tok_idx=0) out = l0.compute_prompt_embeds_cpu(ids, raw_tok, min_tok_idx=0) assert out.shape == (len(ids), 5120) and out.dtype == torch.bfloat16 and torch.isfinite(out).all() # Autograd backward() verification with anomaly detection (proves ZERO inplace version errors!) l0.train() l0.use_learned_gate = True l0.build_code_plan(ids, raw_tok, min_tok_idx=0) with torch.autograd.detect_anomaly(): y = l0(torch.tensor([ids], dtype=torch.long)) loss = (y.float() ** 2).mean() loss.backward() assert l0.channel_gate.grad is not None and torch.isfinite(l0.channel_gate.grad).all() assert l0.ortho_proj[2].weight.grad is not None and torch.isfinite(l0.ortho_proj[2].weight.grad).all() assert l0.ast_role_embed.weight.grad is not None and torch.isfinite(l0.ast_role_embed.weight.grad).all() print(f"CODE_LAYER0_V18_1_SELF_TEST_PASSED (+AUTOGRAD_BACKWARD_OK): seq_len={len(ids)} | grounded_spans={plan['num_spans']} | idents={[s['ident'] for s in plan['spans']]}") if __name__ == "__main__": _self_test()