#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" khalil_basran_code_layer0.py ============================ Stage 18.2 (**Al-Khalīl al-Barmajī**) — 100% Standalone CPU/GPU **Khalīl-Sībawayh-Basran Code Layer-0**: Unifies 4 classical Arabic structural algorithms directly into Layer-0 (`d_model = 5120`, `0.00 GB` GPU VRAM during `vLLM` FP8 serving, 100% out-of-place autograd-safe during PyTorch QLoRA training!): 1. **al-Khalīl & Sībawayh Factored Code Manifold** (`stage18_0_code_layer0_istighna_27b.pt`, `121 MB`: `12,288` stems × `10` *Awzān* × `6` leading delimiters) — aligns `snake_case`, `camelCase`, `PascalCase`, and `UPPER_SNAKE` equivalents into the exact same stem-root subspace while strictly skipping quoted string literals (`'...'`, `"..."`). 2. **al-Khalīl `24-D` Orthographic/Acronym Descriptor (`ortho_proj`)** — encodes leading/trailing `_`, `__dunder__`, acronym runs (`HTTPResponse`), letter<->digit boundaries (`200OK`), version prefixes (`v2`), morpheme count, and character class ratios. 3. **Basran (Ibn al-Sarrāj *al-Uṣūl*) `16-Role ʿĀmil / Maʿmūl` AST Governance Embedding** — distinguishes `def`/`class` governors, calls, keyword arguments, type annotations, return types, exceptions, decorators, attributes, imports, dunders, constants, comprehension binders, and versioned alnums. 4. **Basran *ʿĀʾid* Cross-Convention Co-Reference Binding (`coref_embed`)** — assigns all occurrences of the same canonical Sībawayh stem-tuple across a prompt (including `transaction_sequence_id` <-> `transactionSequenceId`!) the exact same co-reference slot (`1..15`), binding long-range symbol identity! """ from __future__ import annotations import re from collections import Counter from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn 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" BASRAN_16_AST_ROLES: List[str] = [ "GENERIC_IDENT", # 0 "FUNC_DEF_AMIL", # 1: def foo "CLASS_DEF_AMIL", # 2: class Bar "CALL_AMIL", # 3: foo( "KWARG_MAMUL", # 4: vault_key= "PARAM_MAMUL", # 5: x: int "RETURN_TYPE", # 6: -> dict "EXCEPT_TYPE", # 7: raise/except ValueError "DECORATOR_AMIL", # 8: @dataclass "ATTR_METHOD", # 9: .fetch_secret "IMPORT_MOD", # 10: import/from pkg "DUNDER_SLOT", # 11: __init__ "CONST_UPPER", # 12: MAX_FLOW "COMP_BINDER", # 13: for item in "SCHEMA_KEY", # 14: multi-convention field "ALNUM_VERSION", # 15: v2HTTP, 200OK ] ROLE16_TO_ID: Dict[str, int] = {r: i for i, r in enumerate(BASRAN_16_AST_ROLES)} NUM_COREF_SLOTS = 16 # 0 = singleton/none, 1..15 = co-referenced stem-families in prompt _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_]*$") _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 split_identifier_sibawayh(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 def compute_khalil_ortho_24d(ident: str, span_bpe_len: int, wazn: str, n_stems: int) -> List[float]: 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)) return [ 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, ] class KhalilBasranCodeLayer0(nn.Module): """ Stage 18.2 Unified Khalīl + Sībawayh + Basran 16-Role AST + Co-Reference (*ʿĀʾid*) Layer-0. Strictly zero-initialized residuals (`0.000` initial degradation) and 100% out-of-place autograd-safe. """ def __init__( self, base_embed: nn.Embedding, code_manifold_path: Path = OUT_CODE_LAYER0_ISTIGHNA_PT, alpha_code_span: float = 0.025, 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"])} 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(BASRAN_16_AST_ROLES), d_model, dtype=torch.float32, device=device) nn.init.zeros_(self.ast_role_embed.weight) self.coref_embed = nn.Embedding(NUM_COREF_SLOTS, d_model, dtype=torch.float32, device=device) nn.init.zeros_(self.coref_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()}) if "coref_embed" in state: self.coref_embed.load_state_dict({k: v.to(device=device, dtype=torch.float32) for k, v in state["coref_embed"].items()}) self.use_learned_gate = True def export_trained_state(self) -> Dict[str, Any]: return { "version": "stage18_2_khalil_basran_16role", "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()}, "coref_embed": {k: v.detach().cpu().float() for k, v in self.coref_embed.state_dict().items()}, } def clear_plan(self) -> None: self._active_plan = None @staticmethod def _detect_basran_role16(pieces: List[str], s_idx: int, e_idx: int, ident: str) -> str: prev_ctx = "".join(pieces[max(0, s_idx - 4) : s_idx]).strip() next_ctx = "".join(pieces[e_idx : min(len(pieces), e_idx + 2)]).lstrip() if len(ident) > 4 and ident.startswith("__") and ident.endswith("__"): return "DUNDER_SLOT" if prev_ctx.endswith("@"): return "DECORATOR_AMIL" if re.search(r"\bdef$", prev_ctx): return "FUNC_DEF_AMIL" if re.search(r"\bclass$", prev_ctx): return "CLASS_DEF_AMIL" if re.search(r"\b(?:raise|except)$", prev_ctx) or ident.endswith("Error") or ident.endswith("Exception"): return "EXCEPT_TYPE" if re.search(r"\b(?:import|from)$", prev_ctx): return "IMPORT_MOD" if prev_ctx.endswith("->"): return "RETURN_TYPE" if prev_ctx.endswith("."): return "ATTR_METHOD" if next_ctx.startswith("("): return "CALL_AMIL" if next_ctx.startswith("=") and not next_ctx.startswith("=="): return "KWARG_MAMUL" if next_ctx.startswith(":"): return "PARAM_MAMUL" if re.search(r"\bfor$", prev_ctx): return "COMP_BINDER" if ident.isupper() and "_" in ident: return "CONST_UPPER" if any(c.isdigit() for c in ident) and any(c.isalpha() for c in ident): return "ALNUM_VERSION" if "_" in ident or any(c.isupper() for c in ident[1:]): return "SCHEMA_KEY" return "GENERIC_IDENT" @torch.no_grad() def build_code_plan( self, input_ids_1d: List[int], raw_tok: FastTokenizer, min_tok_idx: int = 0, max_tok_idx: Optional[int] = None, ) -> Dict[str, Any]: T = len(input_ids_1d) end_lim = T if max_tok_idx is None else min(T, max_tok_idx) 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 < end_lim: pc = pieces[i] 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 < end_lim: 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 if span_len >= 2 and ("_" in combined or any(c.isupper() for c in combined[1:]) or len(combined) >= 7): role = self._detect_basran_role16(pieces, i, j, combined) parsed = split_identifier_sibawayh(lead_char + combined) wazn = "alnum_ident" sib_vec: Optional[torch.Tensor] = None n_stems = 1 stem_sig = combined.lower().strip("_") if parsed is not None: delim, wazn, stems, _ = parsed n_stems = len(stems) stem_sig = "+".join(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_khalil_ortho_24d(combined, span_len, wazn, n_stems) spans.append({ "start": i, "end": j, "ident": combined, "role_id": ROLE16_TO_ID[role], "stem_sig": stem_sig, "sib_vec": sib_vec, "ortho_24": ortho_24, }) i = j else: i += 1 # Basran *ʿĀʾid* Co-Reference Slot Assignment: # Stem-families appearing >=2 times (even across snake_case <-> camelCase!) share a consistent slot 1..15! sig_counts = Counter(sp["stem_sig"] for sp in spans) sig_to_slot: Dict[str, int] = {} next_slot = 1 for sp in spans: sig = sp["stem_sig"] if sig_counts[sig] >= 2: if sig not in sig_to_slot: sig_to_slot[sig] = next_slot next_slot = 1 + (next_slot % (NUM_COREF_SLOTS - 1)) sp["coref_id"] = sig_to_slot[sig] else: sp["coref_id"] = 0 plan = {"seq_len": T, "spans": spans, "num_spans": len(spans), "num_coref_groups": len(sig_to_slot)} self._active_plan = plan return plan def forward(self, input_ids: torch.Tensor) -> torch.Tensor: base = self.base_embed(input_ids) 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) coref_t = torch.tensor([sp["coref_id"] for sp in spans], dtype=torch.long, device=dev) struct_deltas = self.ortho_proj(ortho_t) + self.ast_role_embed(role_t) + self.coref_embed(coref_t) 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() 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_seg = gate * (fused_nm.unsqueeze(0) - seg) + struct_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) return (base_f + delta_full.unsqueeze(0)).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: cands = list(ROOT.rglob("tokenizer.json")) raw_tok = FastTokenizer.from_file(str(cands[0])) emb = nn.Embedding(raw_tok.get_vocab_size(), 5120) nn.init.normal_(emb.weight, std=0.02) l0 = KhalilBasranCodeLayer0(base_embed=emb, alpha_code_span=0.025) sample = ( "class DoubleEntryLedger:\n" " def rollback_to_savepoint(self, *, savepoint_name: str) -> dict:\n" " # maps savepoint_name -> savepointName and raises KeyError\n" " return {'savepointName': savepointName}\n" ) ids = raw_tok.encode(sample).ids plan = l0.build_code_plan(ids, raw_tok) l0.train() l0.use_learned_gate = True with torch.autograd.detect_anomaly(): y = l0(torch.tensor([ids], dtype=torch.long)) (y.float() ** 2).mean().backward() assert l0.channel_gate.grad is not None and torch.isfinite(l0.channel_gate.grad).all() assert l0.coref_embed.weight.grad is not None and torch.isfinite(l0.coref_embed.weight.grad).all() print( f"KHALIL_BASRAN_16ROLE_LAYER0_OK | spans={plan['num_spans']} | coref_groups={plan['num_coref_groups']} | " f"roles={[(s['ident'], BASRAN_16_AST_ROLES[s['role_id']], s['coref_id']) for s in plan['spans']]}" ) if __name__ == "__main__": _self_test()