GRAIL v0.14.0

Documentation & API Reference

It depends only on numpy. PyTorch or MLX are lazy-loaded inside the sampler and remain unimported unless actually used. grail-sampler drops into HuggingFace Transformers, MLX, vLLM, llama.cpp (native C++17), oMLX, and SGLang without truncation at the downstream boundary (temperature=1.0, top_p=1.0, top_k=0, min_p=0.0, repeat_penalty=1.0).

# PyTorch / HuggingFace / vLLM / llama-cpp-python / SGLang
pip install "grail-sampler[torch]"

# Apple Silicon MLX / oMLX
pip install "grail-sampler[mlx]"

# Both backends
pip install "grail-sampler[all]"

Zero-Friction CLI (grail-demo)

Installing grail-sampler registers grail-demo for side-by-side min_p vs. GRAIL runs on any local or HuggingFace checkpoint across MLX and PyTorch.

# Cross-Frame GRAIL-SC vs. min_p on Apple Silicon MLX
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

# Tiny-Draft Sparse Contrast (39-52 tok/s on MLX; also works on PyTorch with --backend torch)
grail-demo \
  --model mlx-community/Qwen3.6-35B-A3B-4bit \
  --draft-model mlx-community/Qwen3-0.6B-4bit \
  --prompt "Write a literary essay on the uses of boredom in everyday life." \
  --mode cross-frame \
  --no-fork \
  --compare-minp

# Strictly chat-turn checkpoints (Gemma-4-12B-it, Meta-Llama-3.1-8B-Instruct)
grail-demo \
  --model mlx-community/gemma-4-12B-it-4bit \
  --prompt "Describe the acoustics of an empty concrete parking garage at night." \
  --mode in-turn \
  --compare-minp

PyTorch & HuggingFace

Attach GrailLogitsProcessor directly inside model.generate(), or call generate_sc() / generate_draft_sc() for one-line contrastive decoding on CPU, CUDA, or Apple MPS (no accelerate required).

Single-Stream Processor

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from grail_sampler import GrailConfig, GrailLogitsProcessor

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)

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 table (3.19 ms/tok on Apple MPS)
)

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))

Batched B=2 Contrastive generate_sc()

from grail_sampler import GrailSCConfig, build_cross_frame_prompts, generate_sc

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-Size / Cross-Tokenizer generate_draft_sc()

from grail_sampler import GrailSCConfig, build_cross_frame_prompts, generate_draft_sc

_, pos_ids, _ = build_cross_frame_prompts(tok_large, user_q, neg_style="chat_textbook")
_, _, neg_ids = build_cross_frame_prompts(tok_small, user_q, neg_style="chat_textbook")

res = generate_draft_sc(
    model_large, tok_large, pos_ids,
    model_small, tok_small, neg_ids,
    prompt_text=user_q,
    cfg=GrailSCConfig.stock_technical(),
    sparse_draft=True,   # Zero-sync syntax-gated skipping (~35% fewer draft passes)
    max_skip_chunk=2,
    max_new_tokens=512,
)
print(res["tok_s"], res["draft_skip_pct"], res["text"])

Apple Silicon MLX

GrailSampler and GrailSCSampler run inside a single Metal synchronization per token with compiled prestep/finalizer kernels and native KV/DeltaNet fork rewind.

import dataclasses
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_draft_sc_stepper,
)

m_pos, tok_pos = load("mlx-community/Qwen3.6-35B-A3B-4bit")
m_neg, tok_neg = load("mlx-community/Qwen3-0.6B-4bit")
lm_pos = m_pos.language_model if hasattr(m_pos, "language_model") else m_pos
lm_neg = m_neg.language_model if hasattr(m_neg, "language_model") else m_neg
lm_norm = dequant_lm_head_norm(lm_pos.lm_head, dtype=mx.float16, proj_dim=128)

user_q = "Explain how synaptic downscaling during slow-wave sleep restores cortical signal-to-noise."
title = "Synaptic Downscaling During Slow-Wave Sleep"
_, pos_ids, _ = build_cross_frame_prompts(tok_pos, user_q, title_hint=title, neg_style="chat_textbook")
_, _, neg_ids = build_cross_frame_prompts(tok_neg, user_q, title_hint=title, neg_style="chat_textbook")

zp0, zn0, step_both, snap, rollback = make_draft_sc_stepper(
    lm_pos, tok_pos, pos_ids, lm_neg, tok_neg, neg_ids,
    sparse_draft=True, max_skip_chunk=2,
)
cfg = dataclasses.replace(
    GrailSCConfig.stock_technical(),
    opening_alpha_boost=0.45,
    s1_branches=3, s1_tokens=28, max_p_forks=0,  # 39.2 tok/s Pareto S1 fork (10W-2L A/B)
)
res = GrailSCSampler(tok_pos, lm_norm).generate(
    pos_ids, neg_ids, user_q, None, None, snap, rollback,
    cfg=cfg, max_new=512, title_hint=title, step_both=step_both, prefilled=(zp0, zn0),
)
print(res["tok_s"], res["text"])

Multi-Turn Chat & Speculative / MTP Verification

Multi-Turn Chat (reset_turn() / reset_turn_state())

Between assistant turns in a multi-turn session, call proc.reset_turn(new_prompt_text=...) (PyTorch) or sampler.reset_turn_state(state) (MLX). Sentence length, quote parity, and antithesis state reset cleanly while long-horizon stem and embedding anti-echo memory persists across turns.

Speculative & Multi-Token Prediction (verify_draft_batch())

Given target_logits_seq of shape [K + 1, V] from one parallel target forward pass and K draft tokens (plus optional draft_probs_seq [K, V]), verify_draft_batch() runs exact Leviathan-et-al. rejection sampling sequentially through GRAIL's stateful logit transform, advancing internal state only for accepted tokens and sampling the exact residual bonus token on rejection:

# PyTorch GrailLogitsProcessor (stateful)
accepted_ids, bonus_token, n_accepted = proc.verify_draft_batch(
    target_logits_seq,      # [K + 1, V]
    draft_ids,              # list[int] of length K
    draft_probs_seq=q_seq,  # optional [K, V]; omit for deterministic greedy/MTP drafts
)

# MLX GrailSampler (stateless: pass explicit state, q_basis, cfg, rng)
accepted_ids, bonus_token, n_accepted = sampler.verify_draft_batch(
    target_logits_seq, draft_ids, state, q_basis, cfg, rng, draft_probs_seq=q_seq,
)

Presets & Key Parameters

Preset Use Case Key Parameters
GrailConfig.goldilocks() Default single-stream (technical & literary) kl_budget=0.24, adaptive_cliff_xtc=True, flat_temp_boost=0.20, hot_temp_cool=0.12, anti_antithesis=1.0, 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() Single-stream stock RLHF technical prose kl_budget=0.28, anti_nominalization=0.50, anti_byline_opener=True, min_para_words=40, colon_semi_cooldown_steps=28
GrailSCConfig.stock_technical() Cross-Frame, In-Turn & Sparse Draft-Contrast 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

Inference Engine Adapters

All engine adapters are tested in tests/test_examples.py.


Model-Family Guide & Known Limits

  1. Match contrastive framing to checkpoint family: Base-capable instruct checkpoints (Qwen3.6, Qwen3) work best with build_cross_frame_prompts(..., neg_style="chat_textbook") and Tiny-Draft Sparse Contrast. Strictly chat-turn checkpoints (Gemma-4-12B-it, Meta-Llama-3.1-8B-Instruct) perform best inside their native chat turn via build_inturn_contrast_prompts().
  2. Skip negative "don't write X" prompt rules: Instructing a model not to write "is not X; it is Y" puts that pattern directly into attention. Describe the desired register positively instead.
  3. Avoid binary "X vs. Y" titles for open exposition: Adversarial titles push models into repetitive contrastive pivots.
  4. Support-collapse boundary: Sampling in logit space lets you reweight probability mass that already exists within the model's output distribution, but it cannot create probability mass where the training process drove it to zero. A paraphrase is always a point within the support of the model's distribution; when the model has effectively assigned zero probability to that region of text space, no amount of reweighting will bring it back. On chat-turn checkpoints GRAIL improves readability, reduces repetition, and wins blind preference tests, while leaving weight-level behavior bounded by what the base model learned.