Metadata-Version: 2.4
Name: grail-sampler
Version: 0.14.0
Summary: Model-agnostic geometric logit-space sampler (GRAIL & GRAIL-SC) for long-horizon LLM prose.
Author: David Torcivia
License-Expression: MIT
Project-URL: Homepage, https://github.com/davidtorcivia/grail-sampler
Project-URL: Repository, https://github.com/davidtorcivia/grail-sampler
Project-URL: Demo, https://davidtorcivia.github.io/grail-sampler/
Project-URL: Issues, https://github.com/davidtorcivia/grail-sampler/issues
Keywords: llm,sampling,logits-processor,decoding,fisher-rao,mlx,pytorch,vllm,llama-cpp
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Provides-Extra: torch
Requires-Dist: torch>=2.1; extra == "torch"
Provides-Extra: mlx
Requires-Dist: mlx>=0.18; extra == "mlx"
Provides-Extra: all
Requires-Dist: torch>=2.1; extra == "all"
Requires-Dist: mlx>=0.18; extra == "all"
Dynamic: license-file

# GRAIL (`grail-sampler`)

[![CI](https://github.com/davidtorcivia/grail-sampler/actions/workflows/ci.yml/badge.svg)](https://github.com/davidtorcivia/grail-sampler/actions/workflows/ci.yml)
[![Demo](https://img.shields.io/badge/Live%20Samples-GitHub%20Pages-1d5b4c)](https://davidtorcivia.github.io/grail-sampler/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

A drop-in logit sampler for PyTorch/HuggingFace, Apple Silicon MLX, oMLX, vLLM, llama.cpp, and SGLang.

## Why Use It

Standard samplers (`min_p`, `top_p`, `temperature`) apply one cutoff to every token. That cuts off rare, specific words (`>5` nats surprisal drops to ~`0%`, vs. `18%` in published prose), while leaving models free to repeat their own vocabulary and fall into stock RLHF phrasing (`"not merely X; it is Y"`, `-tion`/`-ment` nominalizations, excessive colons and semicolons).

GRAIL modifies next-token logits to fix those failure modes on unmodified open-weight models, running at **99.3% of native `min_p` speed** (`0.18 ms/tok` overhead on Apple Silicon MLX).

### What It Does

- **Splits mid-word spelling from word starts:** Clamps intra-word continuations tightly (`min_p=0.02, T=0.72`) so words do not misspell or fuse together. Leaves word starts unclipped down to a far-tail floor (`tail_floor_nats=9.5`) that blocks glitch tokens while keeping valid rare words reachable.
- **Reduces self-repetition without topic drift:** Tracks recent tokens, 5-character stems, and sentence-opener grammar classes inside a Fisher-Rao KL trust region (`KL <= kl_budget`). Exempts prompt stems and projects long-horizon repulsion orthogonal to prompt embeddings so the output stays on topic.
- **Keeps surprisal inside a bounded band:** Raises temperature during flat passages (`s < 2.15`) and cools down noisy passages (`s > 2.68`).
- **Damps common AI phrasing habits:** Penalizes contrastive antithesis (`not merely/just/simply ...; it / but`), repeated colons and semicolons (`colon_semi_cooldown_steps=28`), discourse clichés (`Furthermore`, `Crucially`), and non-prompt nominalizations (`-tion`, `-ment`, `-ity`) outside quotes.
- **Optional contrastive and beam modes for aligned chat models:**
  - **`GRAIL-SC` (Batched `B=2` or Tiny-Draft Sparse Contrast):** Subtracts a second stream's log-probabilities (`log P_+ - alpha * log P_-`) gated by Jensen-Shannon divergence, with **Asymmetric Plausibility Gating** (`boost_min_p=0.015`: suppresses clichés freely while restricting positive boosts to plausible positive-model tokens) and optional **Opening Alpha Surge** (`opening_alpha_boost`). Supports **Cross-Frame mode** (`build_cross_frame_prompts`, `neg_style="chat_textbook"`), **In-Turn Prefill Contrast** (`build_inturn_contrast_prompts`), and **Zero-Sync Sparse Draft Contrast** on both MLX (`make_draft_sc_stepper`) and PyTorch (`generate_draft_sc`).
  - **`GRAIL-SMC` & `Fast-SMC` (Batched `B=4` or `B=6`):** Advances parallel candidates and resamples at sentence boundaries using model-internal surprisal wave contrast, LLR, and stem-echo penalties. Setting `beam_collapse_at=100` runs the beam over the opening sentences and then collapses to `B=1` or `B=2` (`29–36 tok/s`).
- **Multi-turn & speculative decoding ready:** Call `reset_turn()` (PyTorch) or `reset_turn_state()` (MLX) between chat turns to clear sentence/quote state while preserving long-horizon anti-echo memory, and `verify_draft_batch()` for exact Leviathan-et-al. rejection sampling over speculative or MTP draft batches (`[K+1, V]`).

![GRAIL and GRAIL-SC Pipeline](assets/tail_split_architecture.svg)

### Documentation & Integrations

- [Technical Paper](paper/grail_paper.md): Fisher-Rao trust-region math, ablations, layer probes, and full tables.
- [Essay 1: The Eight Laws of Machine Tells](posts/the_laws_of_machine_tells.md): Mechanistic analysis of tail truncation, self-echo, and chat-role collapse.
- [Essay 2: Introducing GRAIL & GRAIL-SC](posts/introducing_grail_and_grail_sc.md): Design notes and trade-offs.
- [Side-by-Side Unedited Samples](samples/side_by_side_comparisons.md) & [Live Interactive Showcase](https://davidtorcivia.github.io/grail-sampler/): Full multi-paragraph transcripts comparing `min_p` against GRAIL modes.
- [Inference Engine Integrations](examples/README.md): Adapters for HuggingFace (`generate_sc` / `generate_draft_sc`), MLX, oMLX, vLLM (V0 & V1), native C++17 [llama.cpp](examples/llamacpp_grail_sampler.hpp), and SGLang.

---

## Before and After Samples

Every comparison below uses the exact same unmodified public model (`Qwen3.6-35B-A3B` or `Gemma-4-12B-it`) and prompt. Only the sampler changes. Detectors reported: `Mesmer-9B` P(Human) (**higher is better**) and `Desklib`, `TMR`, `ModernBERT` AI% (**lower is better**), plus blind cross-family ratings (1 to 10 Accuracy / Coherence / Naturalness).

### 1. Literary Essay (*The Uses of Boredom*)

- **Standard `min_p` (`T=0.8, min_p=0.05` | Mesmer `0.0%` Human | Desklib `100.0%` AI | TMR `98.7%` AI | ModernBERT `98.9%` AI):**
  > *"Boredom, often perceived as a negative state, can actually be a valuable tool in various aspects of life. In the workplace, it can serve as a catalyst for creativity and problem-solving. When employees are not overly stimulated or distracted, they may find themselves in a state of mind that allows for innovative thinking and the exploration of new ideas."*

- **`GRAIL-SC-SMC` (328 words | Mesmer `98.8%` Human | Desklib `1.5%` AI | ModernBERT `5.1%` AI | Judge `9 / 9 / 9`):**
  > *"Boredom isn't quite like sleepiness. If you start to nod off, you may still try to stay awake, if you've got somewhere you need to be, someone you need to see, or only just a hotel room to get to before you can fall into a well-deserved slumber.*
  >
  > *The emotional discomfort of boredom is more like how uncomfortable it is at a party of which you disapprove, for moral or cultural reasons. You want to leave, but can't. You're just sitting there, staring at the walls, and counting the annoying little flashes of light. Or – as Samuel Johnson once did – sitting in an uninteresting conversation. 'I was desperate for a quarrel', he wrote, 'but nobody chose to give me the pleasure.'*
  >
  > *Boredom gets mixed up with sleepiness, because both are states of under-stimulation, but sleepiness at least comes with hopes. Once you've closed your eyes and let the moment take you, there's something restorative in the waiting. Boredom has none of that."*

### 2. Science Prose (*Wild Yeast and Acid Balance in Hearth Bread*)

- **Standard `min_p` (`T=0.8, min_p=0.05` | Mesmer `0.0%` Human | Desklib `100.0%` AI | TMR `98.5%` AI | ModernBERT `98.9%` AI):**
  > *"Why? The answer is wild yeast. Wild yeast is the living organism that makes bread rise. It's also the source of the flavor and texture of hearth bread. Without wild yeast, a hearth bread would be a flat, dense cracker. But wild yeast is a fickle beast. It's sensitive to temperature and humidity. It's also sensitive to acid. Let's take a look at how acid impacts hearth bread."*

- **Cross-Frame `Fast-SC-SMC` (`33.7 tok/s`, 307 words | Mesmer `99.5%` Human | Desklib `0.9%` AI | TMR `2.7%` AI | ModernBERT `11.2%` AI):**
  > *"The problem lies mainly with wild yeast. Yeast, just like bacteria, varies from place to place. The species of yeast (and bacteria) vary from zone to zone, building to building, floor to floor, even within the same square foot. This being our fermenting medium, it offers a huge variance in speed and acidity at any given time in the mixing, fermentation, shaping and final bake of hearth bread (or any bread). Water is also a major factor for acid balance since it is never pure (think distilled vs filtered vs tap)."*

### 3. Systems Engineering (Chat Mode, *B-Trees vs. LSM-Trees*)

- **Standard `min_p` (`T=0.8, min_p=0.05` | Desklib `95.0%` AI | ModernBERT `98.8%` AI):**
  > *"The enduring dominance of B-trees in read-heavy, low-latency transactional systems is not merely a relic of legacy architecture but a testament to the profound physical advantages of in-place updates and predictable memory access patterns. While Log-Structured Merge Trees (LSM-trees) have revolutionized write-throughput for massive-scale storage engines by amortizing random writes into sequential appends, they introduce a suite of structural penalties that become glaring liabilities when the workload shifts toward frequent, concurrent point lookups."*

- **`GRAIL-SC` (589 words | Desklib `4.1%` AI | TMR `1.8%` AI | ModernBERT `1.7%` AI | Judge `9 / 9 / 9`):**
  > *"When you query a database, the hardware does not care about your algebra. It cares about electrons moving through transistors and magnetic flux switching in platters or charge traps in silicon. To understand why traditional B-trees often beat Log-Structured Merge-trees, specifically for point lookups, you have to look past SQL execution plans and watch how the CPU bus, memory hierarchy, and storage controller tick. A B-tree is a balanced tree where every node lives on disk or RAM, usually in eight-kilobyte or sixteen-kilobyte pages. When you search for a specific key, the engine walks the root down to a leaf. On a hard drive, this is catastrophic. A modern spindle takes nine milliseconds to move a read/write head and wait for rotation. If your index is deep, you might spawn twelve separate mechanical seeks. That is nearly a hundred milliseconds of pure stall time. The CPU sits idle. You are bounded by the physical limitation of aluminum spinning in a vacuum."*

### 4. Observational Prose (Chat Mode, *The Sound of an Empty Parking Garage*, Stock `Gemma-4-12B-it`)

- **Standard `min_p` (`T=0.8, min_p=0.05` | Desklib `100.0%` AI | TMR `98.5%` AI | ModernBERT `98.7%` AI | Stem Echo `0.192`):**
  > *"## The Architecture of Solitude: A Study of the Nocturnal Parking Garage*
  >
  > *There is a specific category of liminality that exists only in the transition between utility and abandonment. It is the architecture of the 'in-between'—the spaces designed for movement that are currently devoid of it. The parking garage at night is perhaps the most profound manifestation of this state. Stripped of the frantic commerce of the day, it transforms from a utilitarian vessel of transit into a cathedral of industrial solitude..."*

- **In-Turn `GRAIL-SC + Fork` (`28.2 tok/s`, 307 words | Desklib `77.2%` AI | ModernBERT `38.4%` AI | Stem Echo `0.094` | Blind `Qwen3.6` Judge `10 / 9 / 9`):**
  > *"The low hum of the building exists just before you step inside, a dull vibration in the concrete and steel that feels like a held breath. Once the heavy door swings shut, the noise of the street—the hiss of tires on wet asphalt and the distant, rhythmic thrum of the highway—snaps into a different category. It stops being city noise and becomes a hollow resonance. In here, the air is thick and still, carrying a damp weight that smells of old rubber and old oil. Every drop of water from a leaky roof pipe hits the concrete with a flat, dry thud..."*

See [`samples/side_by_side_comparisons.md`](samples/side_by_side_comparisons.md) for longer unedited side-by-side transcripts.

---

## Installation

`grail_sampler` keeps its core zero-dependency and imports PyTorch or MLX lazily:

```bash
# Install directly from GitHub (or editable local checkout)
pip install "grail-sampler[torch] @ git+https://github.com/davidtorcivia/grail-sampler.git"
pip install "grail-sampler[mlx] @ git+https://github.com/davidtorcivia/grail-sampler.git"

# Local editable install
pip install -e ".[torch]"
pip install -e ".[mlx]"
```

---

## Quickstart

### Zero-Friction CLI (`grail-demo`)

Compare `min_p` and GRAIL side by side on any local or HuggingFace model (MLX or PyTorch):

```bash
grail-demo \
  --model mlx-community/Qwen3.6-35B-A3B-4bit \
  --prompt "Explain how wild yeast, hydration, and acid balance shape sourdough crumb and flavor." \
  --mode cross-frame \
  --compare-minp

# Fast Sparse Draft-Contrast (42.5 tok/s, 88% of bare min_p):
# add --draft-model mlx-community/Qwen3-0.6B-4bit --no-fork
```

### PyTorch / HuggingFace (Single-Stream `GRAIL` & Batched `B=2` `generate_sc`)

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from grail_sampler import GrailConfig, GrailLogitsProcessor, GrailSCConfig, build_cross_frame_prompts, generate_sc

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507")
dev = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B-Instruct-2507", dtype=torch.float16).to(dev)

# 1. Single-stream drop-in LogitsProcessor
prompt = "Why B-Trees Still Beat LSM-Trees on Read-Heavy Workloads\n\n"
inputs = tok(prompt, return_tensors="pt").to(dev)
proc = GrailLogitsProcessor(
    tokenizer=tok,
    lm_head_weight=model.get_output_embeddings().weight,
    prompt_text=prompt,
    cfg=GrailConfig.goldilocks(),
    proj_dim=128,  # 128-dim FP16 semantic projection (~3.19 ms/tok on MPS)
)
# Pass temperature=1.0, top_p=1.0, top_k=0 so generation_config defaults do not re-clip the tail.
out = model.generate(**inputs, do_sample=True, temperature=1.0, top_p=1.0, top_k=0, logits_processor=[proc], max_new_tokens=512)
print(tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))

# 2. One-line batched B=2 Cross-Frame GRAIL-SC (CPU, CUDA, or MPS; no accelerate required)
user_q = "Explain why B-trees still beat LSM-trees on read-heavy workloads."
_, pos_ids, neg_ids = build_cross_frame_prompts(tok, user_q, neg_style="chat_textbook")
res = generate_sc(model, tok, pos_ids, neg_ids, prompt_text=user_q, cfg=GrailSCConfig.stock_technical(), max_new_tokens=512)
print(res["text"])
```

### Cross-Frame `GRAIL-SC` (Apple Silicon MLX)

For models that support role-free document continuation (such as `Qwen3.6` or `Qwen3`), contrasting document continuation against the model's own chat template (`log P_doc - alpha * log P_chat`) runs in a single batched `B=2` pass at `~35 tok/s`:

```python
import mlx.core as mx
from mlx_lm import load
from grail_sampler import (
    GrailSCConfig,
    GrailSCSampler,
    build_cross_frame_prompts,
    dequant_lm_head_norm,
    make_batched_sc_stepper,
)

model, tok = load("mlx-community/Qwen3.6-35B-A3B-4bit")
lm = model.language_model if hasattr(model, "language_model") else model
lm_norm = dequant_lm_head_norm(lm.lm_head, dtype=mx.float16, proj_dim=128)

user_q = "Explain how wild yeast, hydration, and acid balance shape sourdough crumb and flavor."
_, pos_ids, neg_chat_ids = build_cross_frame_prompts(tok, user_q, title_hint="Wild Yeast and Acid Balance in Hearth Bread")

zp0, zn0, step_both, snap_both, rb_both = make_batched_sc_stepper(lm, pos_ids, neg_chat_ids)
sampler = GrailSCSampler(tok, lm_norm)
res = sampler.generate(
    pos_ids, neg_chat_ids, user_q, None, None, snap_both, rb_both,
    cfg=GrailSCConfig.stock_technical(),
    max_new=512,
    step_both=step_both,
    prefilled=(zp0, zn0),
)
print(res["text"])
```

### Presets

| Preset | Use Case | Key Settings |
| :--- | :--- | :--- |
| `GrailConfig.goldilocks()` | Default single-stream (technical and literary) | `kl_budget=0.24`, `adaptive_cliff_xtc=True`, `flat_temp_boost=0.20`, `hot_temp_cool=0.12`, `anti_antithesis=1.0`, `anti_syntax_echo=0.6`, `tail_floor_nats=9.5`, `colon_semi_cooldown_steps=28` |
| `GrailConfig.minimal_goldilocks()` | Base or lightly aligned models | `kl_budget=0.16`, `use_cliff_xtc=False`, `flat_temp_boost=0.26`, `hot_temp_cool=0.12`, `tail_floor_nats=9.5` |
| `GrailConfig.stock_technical()` | Stock RLHF chat models on long technical prose | `kl_budget=0.28`, `flat_temp_boost=0.18`, `hot_temp_cool=0.12`, `anti_nominalization=0.50`, `anti_antithesis=1.0`, `anti_syntax_echo=0.6`, `anti_byline_opener=True`, `tail_floor_nats=9.5`, `colon_semi_cooldown_steps=28` |
| `GrailSCConfig.stock_technical()` | Dual-stream `GRAIL-SC` and Cross-Frame `GRAIL-SC` | `alpha=0.85`, `jsd_tau=0.05`, `boost_min_p=0.015`, `probe_temp=1.25`, `neg_refresh_window=96`, `min_tokens_before_eos=80`, `anti_byline_opener=True`, `tail_floor_nats=9.5`, `colon_semi_cooldown_steps=28`, `anti_nominalization=0.50`, `anti_antithesis=1.0`, `anti_syntax_echo=0.6` |

### Prompt Hygiene & Known Limits

1. **Skip negative "don't write X" rules:** Telling a model not to use `"is not X; it is Y"` puts that pattern into attention. Dropping that line reduced opening antithesis hits on `Qwen3.6-35B-A3B` from 3 to 0. Describe the desired style positively instead.
2. **Avoid binary `"X vs. Y"` titles for open exposition:** Adversarial titles push models into repetitive `"not because of X, but because of Y"` pivots.
3. **Document continuation vs. chat templates:** Strictly chat-turn models (`Gemma-4-12B-it`, `Meta-Llama-3.1-8B-Instruct`) perform best inside their native chat turn using `build_inturn_contrast_prompts` (`7W–1L` on `Gemma-4-12B-it`, `8W–4L` on `Llama-3.1-8B-Instruct` vs. `min_p`). For base-capable instruct models (`Qwen3.6`, `Qwen3`), Cross-Frame `GRAIL-SC` (`build_cross_frame_prompts`) and Tiny-Draft Sparse Contrast (`make_draft_sc_stepper`) remove chat-mode tail collapse in logit space at up to `42.5 tok/s`.

---

## Inference Engine Integrations

All adapters are verified in [`tests/test_examples.py`](tests/test_examples.py) (see [`examples/README.md`](examples/README.md)):

- **HuggingFace Transformers:** [`examples/huggingface_grail.py`](examples/huggingface_grail.py)
- **Apple Silicon MLX (`mlx-lm`):** [`examples/mlx_grail_demo.py`](examples/mlx_grail_demo.py)
- **oMLX:** [`examples/omlx_integration.py`](examples/omlx_integration.py)
- **vLLM (V0 & V1):** [`examples/vllm_integration.py`](examples/vllm_integration.py)
- **llama.cpp:** [`examples/llamacpp_integration.py`](examples/llamacpp_integration.py) (Python adapter + C++ `llama_sampler_i` skeleton)
- **SGLang:** [`examples/sglang_integration.py`](examples/sglang_integration.py)

---

## Benchmarks

### 1. Multi-Domain Generalization (12 Prompts: Technical, Science, Literary, Essay)

Evaluated on stock `Qwen3.6-35B-A3B` across 12 diverse prompts (3 systems engineering, 3 physical science, 3 literary observation, 3 essays; 380 tokens each). Blind 1–10 ratings and position-balanced A/B pairwise wins vs. `min_p` come from `Gemma-4-12B-it`:

| Sampler (`Qwen3.6-35B-A3B`) | Speed | Mesmer P(Human) Mean / Median (`>=50%`, Peak) | Desklib AI% (`<=20%`) | TMR AI% | ModernBERT AI% | Stem Echo | Antithesis (12) | Judge Acc / Coh / Nat | Blind A/B vs. `min_p` |
| :--- | ---: | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `min_p` (`T=0.8, min_p=0.05`) | 48.2 tok/s | 0.0% / 0.0% (0/12, 0.0%) | 100.0% (0/12) | 97.7% | 86.7% | 0.325 | 5 | 7.6 / 8.9 / 5.5 | baseline |
| **`Fast-SMC`** (`B=4 -> B=1` at 100 tok) | **36.3 tok/s** | 0.6% / 0.2% (0/12, 2.1%) | 52.8% (5/12) | 71.0% | 49.0% | 0.192 | 2 | **8.1 / 8.4 / 5.8** | 7W – 5L |
| **`Fast-SC-SMC`** (`B=6 -> B=2` at 100 tok) | **28.9 tok/s** | 29.3% / 5.6% (3/12, **99.6%**) | **44.9% (6/12)** | 64.5% | **21.8%** | **0.177** | 2 | 7.6 / 7.2 / 6.5 | 7W – 5L |
| **`Cross-Frame GRAIL-SC`** (`B=2`, no fork) | **35.2 tok/s** | **47.0% / 35.6% (6/12, 99.4%)** | 53.9% (4/12) | **59.0%** | 32.7% | 0.197 | **0** | 7.1 / 7.2 / 6.3 | **8W – 3L – 1T** |
| **`Cross-Frame GRAIL-SC + Fork`** (`B=2 + B=8`) | 29.1 tok/s | 33.0% / 0.2% (4/12, 96.0%) | 61.5% (3/12) | 66.8% | 30.7% | 0.185 | **0** | 8.4 / 8.2 / 7.2 | 8W – 4L |
| **`Dual-Failure + Surge + Fork`** (`chat_textbook`, `B=2 + B=8`) | 31.0 tok/s | 35.7% / 2.6% (4/12, **99.9%**) | 42.5% (5/12) | 59.5% | 29.4% | 0.212 | 1 | **8.6 / 8.3 / 8.2** | **9W – 3L** |
| **`Dual-Failure + S1-Only Fork`** (`s1_tokens=40, max_p_forks=0`) | 28.1 tok/s | 33.1% / 0.3% (4/12, **99.9%**) | **40.0% (6/12)** | 60.7% | **13.8%** | 0.226 | 2 | 8.5 / 8.0 / 7.8 | **9W – 3L** |
| **`Tiny-Draft Sparse Contrast`** (`Qwen3.6-35B` vs. `Qwen3-0.6B-4bit`, `n=12`) | 42.5 tok/s | 45.6% / 33.6% (**6/12**, 99.1%) | 46.2% (4/12) | 59.5% | 33.9% | 0.223 | 2 | 8.1 / 7.2 / 7.1 | 7W – 4L – 1T |
| **`Tiny-Draft + Plausibility`** (3-seed mean `n=36`, `boost_min_p=0.015`) | **51.6 ± 1.0 tok/s** | 45.0 ± 2.9% (17/36, **99.9%**) | 55.0 ± 9.8% | **49.2 ± 6.0%** | 33.4 ± 3.6% | 0.232 | **0** *(1/36)* | 7.3 / 7.1 / 7.2 | 7W – 5L |
| **`Tiny-Draft + Plausibility + S1 Fork`** (`3×28`, `max_p_forks=0`) | **39.2 tok/s** | 28.7% / 1.5% (3/12, **99.7%**) | **39.2% (5/12)** | 58.3% | 39.4% | **0.185** | **0** | **9.2 / 9.2 / 7.1** | **10W – 2L** |
| **`Sparse Draft-Contrast`** (`Qwen3.6-35B` vs. `Qwen3-4B`, `n=12`) | 23.7 tok/s | 45.7% / **40.6% (6/12**, 98.3%) | 47.3% (**6/12**) | 54.5% | **20.2%** | 0.193 | **0** | 6.9 / 6.9 / 6.6 | 6W – 5L – 1T |

- **Tiny-Draft + Plausibility + Fast S1 Fork (`39.2 tok/s`, `3×28`, `max_p_forks=0`)** sets the Pareto frontier on `Qwen3.6-35B`: **`10W–2L` (`83.3%`)** blind cross-family A/B wins over `min_p`, **`9.2 / 9.2 / 7.1`** blind judge scores (beating `min_p`'s `7.6 / 8.9 / 5.5` on Accuracy, Coherence, and Naturalness simultaneously), lowest 12-prompt `Desklib` (`39.2%`), **`0.185` stem echo**, and **`0/12` antithesis**.
- **3-Seed Confidence Intervals (`Tiny-Draft + Plausibility`, `n=36` essays across 3 seeds):** **`51.6 ± 1.0 tok/s`**, **`45.0 ± 2.9%` `Mesmer-9B` P(Human)** (`17/36 >= 50%`, `99.9%` peak), **`49.2 ± 6.0%` `TMR`**, **`33.4 ± 3.6%` `ModernBERT`**, **`0.232 ± 0.017` stem echo**, `1` antithesis across 36 essays, and zero short/byline runs (`min 137–229w` across all 3 seeds).
- **Zero-Regression Factuality & Reasoning Check (80 Verifiable Questions across `Qwen3.6-35B` and `Llama-3.1-8B`):** Comparing `min_p` vs. default `GRAIL` (`GrailConfig.goldilocks()`) across 40 math/reasoning + 40 factual QA items gives **exact `63/80` (`78.8%`) vs. `63/80` (`78.8%`)** overall and **`38/40` (`95.0%`) vs. `38/40` (`95.0%`)** on factual QA (`Qwen3.6`: `30/40` GRAIL vs. `29/40` `min_p`; `Llama-3.1-8B`: `33/40` GRAIL vs. `34/40` `min_p`).

- **Cross-Family In-Turn Contrast on `Gemma-4-12B-it` (8 Balanced Prompts, Blind `Qwen3.6` Judge) and `Meta-Llama-3.1-8B-Instruct` (12 Prompts, Blind `Gemma-4` Judge):**

| Model & Sampler (Native Chat Turn) | Speed | Avg Words | Desklib AI% | TMR AI% | ModernBERT AI% | Stem Echo | Antithesis | Judge Acc / Coh / Nat | Blind A/B vs. `min_p` |
| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `Gemma-4-12B-it` (`min_p`, `n=8`) | 44.0 tok/s | 264 | 99.8% | 96.5% | 96.4% | 0.250 | 2 | 8.6 / 8.6 / 8.0 | baseline |
| `Gemma-4-12B-it` (**`In-Turn GRAIL-SC`**, `B=2`) | **35.0 tok/s** | 308 | **60.9%** | **49.7%** | 37.1% | **0.144** | 3 | 8.8 / 8.2 / **9.0** | **7W – 1L** |
| `Gemma-4-12B-it` (**`In-Turn GRAIL-SC + Fork`**) | 29.4 tok/s | 308 | 68.1% | 53.8% | **33.7%** | 0.167 | 4 | **8.9 / 9.0 / 8.9** | **7W – 1L** |
| `Llama-3.1-8B-Instruct` (`min_p`, `n=12`) | 78.0 tok/s | 298 | 100.0% | 96.1% | 98.7% | 0.296 | 0 | 9.2 / 9.2 / 7.4 | baseline |
| `Llama-3.1-8B-Instruct` (**`In-Turn GRAIL-SC`**, `B=2`) | **53.5 tok/s** | 303 | **60.5%** | **57.4%** | **22.5%** | **0.133** | **0** | 7.7 / 6.6 / 6.5 | **8W – 4L** |

### 2. Throughput & Memory (Apple Silicon MLX & PyTorch MPS)

`GRAIL` runs its token updates on GPU with a single Metal sync per token, a compiled finalizer, on-demand batched opening forks (`make_batched_grail_stepper`), and a 128-dim FP16 semantic table (`63.6 MB` for a 248k vocabulary, 32x smaller than FP32). On PyTorch MPS (`151,936` vocab, `proj_dim=128` FP16), Top-K-First dynamic masking + zero-alloc `(z, lse)` caching + Gram-matrix Fisher-Rao brings `GrailLogitsProcessor` to **`3.19 ms/tok`** (`-38.1%` vs. `5.15 ms/tok`) and `GrailSCLogitsProcessor` to **`3.70 ms/tok`** (`-36.6%` vs. `5.84 ms/tok`).

![GRAIL Throughput and Memory](assets/v07_speed_and_memory.svg)

| Mode (Apple Silicon MLX, JL-128 `63.6–67.1 MB`) | `Qwen3.6-35B-A3B` (MoE) | `Gemma-4-12B-it` (Dense) | Notes |
| :--- | ---: | ---: | :--- |
| `min_p` (`T=0.8, min_p=0.05`) | 40.5 tok/s (100%) | 42.4 tok/s (100%) | Bare `mlx-lm` baseline |
| **`GRAIL`** (single-stream) | **40.2 tok/s (99.3%)** | **36.0 tok/s (84.9%)** | `0.18 ms/tok` overhead on `Qwen3.6` |
| **`GRAIL`** (+ batched `B=4` opening fork) | **33.5 tok/s (82.7%)** | **31.8 tok/s (75.0%)** | Native `B=1` KV cache; merges only at forks |
| **`GRAIL-SC`** (batched `B=2`) | **33.9 tok/s (83.7%)** | **32.0 tok/s (75.5%)** | Positive + contrastive stream in one pass |
| **`GRAIL-SC`** (`B=2` + batched `B=8` fork) | **27.1 tok/s (66.9%)** | **25.5 tok/s (60.1%)** | Anchor-refreshed dual stream + opening fork |
| **`Fast-SMC`** (`B=4 -> B=1` at 100 tok) | **36.3 tok/s** *(380t)* | — | `+77%` faster than full-length `B=4` SMC |
| **`Fast-SC-SMC`** (`B=6 -> B=2` at 100 tok) | **28.9 tok/s** *(380t)* | — | `+55%` faster than full-length `B=6` SC-SMC |
| **`GRAIL-SMC`** (full-length `B=4`) | 20.5 tok/s (50.6%) | **24.1 tok/s (56.8%)** | 4 parallel trajectories |
| **`GRAIL-SC-SMC`** (full-length `K=3, B=6`) | 18.6 tok/s (45.9%) | 17.1 tok/s (40.3%) | 3 dual-contrastive trajectories (6 streams) |

### 3. Head-to-Head vs. Published Samplers (Stock `Qwen3.6-35B-A3B`)

Mean across 4 document-continuation prompts (2 technical, 2 literary), judged blindly by `Gemma-4-12B-it`:

![9-Sampler Head-to-Head](assets/baseline_head_to_head.svg)

| Sampler (Identical Stock Weights) | Mesmer P(Human) Mean (Peak) | Desklib AI% | TMR AI% | ModernBERT AI% | Tail >5 nats | Stem Echo | Antithesis (4) | Judge Acc / Coh / Nat |
| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `min_p` (Nguyen et al. 2024) | 0.0% (0.0%) | 99.5% | 71.3% | 74.7% | 0.0% | 0.284 | 3 | 9.0 / 10.0 / 8.5 |
| `top_p` (Holtzman et al. 2020) | 0.0% (0.0%) | 99.7% | 95.2% | 75.2% | 1.2% | 0.348 | 2 | 9.5 / 9.5 / 9.2 |
| `DRY` (Repetition Penalty) | 0.0% (0.0%) | 94.3% | 71.6% | 50.4% | 0.0% | 0.309 | 3 | 7.5 / 9.2 / 7.8 |
| `Typical` (Meister et al. 2023) | 3.5% (14.0%) | 62.8% | 58.6% | 74.7% | 4.1% | 0.283 | 0 | 9.0 / 9.8 / 8.5 |
| `XTC` (Standalone) | 17.0% (67.9%) | 80.8% | 74.7% | 74.3% | 6.7% | 0.239 | 0 | 7.8 / 8.8 / 7.8 |
| `Eta` (Hewitt et al. 2022) | 18.9% (70.8%) | 73.6% | 65.5% | 3.3% | 12.7% | 0.242 | 0 | 8.0 / 9.0 / 8.8 |
| **`GRAIL-SC`** (Batched `B=2`, Anchor) | 14.9% (55.1%) | **17.6%** | **28.0%** | **1.8%** | 15.2% | 0.288 | **0** | 7.5 / 8.5 / 7.8 |
| **`GRAIL-SMC`** (Sentence-Aligned `B=4`) | **29.3% (89.6%)** | 62.4% | 76.4% | 74.1% | 14.6% | 0.238 | **0** | **8.0 / 8.0 / 7.8** |
| **`GRAIL-SC-SMC`** (Sentence-Aligned `K=3, B=6`) | **24.8% (98.8%)** | **25.7%** | 41.5% | **2.7%** | 11.8% | **0.201** | **0** | **8.0 / 8.5 / 8.0** |

### 4. Final-Layer Chat Tail Collapse & Clause-Start Surprisal Wave

![Final-Layer Chat Tail Collapse and Clause-Start Surprisal Wave](assets/layer_collapse_and_surprisal_wave.svg)

- **Chat templates crush the rare-word tail in the final layers:** Logit-lens probes on `Qwen3-4B-Instruct` (36 layers) show chat mode carrying `13.9%` tail mass (`>5` nats) through layer 32, then dropping **50x** to `0.28%` across layers 32–35 (vs. `16.3%` in document mode). On `Gemma-4-12B-it` (48 layers), chat mode holds `18.2%` tail mass through layer 46, then drops **107x** to `0.17%` in layer 47 alone (vs. `10.7%` in document mode).
- **Why logit-space subtraction works where KV masking fails:** Zeroing the `<|im_start|>assistant` / `<|turn>model` KV entries after prefill still left chat `Mesmer` at `0.0%` on both `Qwen3.6` (DeltaNet + attention) and `Gemma-4` (pure attention), and naive final-layer residual damping broke language alignment. Subtracting `P_chat` in logit space removes the chat prior without corrupting syntax or spelling.
- **Clause-start surprisal wave:** Pre-2020 human prose averages `+0.97` nats higher surprisal at clause starts (`3.69`) than mid-clause (`2.72`). `GRAIL-SC` matches human mean surprisal (`2.92` vs. `2.88`), std (`3.16` vs. `3.10`), and `>5`-nat share (`22.6%` vs. `22.2%`) within `1.1%`.

### 5. Standard Chat-Mode & Cross-Architecture Validation

![Standard Chat-Mode 3-Encoder Validation](assets/step89_stock_3encoder_sweep.svg)

| Stock Model (Chat Mode) | Sampler | Desklib AI% | TMR AI% | ModernBERT AI% | Tail >5 nats | Nominalizations | Avg Word Len | Stem Echo |
| :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `Gemma-4-12B-it` | `min_p` (`T=0.8, min_p=0.05`) | 97.2% | 65.6% | 98.7% | 0.0% | 5.1% | 5.08 | 0.250 |
| `Gemma-4-12B-it` | **`GRAIL`** (single-stream) | **57.3%** | **32.7%** | **37.3%** | 6.7% | **3.0%** | 4.81 | **0.139** |
| `Gemma-4-12B-it` | **`GRAIL-SC`** (dual-stream) | 64.0% | 33.7% | 38.0% | 6.0% | **2.5%** | 4.82 | 0.151 |
| `Qwen3.6-35B-A3B` | `min_p` (`T=0.8, min_p=0.05`) | 95.2% | 35.7% | 98.8% | 0.0% | 5.5% | 5.30 | 0.178 |
| `Qwen3.6-35B-A3B` | **`GRAIL`** (single-stream) | **45.1%** | **3.4%** | **3.8%** | 9.7% | 3.4% | 5.09 | **0.115** |
| `Qwen3.6-35B-A3B` | **`GRAIL-SC`** (dual-stream) | **24.3%** | **2.9%** | **3.9%** | 6.0% | **2.8%** | **4.85** | 0.128 |

![Cross-Architecture Stock Model Benchmark](assets/cross_arch_benchmark.svg)

| Stock Model (Document Framing) | Sampler | Essays | Mesmer P(Human) | Desklib AI% | TMR AI% | ModernBERT AI% | Tail >5 nats | Stem Echo |
| :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `Qwen3-4B-Instruct` (Dense) | `min_p` | 12 | 0.0% | 99.8% | 98.6% | 98.6% | 0.2% | 0.358 |
| `Qwen3-4B-Instruct` (Dense) | **`GRAIL`** | 12 | 0.0% | **54.1%** | 98.4% | 98.7% | 11.8% | **0.183** |
| `Qwen3-4B-Instruct` (Dense) | **`GRAIL-SC`** | 6 | **0.5%** | **35.9%** | 98.4% | 98.7% | 12.9% | 0.218 |
| `SmolLM2-1.7B` (Llama) | `min_p` | 12 | 0.0% | 99.9% | 98.5% | 98.9% | 0.5% | 0.497 |
| `SmolLM2-1.7B` (Llama) | **`GRAIL`** | 12 | 3.2% | **23.2%** | **89.5%** | **83.6%** | 24.8% | **0.156** |
| `Inkling-2-Mini` (Sparse MoE) | `min_p` | 12 | 0.0% | 73.0% | 98.4% | 98.8% | 0.1% | 0.344 |
| `Inkling-2-Mini` (Sparse MoE) | **`GRAIL`** | 12 | 0.1% | **22.4%** | 98.0% | 96.8% | 13.1% | **0.150** |
| `Qwen3.6-35B-A3B` (Hybrid MoE) | `min_p` | 6 | 0.0% | 99.5% | 98.6% | 98.8% | 0.0% | 0.303 |
| `Qwen3.6-35B-A3B` (Hybrid MoE) | **`GRAIL`** | 6 | 0.2% | **20.5%** | **97.9%** | 99.1% | 16.2% | **0.160** |
| `Qwen3.6-35B-A3B` (Hybrid MoE) | **`GRAIL-SC`** | 6 | **19.1%** | 20.8% | 98.0% | 99.0% | 18.2% | 0.186 |

### 6. Leave-One-Out Ablation

![Leave-One-Out Ablation](assets/leave_one_out_ablation.svg)

---

## Running Tests, Benchmarks & Charts

```bash
python -m unittest discover -s tests -v
python scripts/benchmark_throughput.py --backend torch --vocab 151936 --steps 120
python scripts/generate_charts.py
```

## License

MIT. See [LICENSE](LICENSE).
