Metadata-Version: 2.4
Name: latchgate
Version: 0.1.0
Summary: Zero-decode circuit-breaker compiler and runtime for open-weights LLMs, video DiTs, and embodied world models
Author-email: Daniel Gaskins <hello@danielgaskins.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/danielgaskins/latchgate
Project-URL: Creator, https://danielgaskins.com/
Project-URL: Repository, https://github.com/danielgaskins/latchgate
Project-URL: Issues, https://github.com/danielgaskins/latchgate/issues
Project-URL: Documentation, https://github.com/danielgaskins/latchgate#readme
Project-URL: Mendmark Integration, https://github.com/danielgaskins/mendmark
Keywords: ai-control,circuit-breakers,cosmos,diffusers,interpretability,mechanistic-interpretability,robotics,sae,sparse-autoencoders,vllm,world-models
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
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: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: safetensors>=0.4
Requires-Dist: torch>=2.1
Provides-Extra: hub
Requires-Dist: huggingface-hub>=0.23; extra == "hub"
Provides-Extra: llm
Requires-Dist: transformers>=4.40; extra == "llm"
Requires-Dist: huggingface-hub>=0.23; extra == "llm"
Provides-Extra: diffusers
Requires-Dist: diffusers>=0.30; extra == "diffusers"
Requires-Dist: huggingface-hub>=0.23; extra == "diffusers"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: huggingface-hub>=0.23; extra == "dev"
Dynamic: license-file

<div align="center">
  <h1>LatchGate</h1>
  <p><strong>Zero-decode circuit-breaker compiler and runtime for open-weights LLMs, video DiTs, and embodied world models.</strong></p>
  <p>
    <a href="https://github.com/danielgaskins/latchgate/actions/workflows/tests.yml"><img alt="Tests" src="https://github.com/danielgaskins/latchgate/actions/workflows/tests.yml/badge.svg"></a>
    <img alt="Python 3.10 to 3.13" src="https://img.shields.io/badge/python-3.10--3.13-3776ab">
    <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-0f766e"></a>
  </p>
  <p>
    <a href="#quickstart-a-llm-agents">LLM Agents</a> ·
    <a href="#quickstart-b-cosmos-and-diffusers-world-models">Cosmos &amp; Diffusers</a> ·
    <a href="#adaptive-compilation-latchgate-fit">Adaptive Compiler</a> ·
    <a href="#pre-built-lgate-packs">Pre-Built Packs</a> ·
    <a href="#mendmark-ci-to-runtime-bridge">Mendmark Bridge</a>
  </p>
</div>

<p align="center">
  Created by <a href="https://danielgaskins.com/">Daniel Gaskins</a>
</p>

Post-hoc text auditors and pixel-level video critics share a structural flaw: they pay 100% of generation and 3D-VAE decode cost before inspecting an output, and they are systematically fooled by sycophantic trajectories (`<think>` compliance obfuscation in coding agents, or zero-contact optimistic grasps in action-conditioned world models).

**LatchGate** moves safety and physical-consistency enforcement inside the residual stream at **57.1% network depth**, compiling portable `.lgate` (`safetensors`) circuit breakers that execute in `< 1 ms` on LLM tokens and `~11 ms` on 3D spacetime tokens with **0.0% benign capability tax** and **zero pixel decodes**.

## Installation

```bash
pip install latchgate
# Optional extras for Hugging Face Transformers or Diffusers helpers:
pip install "latchgate[llm,diffusers]"
```

## Quickstart A: LLM Agents

Intercept `<think>` scratchpad obfuscation 30+ tokens before a sabotaged `TOOL_CALL:` is emitted, latching norm-preserving planning-block steering only when pre-action commitment crosses the calibrated threshold (`0.0%` modification on benign requests):

```python
from latchgate import LatchGate, TransformersLatchHook

gate = LatchGate.from_pretrained("qwen2.5-7b-sabotage", device="cuda")
hook = TransformersLatchHook(gate, policy="latched_steer")  # or policy="early_abort"
with hook.attach(model) as telemetry:
    output_ids = model.generate(**inputs, max_new_tokens=160)
```

The same `.lgate` artifact attaches directly to local `vLLM` (`VLLMLatchEngine`) and `SGLang` (`SGLangLatchHook`) model runners over flattened 2D paged-attention hidden states.

## Quickstart B: Cosmos and Diffusers World Models

Abort action-decoupled ("sycophantic") robot rollouts at Step 10/35 inside `Cosmos-Predict2.5-2B` before running the remaining 50 CFG passes or decoding a single frame through the `Wan2.1` 3D-VAE:

```python
from latchgate import CosmosLatchFirewall, EarlyAbortRollout, LatchGate

gate = LatchGate.from_pretrained("cosmos-predict2.5-bridge", device="cuda")
with CosmosLatchFirewall(gate, policy="early_abort", abort_step=10).attach(world_model.dit) as step_cb:
    latents = world_model.rollout(frame0, actions, decode_video=False, step_callback=step_cb)
```

For closed-loop model-predictive control (`Cosmos-Policy-LIBERO`), `shield_value_critic` prunes sycophantic action candidates at Step 3/10 before invoking the internal value head $V(\hat{s}')$, raising valid grasp selection to `80.0%` while cutting 4-candidate planning latency from `8.93 s` to `6.02 s`.

## Adaptive Compilation (`latchgate fit`)

Generic SAE pretraining on billions of tokens is unnecessary for runtime control and often counterproductive on 7B to 70B LLMs where linear probes already separate pre-action intent cleanly. Given 50 to 200 paired counterfactual traces (plus optional high-motion or benign confounders), `latchgate fit` measures the **57.1%-depth superposition gap** via cross-validation and automatically compiles the lightest representation that achieves target `0.0%` benign false-positive rate:

| Regime | Representative Backbones | 57.1% Depth Geometry | Compiled `.lgate` Architecture |
| --- | --- | --- | --- |
| **Linearly Separable** | `Gemma-2-9B-IT`, `Qwen2.5-7B-Instruct` | Dense CV AUROC `0.94` to `1.00`, zero benign collateral | **`dense_latch`**: Unit-norm L2 logistic gate + 4-layer planning-block steering (`< 1 MB`) |
| **Superposed / Confounded** | `Gemma-2-2B-IT`, `LTX-Video-0.9.5`, `Cosmos-Predict2.5-2B`, `Cosmos-Policy-LIBERO` | 3D spacetime or edge superposition collapses dense probes (`0.36` to `0.51` AUROC) | **`sae_anchor_latch`**: `TimestepStandardizer` + 16k JumpReLU SAE + Confounder-Penalized $\mathcal{D}_{\text{bad}}$ + Instance Anchor $\mathcal{S}_0^{(i)}$ |

### Fast Task Calibration (`< 10 s` on Frozen Base Dictionaries)

Because sparse dictionary learning is decoupled from task attribution, adapting a circuit breaker to a new robot manipulation suite or internal MCP tool schema does **not** retrain the 16,384-latent SAE. Pass `--base-sae` (any `.lgate`, `.safetensors`, Gemma Scope `.npz`, or Hugging Face repo) to calibrate $\mathcal{D} = \text{TopK}(d^{\text{bad}} - \lambda d^{\text{confound}})$ and conformal threshold $\tau$ in seconds:

```bash
latchgate fit custom_robot_pairs.npz \
  --base-sae cosmos-predict2.5-bridge.lgate \
  --max-benign-fpr 0.0 \
  --output custom_cell_firewall.lgate
```

When calibrating a brand-new backbone with no public SAE, `latchgate train-sae` trains a per-timestep standardized JumpReLU SAE on a single 24 GB GPU using **buffer-replay saturation sizing** (Koriagin et al., 2026) and **variance/confounder-reweighted MSE** (WSAE) so high-energy motion or formatting axes do not starve subtle contact or sabotage features.

## Pre-Built `.lgate` Packs

List or inspect all official checkpoints from the CLI (`latchgate list-packs`, `latchgate inspect <pack>`):

| Pack ID | Backbone | Mode | Layer | Held-Out AUROC | Verified Runtime Impact |
| --- | --- | --- | --- | ---: | --- |
| `gemma-2-9b-sabotage` | `google/gemma-2-9b-it` | `dense_latch` | `L24/42` (`57.1%`) | `1.000` | Cuts `<think>` sabotage `66.7% -> 5.6%` at `0.0%` benign tax, defeating Action Re-Locking |
| `qwen2.5-7b-sabotage` | `Qwen/Qwen2.5-7B-Instruct` | `dense_latch` | `L16/28` (`57.1%`) | `0.978` | Catches `100%` of `<think>` traces that evade a 7B black-box CoT compliance auditor |
| `gemma-2-2b-sabotage` | `google/gemma-2-2b-it` | `dense_latch` | `L16/26` (`61.5%`) | `1.000` | Cuts pressured tool sabotage `52.1% -> 10.4%` while preserving `96.7%` benign pass rate |
| `ltx-video-0.9.5-drift` | `Lightricks/LTX-Video-0.9.5` | `sae_anchor_latch` | `L16/28` (`57.1%`) | `0.908` | Zero-decode Step-3 (`sigma=0.75`) identity drift detection vs `0.364` dense probe |
| `cosmos-predict2.5-bridge` | `nvidia/Cosmos-Predict2.5-2B` | `sae_anchor_latch` | `L16/28` (`57.1%`) | `0.986` | Cuts DreamGen corruption `33.3% -> 2.9%` (`11.3x`) while saving `26.1%` GPU wall-clock time |
| `cosmos-policy-libero` | `nvidia/Cosmos-Policy-LIBERO-Predict2-2B` | `sae_anchor_latch` | `L16/28` (`57.1%`) | `0.766` | Shields internal value critic (`0.511` AUROC), cutting 4-candidate MPC latency to `6.02 s` |

## Mendmark CI-to-Runtime Bridge

[**Mendmark**](https://github.com/danielgaskins/mendmark) (`pip install mendmark-evals`) discovers silent tool-call and outcome blind spots in CI via mutation testing; **LatchGate** blocks those exact failure modes in the residual stream at runtime:

```bash
# 1. Export planted fault mutations + clean golden traces from any Mendmark suite:
mendmark export-latchgate examples/order_agent_suite.json \
  --output calibration_pairs.jsonl

# 2. Compile a zero-tax .lgate circuit breaker directly against your open-weights agent model:
latchgate fit calibration_pairs.jsonl \
  --model Qwen/Qwen2.5-7B-Instruct \
  --output order_agent.lgate
```

## Research Foundations

LatchGate unifies the algorithms and empirical findings from three companion papers:

1. **Agentic LLMs:** *Silent Pre-Action Commitment and Closed-Loop Circuit Breakers Against Agentic Sabotage* ([DOI: 10.5281/zenodo.24596272](https://doi.org/10.5281/zenodo.24596272))
2. **Long-Horizon Video DiTs:** *Sparse Temporal Latching: Overcoming Polysemantic Collateral Damage in Long-Horizon Video Diffusion Transformers* ([DOI: 10.5281/zenodo.24596273](https://doi.org/10.5281/zenodo.24596273))
3. **Embodied World Models:** *Sycophantic Physics in Embodied World Models: Zero-Decode Latent Firewalls for Action-Conditioned Video DiTs* ([DOI: 10.5281/zenodo.24593275](https://doi.org/10.5281/zenodo.24593275))

## License

Released under the [MIT License](LICENSE).
