Run this model with HF Jobs

Run enver/rootformer-code-v19.2-qwen38-nwp on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 20,470 Bytes
c5a2aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/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()