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: 18,520 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
#!/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()