Skip to main content

OptiSpec

Renewal-Reward Optimal Control for Grammar-Coupled Self-Speculative Decoding

OptiSpec accelerates open-source Hugging Face causal language models with zero auxiliary draft-model VRAM overhead, combining grammar-forced span jumping, closed-form Ridge early-exit adapters, Dinkelbach optimal depth/stopping control, and provably lossless verification ($\epsilon = 0 \implies \text{TV} = 0$).


Key Features

  • Zero Draft-Model VRAM: Reuses hidden states $h^{(k)}$ from intermediate transformer layers $1..k$ directly into verification layers $k+1..N$.
  • Works on Any Hugging Face CausalLM:
    • Curated Sub-4B Presets: Qwen/Qwen3-4B, Qwen/Qwen3-1.7B, Qwen/Qwen2.5-3B-Instruct, NousResearch/Hermes-3-Llama-3.2-3B, meta-llama/Llama-3.2-3B-Instruct, google/gemma-2-2b-it, google/gemma-3-1b-it, google/gemma-3-4b-it, LGAI-EXAONE/EXAONE-3.5-2.4B-Instruct, LGAI-EXAONE/EXAONE-4.0-1.2B, microsoft/Phi-3.5-mini-instruct, HuggingFaceTB/SmolLM2-1.7B-Instruct.
    • 1-Command Auto-Onboarding (optispec fit): Profile GPU latency (~30s) + fit closed-form Ridge adapters + Theorem 2 optimal exits $K^*$ in ~1–2 minutes for any unseen HF model.
  • Interactive Gradio Comparison Demo (optispec demo): Live side-by-side streaming comparing Standard AR vs OptiSpec with token-level color provenance (Grammar Forced, Early-Exit Draft, Target Bonus), throughput speedup, layer savings, and TV bound.
  • OpenAI-Compatible HTTP Server (optispec serve): Drop-in /v1/chat/completions endpoint supporting tools, response_format JSON Schema (xgrammar), and stream=True.

Installation

Note: The PyPI distribution name is optimalspec, while the Python import module (import optispec) and CLI command (optispec) remain optispec.

# Core runtime
pip install optimalspec

# With Gradio live comparison demo UI
pip install "optimalspec[demo]"

# Everything (Demo UI + OpenAI Server + Training/Distillation + XGrammar + 4-bit)
pip install "optimalspec[all]"

For local development with uv:

uv sync --all-extras --extra dev
uv run pytest -v

Quickstart

1. Launch the Gradio Live Comparison Demo

optispec demo --model Qwen/Qwen3-4B

Select any curated preset or enter any Hugging Face model ID, click Load / Auto-Fit Model, and compare Standard AR vs OptiSpec side-by-side.

2. Python SDK

from optispec import GenerateConfig, OptiSpecEngine

engine = OptiSpecEngine.from_pretrained("Qwen/Qwen3-4B", adapter="auto", epsilon=0.0)
result = engine.chat(
    [{"role": "user", "content": "Check the weather in Seoul in celsius."}],
    tools=[...],
    config=GenerateConfig(max_new_tokens=192, temperature=0.0),
)
print(f"{result.tokens_per_sec:.1f} tok/s | TV={result.tv_bound_total:.4f}")
print(result.generated_text)

3. Onboard Any New Hugging Face Model (and Push to Hub)

# Fast 1-2 minute closed-form Ridge calibration (zero gradient training)
optispec fit --model google/gemma-3-1b-it --mode ridge-fast

# Optional: full low-rank KL self-distillation & share adapter bundle on HF Hub
optispec fit --model LGAI-EXAONE/EXAONE-3.5-2.4B-Instruct --mode distill --push-to-hub username/exaone-3.5-2.4b-optispec

4. OpenAI-Compatible Server

optispec serve --model Qwen/Qwen3-4B --port 8000

See examples/03_openai_client.py for calling it with the standard openai Python SDK.


Architecture

  • Layer 0 (optispec.core): Pure mathematical solvers — Dinkelbach fractional programming (renewal.py), Exact/Submodular exit selection (layer_selection.py), Theorem 3 lossless/$\epsilon$-bounded verifier (verifier.py).
  • Layer 1 (optispec.grammar): Uniform GrammarConstraint protocol, multi-format ToolCallSchemaFSM with schema-mask precompilation, and optional XGrammarConstraint.
  • Layer 2 (optispec.engine): Universal BackboneAdapter (Llama/Qwen/Gemma2/Gemma3/EXAONE/GPT-NeoX), PartialLayerRunner with exact KV rollback, and unified streaming decoders.
  • Layer 3 (optispec.adapters): LowRankExitAdapter, dependency-free ConfidenceCalibrator, safetensors+JSON bundle serialization, hardware profiler cache, and auto_fit.
  • Layer 4 (optispec.api, cli, demo, server): Public SDK, Typer CLI, Gradio comparison UI, and FastAPI OpenAI server.

See docs/architecture.md and docs/supported_models.md for details.

Metadata

Release files for optimalspec 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for optimalspec 0.2.1
File Size Uploaded Provenance Actions
optimalspec-0.2.1.tar.gz 369.0 kB With provenance Details for optimalspec-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for optimalspec 0.2.1
File Interpreter ABI Platform Actions
optimalspec-0.2.1-py3-none-any.whl Python 3 none any Details for optimalspec-0.2.1-py3-none-any.whl

Total release size: 448.3 kB

Release files / optimalspec-0.2.1.tar.gz

Download URL optimalspec-0.2.1.tar.gz
Size 369.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e28af2183e95e301247e3d6bad19cc49df4c4961f737662ee12e28e4209a204f
BLAKE2b-256 checksum
How to use checksums
bb786c69615ff6fbf185df9c843cb12adfaa66dbb86930df67bad6806a410e97
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / optimalspec-0.2.1-py3-none-any.whl

Download URL optimalspec-0.2.1-py3-none-any.whl
Size 79.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c132c4570278ac383d555dd0c6421d034db5b47ce23a8f424023ab691c56b45a
BLAKE2b-256 checksum
How to use checksums
c4354fd3957b52ba7c2ce6f24f73e782a4f161fed79e15de86693bc9f4f45f41
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for optimalspec 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for optimalspec-0.2.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page