Predictive Context Packing with JEPA v3
We cut local 27B prompt tokens by -84.28% (247,172 to 38,860 tokens across N=12 tasks) and accelerated end-to-end wall-clock execution by +78.07% / 4.56x faster (163.6s to 35.9s) with 100.0% (12/12 exact sourcemap.locate() resolution) by replacing blind full-file dumps with a resident 384-D JEPA v3 neural predictor and an AST-aware context slicer.
Reading time: 90 seconds for the headline ledger and 6 KPI cards · 12 minutes for the full 4-loop architectural trace, 4 interactive sandboxes, and honest failure boundaries.
1. Why Local 27B Models Choke on Full-File Contexts (The Prefill Bottleneck)
When a local 27-billion-parameter dense model (Qwen3.8-27B running on an OMEN dual Intel Arc Pro B70 workstation or an AM4 dual-GPU node pairing an NVIDIA RTX 5070 with an RTX 4070 Ti SUPER over a dedicated 1 Gbps link) executes a multi-file coding task, the dominant latency bottleneck is not token generation. It is prompt prefill.
Standard agent harnesses pack three or four full source files into the prompt with 1-based line numbers so the model can cite exact lines for patch verification. Across a typical 3-file slice totaling 1,800 to 3,200 lines of Python, a full-file prompt consumes between 14,000 and 29,600 input tokens. Even with native Flash Attention promoted on the B70 XPU seats, prefilling 25,000 tokens takes 13 to 19 seconds before the first output token is emitted, while pinning KV cache blocks that would otherwise serve parallel worker lanes.
FunctionDef, AsyncFunctionDef, or ClassDef), and its 1-hop intra-file helper callees. The remaining 85% of the file is dead weight during prefill.
Naive chunking breaks local code delivery because stripping lines alters 1-based line numbering. If a surgical patcher or delivery verifier (sourcemap.locate()) expects quotes anchored to the original file's line numbers, any re-indexed snippet causes silent line-number drift. Our AST-aware slicer (render_jepa_ast_sliced_for_model in sourcemap.py) solves both problems simultaneously:
- AST Symbol Decomposition: Each candidate source file is parsed via Python's
astmodule into discrete symbol units with exactlinenoandend_linenospans, signatures, docstrings, and called identifiers. - Predictive Latent Ranking: The resident local JEPA v3 daemon (port npu-slicer) ranks all AST symbols against the task intent in under 2 milliseconds warm cache, selecting the top-K target symbols and automatically pulling in 1-hop intra-file callees.
- Line-Preserving Emission: Kept spans are emitted with their exact original 1-based line numbers (for example,
1..28followed by# ... [lines 29..324 omitted by jepa-v3 context packager] ...and325..368), guaranteeing zero drift whensourcemap.locate()resolves the model's citations.
2. Four Experimental Loops & Three Architectural Pivots
Our earlier 128-D Sovereign JEPA prototype (Model E) proved that non-generative latent predictors could avoid dimensional collapse via VICReg regularization, yet it hit a hard ceiling of 13.46% top-1 recall (R@1) when asked to distinguish fine-grained AST symbols across real multi-repository transitions. To find and remove the bottleneck without guesswork, we built a hydrated corpus of 2,072 verified repository transitions across 4 active codebases (985 code, 480 test, 311 compositional blueprint, and 296 ADR contract transitions) with zero synthetic distractors.
We evaluated every model arm against a frozen 4-Slice Self-Gated Benchmark comprising 260 scenarios (K=20, 5.0% chance) that enforces five automatic anti-shortcut gates: fixed-query R@1 = 5.0%, longest-candidate R@1 = 5.0%, 100.0% own-source masking, zero synthetic status bonuses, and lexical Jaccard < 0.05 on Slice A.
- Loop 1 (Data Density & Operation Cards): Moving from truncated raw diffs (Arm 1A) to dense structural AST + operation cards with separate state and intent encoding (Arm 1C) lifted top-1 retrieval to 64.23% overall R@1.
- Loop 2 (384-D Cross-Attention Predictor & EMA Teacher): Eliminating the 128-D projection bottleneck in favor of a 384-D Zero-Init Residual predictor with 4-head Token Cross-Attention and an EMA Target Encoder (
tau = 0.996) on the AM4 dual-GPU node lifted pure neural retrieval (Arm 2D / 3B) to 71.24% ± 1.13% macro R@1 and 55.83% R@1 (95.83% R@3 vs 0.00% BM25) on Slice A zero-overlap cross-subsystem jumps, while expanding manifold geometry to 225.53 effective rank (0/384 collapsed dims). - Loop 3 (AST Hard Negatives & Uncertainty-Calibrated 3-Signal Router): Adding within-file AST sibling hard negatives, counterfactual intent margins, and an uncertainty-calibrated lexical + latent + blueprint graph gate (Arm 3C) achieved 97.08% ± 0.78% macro R@1: 88.33% R@1 (99.17% R@3) on Slice A, 100.0% R@1 & 100.0% Counterfactual Flip on Slice B, 100.0% R@1 on Slice C code-to-test/blueprint binding, and 100.0% R@1 vs 71.0% raw BM25 (0.0% regression) on Slice D standard lexical navigation.
- Loop 4 (Resident Port npu-slicer Daemon & Live 27B/Frontier A/B Assay): Wiring the winning checkpoint into the resident CPU daemon and HEARTH delivery pipeline cut local 27B prompt tokens by
84.28%and frontier file-pack tokens by -92.90% file-pack token reduction (-76.09% exploratory turns).
3. The Concatenation Bug That Drowned the Intent (0% to 100% Counterfactual Flip)
Why did our initial 384-D neural baseline score 0.0% on Slice B counterfactual pairs? A Slice B pair holds the starting source file state (S) completely identical and swaps only the operator intent (I_1 vs. I_2): for example, starting at motion_50b.py, Intent 1 asks to “Verify golden SHA-256 velocity clamping vectors in the test suite” while Intent 2 asks to “Bind the 50-byte UDP wire brick into the compositional blueprint registry.”
Forensic inspection of the tokenizer revealed a classic silent failure: all-MiniLM-L6-v2 enforces a hard maximum sequence length of 256 wordpiece tokens. When the legacy router concatenated state_text + intent_text into a single string, any AST state card longer than ~1,100 characters consumed all 256 tokens. The operator intent at the tail of the string was truncated to zero bytes before reaching the transformer. Consequently, I_1 and I_2 produced bit-for-bit identical embeddings, forcing a 0.0% counterfactual flip rate.
# THE BUG: Single-sequence concatenation truncates intent_text past 256 wordpieces
raw_input = f"{state_ast_card}\n\nINTENT: {operator_intent}" # intent dropped at token 257!
# THE FIX (JEPA v3): Dual-tower encoding + 4-head Token Cross-Attention + Zero-Init Residual
z_state, tokens_state = encode_state(state_ast_card) # full 256-token budget
z_intent, tokens_intent = encode_intent(operator_intent) # dedicated 256-token budget
delta = cross_attn_predictor(q=tokens_intent, kv=tokens_state)
z_pred = l2_normalize(z_state + alpha_zero_init * delta) # starts as exact identity
Deconstructing 71.24% Pure Neural vs. 97.08% 3-Signal Calibrated Router
Reporting only a blended hybrid number hides how much work the neural predictor actually performs versus lexical matching. We separate the two throughout our ledger:
- Pure Neural 384-D Predictor (Arm 2D / 3B = 71.24% ± 1.13% Macro R@1): Using cosine similarity
cos(z_pred, z_target)alone with zero lexical or graph features, the 384-D cross-attention model achieves55.83% R@1and95.83% R@3on Slice A zero-overlap jumps where BM25 scores0.00%. - Uncertainty-Calibrated 3-Signal Router (Arm 3C = 97.08% ± 0.78% Macro R@1): In production, throwing away exact symbol identifiers when an operator explicitly names
encode_50b_udp_motionwould be self-sabotage. Our calibrated gate computes identifier overlap, lexical margin, and intent verb polarity to dynamically weight Lexical BM25+ID(w_lex), 384-D JEPA cosine(w_jepa), and 1-hop Blueprint/Import DAG adjacency(w_dag).
4. Live 12-Task Paired A/B Assay Across Dual Arc Pro B70s & Dual RTX GPUs
To verify that retrieval accuracy translates into real wall-clock compression without degrading patch resolution, we ran a 12-task paired A/B assay across all three local serving seats: omen-dense-27b (xpu:0) and omen-dense-27b-b (xpu:1) on the OMEN dual Intel Arc Pro B70 workstation, plus am4-vllm on the AM4 dual-GPU node (RTX 5070 + RTX 4070 Ti SUPER).
Each task paired identical prompts and multi-file bundles under Control (numbered_full) versus Treatment (jepa_ast_sliced) at temperature 0.0. Every response was graded by sourcemap.locate() to verify that quoted source lines resolved to the exact 1-based line number in the underlying repository file.
# File: sovereign_core/wire/motion_50b.py (jepa-v3 ast-sliced: 2/14 symbols kept)
1: """50-byte UDP binary wire codec for high-frequency synthetic squad motion frames."""
2: import hashlib
3: import struct
4: from typing import Dict, Tuple
# ... [lines 25..324 omitted by jepa-v3 context packager] ...
325: def encode_50b_udp_motion(actor_id: int, tick: int, pos: Tuple[float, float, float], vel: Tuple[float, float, float]) -> bytes:
326: """Pack a deterministic 50-byte big-endian UDP motion frame with velocity clamping."""
333: return struct.pack(">BBIffffff14s", 0x5A, actor_id & 0xFF, tick, px, py, pz, vx, vy, vz, digest[:14])
# [sourcemap.locate() VERIFIED]: Exact match at sovereign_core/wire/motion_50b.py:333 (0 line drift)
Complete 12-Task Paired A/B Ledger
| Task | Serving Seat | Target AST Symbol | Control Tok | Sliced Tok | Token Delta | Control (s) | Sliced (s) | Speedup | Verified Line Ref |
|---|---|---|---|---|---|---|---|---|---|
| AB-01 | OMEN B70 (xpu:0) | encode_50b_udp_motion |
18,560 | 3,300 | -82.22% | 11.78s | 2.89s | 4.08× | motion_50b.py:333 |
| AB-02 | OMEN B70 (xpu:0) | write_atomic_json |
14,383 | 3,050 | -78.79% | 9.06s | 3.24s | 2.80× | control_channel.py:9 |
| AB-03 | OMEN B70 (xpu:0) | sample_dem_bilinear |
14,849 | 3,201 | -78.44% | 9.93s | 3.21s | 3.10× | dem_sampler.py:41 |
| AB-04 | OMEN B70 (xpu:0) | run_all_benchmarks |
29,593 | 3,368 | -88.62% | 19.44s | 2.94s | 6.62× | substrate_bench.py:502 |
| AB-05 | OMEN B70 (xpu:1) | parse_valheim_db_fast |
24,819 | 2,850 | -88.52% | 16.64s | 2.74s | 6.08× | valheim_db_v37.py:391 |
| AB-06 | OMEN B70 (xpu:1) | encode_tcdata_gzip |
20,322 | 3,337 | -83.58% | 13.32s | 3.10s | 4.30× | tcdata_codec.py:46 |
| AB-07 | OMEN B70 (xpu:1) | get_world_splicer_status |
28,046 | 3,017 | -89.24% | 18.99s | 2.89s | 6.56× | world_splicer_api.py:211 |
| AB-08 | OMEN B70 (xpu:1) | audit_drift |
29,605 | 4,136 | -86.03% | 19.98s | 3.18s | 6.29× | decision_engine.py:786 |
| AB-09 | AM4 Dual RTX GPU | get_blueprint_graph_payload |
17,863 | 3,813 | -78.65% | 12.10s | 3.61s | 3.35× | blueprint_atlas_api.py:72 |
| AB-10 | AM4 Dual RTX GPU | handle_tactical_intel_get |
14,692 | 2,741 | -81.34% | 9.84s | 2.56s | 3.84× | tactical_intel_api.py:33 |
| AB-11 | OMEN B70 (xpu:0) | scan_corpus |
20,883 | 3,261 | -84.38% | 13.38s | 2.87s | 4.67× | corpus_scanner.py:565 |
| AB-12 | AM4 Dual RTX GPU | get_jepa_observatory_payload |
13,557 | 2,786 | -79.45% | 9.18s | 2.67s | 3.44× | jepa_observatory_api.py:55 |
| TOTAL / AGGREGATE (12 Paired Tasks) | 247,172 | 38,860 | -84.28% | 163.63s | 35.88s | 4.56× (+78.07%) | 12/12 Exact | ||
5. Lego Bricks, Lincoln Logs & Sub-Second Iteration Physics
Context packing is only half of the leverage equation. Before an agent writes a single line of code, the resident port npu-slicer daemon ranks the operator's brief against our unified registry of 48 L0-L3 blueprints (19 Bricks, 8 Lincoln Logs, 8 Walls, 9 Houses, 4 Landscapes) to issue a deterministic REUSE, UPDATE, or MINT verdict.
Crucially, our taxonomy separates L0A Atomic Lego Bricks (pure functions, binary codecs, and math kernels) from L0B Lincoln Logs: 8 notched interop & hot-reload substrates that bypass traditional 30-to-180-second build/restart cycles via in-memory ZDO splicing, binary sector hot-patching, zero-copy WebGL2 80-byte instance filemaps, and atomic POSIX symlink swaps.
6. Where It Breaks & Honest Operating Boundaries
A benchmark report is only trustworthy if it documents the exact regimes where its mechanisms lose their advantage or require a fallback. Across our four experimental loops and adversarial audits, three operational boundaries define where JEPA v3 context packing must be constrained or disabled:
K=20 symbols per scenario), the pure 384-D neural predictor achieves 71.24% ± 1.13% macro R@1 and 55.83% R@1 on zero-overlap jumps. However, if you run pure neural cosine similarity across an unconstrained repository-wide pool of K > 500 symbols without lexical or 1-hop import graph pruning, sibling helper functions with nearly identical AST shapes create false-positive collisions. The calibrated 3-signal gate (97.08% ± 0.78%) is mandatory in production: lexical and import-graph signals narrow the candidate set first, and the 384-D JEPA predictor resolves semantic and cross-subsystem jumps within that bounded neighborhood.
(file_sha256, symbol_name, start_line, end_line) in the resident port npu-slicer daemon's LRU cache, ranking a 3-file bundle takes 1.74 ms p50 (2.52 ms under multi-seat load) with 0.0 MiB of GPU VRAM contention on the dual Arc Pro B70 cards. On a cold cache, however, first-touch AST parsing and CPU MiniLM-L6-v2 encoding cost 11-35 ms per uncached file (reaching 43.7 ms to 143.7 ms when cold-encoding three large uncached files simultaneously, as recorded in tasks AB-08, AB-11, and AB-12). Compared to saving 6,500 to 16,800 ms of 27B GPU prefill time, a 140 ms cold-encode tax is a 100× net win, but sub-10ms real-time callers must pre-warm the symbol cache on file save.
HEARTH_JEPA_PACK=0 or context_mode="numbered_full") and our October 23 NPU Pre-Flight Gatekeeper, which automatically routes whole-file invariant prompts to numbered_full mode (0/20 (0.0%) false-sliced whole-file prompts & F1 = 1.000 thrash detection across 26 traces).
7. Intel AI Boost NPU + DDR5-6000 /dev/shm Offload & Why We Red-Teamed Our Own 5.22× Headline
Twenty-four hours after completing Loop 4, we targeted two pieces of workstation silicon that sat idle while the Intel Arc Pro B70 GPUs served 27B models: the Intel AI Boost NPU (/dev/accel/accel0) and 128 GB of DDR5-6000 RAM (/dev/shm). By compiling the 384-D MiniLM encoder onto the NPU via OpenVINO (40.6 ms warm blob load from /dev/shm/mechsuit-ov-cache, dual-slot pinned async InferRequest pool) and storing AST symbol spans plus FP16 line embeddings in /dev/shm/mechsuit-ast-arena/ (0.22 ms warm hit), we achieved 89.85% host CPU saved on Intel AI Boost NPU (/dev/accel/accel0, 0 open /dev/dri GPU FDs).
In addition to Step-1 AST symbol ranking, the NPU + /dev/shm arena powers Step-2 quote verification pre-screening (quote_attach), achieving -90.24% Step-2 quote tokens (15/15 = 100.0% real-claim recall in 12.65 ms cold) across 15 real historical 27B and 30B delivery claims, alongside a 1 Hz Agent Thrash Sentinel (0.38 ms per poll).
When our initial NPU benchmark pass (v1) reported 20/20 green gates and a naive 5.22× throughput multiplier on the first try, we dispatched three cold-context frontier auditors (Claude Sonnet 5.5, Codex GPT-6.1-Sol, and a cold CLI subagent) to break our code and falsify our math. They exposed six real flaws in v1, and fixing every one of them in v2 confirmed 3.05x regime-weighted GPU prefill speedup & 1.83x-2.03x full Prefill+Decode 27B throughput on the exact same silicon:
| Audit Surface | v1 Claimed | What the 3-Lane Cold-Context Red Team Exposed in v1 | Hardened v2 Fix & Verified Receipt (Oct 23, 2026) |
|---|---|---|---|
| 1. Whole-File False-Slice Rate | 0.00% (0/10) | 80.0% (8/10) false-sliced on implicit whole-file prompts because in [a-z_]+ matched .py filename stems (in hybrid_router.py) |
0.00% (0/20) false-sliced, 100% (10/10) surgical (filename stems stripped before regex/AST matching) |
| 2. Step-2 Quote Recall & Cold Latency | 100% in 4.19 ms | v1 pre-warmed /dev/shm before timing (true cold = 117.62 ms) and <18 char filter dropped SKIP_DAYS = 7 |
15/15 (100.0%) real-claim recall in 12.65 ms cold (17.38 ms p95), -90.24% tokens (floor lowered to >= 8 chars, FP16 line vectors persisted by file_sha256) |
| 3. 1 Hz Thrash Sentinel | F1 = 1.000 (N=20) | Missed 3/3 (0% recall) on silent polite failure loops at 0.80 cosine threshold; English gerunds (Testing) collided as targets |
F1 = 1.000 across 26 traces (3/3 polite loops caught, 0/3 debug FP) (locked 0.65 threshold on p0 sentence pooling + code-only target regex) |
| 4. 27B Throughput Multiplier (Amdahl) | 5.22× naive ratio | Divided prompt tokens without adding constant 27B Decode time (~220 tok @ 41 tok/s = 5.37s) and 15% whole-file tasks (1.0×) |
3.05× GPU Prefill speedup & 1.83×-2.03× Full Prefill+Decode 27B throughput on identical silicon and problem sets |
| 5. Zero GPU Contention (B70 Cards) | 0.0 MiB (xpu-smi) | Calling core.available_devices during OpenVINO init opened 3 /dev/dri/renderD* GPU file descriptors on the B70 cards |
0 open /dev/dri/* GPU FDs in /proc/pid/fd via ZE_ENABLE_ALT_DRIVERS=libze_intel_npu.so.1 and direct "NPU" binding |
| 6. AST Cache Key & Batch Invariance | 0% collision | Hashed only lines [:18] of each symbol (missing edits at line 60) and used batch-size-dependent IDF weighting |
0% body-edit collision & max_diff = 0.0 batch invariance (full symbol span hash + line-number stripping + static_vocab_idf.v3) |