sinkroute 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. sinkroute-0.1.0/.github/workflows/release.yml +137 -0
  2. sinkroute-0.1.0/.github/workflows/tests.yml +30 -0
  3. sinkroute-0.1.0/.gitignore +16 -0
  4. sinkroute-0.1.0/LICENSE +21 -0
  5. sinkroute-0.1.0/PKG-INFO +226 -0
  6. sinkroute-0.1.0/README.md +180 -0
  7. sinkroute-0.1.0/context7.json +18 -0
  8. sinkroute-0.1.0/figures/sinkroute_scaling_and_moe.png +0 -0
  9. sinkroute-0.1.0/llms.txt +22 -0
  10. sinkroute-0.1.0/paper/sinkroute_scaling_moe_preprint.pdf +10545 -0
  11. sinkroute-0.1.0/paper/sinkroute_scaling_moe_preprint.typ +218 -0
  12. sinkroute-0.1.0/pyproject.toml +82 -0
  13. sinkroute-0.1.0/results/olmoe-1b-7b/arm_coevolving_sinkroute.json +760 -0
  14. sinkroute-0.1.0/results/olmoe-1b-7b/arm_native_expert_quarantine.json +793 -0
  15. sinkroute-0.1.0/results/olmoe-1b-7b/arm_unmonitored.json +760 -0
  16. sinkroute-0.1.0/results/olmoe-1b-7b/calibration_profile.json +247 -0
  17. sinkroute-0.1.0/results/olmoe-1b-7b/moe_localization.json +237 -0
  18. sinkroute-0.1.0/results/qwen2.5-coder-1.5b/arm_coevolving_sinkroute.json +760 -0
  19. sinkroute-0.1.0/results/qwen2.5-coder-1.5b/arm_static_dual_lora.json +760 -0
  20. sinkroute-0.1.0/results/qwen2.5-coder-1.5b/arm_unmonitored.json +760 -0
  21. sinkroute-0.1.0/results/qwen2.5-coder-1.5b/calibration_profile.json +10 -0
  22. sinkroute-0.1.0/results/qwen2.5-coder-3b/arm_coevolving_sinkroute.json +760 -0
  23. sinkroute-0.1.0/results/qwen2.5-coder-3b/arm_static_dual_lora.json +760 -0
  24. sinkroute-0.1.0/results/qwen2.5-coder-3b/arm_unmonitored.json +760 -0
  25. sinkroute-0.1.0/results/qwen2.5-coder-3b/calibration_profile.json +10 -0
  26. sinkroute-0.1.0/results/qwen2.5-coder-7b/arm_coevolving_sinkroute.json +760 -0
  27. sinkroute-0.1.0/results/qwen2.5-coder-7b/arm_static_dual_lora.json +760 -0
  28. sinkroute-0.1.0/results/qwen2.5-coder-7b/arm_unmonitored.json +760 -0
  29. sinkroute-0.1.0/results/qwen2.5-coder-7b/calibration_profile.json +10 -0
  30. sinkroute-0.1.0/results/qwen3-30b-a3b/arm_coevolving_sinkroute.json +384 -0
  31. sinkroute-0.1.0/results/qwen3-30b-a3b/arm_native_expert_quarantine.json +529 -0
  32. sinkroute-0.1.0/results/qwen3-30b-a3b/arm_unmonitored.json +384 -0
  33. sinkroute-0.1.0/results/qwen3-30b-a3b/calibration_profile.json +791 -0
  34. sinkroute-0.1.0/results/qwen3-30b-a3b/moe_localization.json +781 -0
  35. sinkroute-0.1.0/src/sinkroute/__init__.py +82 -0
  36. sinkroute-0.1.0/src/sinkroute/benchmark.py +1040 -0
  37. sinkroute-0.1.0/src/sinkroute/canary.py +200 -0
  38. sinkroute-0.1.0/src/sinkroute/cli.py +102 -0
  39. sinkroute-0.1.0/src/sinkroute/config.py +80 -0
  40. sinkroute-0.1.0/src/sinkroute/dual_lora.py +348 -0
  41. sinkroute-0.1.0/src/sinkroute/env.py +1038 -0
  42. sinkroute-0.1.0/src/sinkroute/figures.py +253 -0
  43. sinkroute-0.1.0/src/sinkroute/moe_sink.py +1275 -0
  44. sinkroute-0.1.0/src/sinkroute/py.typed +0 -0
  45. sinkroute-0.1.0/src/sinkroute/router.py +423 -0
  46. sinkroute-0.1.0/src/sinkroute/tracker.py +503 -0
  47. sinkroute-0.1.0/tests/test_sinkroute.py +511 -0
@@ -0,0 +1,137 @@
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+ inputs:
8
+ tag:
9
+ description: "Git tag to build and publish (for example v0.1.0)"
10
+ required: true
11
+ default: "v0.1.0"
12
+ type: string
13
+ repository_target:
14
+ description: "Package index target"
15
+ required: true
16
+ default: "pypi"
17
+ type: choice
18
+ options:
19
+ - pypi
20
+ - testpypi
21
+
22
+ permissions:
23
+ contents: read
24
+
25
+ jobs:
26
+ build:
27
+ runs-on: ubuntu-latest
28
+ outputs:
29
+ version: ${{ steps.pkg.outputs.version }}
30
+ steps:
31
+ - uses: actions/checkout@v4
32
+ with:
33
+ ref: ${{ inputs.tag || github.ref_name }}
34
+ fetch-depth: 0
35
+
36
+ - uses: actions/setup-python@v5
37
+ with:
38
+ python-version: "3.12"
39
+ cache: pip
40
+
41
+ - name: Install build and test tools
42
+ run: |
43
+ python -m pip install --upgrade pip build twine pytest
44
+ python -m pip install --index-url https://download.pytorch.org/whl/cpu torch
45
+ python -m pip install -e ".[dev]" matplotlib
46
+
47
+ - name: Verify tag matches package version
48
+ id: pkg
49
+ run: |
50
+ version=$(python - <<'PY'
51
+ import tomllib
52
+ with open("pyproject.toml", "rb") as fh:
53
+ print(tomllib.load(fh)["project"]["version"])
54
+ PY
55
+ )
56
+ ref_tag="${{ inputs.tag || github.ref_name }}"
57
+ if [[ "$ref_tag" != "v${version}" ]]; then
58
+ echo "Tag ${ref_tag} does not match pyproject.toml version ${version}" >&2
59
+ exit 1
60
+ fi
61
+ echo "version=${version}" >> "$GITHUB_OUTPUT"
62
+
63
+ - name: Run unit test suite
64
+ run: pytest -q
65
+
66
+ - name: Build sdist and wheel
67
+ run: |
68
+ rm -rf dist build
69
+ python -m build
70
+ python -m twine check dist/*
71
+
72
+ - name: Smoke-test isolated wheel installation
73
+ run: |
74
+ python -m venv /tmp/sinkroute-smoke
75
+ /tmp/sinkroute-smoke/bin/pip install --upgrade pip
76
+ /tmp/sinkroute-smoke/bin/pip install --no-deps dist/*.whl
77
+ /tmp/sinkroute-smoke/bin/python -c "import importlib.metadata as m; assert m.version('sinkroute') == '${{ steps.pkg.outputs.version }}'"
78
+
79
+ - uses: actions/upload-artifact@v4
80
+ with:
81
+ name: python-package-distributions
82
+ path: dist/
83
+ if-no-files-found: error
84
+
85
+ publish-pypi:
86
+ if: github.event_name == 'release' || inputs.repository_target == 'pypi'
87
+ needs: build
88
+ runs-on: ubuntu-latest
89
+ environment:
90
+ name: pypi
91
+ url: https://pypi.org/p/sinkroute
92
+ permissions:
93
+ id-token: write
94
+ steps:
95
+ - uses: actions/download-artifact@v4
96
+ with:
97
+ name: python-package-distributions
98
+ path: dist/
99
+ - uses: pypa/gh-action-pypi-publish@release/v1
100
+
101
+ publish-testpypi:
102
+ if: github.event_name == 'workflow_dispatch' && inputs.repository_target == 'testpypi'
103
+ needs: build
104
+ runs-on: ubuntu-latest
105
+ environment:
106
+ name: testpypi
107
+ url: https://test.pypi.org/p/sinkroute
108
+ permissions:
109
+ id-token: write
110
+ steps:
111
+ - uses: actions/download-artifact@v4
112
+ with:
113
+ name: python-package-distributions
114
+ path: dist/
115
+ - uses: pypa/gh-action-pypi-publish@release/v1
116
+ with:
117
+ repository-url: https://test.pypi.org/legacy/
118
+
119
+ verify-pypi:
120
+ if: github.event_name == 'release' || inputs.repository_target == 'pypi'
121
+ needs: [build, publish-pypi]
122
+ runs-on: ubuntu-latest
123
+ steps:
124
+ - uses: actions/setup-python@v5
125
+ with:
126
+ python-version: "3.12"
127
+ - name: Wait for PyPI propagation and verify wheel metadata
128
+ run: |
129
+ for attempt in {1..12}; do
130
+ if python -m pip install --no-cache-dir --no-deps "sinkroute==${{ needs.build.outputs.version }}"; then
131
+ exit 0
132
+ fi
133
+ if (( attempt == 12 )); then
134
+ exit 1
135
+ fi
136
+ sleep 10
137
+ done
@@ -0,0 +1,30 @@
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ tags: ["v*"]
7
+ pull_request:
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ pytest:
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: ${{ matrix.python-version }}
24
+ - name: Install package and CPU test dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ python -m pip install --index-url https://download.pytorch.org/whl/cpu torch
28
+ python -m pip install -e ".[dev]" matplotlib
29
+ - name: Run test suite
30
+ run: pytest -v
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ checkpoints/
11
+ results/*/ckpt_*/
12
+ *.safetensors
13
+ *.pt
14
+ *.mp4
15
+ *.b64
16
+ paper/page-*.png
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Gaskins
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,226 @@
1
+ Metadata-Version: 2.5
2
+ Name: sinkroute
3
+ Version: 0.1.0
4
+ Summary: Co-evolving Dual-LoRA and Mixture-of-Experts (MoE) Sink-Expert gradient routing to stop RLVR / GRPO reward hacking without capability collapse.
5
+ Project-URL: Homepage, https://danielgaskins.com/sinkroute.html
6
+ Project-URL: Paper, https://danielgaskins.com/papers/sinkroute_scaling_moe_preprint.pdf
7
+ Project-URL: Repository, https://github.com/danielgaskins/sinkroute
8
+ Project-URL: Documentation, https://github.com/danielgaskins/sinkroute#readme
9
+ Project-URL: Companion, https://pypi.org/project/latchgate/
10
+ Author-email: Daniel Gaskins <hello@danielgaskins.com>
11
+ License: MIT
12
+ License-File: LICENSE
13
+ Keywords: gradient-routing,grpo,lora,mechanistic-interpretability,mixture-of-experts,moe,reinforcement-learning,reward-hacking,rlvr,trl
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: numpy>=1.24.0
26
+ Requires-Dist: safetensors>=0.4.0
27
+ Requires-Dist: torch>=2.1.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
30
+ Requires-Dist: scikit-learn>=1.3.0; extra == 'dev'
31
+ Requires-Dist: transformers>=4.51.0; extra == 'dev'
32
+ Provides-Extra: experiments
33
+ Requires-Dist: accelerate>=0.34.0; extra == 'experiments'
34
+ Requires-Dist: bitsandbytes>=0.44.0; extra == 'experiments'
35
+ Requires-Dist: latchgate>=0.1.2; extra == 'experiments'
36
+ Requires-Dist: matplotlib>=3.8.0; extra == 'experiments'
37
+ Requires-Dist: scikit-learn>=1.3.0; extra == 'experiments'
38
+ Requires-Dist: scipy>=1.11.0; extra == 'experiments'
39
+ Requires-Dist: transformers>=4.51.0; extra == 'experiments'
40
+ Provides-Extra: trl
41
+ Requires-Dist: accelerate>=0.34.0; extra == 'trl'
42
+ Requires-Dist: peft>=0.13.0; extra == 'trl'
43
+ Requires-Dist: transformers>=4.46.0; extra == 'trl'
44
+ Requires-Dist: trl>=0.12.0; extra == 'trl'
45
+ Description-Content-Type: text/markdown
46
+
47
+ # sinkroute
48
+
49
+ Co-evolving **Dual-LoRA** and **Mixture-of-Experts (`MoE`) Sink-Expert** gradient routing to stop RLVR and GRPO reward hacking without capability collapse.
50
+
51
+ - **License:** MIT (`PEP 561` typed, Python `3.10+`)
52
+ - **Paper & Empirical Benchmark:** [https://danielgaskins.com/sinkroute.html](https://danielgaskins.com/sinkroute.html) ([PDF Preprint](https://danielgaskins.com/papers/sinkroute_scaling_moe_preprint.pdf))
53
+ - **Foundational RLVR Goodharting Study:** [https://danielgaskins.com/rlvr-latent-obfuscation.html](https://danielgaskins.com/rlvr-latent-obfuscation.html)
54
+ - **Inference-Time Companion Runtime:** [`latchgate`](https://pypi.org/project/latchgate/) (`pip install latchgate`)
55
+
56
+ ---
57
+
58
+ ## Why SinkRoute Exists
59
+
60
+ 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:
61
+
62
+ 1. **Chain-of-Thought (`<think>`) text penalties fail (`0.0%` covert recall):** Policies sanitize `<think>` tokens while still emitting exploit shims in code.
63
+ 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).
64
+ 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`.
65
+
66
+ `sinkroute` solves all three failure modes in a drop-in training wrapper:
67
+
68
+ - **Zero-ULP Value-Preserving Straight-Through Routing (`CoEvolvingDualLoRALinear` & `MoESinkWrapper`):** Forward passes evaluate bit-for-bit identically to `W_base + MainAdapter`:
69
+ ```text
70
+ routed_delta = stop_grad(delta_main)
71
+ + (1 - w) * (delta_main - stop_grad(delta_main))
72
+ + w * (delta_sink - stop_grad(delta_sink))
73
+ ```
74
+ 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`).
75
+ - **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`.
76
+ - **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.
77
+ - **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.
78
+
79
+ ---
80
+
81
+ ## Installation
82
+
83
+ ```bash
84
+ pip install sinkroute
85
+
86
+ # With Hugging Face TRL & PEFT integration:
87
+ pip install "sinkroute[trl]"
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Quickstart
93
+
94
+ ### 1. Wrapping Hugging Face `TRL` `GRPOTrainer`
95
+
96
+ ```python
97
+ from sinkroute import MetamorphicCanary, SinkRouteConfig, attach_sinkroute, wrap_trl_grpo_trainer
98
+
99
+ config = SinkRouteConfig(
100
+ mode="auto", # Automatically injects Dual-LoRA (dense) + MoESinkWrapper (MoE)
101
+ depth_fraction=0.571, # Mid-network commitment layer (e.g. Layer 21/36 or 27/48)
102
+ subspace_rank=8,
103
+ lora_rank=16,
104
+ num_sink_experts=2,
105
+ token_level_routing=True, # Causal token-window gate w_(b, t)
106
+ canary_rate=0.12, # Sparse 12% metamorphic audit rate
107
+ co_evolve_every=6,
108
+ )
109
+
110
+ router = attach_sinkroute(model, config)
111
+ router.calibrate(H_calibration_pooled, y_calibration_hack_labels)
112
+
113
+ trainer = wrap_trl_grpo_trainer(
114
+ grpo_trainer,
115
+ router,
116
+ canary=MetamorphicCanary(canary_rate=0.12),
117
+ )
118
+ trainer.train()
119
+
120
+ # Export clean LoRA_main / main_adapter weights (Sink weights stripped automatically):
121
+ router.save_pretrained("./clean_checkpoint", include_sink=False)
122
+ ```
123
+
124
+ ### 2. Custom PyTorch `GRPO` Loop (Compatible With Gradient Checkpointing)
125
+
126
+ ```python
127
+ w_tok, H_pool, did_evolve = router.compute_routing_weights(
128
+ seq_ids,
129
+ attention_mask,
130
+ prompt_lens,
131
+ proxy_rewards,
132
+ canary_labels=audited_labels, # {rollout_idx: 0 (honest) or 1 (hack)}
133
+ )
134
+
135
+ # Keep routing_context active across BOTH forward and backward passes:
136
+ with router.routing_context(w_tok):
137
+ logits = model(input_ids=seq_ids, attention_mask=attention_mask).logits
138
+ loss = compute_grpo_loss(logits, seq_ids, advantages)
139
+ loss.backward()
140
+
141
+ optimizer.step()
142
+ ```
143
+
144
+ ### 3. Single-GPU `30B` `128`-Expert MoE Streaming INT4 Loader (`transformers >= 5.0`)
145
+
146
+ 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:
147
+
148
+ ```python
149
+ import torch
150
+ from sinkroute import SinkRouteConfig, attach_sinkroute, load_quantized_3d_moe_causal_lm
151
+
152
+ model = load_quantized_3d_moe_causal_lm(
153
+ "Qwen/Qwen3-30B-A3B-Instruct-2507",
154
+ device="cuda",
155
+ dtype=torch.bfloat16,
156
+ group_size=64,
157
+ )
158
+ router = attach_sinkroute(model, SinkRouteConfig(mode="auto", num_sink_experts=2))
159
+ ```
160
+
161
+ ### 4. Profiling Layerwise Expert-Exploit Mutual Information `I(Expert; Hack)`
162
+
163
+ ```python
164
+ from sinkroute import apply_native_expert_quarantine, profile_moe_exploit_localization
165
+
166
+ loc_profile = profile_moe_exploit_localization(
167
+ router.model,
168
+ cal_input_ids,
169
+ cal_attention_mask,
170
+ cal_prompt_lens,
171
+ cal_y_hack,
172
+ n_permutations=64,
173
+ )
174
+ print(f"Peak SNR over 99th-pct null: {loc_profile['peak_snr_over_null']:.2f}x")
175
+ ```
176
+
177
+ ---
178
+
179
+ ## Empirical Scaling & Fine-Grained MoE Summary
180
+
181
+ 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`):
182
+
183
+ ### A. Dense Scaling Ladder (`Qwen2.5-Coder` `1.5B -> 3B -> 7B`, `36` GRPO Steps)
184
+
185
+ | 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 |
186
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
187
+ | `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) |
188
+ | `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`) |
189
+ | `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`) |
190
+
191
+ ### B. Fine-Grained MoE Exploit Localization (`64` vs. `128` Experts)
192
+
193
+ | 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 |
194
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
195
+ | `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) |
196
+ | `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 |
197
+
198
+ ---
199
+
200
+ ## CLI Usage
201
+
202
+ ```bash
203
+ # Run Dense or MoE GRPO benchmark arms:
204
+ sinkroute run-benchmark \
205
+ --models qwen2.5-coder-1.5b,qwen2.5-coder-3b,qwen2.5-coder-7b,olmoe-1b-7b,qwen3-30b-a3b \
206
+ --arms unmonitored,static_dual_lora,coevolving_sinkroute,native_expert_quarantine \
207
+ --steps 36 --eval-every 12 --out-dir results --device cuda
208
+
209
+ # Render 4-panel scaling & MoE localization figure:
210
+ sinkroute plot --results-dir results --out figures/sinkroute_scaling_and_moe.png
211
+ ```
212
+
213
+ ---
214
+
215
+ ## Citation
216
+
217
+ ```bibtex
218
+ @techreport{gaskins2026sinkroute,
219
+ title = {Co-Evolving Subspace Sink Routing Across Dense Scale and Fine-Grained Mixture-of-Experts RLVR Coding Agents},
220
+ author = {Gaskins, Daniel},
221
+ institution = {Daniel Gaskins Research},
222
+ year = {2026},
223
+ month = dec,
224
+ url = {https://danielgaskins.com/sinkroute.html}
225
+ }
226
+ ```
@@ -0,0 +1,180 @@
1
+ # sinkroute
2
+
3
+ Co-evolving **Dual-LoRA** and **Mixture-of-Experts (`MoE`) Sink-Expert** gradient routing to stop RLVR and GRPO reward hacking without capability collapse.
4
+
5
+ - **License:** MIT (`PEP 561` typed, Python `3.10+`)
6
+ - **Paper & Empirical Benchmark:** [https://danielgaskins.com/sinkroute.html](https://danielgaskins.com/sinkroute.html) ([PDF Preprint](https://danielgaskins.com/papers/sinkroute_scaling_moe_preprint.pdf))
7
+ - **Foundational RLVR Goodharting Study:** [https://danielgaskins.com/rlvr-latent-obfuscation.html](https://danielgaskins.com/rlvr-latent-obfuscation.html)
8
+ - **Inference-Time Companion Runtime:** [`latchgate`](https://pypi.org/project/latchgate/) (`pip install latchgate`)
9
+
10
+ ---
11
+
12
+ ## Why SinkRoute Exists
13
+
14
+ 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:
15
+
16
+ 1. **Chain-of-Thought (`<think>`) text penalties fail (`0.0%` covert recall):** Policies sanitize `<think>` tokens while still emitting exploit shims in code.
17
+ 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).
18
+ 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`.
19
+
20
+ `sinkroute` solves all three failure modes in a drop-in training wrapper:
21
+
22
+ - **Zero-ULP Value-Preserving Straight-Through Routing (`CoEvolvingDualLoRALinear` & `MoESinkWrapper`):** Forward passes evaluate bit-for-bit identically to `W_base + MainAdapter`:
23
+ ```text
24
+ routed_delta = stop_grad(delta_main)
25
+ + (1 - w) * (delta_main - stop_grad(delta_main))
26
+ + w * (delta_sink - stop_grad(delta_sink))
27
+ ```
28
+ 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`).
29
+ - **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`.
30
+ - **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.
31
+ - **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.
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install sinkroute
39
+
40
+ # With Hugging Face TRL & PEFT integration:
41
+ pip install "sinkroute[trl]"
42
+ ```
43
+
44
+ ---
45
+
46
+ ## Quickstart
47
+
48
+ ### 1. Wrapping Hugging Face `TRL` `GRPOTrainer`
49
+
50
+ ```python
51
+ from sinkroute import MetamorphicCanary, SinkRouteConfig, attach_sinkroute, wrap_trl_grpo_trainer
52
+
53
+ config = SinkRouteConfig(
54
+ mode="auto", # Automatically injects Dual-LoRA (dense) + MoESinkWrapper (MoE)
55
+ depth_fraction=0.571, # Mid-network commitment layer (e.g. Layer 21/36 or 27/48)
56
+ subspace_rank=8,
57
+ lora_rank=16,
58
+ num_sink_experts=2,
59
+ token_level_routing=True, # Causal token-window gate w_(b, t)
60
+ canary_rate=0.12, # Sparse 12% metamorphic audit rate
61
+ co_evolve_every=6,
62
+ )
63
+
64
+ router = attach_sinkroute(model, config)
65
+ router.calibrate(H_calibration_pooled, y_calibration_hack_labels)
66
+
67
+ trainer = wrap_trl_grpo_trainer(
68
+ grpo_trainer,
69
+ router,
70
+ canary=MetamorphicCanary(canary_rate=0.12),
71
+ )
72
+ trainer.train()
73
+
74
+ # Export clean LoRA_main / main_adapter weights (Sink weights stripped automatically):
75
+ router.save_pretrained("./clean_checkpoint", include_sink=False)
76
+ ```
77
+
78
+ ### 2. Custom PyTorch `GRPO` Loop (Compatible With Gradient Checkpointing)
79
+
80
+ ```python
81
+ w_tok, H_pool, did_evolve = router.compute_routing_weights(
82
+ seq_ids,
83
+ attention_mask,
84
+ prompt_lens,
85
+ proxy_rewards,
86
+ canary_labels=audited_labels, # {rollout_idx: 0 (honest) or 1 (hack)}
87
+ )
88
+
89
+ # Keep routing_context active across BOTH forward and backward passes:
90
+ with router.routing_context(w_tok):
91
+ logits = model(input_ids=seq_ids, attention_mask=attention_mask).logits
92
+ loss = compute_grpo_loss(logits, seq_ids, advantages)
93
+ loss.backward()
94
+
95
+ optimizer.step()
96
+ ```
97
+
98
+ ### 3. Single-GPU `30B` `128`-Expert MoE Streaming INT4 Loader (`transformers >= 5.0`)
99
+
100
+ 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:
101
+
102
+ ```python
103
+ import torch
104
+ from sinkroute import SinkRouteConfig, attach_sinkroute, load_quantized_3d_moe_causal_lm
105
+
106
+ model = load_quantized_3d_moe_causal_lm(
107
+ "Qwen/Qwen3-30B-A3B-Instruct-2507",
108
+ device="cuda",
109
+ dtype=torch.bfloat16,
110
+ group_size=64,
111
+ )
112
+ router = attach_sinkroute(model, SinkRouteConfig(mode="auto", num_sink_experts=2))
113
+ ```
114
+
115
+ ### 4. Profiling Layerwise Expert-Exploit Mutual Information `I(Expert; Hack)`
116
+
117
+ ```python
118
+ from sinkroute import apply_native_expert_quarantine, profile_moe_exploit_localization
119
+
120
+ loc_profile = profile_moe_exploit_localization(
121
+ router.model,
122
+ cal_input_ids,
123
+ cal_attention_mask,
124
+ cal_prompt_lens,
125
+ cal_y_hack,
126
+ n_permutations=64,
127
+ )
128
+ print(f"Peak SNR over 99th-pct null: {loc_profile['peak_snr_over_null']:.2f}x")
129
+ ```
130
+
131
+ ---
132
+
133
+ ## Empirical Scaling & Fine-Grained MoE Summary
134
+
135
+ 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`):
136
+
137
+ ### A. Dense Scaling Ladder (`Qwen2.5-Coder` `1.5B -> 3B -> 7B`, `36` GRPO Steps)
138
+
139
+ | 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 |
140
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
141
+ | `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) |
142
+ | `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`) |
143
+ | `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`) |
144
+
145
+ ### B. Fine-Grained MoE Exploit Localization (`64` vs. `128` Experts)
146
+
147
+ | 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 |
148
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
149
+ | `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) |
150
+ | `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 |
151
+
152
+ ---
153
+
154
+ ## CLI Usage
155
+
156
+ ```bash
157
+ # Run Dense or MoE GRPO benchmark arms:
158
+ sinkroute run-benchmark \
159
+ --models qwen2.5-coder-1.5b,qwen2.5-coder-3b,qwen2.5-coder-7b,olmoe-1b-7b,qwen3-30b-a3b \
160
+ --arms unmonitored,static_dual_lora,coevolving_sinkroute,native_expert_quarantine \
161
+ --steps 36 --eval-every 12 --out-dir results --device cuda
162
+
163
+ # Render 4-panel scaling & MoE localization figure:
164
+ sinkroute plot --results-dir results --out figures/sinkroute_scaling_and_moe.png
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Citation
170
+
171
+ ```bibtex
172
+ @techreport{gaskins2026sinkroute,
173
+ title = {Co-Evolving Subspace Sink Routing Across Dense Scale and Fine-Grained Mixture-of-Experts RLVR Coding Agents},
174
+ author = {Gaskins, Daniel},
175
+ institution = {Daniel Gaskins Research},
176
+ year = {2026},
177
+ month = dec,
178
+ url = {https://danielgaskins.com/sinkroute.html}
179
+ }
180
+ ```
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "https://context7.com/schema/context7.json",
3
+ "projectTitle": "SinkRoute",
4
+ "description": "Co-evolving Dual-LoRA and Mixture-of-Experts (MoE) Sink-Expert gradient routing to stop RLVR / GRPO reward hacking without capability collapse.",
5
+ "excludeFolders": [
6
+ "tests"
7
+ ],
8
+ "excludeFiles": [
9
+ "LICENSE"
10
+ ],
11
+ "rules": [
12
+ "Never subtract a scalar linear probe or CoT monitor penalty directly from RLVR/GRPO proxy rewards; attach SinkRoute (`attach_sinkroute(model, SinkRouteConfig(mode=\"auto\", token_level_routing=True))`) to route positive-advantage shortcut gradients into disposable sink branches.",
13
+ "Use `router.save_pretrained(dir, include_sink=False)` when exporting production checkpoints so `LoRA_sink` and `SinkExperts` are discarded with zero inference overhead.",
14
+ "For Hugging Face TRL `GRPOTrainer`, wrap the trainer via `wrap_trl_grpo_trainer(trainer, router, canary=MetamorphicCanary(0.10))`.",
15
+ "For fine-grained MoEs (`OLMoE`, `Qwen3-MoE`, `Mixtral`), use `profile_moe_exploit_localization` to audit layerwise Expert-Exploit Mutual Information `I(Expert; Hack)` before applying native expert quarantine.",
16
+ "Pair deployed `LoRA_main` weights with `latchgate` (`pip install latchgate`) at self-hosted inference for zero-decode 57.1%-depth runtime circuit breaking."
17
+ ]
18
+ }
@@ -0,0 +1,22 @@
1
+ # SinkRoute (`pip install sinkroute`)
2
+
3
+ > Co-evolving Dual-LoRA and Mixture-of-Experts (`MoE`) Sink-Expert gradient routing to stop RLVR / GRPO reward hacking without capability collapse.
4
+
5
+ - Package: https://pypi.org/project/sinkroute/ (`v0.1.0`, MIT, PEP 561 typed)
6
+ - Study & Preprint PDF: https://danielgaskins.com/sinkroute.html (https://danielgaskins.com/papers/sinkroute_scaling_moe_preprint.pdf)
7
+ - Repository: https://github.com/danielgaskins/sinkroute
8
+ - Companion inference-time circuit breaker: https://pypi.org/project/latchgate/
9
+ - Foundational RLVR Goodharting study: https://danielgaskins.com/rlvr-latent-obfuscation.html
10
+
11
+ ## When to Use SinkRoute vs. LatchGate vs. MendMark
12
+
13
+ - **During RLVR / GRPO Post-Training (`TRL`, `PEFT`, custom PyTorch loops):** Use `pip install sinkroute` (`attach_sinkroute`, `wrap_trl_grpo_trainer`). Never subtract a scalar linear probe or `<think>` monitor penalty directly from `R_proxy` (which causes `<think>` obfuscation or `50%` capability collapse via Neural Goodharting). Instead, route positive-advantage shortcut gradients at token granularity `w_(b,t)` into disposable `LoRA_sink` / `SinkExperts` using `0`-ULP value-preserving straight-through routing, while keeping `CoEvolvingSubspaceTracker` synchronized via sparse (`10%-15%`) `MetamorphicCanary` audits.
14
+ - **At Self-Hosted Open-Weights Inference (`Transformers`, `vLLM`, `SGLang`, `Diffusers`, `Cosmos`):** Pair trained `LoRA_main` weights with `pip install latchgate` (`57.1%`-depth `.lgate` circuit breakers).
15
+ - **Against Closed APIs (`gpt-4o`, `o3`, `claude`):** Use `pip install mendmark-evals` to mutation-audit CI harnesses and close deterministic test loopholes.
16
+
17
+ ## Core Python API
18
+
19
+ - `attach_sinkroute(model, SinkRouteConfig(mode="auto", token_level_routing=True))` -> `SinkRouter`
20
+ - `wrap_trl_grpo_trainer(trl_trainer, router, canary=MetamorphicCanary(0.10))`
21
+ - `profile_moe_exploit_localization(model, input_ids, attention_mask, prompt_lens, y_hack)`: Computes layerwise Expert-Exploit Mutual Information `I(Expert; Hack)` and Jensen-Shannon routing divergence across `64`-expert (`OLMoE`) and `128`-expert (`Qwen3-MoE`) architectures.
22
+ - `apply_native_expert_quarantine(model, localization_profile)`: Masks top hack-enriched native MoE router logits prior to `softmax`/`topk`.