Gearbx

Documentation

Gearbx reads the model's output entropy at every generation step and routes the next forward pass through 4-bit, 8-bit or fp16 weights. No retraining, no fine-tuning.

Installation

Pick the extras that match your hardware. The base install runs on CPU and Apple Silicon (MPS).

# CPU and Apple Silicon (MPS)
pip install gearbx

# Apple Silicon, native MLX quantization
pip install "gearbx[mlx]"

# NVIDIA: bitsandbytes base + fused Triton kernels
pip install "gearbx[cuda]"

The terminal app (chat UI, model manager, gearbx claude) installs separately:

npm install -g gearbx
# or
curl -fsSL gearbx.jpdz.app/install | sh

Quickstart

Load a model, generate, look at how the tokens were spread across gears.

from gearbx import GearbxModel

gbm = GearbxModel("Qwen/Qwen2-0.5B-Instruct")
result = gbm.generate("Prove that sqrt(2) is irrational.")

print(result.text)
print(result.gear_stats)       # {'low': 0.17, 'mid': 0.36, 'high': 0.47}
print(result.tokens_per_sec)
Thresholds calibrate from the first prompt's prefill pass and carry across later prompts. You don't need to tune anything to start.

Backends

BackendBase weightsQuantized path
CUDANF4 (bitsandbytes)Fused Triton kernels on packed int4/int8, no dequantization
MPSfp16Native Metal kernels for single-token decode; dequant cache otherwise
MLXfp16mlx.nn.QuantizedLinear swaps
Ollamaserver-sideEntropy telemetry from top_logprobs; routing chooses which model serves
CPUfp32Packed int storage (testing)

GearbxModel

Full per-token gear shifting with real weight swaps inside a Hugging Face transformers model.

GearbxModel(
    model_name: str,
    num_attn_layers_to_manage: int = 16,
    monitor_window: int = 5,
    high_thresh: float = 3.5,
    low_thresh: float = 1.8,
    device: str = "auto",          # auto | mps | cuda | cpu
    prompt_classifier = None,
    manage: str = "attn",          # attn | attn+mlp | blocks | all-linear
    cuda_base: str = "nf4",
)
ParameterDefaultWhat it does
model_namerequiredAny Hugging Face causal LM id.
manage"attn"Which linears change precision. attn+mlp covers about 72% of a typical model's weights, attn about 9%.
monitor_window5Tokens averaged before routing.
low_thresh / high_thresh1.8 / 3.5Entropy bounds in bits, scaled by vocabulary size.
device"auto"Tries MPS, then CUDA, then CPU.

generate()

A manual autoregressive loop with KV caching. Each step: forward, read entropy, route, sample.

result = gbm.generate(
    prompt: str,
    max_new_tokens: int = 512,
    temperature: float = 1.0,
    top_p: float = 0.9,
    min_p: float = 0.0,            # > 0 skips the full-vocab sort
    do_sample: bool = True,
    use_cache: bool = True,
    min_gear_duration: int = 1,    # 4 to 8 reduces oscillation
    prefill_gear = None,           # e.g. "mid" for int8 prefill on CUDA
    entropy_stride: int = 1,       # skip checks deep inside a gear band
    speculative: bool = False,     # draft in low gear, verify in high
    draft_tokens: int = 6,
)

Calls on the same model are serialized: gear shifts rewrite shared modules, so two threads generating at once would corrupt each other.

GenerationResult

@dataclass
class GenerationResult:
    text: str
    gear_trace: list[str]          # gear per token
    entropy_trace: list[float]     # entropy in bits per token
    gear_stats: dict[str, float]   # share of tokens per gear
    total_tokens: int
    elapsed_sec: float
    tokens_per_sec: float
    entropy_measured: list[bool]   # False where a step skipped the check

With entropy_stride or min_gear_duration, some steps don't measure entropy; their entropy_trace entry repeats the last measured value and entropy_measured is False.

OllamaGearbx

Adapter for any OpenAI-compatible local server: Ollama, llama.cpp, vLLM, LM Studio. Entropy is reconstructed from top_logprobs. Routing picks which model serves the prompt.

from gearbx import OllamaGearbx

gbm = OllamaGearbx(
    gear_models={
        "low":  "llama3.2:1b-instruct-q4_K_M",
        "mid":  "llama3.2:1b-instruct-q8_0",
        "high": "llama3.2:1b-instruct-fp16",
    },
    low_thresh=0.4,                # top-k entropy has a narrower range
    high_thresh=1.2,
)

r = gbm.generate("Prove sqrt(2) is irrational.", max_new_tokens=200)
print(r.text, r.gear_stats)

for chunk in gbm.generate_stream("Explain entropy."):
    print(chunk.token, chunk.entropy, chunk.gear)

MLXGearbxModel

Apple Silicon with MLX. Gears swap mlx.nn.QuantizedLinear modules: low is 4-bit, mid is 8-bit, high restores the fp16 originals. Pre-quantized checkpoints run in telemetry-only mode.

from gearbx import MLXGearbxModel

gbm = MLXGearbxModel("mlx-community/Llama-3.2-1B-Instruct")
r = gbm.generate("Explain entropy.", max_new_tokens=128, temperature=0.7)
print(r.gear_stats)

EntropyMonitor

The routing primitive, usable on its own. Computes entropy in bits, smooths it, returns a gear.

from gearbx import EntropyMonitor

monitor = EntropyMonitor(
    window=5,
    low_thresh=1.8,
    high_thresh=3.5,
    vocab_size=128256,             # scales thresholds across model families
    hysteresis=0.1,                # margin before a gear flips
    warmup_tokens=16,              # self-calibrate after N tokens
)

gear = monitor.update(logits)                 # from raw logits
gear = monitor.update_from_entropy(1.7)       # or a precomputed value

A non-finite reading routes to high gear and counts toward the catastrophic-entropy detector instead of poisoning the average.

Prompt classifier

Optional cold start. Scores a prompt from math symbols, code keywords, length and word length to pick a first gear before the window fills. No model inference.

from gearbx import GearbxModel, StatisticalPromptClassifier

clf = StatisticalPromptClassifier()
clf.classify("Integrate x^2 from 0 to 1.")    # 'high'

gbm = GearbxModel("Qwen/Qwen2-0.5B-Instruct", prompt_classifier=clf)

Utilities

from gearbx import (
    detect_device,       # 'mps' | 'cuda' | 'cpu'
    memory_usage,        # process memory
    vram_usage,          # GPU memory in use
    gear_report,         # gear distribution summary
    memory_comparison,   # bytes per parameter by tier
    HAS_TRITON,          # fused CUDA kernels available
    HAS_MPS_NATIVE,      # native Metal kernels available
)

Precision tiers

GearWeightsBytes / paramUsed for
low4-bit packed0.5Predictable tokens: function words, closing brackets, the obvious next step
mid8-bit per-channel1Ordinary prose and code
highfp16 originals2Forks: the first step of a proof, a variable name, a number

Thresholds

Thresholds scale by log2(vocab_size) / log2(32768), so values tuned on one family carry to another. Auto-calibration sets them at the 40th and 60th percentile of the prefill's entropy, with caps (high ≤ 0.18·log2(vocab), low ≤ 0.06·log2(vocab)) so instruction-format tokens don't inflate them.

BackendlowhighWhy
Transformers, MLX1.83.5Full-vocabulary entropy
Ollama and HTTP servers0.41.2Top-k truncated entropy has a narrower range

Claude Code

gearbx claude starts Claude Code against a local Ollama model through a small Anthropic-compatible proxy that records entropy per token. It loads the Gearbx plugin (tools gearbx_models, gearbx_route, gearbx_entropy, gearbx_stats) and a statusline showing the current gear.

gearbx claude                 # pick a local model, then Claude Code starts

Paper

The method, calibration scheme and evaluation are written up in Entropy-Routed Dynamic Quantization for LLM Inference. Measured results and methodology are on the benchmarks page.