Metadata-Version: 2.5
Name: optimalspec
Version: 0.2.1
Summary: Renewal-Reward Optimal Control for Grammar-Coupled Self-Speculative Decoding on Hugging Face Models
Author: SuHyun Bae
License: MIT License
        
        Copyright (c) 2026 SuHyun Bae
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: early-exit,llm,speculative-decoding,structured-generation,tool-calling,transformers
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: accelerate>=1.0.0
Requires-Dist: huggingface-hub>=0.26.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: rich>=13.0.0
Requires-Dist: safetensors>=0.4.5
Requires-Dist: torch>=2.4.0
Requires-Dist: tqdm>=4.66.0
Requires-Dist: transformers>=4.51.0
Requires-Dist: typer>=0.12.0
Provides-Extra: all
Requires-Dist: bitsandbytes>=0.45.0; extra == 'all'
Requires-Dist: datasets>=3.0.0; extra == 'all'
Requires-Dist: fastapi>=0.115.0; extra == 'all'
Requires-Dist: gradio>=5.0.0; extra == 'all'
Requires-Dist: pydantic>=2.9.0; extra == 'all'
Requires-Dist: scikit-learn>=1.5.0; extra == 'all'
Requires-Dist: uvicorn>=0.32.0; extra == 'all'
Requires-Dist: xgrammar>=0.1.18; extra == 'all'
Provides-Extra: demo
Requires-Dist: gradio>=5.0.0; extra == 'demo'
Provides-Extra: dev
Requires-Dist: httpx>=0.27.0; extra == 'dev'
Requires-Dist: mypy>=1.13.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0.12; extra == 'dev'
Provides-Extra: grammar
Requires-Dist: xgrammar>=0.1.18; extra == 'grammar'
Provides-Extra: quant
Requires-Dist: bitsandbytes>=0.45.0; extra == 'quant'
Provides-Extra: serve
Requires-Dist: fastapi>=0.115.0; extra == 'serve'
Requires-Dist: pydantic>=2.9.0; extra == 'serve'
Requires-Dist: uvicorn>=0.32.0; extra == 'serve'
Provides-Extra: train
Requires-Dist: datasets>=3.0.0; extra == 'train'
Requires-Dist: scikit-learn>=1.5.0; extra == 'train'
Description-Content-Type: text/markdown

# 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`.

```bash
# 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`:

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

---

## Quickstart

### 1. Launch the Gradio Live Comparison Demo

```bash
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

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

```bash
# 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

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

See [examples/03_openai_client.py](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](docs/architecture.md) and [docs/supported_models.md](docs/supported_models.md) for details.
