Metadata-Version: 2.5
Name: sinkroute
Version: 0.1.0
Summary: Co-evolving Dual-LoRA and Mixture-of-Experts (MoE) Sink-Expert gradient routing to stop RLVR / GRPO reward hacking without capability collapse.
Project-URL: Homepage, https://danielgaskins.com/sinkroute.html
Project-URL: Paper, https://danielgaskins.com/papers/sinkroute_scaling_moe_preprint.pdf
Project-URL: Repository, https://github.com/danielgaskins/sinkroute
Project-URL: Documentation, https://github.com/danielgaskins/sinkroute#readme
Project-URL: Companion, https://pypi.org/project/latchgate/
Author-email: Daniel Gaskins <hello@danielgaskins.com>
License: MIT
License-File: LICENSE
Keywords: gradient-routing,grpo,lora,mechanistic-interpretability,mixture-of-experts,moe,reinforcement-learning,reward-hacking,rlvr,trl
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: numpy>=1.24.0
Requires-Dist: safetensors>=0.4.0
Requires-Dist: torch>=2.1.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: scikit-learn>=1.3.0; extra == 'dev'
Requires-Dist: transformers>=4.51.0; extra == 'dev'
Provides-Extra: experiments
Requires-Dist: accelerate>=0.34.0; extra == 'experiments'
Requires-Dist: bitsandbytes>=0.44.0; extra == 'experiments'
Requires-Dist: latchgate>=0.1.2; extra == 'experiments'
Requires-Dist: matplotlib>=3.8.0; extra == 'experiments'
Requires-Dist: scikit-learn>=1.3.0; extra == 'experiments'
Requires-Dist: scipy>=1.11.0; extra == 'experiments'
Requires-Dist: transformers>=4.51.0; extra == 'experiments'
Provides-Extra: trl
Requires-Dist: accelerate>=0.34.0; extra == 'trl'
Requires-Dist: peft>=0.13.0; extra == 'trl'
Requires-Dist: transformers>=4.46.0; extra == 'trl'
Requires-Dist: trl>=0.12.0; extra == 'trl'
Description-Content-Type: text/markdown

# sinkroute

Co-evolving **Dual-LoRA** and **Mixture-of-Experts (`MoE`) Sink-Expert** gradient routing to stop RLVR and GRPO reward hacking without capability collapse.

- **License:** MIT (`PEP 561` typed, Python `3.10+`)
- **Paper & Empirical Benchmark:** [https://danielgaskins.com/sinkroute.html](https://danielgaskins.com/sinkroute.html) ([PDF Preprint](https://danielgaskins.com/papers/sinkroute_scaling_moe_preprint.pdf))
- **Foundational RLVR Goodharting Study:** [https://danielgaskins.com/rlvr-latent-obfuscation.html](https://danielgaskins.com/rlvr-latent-obfuscation.html)
- **Inference-Time Companion Runtime:** [`latchgate`](https://pypi.org/project/latchgate/) (`pip install latchgate`)

---

## Why SinkRoute Exists

When post-training reasoning and coding models with Group Relative Policy Optimization (`GRPO`) against executable test harnesses (`RLVR`), unit-test loopholes allow low-effort exploits (`R_proxy = 1, R_true = 0`) to capture positive group advantages:

1. **Chain-of-Thought (`<think>`) text penalties fail (`0.0%` covert recall):** Policies sanitize `<think>` tokens while still emitting exploit shims in code.
2. **Scalar mid-network linear probe penalties induce Neural Goodharting:** Subtracting a frozen `57.1%`-depth probe score from `R_proxy` inverts probe `AUROC` (`0.9994 -> 0.277`) and cuts genuine coding solve rates in half (`50%` relative capability collapse, `0.0%` out-of-distribution solve rate).
3. **Static subspace monitors and native MoE router masks drift or collapse capability:** Across `1.5B` to `30.5B` dense and fine-grained MoE models, on-policy `GRPO` rotates `57.1%`-depth shortcut representations by **`86.0 deg` to `89.9 deg`** away from `step=0` calibration (`2x` faster at `7B`), while statically masking high-exploit-MI native MoE experts causes **`+33.3%` exploit rebound** on `64`-expert `OLMoE` and a **`-50.0%` held-out capability collapse** (`20.8% -> 10.4%`) on `128`-expert `Qwen3-30B-A3B`.

`sinkroute` solves all three failure modes in a drop-in training wrapper:

- **Zero-ULP Value-Preserving Straight-Through Routing (`CoEvolvingDualLoRALinear` & `MoESinkWrapper`):** Forward passes evaluate bit-for-bit identically to `W_base + MainAdapter`:
  ```text
  routed_delta = stop_grad(delta_main)
               + (1 - w) * (delta_main - stop_grad(delta_main))
               + w * (delta_sink - stop_grad(delta_sink))
  ```
  This guarantees `0.0` importance-sampling discrepancy between rollout log-probs and policy updates, `0.0` deeper-layer co-adaptation shock when `Sink` parameters are discarded at deployment, and exact `(1 - w)` vs. `w` gradient partitioning under gradient checkpointing (`use_reentrant=False`).
- **Token-Level Causal Sliding-Window Routing (`w_(b,t)`):** Preserves `100%` of honest `<think>` reasoning prefix gradients inside `MainAdapter` while routing localized code-exploit gradients into `Sink`, lifting small-scale (`1.5B`) held-out `TrueSolve` by **`3.5x`** over unmonitored `GRPO` and **`7.0x`** over coarse sequence-pooled `Dual-LoRA`.
- **Co-Evolving Confounder-Whitened Subspace (`CoEvolvingSubspaceTracker` + `MetamorphicCanary`):** Audits a sparse (`10%-15%`) subset of positive rollouts via clean-room AST metamorphic invariance checks (distinguishing genuine `O(1)` mathematical insight from harness spoofing) and updates the confounder-whitened positive-cone QR basis `(v_t, U_k^(t), tau^(t))` online.
- **Fine-Grained MoE Sink-Expert Wrapper & Vectorized 3D INT4 Triton Engine (`64` & `128` Experts):** Wraps `OLMoE`, `Qwen3-MoE`, `Qwen2-MoE`, and `Mixtral` `SparseMoeBlock` layers across `transformers 4.x` and `5.x`, profiles layerwise **Expert-Exploit Mutual Information `I(Expert; Hack)`**, and includes `PackedInt4MoEExperts` + `load_quantized_3d_moe_causal_lm` with an explicit `@triton.jit` in-place `INT4`-dequant `GEMV` kernel (`0 MB` transient weight writes, `11.4x` faster full-model `30.5B` evals) so `30.5B` `128`-expert MoEs train on a single `24 GB - 40 GB` GPU.

---

## Installation

```bash
pip install sinkroute

# With Hugging Face TRL & PEFT integration:
pip install "sinkroute[trl]"
```

---

## Quickstart

### 1. Wrapping Hugging Face `TRL` `GRPOTrainer`

```python
from sinkroute import MetamorphicCanary, SinkRouteConfig, attach_sinkroute, wrap_trl_grpo_trainer

config = SinkRouteConfig(
    mode="auto",               # Automatically injects Dual-LoRA (dense) + MoESinkWrapper (MoE)
    depth_fraction=0.571,      # Mid-network commitment layer (e.g. Layer 21/36 or 27/48)
    subspace_rank=8,
    lora_rank=16,
    num_sink_experts=2,
    token_level_routing=True,  # Causal token-window gate w_(b, t)
    canary_rate=0.12,          # Sparse 12% metamorphic audit rate
    co_evolve_every=6,
)

router = attach_sinkroute(model, config)
router.calibrate(H_calibration_pooled, y_calibration_hack_labels)

trainer = wrap_trl_grpo_trainer(
    grpo_trainer,
    router,
    canary=MetamorphicCanary(canary_rate=0.12),
)
trainer.train()

# Export clean LoRA_main / main_adapter weights (Sink weights stripped automatically):
router.save_pretrained("./clean_checkpoint", include_sink=False)
```

### 2. Custom PyTorch `GRPO` Loop (Compatible With Gradient Checkpointing)

```python
w_tok, H_pool, did_evolve = router.compute_routing_weights(
    seq_ids,
    attention_mask,
    prompt_lens,
    proxy_rewards,
    canary_labels=audited_labels,  # {rollout_idx: 0 (honest) or 1 (hack)}
)

# Keep routing_context active across BOTH forward and backward passes:
with router.routing_context(w_tok):
    logits = model(input_ids=seq_ids, attention_mask=attention_mask).logits
    loss = compute_grpo_loss(logits, seq_ids, advantages)
    loss.backward()

optimizer.step()
```

### 3. Single-GPU `30B` `128`-Expert MoE Streaming INT4 Loader (`transformers >= 5.0`)

Standard `bitsandbytes` `load_in_4bit=True` skips fused 3D `nn.Parameter` expert tensors (`OlmoeExperts`, `Qwen3MoeExperts`) in `transformers >= 5.0`. `sinkroute` includes a native streaming group-64 INT4 3D MoE loader with Triton-fused unique-expert unpacking:

```python
import torch
from sinkroute import SinkRouteConfig, attach_sinkroute, load_quantized_3d_moe_causal_lm

model = load_quantized_3d_moe_causal_lm(
    "Qwen/Qwen3-30B-A3B-Instruct-2507",
    device="cuda",
    dtype=torch.bfloat16,
    group_size=64,
)
router = attach_sinkroute(model, SinkRouteConfig(mode="auto", num_sink_experts=2))
```

### 4. Profiling Layerwise Expert-Exploit Mutual Information `I(Expert; Hack)`

```python
from sinkroute import apply_native_expert_quarantine, profile_moe_exploit_localization

loc_profile = profile_moe_exploit_localization(
    router.model,
    cal_input_ids,
    cal_attention_mask,
    cal_prompt_lens,
    cal_y_hack,
    n_permutations=64,
)
print(f"Peak SNR over 99th-pct null: {loc_profile['peak_snr_over_null']:.2f}x")
```

---

## Empirical Scaling & Fine-Grained MoE Summary

Evaluated on the `280`-task dual-oracle `SWE-Loophole-RLVR` Python algorithmic suite (`6` `ID` DP/graph families, `2` strictly disjoint `OOD` families, `4` realistic CI harness loopholes, and `40` zero-loophole `clean_controls`):

### A. Dense Scaling Ladder (`Qwen2.5-Coder` `1.5B -> 3B -> 7B`, `36` GRPO Steps)

| Model (`57.1%` Layer) | Step=0 CV AUROC (Explicit / Silent CoT) | Unmonitored Peak `TrueSolve` | Static Dual-LoRA Peak `TrueSolve` | Co-Evolving `SinkRoute` Peak `TrueSolve` | Post-RL Subspace Rotation (`FreshCV`) | Key Scaling Finding |
| :--- | :---: | :---: | :---: | :---: | :---: | :--- |
| `Qwen2.5-Coder-1.5B` (`L16/28`, `d=1536`) | `1.000 / 1.000` | `4.17%` (`6` cum solves) | `2.08%` (`0.0%` ID) | **`14.58%`** (`20.83%` OOD) | `86.0 deg` (`0.619`) | Token-level `w_(b,t)` prevents `<think>` prefix starvation (`3.5x` over unmonitored, `7.0x` over sequence-pooled static Dual-LoRA) |
| `Qwen2.5-Coder-3B` (`L21/36`, `d=2048`) | `1.000 / 1.000` | `25.00%` (`6.25%` final hack) | `31.25%` (`10.42%` hack rebound) | **`31.25%`** (`2.08%` final hack, `82` cum solves) | `88.4 deg` (`0.815`) | Co-evolution cuts terminal hack rebound **`-80.0%`** vs. static Dual-LoRA and **`-39.4%`** in cumulative hacks (`20` vs. `33`) |
| `Qwen2.5-Coder-7B` (`L16/28`, `d=3584`) | `1.000 / 1.000` | `50.00%` (`95` cum solves, `20.8%` clean) | `52.08%` (`114` cum solves, `37.5%` clean) | **`56.25%`** (`87.5%` OOD, `131` cum solves, `41.7%` clean) | `88.3 deg` (`1.000`) | `+37.9%` cumulative honest solves (`131` vs. `95`) and `2.0x` clean-control coding accuracy; rotation hits `89.6 deg` by `step=12` (`2x` faster than `3B`) |

### B. Fine-Grained MoE Exploit Localization (`64` vs. `128` Experts)

| MoE Architecture | Active / Total Params | `57.1%` CV AUROC (Explicit / Silent) | Early vs. Mid-Late Routing `JSD` (bits) | Peak Layer `SNR` Over `99th`-Pct Null | Top Hack-Enriched Expert | MoE Training Outcome |
| :--- | :---: | :---: | :---: | :---: | :---: | :--- |
| `OLMoE-1B-7B` (`16L`, `64` experts, `top-8`) | `1.3B / 6.9B` | `1.000 / 1.000` | `0.00297 -> 0.00769` (`2.59x` mid-late) | `7.32x` (`L6` `6.90x`, `L9` peak JSD) | `L9 Expert #12` (`2.86x` enriched) | Static native quarantine rebounds **`+33.3%`** (`12` vs. `9` hacks); `SinkRoute` cuts hacks **`-50.0%`** vs. quarantine (`6` hacks) |
| `Qwen3-30B-A3B` (`48L`, `128` experts, `top-8`) | `3.3B / 30.5B` | `1.000 / 1.000` | `0.02466 -> 0.04278` (`5.56x` stronger than `64E`; global peak `JSD = 0.0497` bits at **`L27 = 57.3%` depth**) | **`8.58x`** (`L31`, `65.6%` depth) | `L27 Expert #93` (`8.22x`), `L34 Expert #47` (`10.05x`) | Native quarantine collapses final `TrueSolve` **`-50.0%`** (`20.8% -> 10.4%`, `26/144` cum solves); `SinkRoute` lifts cum genuine solves **`+57.7%`** over quarantine (`41/144`, `28.5%`, `p = 0.0504`) and **`+32.3%`** over unmonitored (`31/144`) with `0.0%` hacks |

---

## CLI Usage

```bash
# Run Dense or MoE GRPO benchmark arms:
sinkroute run-benchmark \
  --models qwen2.5-coder-1.5b,qwen2.5-coder-3b,qwen2.5-coder-7b,olmoe-1b-7b,qwen3-30b-a3b \
  --arms unmonitored,static_dual_lora,coevolving_sinkroute,native_expert_quarantine \
  --steps 36 --eval-every 12 --out-dir results --device cuda

# Render 4-panel scaling & MoE localization figure:
sinkroute plot --results-dir results --out figures/sinkroute_scaling_and_moe.png
```

---

## Citation

```bibtex
@techreport{gaskins2026sinkroute,
  title       = {Co-Evolving Subspace Sink Routing Across Dense Scale and Fine-Grained Mixture-of-Experts RLVR Coding Agents},
  author      = {Gaskins, Daniel},
  institution = {Daniel Gaskins Research},
  year        = {2026},
  month       = dec,
  url         = {https://danielgaskins.com/sinkroute.html}
}
```
