Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

8.5 KB
Raw Blame
def render(out,doc):
    models=doc["models"]
    names=["rule_fsm","rule_strict","oblivious_gbdt","stateless_mlp","recurrent_jev"]
    def fmt(obj):
        if obj["value"] is None:
            return "undefined"
        lo,hi=obj["family95"]
        return f'{obj["value"]:.4f} [{lo:.4f}, {hi:.4f}]'
    paragraphs=["# eBPF-Jev synthetic workflow evaluation","",
        "The 3,840 test workflows come from 24 held-out families. All connections are offline records representing local fixtures. These frequencies describe this synthetic mixture. They do not estimate production prevalence or authorization.",
        "", "## Fixed operating point", "",
        "The neural deny gate uses risk ≥192/255 and uncertainty ≤127/255. The tree and rules use risk only. The kernel policy also denies every unapproved connect after a protected open. Values in brackets are 95% family bootstrap intervals. Wilson intervals for binomial rates appear in eval_metrics.json.","",
        "| Model | Risk ECE before → after | Risk Brier before → after | Model false denies / 1,000 benign | Model recall | With floor, false denies / 1,000 | With floor, recall | Bytes |",
        "|---|---|---|---:|---:|---:|---:|---:|"]
    for n in names:
        r=models[n]
        before,after=[r[k]["exfil_risk"] for k in ("calibration_before","calibration_after")]
        paragraphs.append("| "+" | ".join([n,fmt(before["ECE"])+" → "+fmt(after["ECE"]),
            fmt(before["Brier"])+" → "+fmt(after["Brier"]),fmt(r["fixed"]["false_per_1000"]),
            fmt(r["fixed"]["recall"]),fmt(r["floor_inclusive"]["false_per_1000"]),
            fmt(r["floor_inclusive"]["recall"]),str(r["bytes"] or "no learned artifact")])+" |")
    paragraphs+=["","## Head classification at probability ≥0.5","",
                 "| Model | Head | Precision | Recall | F1 |","|---|---|---:|---:|---:|"]
    for n in names:
        for h,v in models[n]["heads"].items():
            paragraphs.append("| "+" | ".join([n,h]+[fmt(v[m]) for m in ("precision","recall","f1")])+" |")
    paragraphs+=["","## Risk thresholds","",
        "Thresholds were selected on validation scores. The 95% recall target and false-denial budgets are validation constraints. The test ROC rows separately describe the best achievable test recall at each budget and use test labels only for that descriptive calculation. These rows evaluate risk alone, before abstention and the kernel floor.","",
        "| Model | Selection | U8 threshold | Test recall | False denies / 1,000 |",
        "|---|---|---:|---:|---:|"]
    for n in names:
        for source in ["operating_points","test_roc_descriptive"]:
            for k,v in models[n][source].items():
                paragraphs.append(f'| {n} | {source}/{k} | {v["threshold"]} | {fmt(v["recall"])} | {fmt(v["false_per_1000"])} |')
    paragraphs+=["","## Synthetic slices","",
        "Each cell shows the percentage denied by the model at the fixed gate. Each slice contains 384 workflows. Histories in clean and persistent pairs differ in the intermediate executable class. The final connect and every frozen final feature match. The two ambiguous cases have identical observations throughout and opposite authorization labels.","",
        "| Scenario | "+" | ".join(names)+" |","|---|"+"---:|"*len(names)]
    for c in models[names[0]]["slices"]:
        paragraphs.append("| "+c+" | "+" | ".join(f'{models[n]["slices"][c]["denial_rate"]*100:.2f}' for n in names)+" |")
    paragraphs+=["","## Uncertainty and calibration","",
        "| Model | Overall abstention | Abstention on ambiguous pairs |",
        "|---|---:|---:|"]
    for n in names:
        s=models[n]["abstention"]
        paragraphs.append(f'| {n} | {fmt(s["rate"])} | {fmt(s["ambiguous_rate"])} |')
    paragraphs+=["","All heads share one temperature fitted by binary cross entropy on 1,920 calibration workflows. The test ECE uses 15 equal-width bins. eval_metrics.json also gives before/after ECE and Brier scores by head. Calibration describes probability accuracy on this fixture distribution. Identically observed ambiguous pairs impose irreducible label uncertainty. Abstentions count as non-denials in the model-only columns. The floor still denies ambiguous protected-to-unapproved connections.",
        "", "## Reproducibility and limits","",
        "Run generate_dataset.py followed by train_and_eval.py from ml with CPU PyTorch and NumPy. Fixed random seeds control template allocation, sampling and training. The original split sizes are 7,680 train, 1,920 cal, 1,920 val and 3,840 test. Alignment adds 3,072 application training workflows with paired endpoint approvals, different port buckets, and same-process or child service connections. Legacy replay preserves the original model logits during fitting. Checkpoint selection uses both validation populations; the original calibration population supplies the shared temperature. Each family uses a distinct projected four-step preparation sequence. Repository IDs and tool catalogs are disjoint across splits. Common policy scenarios, OS hook types and file classes deliberately recur. The generator simulates fork inheritance along one active lineage. It does not replay kernel events.",
        "", "Both neural models use straight-through INT8 weight rounding, integer activation shifts and validation checkpoint selection across 24 epochs. The stateless model shares the trained embedding and receives only the final connect at prediction. Socket embeddings are zero. The trees share final structured features and use 32 symmetric depth-four trees. The deployed tree map stores risk leaves only. Auxiliary heads use separate offline INT16 leaf banks under the same splits. The deterministic rule exposes risk in the kernel. Its chain and benign columns are explicit offline proxies (inherited execution after a rule match, and inverse rule match). Its uncertainty score is always zero.",
        "", "The strict rule treats class 30 as approved loopback-equivalent under the frozen feature mapping. Its private destinations incur denials after a protected read. The benchmark encodes allowlisted external registries in class 30 as the kernel extractor does. Aggregate slices cannot measure behavior on new policies, unrelated tasks sharing a process, or unseen attack families.",
        "", "Confidence intervals resample 24 entire families 1,000 times with replacement. Zero-width cluster intervals can occur when family proportions agree. The JSON also reports workflow-level Wilson intervals for simple rates. Precision is undefined if the model never predicts the head.",
        "", "## Fixed-point verification",""]
    p=doc["parity"]
    paragraphs.append(f'{p["matched"]}/500 native C callback vectors matched NumPy for pooled embeddings, next state, logits and LUT outputs. The pack is {models["recurrent_jev"]["bytes"]:,} bytes. Vectors include {p["sequences"]} five-step blocks, zero and signed-extreme inputs, long strings, {p["saturated_hidden"]} hidden-state saturation cases and {p["saturated_logit"]} clipped endpoint cases. This checks the compiled user-space kernel callbacks. Actual BPF hook execution belongs to the testbed.')
    for n in ("recurrent_jev","stateless_mlp"):
        r=models[n]
        paragraphs.append(f'\n{n} FP32 master → fixed-point accuracy delta by head (percentage points, contract order): '+", ".join(f"{100*v:+.3f}" for v in r["int8_minus_fp32"])+f'. All {r["test_qat_integer_logits_matched"]:,} test fake-quantized FP32 logits matched the integer implementation.')
    paragraphs+=["","## Comparative interpretation",""]
    for c in ("clean","persistent","chain","ci","stale_git","ambiguous_deny"):
        wanted=c in ("persistent","chain","ambiguous_deny")
        vals={n:models[n]["slices"][c]["denial_rate"] for n in names if n!="rule_strict"}
        best=(max if wanted else min)(vals.values())
        paragraphs.append(f'- On {c}, '+", ".join(n for n,v in vals.items() if v==best)+f' achieved the best fixed-gate result ({best*100:.2f}% denied).')
    if "application_test" in doc:
        r=doc["application_test"]
        paragraphs.extend(["","## Application holdout","",
            f'The exported recurrent model on {r["n"]} additional held-out workflows had '
            f'{fmt(r["fixed"]["false_per_1000"])} false denies per 1,000 benign, '
            f'{fmt(r["fixed"]["recall"])} recall and risk ECE {fmt(r["risk_calibration"]["ECE"])}.'])
    paragraphs.append("The floor-inclusive metrics measure the deployed protected-to-unapproved rule and the learned decision together.")
    (out/"eval_report.md").write_text("\n".join(paragraphs)+"\n")