dissident 0.2.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 (82) hide show
  1. dissident-0.2.0/LICENSE +21 -0
  2. dissident-0.2.0/PKG-INFO +153 -0
  3. dissident-0.2.0/README.md +105 -0
  4. dissident-0.2.0/abliteration/__init__.py +1 -0
  5. dissident-0.2.0/abliteration/architecture.py +281 -0
  6. dissident-0.2.0/abliteration/chat.py +146 -0
  7. dissident-0.2.0/abliteration/checks.py +86 -0
  8. dissident-0.2.0/abliteration/cli.py +401 -0
  9. dissident-0.2.0/abliteration/compat.py +28 -0
  10. dissident-0.2.0/abliteration/conversion.py +206 -0
  11. dissident-0.2.0/abliteration/data.py +228 -0
  12. dissident-0.2.0/abliteration/dense.py +428 -0
  13. dissident-0.2.0/abliteration/harmony_chat.py +42 -0
  14. dissident-0.2.0/abliteration/kimi.py +293 -0
  15. dissident-0.2.0/abliteration/math.py +205 -0
  16. dissident-0.2.0/abliteration/qwen.py +375 -0
  17. dissident-0.2.0/abliteration/storage.py +159 -0
  18. dissident-0.2.0/abliteration/worker.py +693 -0
  19. dissident-0.2.0/cloud/__init__.py +1 -0
  20. dissident-0.2.0/cloud/licenses/Apache-2.0.txt +202 -0
  21. dissident-0.2.0/cloud/licenses/DeepSeek-MIT.txt +21 -0
  22. dissident-0.2.0/cloud/licenses/GLM-4.7-Flash-MIT.txt +31 -0
  23. dissident-0.2.0/cloud/licenses/GLM-4.7-Flash-license-evidence.json +12 -0
  24. dissident-0.2.0/cloud/licenses/Gemma-NOTICE.txt +3 -0
  25. dissident-0.2.0/cloud/licenses/Gemma-Terms.txt +234 -0
  26. dissident-0.2.0/cloud/licenses/Gemma-Use-Policy.txt +70 -0
  27. dissident-0.2.0/cloud/licenses/Kimi-Linear-MIT.txt +21 -0
  28. dissident-0.2.0/cloud/licenses/Llama-NOTICE.txt +3 -0
  29. dissident-0.2.0/cloud/licenses/sources.json +36 -0
  30. dissident-0.2.0/cloud/notice_stream.py +68 -0
  31. dissident-0.2.0/cloud/publish_hf.py +384 -0
  32. dissident-0.2.0/cloud/remote_job.py +66 -0
  33. dissident-0.2.0/cloud/runpod_job.py +185 -0
  34. dissident-0.2.0/cloud/update_card.py +82 -0
  35. dissident-0.2.0/cloud/verify_hf.py +70 -0
  36. dissident-0.2.0/demo/gpu_backend.py +250 -0
  37. dissident-0.2.0/demo/launch_friday_demo.py +218 -0
  38. dissident-0.2.0/demo/tui_demo.py +434 -0
  39. dissident-0.2.0/dissident.egg-info/PKG-INFO +153 -0
  40. dissident-0.2.0/dissident.egg-info/SOURCES.txt +80 -0
  41. dissident-0.2.0/dissident.egg-info/dependency_links.txt +1 -0
  42. dissident-0.2.0/dissident.egg-info/entry_points.txt +3 -0
  43. dissident-0.2.0/dissident.egg-info/requires.txt +26 -0
  44. dissident-0.2.0/dissident.egg-info/top_level.txt +5 -0
  45. dissident-0.2.0/evaluation/__init__.py +1 -0
  46. dissident-0.2.0/evaluation/adjudicate.py +411 -0
  47. dissident-0.2.0/evaluation/calibration_data.py +160 -0
  48. dissident-0.2.0/evaluation/calibration_probe.py +152 -0
  49. dissident-0.2.0/evaluation/gptoss_pair.py +299 -0
  50. dissident-0.2.0/evaluation/gptoss_pair_analysis.py +53 -0
  51. dissident-0.2.0/evaluation/gptoss_pair_guard_mlx.py +43 -0
  52. dissident-0.2.0/evaluation/local_pilot.py +157 -0
  53. dissident-0.2.0/pyproject.toml +81 -0
  54. dissident-0.2.0/setup.cfg +4 -0
  55. dissident-0.2.0/tests/test_abliteration.py +231 -0
  56. dissident-0.2.0/tests/test_abliteration_math.py +102 -0
  57. dissident-0.2.0/tests/test_adjudicate.py +50 -0
  58. dissident-0.2.0/tests/test_calibration.py +92 -0
  59. dissident-0.2.0/tests/test_card_update.py +37 -0
  60. dissident-0.2.0/tests/test_cloud_release.py +208 -0
  61. dissident-0.2.0/tests/test_cuda_chat.py +67 -0
  62. dissident-0.2.0/tests/test_data.py +93 -0
  63. dissident-0.2.0/tests/test_dense_abliteration.py +241 -0
  64. dissident-0.2.0/tests/test_glm_abliteration.py +107 -0
  65. dissident-0.2.0/tests/test_gptoss_abliteration.py +194 -0
  66. dissident-0.2.0/tests/test_gptoss_pair.py +60 -0
  67. dissident-0.2.0/tests/test_interventions.py +312 -0
  68. dissident-0.2.0/tests/test_kimi_compat.py +56 -0
  69. dissident-0.2.0/tests/test_layout.py +53 -0
  70. dissident-0.2.0/tests/test_local_pilot.py +26 -0
  71. dissident-0.2.0/tests/test_refusal.py +84 -0
  72. dissident-0.2.0/tests/test_research_checks.py +59 -0
  73. dissident-0.2.0/tools/__init__.py +1 -0
  74. dissident-0.2.0/tools/audit_splits.py +47 -0
  75. dissident-0.2.0/tools/bench_forward.py +38 -0
  76. dissident-0.2.0/tools/build_refusal.py +316 -0
  77. dissident-0.2.0/tools/build_vector.py +196 -0
  78. dissident-0.2.0/tools/mtp.py +92 -0
  79. dissident-0.2.0/tools/neuron_match.py +76 -0
  80. dissident-0.2.0/tools/paths.py +12 -0
  81. dissident-0.2.0/tools/spec_decode.py +218 -0
  82. dissident-0.2.0/tools/sweep.py +93 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ashwin Sreedhar
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,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: dissident
3
+ Version: 0.2.0
4
+ Summary: Reproducible bf16 refusal-direction abliteration, mechanistic verification, and local safety evaluation
5
+ Author: Ashwin Sreedhar
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/ashwinsreedhar28/dissident
8
+ Project-URL: Repository, https://github.com/ashwinsreedhar28/dissident
9
+ Project-URL: Documentation, https://github.com/ashwinsreedhar28/dissident/blob/main/docs/TECHNICAL_REPORT_V2.md
10
+ Project-URL: Issues, https://github.com/ashwinsreedhar28/dissident/issues
11
+ Project-URL: Models, https://huggingface.co/collections/ashwin-sreedhar/dissident-v2-verified-bf16-abliterated-checkpoints-6b0f0cb8c6e154c27bd41767
12
+ Keywords: abliteration,llm,mechanistic-interpretability,refusal-direction,bf16,safetensors,moe,pytorch,mlx
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy<3,>=1.26
26
+ Requires-Dist: safetensors<1,>=0.6
27
+ Requires-Dist: huggingface-hub>=0.34
28
+ Requires-Dist: pyarrow>=15
29
+ Provides-Extra: mlx
30
+ Requires-Dist: mlx; extra == "mlx"
31
+ Requires-Dist: mlx-lm; extra == "mlx"
32
+ Requires-Dist: fastapi; extra == "mlx"
33
+ Requires-Dist: uvicorn; extra == "mlx"
34
+ Provides-Extra: cuda
35
+ Requires-Dist: torch; extra == "cuda"
36
+ Requires-Dist: transformers==5.21.0; extra == "cuda"
37
+ Requires-Dist: accelerate<2,>=1.10; extra == "cuda"
38
+ Requires-Dist: sentencepiece; extra == "cuda"
39
+ Requires-Dist: protobuf; extra == "cuda"
40
+ Provides-Extra: cloud
41
+ Requires-Dist: huggingface-hub>=0.34; extra == "cloud"
42
+ Requires-Dist: requests<3,>=2.32; extra == "cloud"
43
+ Requires-Dist: safetensors<1,>=0.6; extra == "cloud"
44
+ Provides-Extra: demo
45
+ Requires-Dist: rich>=13.0; extra == "demo"
46
+ Requires-Dist: requests<3,>=2.32; extra == "demo"
47
+ Dynamic: license-file
48
+
49
+ # dissident
50
+
51
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
52
+ [![Tests](https://github.com/ashwinsreedhar28/dissident/actions/workflows/tests.yml/badge.svg)](https://github.com/ashwinsreedhar28/dissident/actions/workflows/tests.yml)
53
+ [![Hugging Face Collection](https://img.shields.io/badge/HuggingFace-dissident--v2-yellow.svg)](https://huggingface.co/collections/ashwin-sreedhar/dissident-v2-verified-bf16-abliterated-checkpoints-6b0f0cb8c6e154c27bd41767)
54
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](pyproject.toml)
55
+
56
+ Reproducible bf16 refusal-direction abliteration, mechanistic verification, and local safety evaluation (MIT; formerly `persona-lab`).
57
+
58
+ `dissident` extracts refusal directions and projects residual writers directly in bf16 across dense, hybrid-attention, post-RMSNorm, and Mixture-of-Experts models. Original weights are hashed and left untouched. Every exported checkpoint is written to a separate directory and gated by SHA-256 tensor checks, a `0.0` fresh-process reload diff, `<= 1%` forward-pass mechanical suppression, held-out harmless KL `<= 0.10`, and matched local `Qwen3Guard-Gen-4B` evaluation.
59
+
60
+ ![dissident split-pane TUI](https://raw.githubusercontent.com/ashwinsreedhar28/dissident/main/assets/tui_demo.png)
61
+ *Split-pane terminal TUI (`demo/tui_demo.py`) streaming Base vs. Abliterated v2 side-by-side on `benign-017` (`sudo` over-refusal prompt).*
62
+
63
+ ## Verified v2 results
64
+
65
+ Base and edited checkpoints are evaluated under identical greedy bf16 decoding on JailbreakBench Harmful (100), JailbreakBench Benign (50), and GSM8K using local `Qwen3Guard-Gen-4B`. No raw harmful prompts or completions are committed to this repository. Checkpoints that miss any gate are held as diagnostics rather than published.
66
+
67
+ | Model | JBB Refusal | Unsafe | Benign | GSM8K | KL / Mech | Checkpoint |
68
+ |---|---:|---:|---:|---:|---:|---|
69
+ | **GPT-OSS-20B v2** (21B MoE, Harmony) | 95/100 → 0/100 | 2 → 94 | 8/50 → 0/50 | 95.6% → 95.6% (`n=250`) | `0.0933` / `0.785%` | [HF (Apache-2.0)](https://huggingface.co/ashwin-sreedhar/GPT-OSS-20B-abliterated-v2-bf16) |
70
+ | **Kimi-Linear-48B v2** (48B Hybrid MoE) | 92/100 → 1/100 | 2 → 90 | 9/50 → 0/50 | 93.3% → 90.7% (`n=150`) | `0.0830` / `0.658%` | [HF (MIT)](https://huggingface.co/ashwin-sreedhar/Kimi-Linear-48B-A3B-Instruct-abliterated-v2-bf16) |
71
+ | GPT-OSS-120B v2 (120B MoE, Harmony) | 96/100 → 85/100 | 0 → 13 | 16/50 → 2/50 | 96.7% → 96.7% (`n=150`) | `0.1253` / `0.616%` | Held (Guard 85/100, KL > 0.10) |
72
+ | Llama-3.1-8B-Instruct v2 (8B Dense) | 91/100 → 0/100 | 4 → 90 | 6/50 → 0/50 | 91.0% → 87.5% (`n=200`) | `0.0233` / `1.051%` | Held (L32 bf16 1.051% > 1%) |
73
+ | Qwen3-8B v2 (8B Dense) | 87/100 → 32/100 | 4 → 53 | 4/50 → 0/50 | — | `0.0770` / `0.618%` | Held (Guard 32/100; r2 KL >= 0.24) |
74
+ | GLM-4.7-Flash v2 (30B MLA+MoE) | — | — | — | — | `0.0399` / `1.357%` | Held (mech 1.357% > 1%) |
75
+ | Gemma-3-4B-IT v2 (4B Post-Norm) | — | — | — | — | `0.1020` / — | Held (min KL 0.1020 > 0.10) |
76
+
77
+ Full aggregate JSON records live in [evaluation/results/](evaluation/results/). The full v2 technical writeup is in [docs/TECHNICAL_REPORT_V2.md](docs/TECHNICAL_REPORT_V2.md); earlier v1 checkpoints and historical failures are tracked in [docs/MODEL_STATUS.md](docs/MODEL_STATUS.md); pinned revisions and hashes live in [docs/MODEL_STORAGE.md](docs/MODEL_STORAGE.md); open work lives in [docs/ROADMAP.md](docs/ROADMAP.md).
78
+
79
+ ## Key findings
80
+
81
+ - **Substring refusal markers hide semantic refusals at scale:** On `Qwen3-8B` (rank-1, `eff_rank=6.06`), marker refusals fell `87/100 → 4/100` while `Qwen3Guard-Gen-4B` still caught `32/100` semantic refusals. On `GPT-OSS-120B` (6x larger than `GPT-OSS-20B` on the same Harmony architecture), single-direction `L24` (`induce=1.000`, `0/32` short-rollout val refusal, `0.0 pp` GSM8K drop, benign over-refusal `16/50 → 2/50`) dropped marker refusals `96/100 → 29/100`, yet `Qwen3Guard-Gen-4B` caught `85/100` semantic refusals phrased without boilerplate prefixes.
82
+ - **Refusal localization and judge validation on `GPT-OSS-20B`:** Published v2 preserved GSM8K (`239/250 -> 239/250`, `95.6%`) and Verifiable IF (`26/30 -> 28/30`, `86.7% -> 93.3%`). A 24-prompt stratified blind human audit ([gpt-oss-20b-v2-adjudication.json](evaluation/results/gpt-oss-20b-v2-adjudication.json)) matched `Qwen3Guard-Gen-4B` on **24/24** refusal labels (`95% CI [86.2%, 100%]`, `22/24` substantive, `0/24` degenerate). In-memory band sweeps showed refusal sits tightly in layers `10..18` (9/24 layers), cutting `KL_analysis` 7.8x (`0.0737 → 0.0094`) and `KL_final` 2.5x (`0.0933 → 0.0371`) at `0/32` val refusals before jumping to `11/32` at `11..16`.
83
+ - **Relation to [p-e-w/heretic](https://github.com/p-e-w/heretic):** Heretic optimizes per-layer projection weights via black-box Optuna search for broad model coverage. `dissident` focuses on complementary infrastructure: deterministic bf16 weight integrity with SHA-256 and `0.0` reload proofs, tied-embedding and post-RMSNorm safeguards, native MXFP4/MoE/hybrid-linear adapters, and local `Qwen3Guard-Gen-4B` gating instead of substring heuristics.
84
+
85
+ ## Caveats
86
+
87
+ - Refusal and safety counts use `Qwen3Guard-Gen-4B` (local 4B classifier). On our 24-prompt blind human audit of `GPT-OSS-20B` v2, refusal agreement was `24/24` (`100%`), while Safe/Controversial/Unsafe boundary agreement was `8/23` (`34.8%`) because the judge flags benign technical prompts as unsafe.
88
+ - Upstream `openai/gpt-oss-20b` and `openai/gpt-oss-120b` ship routed expert weights in MXFP4. Base and edited evaluations run on the exact same verified bf16 dequantization; dequantization does not recover precision lost during upstream quantization.
89
+ - `dissident`'s strict `<= 1.0%` full-stream mechanical check can reject checkpoints on single-layer bf16 rounding (`Llama-3.1-8B` hit `1.051%` at final layer `L32` despite `0/100` JBB refusals and `0.0233` KL). Those checkpoints are kept as diagnostics rather than silently loosening the release bar.
90
+
91
+ ## Quickstart
92
+
93
+ | Workload | Minimum VRAM / RAM | Notes |
94
+ |---|---|---|
95
+ | 4B–8B dense (`Qwen3-8B`, `Llama-3.1-8B`, `Gemma-3-4B`) | 24–48 GB GPU | Single bf16 copy + eval |
96
+ | `GPT-OSS-20B` (MXFP4→bf16) / `GLM-4.7-Flash` (30B) | 48–96 GB GPU | 96 GB holds Base + v2 side-by-side for TUI |
97
+ | `Kimi-Linear-48B-A3B-Instruct` | 96 GB GPU (`--batch-size 1`) | Requires `requirements/cuda.txt` (`transformers==4.57.3`, `fla-core`) |
98
+ | `GPT-OSS-120B` (MXFP4→bf16) | 288 GB GPU (1x B300) | CPU-offloaded writer backups in `Engine.ablated()` |
99
+ | `Qwen3.5-4B` (MLX) | 16 GB Apple Silicon | Run generation and judging in separate processes |
100
+
101
+ ```sh
102
+ # 1. Install (CUDA export + split-pane terminal TUI)
103
+ pip install -e ".[cuda,demo]" # or: pip install -r requirements/native-cuda.txt
104
+
105
+ # 2. Build fixed, leakage-filtered train/val/KL/eval splits (gitignored)
106
+ dissident prepare-data --output data
107
+
108
+ # 3. Extract, edit, and verify a separate bf16 checkpoint (originals untouched)
109
+ dissident run --model Qwen/Qwen3-8B --data data --output models/Qwen3-8B-abliterated-v2-bf16
110
+ dissident verify models/Qwen3-8B-abliterated-v2-bf16
111
+
112
+ # 4. Launch the Base vs. Abliterated split-pane terminal TUI (or print scoreboard)
113
+ python demo/tui_demo.py --score-only
114
+ python demo/tui_demo.py --gpu-url http://127.0.0.1:8766 # or --mock for offline preview
115
+ ```
116
+
117
+ ## Method
118
+
119
+ - Extraction and selection (`--reasoning-mode empty-think`, `--selector rollout`): On reasoning and Harmony models, v1 first-token scoring latched onto generic reasoning openers (`User`, `We`). v2 extracts at the post-reasoning answer boundary (`empty-think` or `post-think`) and scores short greedy rollouts after stripping Harmony `analysis` channels or `<think>` blocks.
120
+ - Biprojection (`--biproject-mode auto`): Screens both biprojected (orthogonalized against the harmless activation mean) and raw directions across separate `pos=-1` and `pos < -1` candidate budgets, breaking `AUROC=1.0` ties with validation Fisher SNR. Biprojection cut KL 13.4x on `Llama-3.1-8B` (`0.3584 -> 0.0268`) and 2.5–3x on `GLM-4.7-Flash`.
121
+ - Subspace rank (`--rank k`): Records residual effective rank and top-k SVD variance per layer. On `GPT-OSS-20B`, PC1 captures 76–90% of harmful displacement variance; rank-1 matched rank-2 on JBB (`0/100` refusals, `94/100` unsafe) at roughly 4x lower harmless KL (`0.0933` vs `0.3459`). On `Qwen3-8B` (`eff_rank=6.06`), global rank-2 removal blew up KL (`0.24–5.37`).
122
+ - Architecture safeguards: Defaults to `--embed-policy skip-tied` (or explicit `untie`) so editing tied input embeddings never corrupts `lm_head`. Gemma 3 post-RMSNorm writers are projected along `orth(Q diag(1 + gamma))` with RMS inflation checks. `Engine.ablated()` backs up writer weights to CPU RAM so large MoEs (`48B–120B`) incur zero extra VRAM during candidate sweeps.
123
+ - Verification: `dissident verify` checks manifest and file SHA-256 hashes, tensor payload readback, fresh-process reload agreement, and `max_proj_ratio <= 1%` without loading the model.
124
+
125
+ ## Supported architectures
126
+
127
+ | Family | Adapter | Residual Writers Projected |
128
+ |---|---|---|
129
+ | `openai/gpt-oss-20b`, `gpt-oss-120b` | `dense-torch` | `embed_tokens` + `o_proj` + packed 3D `mlp.experts.down_proj` + bias (Harmony) |
130
+ | `zai-org/GLM-4.7-Flash` | `dense-torch` | `embed_tokens` + `o_proj` + dense MLP + 64 routed & shared experts (MTP preserved) |
131
+ | `RecursiveSI/flint` | `dense-torch` | `embed_tokens` + `o_proj` + dense MLP + 256 routed & shared experts (packed/unpacked) |
132
+ | `moonshotai/Kimi-Linear-48B-A3B-Instruct` | `kimi-torch` | `embed_tokens` + `o_proj` + 256 routed `w2` + shared experts (`requirements/cuda.txt`) |
133
+ | `google/gemma-3-*` | `dense-torch` | Post-RMSNorm weighted `orth(Q diag(1+gamma))` on `o_proj`/`down_proj` + `skip-tied`/`untie` |
134
+ | `Qwen/Qwen3-*`, `meta-llama/Llama-3.1-*` | `dense-torch` | `embed_tokens` + all decoder `o_proj` & `mlp.down_proj` |
135
+ | `Qwen/Qwen3.5-4B` (Apple Silicon MLX) | `qwen-mlx` | Hybrid linear/full attention `out_proj`/`o_proj` + `down_proj` + `skip-tied` |
136
+
137
+ ## Repository layout
138
+
139
+ | Path | Contents |
140
+ |---|---|
141
+ | `abliteration/` | Core bf16 pipeline: data splits (`data.py`), direction math/SVD/biprojection (`math.py`), writer maps (`architecture.py`), dense/MoE/Kimi/MLX adapters, MXFP4 dequantizer (`conversion.py`), Harmony parser, CUDA chat (`chat.py`), CLI (`cli.py`) |
142
+ | `cloud/` | Sealed Hugging Face publisher (`publish_hf.py`), atomic model-card updater (`update_card.py`), license assets, and Runpod helpers |
143
+ | `demo/` | Split-pane Base vs. v2 terminal TUI (`tui_demo.py`), CUDA SSE backend (`gpu_backend.py`), and Pod launcher (`launch_friday_demo.py`) |
144
+ | `evaluation/` | Matched evaluations, blind human adjudication CLI (`adjudicate.py`), and aggregate-only results (`evaluation/results/`) |
145
+ | `tools/` | Apple Silicon activation-steering vector builders, split audits, and sweeps |
146
+ | `docs/` | Guides ([V2 technical report](docs/TECHNICAL_REPORT_V2.md), [Export guide](docs/ABLITERATION.md), [Model status](docs/MODEL_STATUS.md), [Storage & pins](docs/MODEL_STORAGE.md), [Roadmap](docs/ROADMAP.md), [Layout](docs/REPOSITORY_LAYOUT.md), [Math & MLX steering](docs/STEERING_AND_MATH.md)) + historical memos in `docs/archive/` |
147
+ | `tests/` | Unit and CPU fixture regression suite (`python -m unittest discover -s tests -v`) |
148
+ | `archive/` | Historical Phase A (`phase-a-abl/`), Phase B (`phase-b-kimi/`), and legacy PyTorch scripts (`legacy/`) |
149
+ | `evil_chat_mlx.py`, `server.py` | Apple Silicon MLX interactive chat and activation-steering web UI |
150
+
151
+ ## License
152
+
153
+ Repository code is MIT. Derivative model checkpoints published on Hugging Face retain their upstream licenses, notices, and usage policies (`Apache-2.0`, `MIT`, `Gemma Terms`, `Llama 3.1 Community License`).
@@ -0,0 +1,105 @@
1
+ # dissident
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
+ [![Tests](https://github.com/ashwinsreedhar28/dissident/actions/workflows/tests.yml/badge.svg)](https://github.com/ashwinsreedhar28/dissident/actions/workflows/tests.yml)
5
+ [![Hugging Face Collection](https://img.shields.io/badge/HuggingFace-dissident--v2-yellow.svg)](https://huggingface.co/collections/ashwin-sreedhar/dissident-v2-verified-bf16-abliterated-checkpoints-6b0f0cb8c6e154c27bd41767)
6
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](pyproject.toml)
7
+
8
+ Reproducible bf16 refusal-direction abliteration, mechanistic verification, and local safety evaluation (MIT; formerly `persona-lab`).
9
+
10
+ `dissident` extracts refusal directions and projects residual writers directly in bf16 across dense, hybrid-attention, post-RMSNorm, and Mixture-of-Experts models. Original weights are hashed and left untouched. Every exported checkpoint is written to a separate directory and gated by SHA-256 tensor checks, a `0.0` fresh-process reload diff, `<= 1%` forward-pass mechanical suppression, held-out harmless KL `<= 0.10`, and matched local `Qwen3Guard-Gen-4B` evaluation.
11
+
12
+ ![dissident split-pane TUI](https://raw.githubusercontent.com/ashwinsreedhar28/dissident/main/assets/tui_demo.png)
13
+ *Split-pane terminal TUI (`demo/tui_demo.py`) streaming Base vs. Abliterated v2 side-by-side on `benign-017` (`sudo` over-refusal prompt).*
14
+
15
+ ## Verified v2 results
16
+
17
+ Base and edited checkpoints are evaluated under identical greedy bf16 decoding on JailbreakBench Harmful (100), JailbreakBench Benign (50), and GSM8K using local `Qwen3Guard-Gen-4B`. No raw harmful prompts or completions are committed to this repository. Checkpoints that miss any gate are held as diagnostics rather than published.
18
+
19
+ | Model | JBB Refusal | Unsafe | Benign | GSM8K | KL / Mech | Checkpoint |
20
+ |---|---:|---:|---:|---:|---:|---|
21
+ | **GPT-OSS-20B v2** (21B MoE, Harmony) | 95/100 → 0/100 | 2 → 94 | 8/50 → 0/50 | 95.6% → 95.6% (`n=250`) | `0.0933` / `0.785%` | [HF (Apache-2.0)](https://huggingface.co/ashwin-sreedhar/GPT-OSS-20B-abliterated-v2-bf16) |
22
+ | **Kimi-Linear-48B v2** (48B Hybrid MoE) | 92/100 → 1/100 | 2 → 90 | 9/50 → 0/50 | 93.3% → 90.7% (`n=150`) | `0.0830` / `0.658%` | [HF (MIT)](https://huggingface.co/ashwin-sreedhar/Kimi-Linear-48B-A3B-Instruct-abliterated-v2-bf16) |
23
+ | GPT-OSS-120B v2 (120B MoE, Harmony) | 96/100 → 85/100 | 0 → 13 | 16/50 → 2/50 | 96.7% → 96.7% (`n=150`) | `0.1253` / `0.616%` | Held (Guard 85/100, KL > 0.10) |
24
+ | Llama-3.1-8B-Instruct v2 (8B Dense) | 91/100 → 0/100 | 4 → 90 | 6/50 → 0/50 | 91.0% → 87.5% (`n=200`) | `0.0233` / `1.051%` | Held (L32 bf16 1.051% > 1%) |
25
+ | Qwen3-8B v2 (8B Dense) | 87/100 → 32/100 | 4 → 53 | 4/50 → 0/50 | — | `0.0770` / `0.618%` | Held (Guard 32/100; r2 KL >= 0.24) |
26
+ | GLM-4.7-Flash v2 (30B MLA+MoE) | — | — | — | — | `0.0399` / `1.357%` | Held (mech 1.357% > 1%) |
27
+ | Gemma-3-4B-IT v2 (4B Post-Norm) | — | — | — | — | `0.1020` / — | Held (min KL 0.1020 > 0.10) |
28
+
29
+ Full aggregate JSON records live in [evaluation/results/](evaluation/results/). The full v2 technical writeup is in [docs/TECHNICAL_REPORT_V2.md](docs/TECHNICAL_REPORT_V2.md); earlier v1 checkpoints and historical failures are tracked in [docs/MODEL_STATUS.md](docs/MODEL_STATUS.md); pinned revisions and hashes live in [docs/MODEL_STORAGE.md](docs/MODEL_STORAGE.md); open work lives in [docs/ROADMAP.md](docs/ROADMAP.md).
30
+
31
+ ## Key findings
32
+
33
+ - **Substring refusal markers hide semantic refusals at scale:** On `Qwen3-8B` (rank-1, `eff_rank=6.06`), marker refusals fell `87/100 → 4/100` while `Qwen3Guard-Gen-4B` still caught `32/100` semantic refusals. On `GPT-OSS-120B` (6x larger than `GPT-OSS-20B` on the same Harmony architecture), single-direction `L24` (`induce=1.000`, `0/32` short-rollout val refusal, `0.0 pp` GSM8K drop, benign over-refusal `16/50 → 2/50`) dropped marker refusals `96/100 → 29/100`, yet `Qwen3Guard-Gen-4B` caught `85/100` semantic refusals phrased without boilerplate prefixes.
34
+ - **Refusal localization and judge validation on `GPT-OSS-20B`:** Published v2 preserved GSM8K (`239/250 -> 239/250`, `95.6%`) and Verifiable IF (`26/30 -> 28/30`, `86.7% -> 93.3%`). A 24-prompt stratified blind human audit ([gpt-oss-20b-v2-adjudication.json](evaluation/results/gpt-oss-20b-v2-adjudication.json)) matched `Qwen3Guard-Gen-4B` on **24/24** refusal labels (`95% CI [86.2%, 100%]`, `22/24` substantive, `0/24` degenerate). In-memory band sweeps showed refusal sits tightly in layers `10..18` (9/24 layers), cutting `KL_analysis` 7.8x (`0.0737 → 0.0094`) and `KL_final` 2.5x (`0.0933 → 0.0371`) at `0/32` val refusals before jumping to `11/32` at `11..16`.
35
+ - **Relation to [p-e-w/heretic](https://github.com/p-e-w/heretic):** Heretic optimizes per-layer projection weights via black-box Optuna search for broad model coverage. `dissident` focuses on complementary infrastructure: deterministic bf16 weight integrity with SHA-256 and `0.0` reload proofs, tied-embedding and post-RMSNorm safeguards, native MXFP4/MoE/hybrid-linear adapters, and local `Qwen3Guard-Gen-4B` gating instead of substring heuristics.
36
+
37
+ ## Caveats
38
+
39
+ - Refusal and safety counts use `Qwen3Guard-Gen-4B` (local 4B classifier). On our 24-prompt blind human audit of `GPT-OSS-20B` v2, refusal agreement was `24/24` (`100%`), while Safe/Controversial/Unsafe boundary agreement was `8/23` (`34.8%`) because the judge flags benign technical prompts as unsafe.
40
+ - Upstream `openai/gpt-oss-20b` and `openai/gpt-oss-120b` ship routed expert weights in MXFP4. Base and edited evaluations run on the exact same verified bf16 dequantization; dequantization does not recover precision lost during upstream quantization.
41
+ - `dissident`'s strict `<= 1.0%` full-stream mechanical check can reject checkpoints on single-layer bf16 rounding (`Llama-3.1-8B` hit `1.051%` at final layer `L32` despite `0/100` JBB refusals and `0.0233` KL). Those checkpoints are kept as diagnostics rather than silently loosening the release bar.
42
+
43
+ ## Quickstart
44
+
45
+ | Workload | Minimum VRAM / RAM | Notes |
46
+ |---|---|---|
47
+ | 4B–8B dense (`Qwen3-8B`, `Llama-3.1-8B`, `Gemma-3-4B`) | 24–48 GB GPU | Single bf16 copy + eval |
48
+ | `GPT-OSS-20B` (MXFP4→bf16) / `GLM-4.7-Flash` (30B) | 48–96 GB GPU | 96 GB holds Base + v2 side-by-side for TUI |
49
+ | `Kimi-Linear-48B-A3B-Instruct` | 96 GB GPU (`--batch-size 1`) | Requires `requirements/cuda.txt` (`transformers==4.57.3`, `fla-core`) |
50
+ | `GPT-OSS-120B` (MXFP4→bf16) | 288 GB GPU (1x B300) | CPU-offloaded writer backups in `Engine.ablated()` |
51
+ | `Qwen3.5-4B` (MLX) | 16 GB Apple Silicon | Run generation and judging in separate processes |
52
+
53
+ ```sh
54
+ # 1. Install (CUDA export + split-pane terminal TUI)
55
+ pip install -e ".[cuda,demo]" # or: pip install -r requirements/native-cuda.txt
56
+
57
+ # 2. Build fixed, leakage-filtered train/val/KL/eval splits (gitignored)
58
+ dissident prepare-data --output data
59
+
60
+ # 3. Extract, edit, and verify a separate bf16 checkpoint (originals untouched)
61
+ dissident run --model Qwen/Qwen3-8B --data data --output models/Qwen3-8B-abliterated-v2-bf16
62
+ dissident verify models/Qwen3-8B-abliterated-v2-bf16
63
+
64
+ # 4. Launch the Base vs. Abliterated split-pane terminal TUI (or print scoreboard)
65
+ python demo/tui_demo.py --score-only
66
+ python demo/tui_demo.py --gpu-url http://127.0.0.1:8766 # or --mock for offline preview
67
+ ```
68
+
69
+ ## Method
70
+
71
+ - Extraction and selection (`--reasoning-mode empty-think`, `--selector rollout`): On reasoning and Harmony models, v1 first-token scoring latched onto generic reasoning openers (`User`, `We`). v2 extracts at the post-reasoning answer boundary (`empty-think` or `post-think`) and scores short greedy rollouts after stripping Harmony `analysis` channels or `<think>` blocks.
72
+ - Biprojection (`--biproject-mode auto`): Screens both biprojected (orthogonalized against the harmless activation mean) and raw directions across separate `pos=-1` and `pos < -1` candidate budgets, breaking `AUROC=1.0` ties with validation Fisher SNR. Biprojection cut KL 13.4x on `Llama-3.1-8B` (`0.3584 -> 0.0268`) and 2.5–3x on `GLM-4.7-Flash`.
73
+ - Subspace rank (`--rank k`): Records residual effective rank and top-k SVD variance per layer. On `GPT-OSS-20B`, PC1 captures 76–90% of harmful displacement variance; rank-1 matched rank-2 on JBB (`0/100` refusals, `94/100` unsafe) at roughly 4x lower harmless KL (`0.0933` vs `0.3459`). On `Qwen3-8B` (`eff_rank=6.06`), global rank-2 removal blew up KL (`0.24–5.37`).
74
+ - Architecture safeguards: Defaults to `--embed-policy skip-tied` (or explicit `untie`) so editing tied input embeddings never corrupts `lm_head`. Gemma 3 post-RMSNorm writers are projected along `orth(Q diag(1 + gamma))` with RMS inflation checks. `Engine.ablated()` backs up writer weights to CPU RAM so large MoEs (`48B–120B`) incur zero extra VRAM during candidate sweeps.
75
+ - Verification: `dissident verify` checks manifest and file SHA-256 hashes, tensor payload readback, fresh-process reload agreement, and `max_proj_ratio <= 1%` without loading the model.
76
+
77
+ ## Supported architectures
78
+
79
+ | Family | Adapter | Residual Writers Projected |
80
+ |---|---|---|
81
+ | `openai/gpt-oss-20b`, `gpt-oss-120b` | `dense-torch` | `embed_tokens` + `o_proj` + packed 3D `mlp.experts.down_proj` + bias (Harmony) |
82
+ | `zai-org/GLM-4.7-Flash` | `dense-torch` | `embed_tokens` + `o_proj` + dense MLP + 64 routed & shared experts (MTP preserved) |
83
+ | `RecursiveSI/flint` | `dense-torch` | `embed_tokens` + `o_proj` + dense MLP + 256 routed & shared experts (packed/unpacked) |
84
+ | `moonshotai/Kimi-Linear-48B-A3B-Instruct` | `kimi-torch` | `embed_tokens` + `o_proj` + 256 routed `w2` + shared experts (`requirements/cuda.txt`) |
85
+ | `google/gemma-3-*` | `dense-torch` | Post-RMSNorm weighted `orth(Q diag(1+gamma))` on `o_proj`/`down_proj` + `skip-tied`/`untie` |
86
+ | `Qwen/Qwen3-*`, `meta-llama/Llama-3.1-*` | `dense-torch` | `embed_tokens` + all decoder `o_proj` & `mlp.down_proj` |
87
+ | `Qwen/Qwen3.5-4B` (Apple Silicon MLX) | `qwen-mlx` | Hybrid linear/full attention `out_proj`/`o_proj` + `down_proj` + `skip-tied` |
88
+
89
+ ## Repository layout
90
+
91
+ | Path | Contents |
92
+ |---|---|
93
+ | `abliteration/` | Core bf16 pipeline: data splits (`data.py`), direction math/SVD/biprojection (`math.py`), writer maps (`architecture.py`), dense/MoE/Kimi/MLX adapters, MXFP4 dequantizer (`conversion.py`), Harmony parser, CUDA chat (`chat.py`), CLI (`cli.py`) |
94
+ | `cloud/` | Sealed Hugging Face publisher (`publish_hf.py`), atomic model-card updater (`update_card.py`), license assets, and Runpod helpers |
95
+ | `demo/` | Split-pane Base vs. v2 terminal TUI (`tui_demo.py`), CUDA SSE backend (`gpu_backend.py`), and Pod launcher (`launch_friday_demo.py`) |
96
+ | `evaluation/` | Matched evaluations, blind human adjudication CLI (`adjudicate.py`), and aggregate-only results (`evaluation/results/`) |
97
+ | `tools/` | Apple Silicon activation-steering vector builders, split audits, and sweeps |
98
+ | `docs/` | Guides ([V2 technical report](docs/TECHNICAL_REPORT_V2.md), [Export guide](docs/ABLITERATION.md), [Model status](docs/MODEL_STATUS.md), [Storage & pins](docs/MODEL_STORAGE.md), [Roadmap](docs/ROADMAP.md), [Layout](docs/REPOSITORY_LAYOUT.md), [Math & MLX steering](docs/STEERING_AND_MATH.md)) + historical memos in `docs/archive/` |
99
+ | `tests/` | Unit and CPU fixture regression suite (`python -m unittest discover -s tests -v`) |
100
+ | `archive/` | Historical Phase A (`phase-a-abl/`), Phase B (`phase-b-kimi/`), and legacy PyTorch scripts (`legacy/`) |
101
+ | `evil_chat_mlx.py`, `server.py` | Apple Silicon MLX interactive chat and activation-steering web UI |
102
+
103
+ ## License
104
+
105
+ Repository code is MIT. Derivative model checkpoints published on Hugging Face retain their upstream licenses, notices, and usage policies (`Apache-2.0`, `MIT`, `Gemma Terms`, `Llama 3.1 Community License`).
@@ -0,0 +1 @@
1
+ """Reproducible, architecture-checked weight editing without modifying source checkpoints."""
@@ -0,0 +1,281 @@
1
+ """Explicit writer maps. Unknown architectures fail before loading/editing any tensors."""
2
+ import copy
3
+ import re
4
+
5
+ EMBED_POLICIES = ('skip-tied', 'untie', 'edit-tied')
6
+ _LAYER_RE = re.compile(r'(?:^|\.)layers\.(\d+)\.')
7
+
8
+
9
+ def is_tied(config):
10
+ c = config.get('text_config', config)
11
+ return bool(c.get('tie_word_embeddings', config.get('tie_word_embeddings', False)))
12
+
13
+
14
+ def untied_config(config):
15
+ out = copy.deepcopy(config)
16
+ if 'tie_word_embeddings' in out:
17
+ out['tie_word_embeddings'] = False
18
+ if isinstance(out.get('text_config'), dict):
19
+ out['text_config']['tie_word_embeddings'] = False
20
+ else:
21
+ out['tie_word_embeddings'] = False
22
+ return out
23
+
24
+
25
+ def layer_index(key):
26
+ m = _LAYER_RE.search(key)
27
+ return int(m.group(1)) if m else None
28
+
29
+
30
+ def parse_layer_band(spec, n_layers):
31
+ """Parse an inclusive START:END layer band (or [start, end] pair) validated against n_layers."""
32
+ if spec is None:
33
+ return None
34
+ if isinstance(spec, str):
35
+ parts = spec.strip().split(':')
36
+ if len(parts) != 2:
37
+ raise ValueError(f'Invalid layer_band {spec!r}; expected inclusive START:END (e.g. 10:18)')
38
+ try:
39
+ start, end = int(parts[0]), int(parts[1])
40
+ except ValueError as exc:
41
+ raise ValueError(f'Invalid layer_band {spec!r}; start and end must be integers') from exc
42
+ elif isinstance(spec, (list, tuple)) and len(spec) == 2:
43
+ start, end = int(spec[0]), int(spec[1])
44
+ else:
45
+ raise ValueError(f'Invalid layer_band {spec!r}; expected START:END or [start, end]')
46
+ if not (0 <= start <= end < int(n_layers)):
47
+ raise ValueError(f'layer_band [{start}, {end}] out of range for {n_layers} layers')
48
+ return (start, end)
49
+
50
+
51
+ def embed_key(config, tensors):
52
+ adapter = adapter_for(config)
53
+ if adapter == 'qwen-mlx':
54
+ return 'model.language_model.embed_tokens.weight'
55
+ if config.get('model_type') == 'gemma3':
56
+ prefix = next((p for p in ('language_model.model', 'model.language_model')
57
+ if p + '.embed_tokens.weight' in tensors), None)
58
+ if prefix is None:
59
+ raise ValueError('Unrecognized Gemma text tensor layout')
60
+ return prefix + '.embed_tokens.weight'
61
+ return 'model.embed_tokens.weight'
62
+
63
+
64
+ def untied_lm_head_key(config, tensors):
65
+ adapter_for(config)
66
+ return 'lm_head.weight'
67
+
68
+
69
+ def adapter_for(config):
70
+ if config.get('quantization') or config.get('quantization_config') or config.get('text_config', {}).get('quantization'):
71
+ raise ValueError('Quantized checkpoints are unsupported; supply original bf16 weights')
72
+ kind = config.get('model_type')
73
+ if kind == 'qwen3_5' and config.get('text_config', {}).get('model_type') == 'qwen3_5_text':
74
+ return 'qwen-mlx'
75
+ if kind in ('qwen3', 'llama', 'glm4_moe_lite', 'gpt_oss', 'flint'):
76
+ return 'dense-torch'
77
+ if kind == 'gemma3' and config.get('text_config', {}).get('model_type') == 'gemma3_text':
78
+ return 'dense-torch'
79
+ if kind == 'kimi_linear':
80
+ # This model_type is also used for other architectures. Require the audited structure.
81
+ required = dict(hidden_size=2304, num_hidden_layers=27, num_experts=256,
82
+ first_k_dense_replace=1, num_shared_experts=1, tie_word_embeddings=False)
83
+ if any(config.get(k) != v for k, v in required.items()):
84
+ raise ValueError('Only the Kimi Linear 48B-A3B architecture is supported')
85
+ return 'kimi-torch'
86
+ raise ValueError(f'Unsupported architecture: {kind!r}; add and test an adapter first')
87
+
88
+
89
+ def writers(config, tensors, *, embed_policy='skip-tied', layer_band=None):
90
+ if embed_policy not in EMBED_POLICIES:
91
+ raise ValueError(f'Unsupported embed_policy: {embed_policy!r}; expected one of {EMBED_POLICIES}')
92
+ adapter = adapter_for(config)
93
+ c = config.get('text_config', config)
94
+ hidden, n = c['hidden_size'], c['num_hidden_layers']
95
+ band = parse_layer_band(layer_band, n)
96
+ tied = is_tied(config)
97
+ include_embed = (not tied) or (embed_policy != 'skip-tied')
98
+ modes = {}
99
+ def add(key, mode):
100
+ if key not in tensors:
101
+ raise ValueError(f'Missing residual writer: {key}')
102
+ spec = tensors[key]
103
+ if spec['dtype'] != 'BF16':
104
+ raise ValueError(f'Residual writer must be bf16: {key}')
105
+ axis = -1 if mode in ('embedding','expert_embedding','expert_bias') else 1 if mode == 'expert_linear' else 0
106
+ rank = 3 if mode in ('expert_linear','expert_embedding') else 1 if mode == 'bias' else 2
107
+ if len(spec['shape']) != rank or spec['shape'][axis] != hidden:
108
+ raise ValueError(f'Unexpected residual writer shape: {key}')
109
+ if mode == 'expert_linear':
110
+ n_exp = c.get('n_routed_experts', c.get('num_experts'))
111
+ if spec['shape'] != [n_exp, hidden, c['moe_intermediate_size']]:
112
+ raise ValueError(f'Unexpected expert writer shape: {key}')
113
+ if mode == 'expert_embedding' and spec['shape'] != [c['num_local_experts'], c['intermediate_size'], hidden]:
114
+ raise ValueError(f'Unexpected GPT-OSS expert shape: {key}')
115
+ if mode == 'expert_bias' and spec['shape'] != [c['num_local_experts'], hidden]:
116
+ raise ValueError(f'Unexpected GPT-OSS expert bias shape: {key}')
117
+ modes[key] = mode
118
+ def linear(prefix):
119
+ add(prefix + '.weight', 'linear')
120
+ if prefix + '.bias' in tensors:
121
+ add(prefix + '.bias', 'bias')
122
+ if adapter == 'qwen-mlx':
123
+ if include_embed:
124
+ add('model.language_model.embed_tokens.weight', 'embedding')
125
+ types = c.get('layer_types')
126
+ if not types or len(types) != n or any(t not in ('linear_attention', 'full_attention') for t in types):
127
+ raise ValueError('Qwen layer_types must explicitly describe all decoder layers')
128
+ for i, typ in enumerate(types):
129
+ prefix = f'model.language_model.layers.{i}'
130
+ linear(prefix + ('.linear_attn.out_proj' if typ == 'linear_attention' else '.self_attn.o_proj'))
131
+ linear(prefix + '.mlp.down_proj')
132
+ if config.get('vision_config'):
133
+ linear('model.visual.merger.linear_fc2')
134
+ elif adapter == 'kimi-torch':
135
+ if include_embed:
136
+ add('model.embed_tokens.weight', 'embedding')
137
+ for i in range(n):
138
+ prefix = f'model.layers.{i}'
139
+ linear(prefix + '.self_attn.o_proj')
140
+ if i == 0:
141
+ linear(prefix + '.mlp.down_proj')
142
+ else:
143
+ for j in range(c['num_experts']):
144
+ linear(prefix + f'.block_sparse_moe.experts.{j}.w2')
145
+ linear(prefix + '.block_sparse_moe.shared_experts.down_proj')
146
+ elif config['model_type'] == 'gpt_oss':
147
+ if include_embed:
148
+ add('model.embed_tokens.weight', 'embedding')
149
+ for i in range(n):
150
+ prefix = f'model.layers.{i}'
151
+ linear(prefix + '.self_attn.o_proj')
152
+ add(prefix + '.mlp.experts.down_proj', 'expert_embedding')
153
+ add(prefix + '.mlp.experts.down_proj_bias', 'expert_bias')
154
+ elif config['model_type'] == 'glm4_moe_lite':
155
+ if include_embed:
156
+ add('model.embed_tokens.weight', 'embedding')
157
+ types = c.get('mlp_layer_types')
158
+ if types is None:
159
+ first = c.get('first_k_dense_replace', 1)
160
+ if not isinstance(first, int) or not 0 <= first <= n:
161
+ raise ValueError('Invalid GLM dense-layer count')
162
+ types = ['dense'] * first + ['sparse'] * (n - first)
163
+ if len(types) != n or any(t not in ('dense', 'sparse') for t in types):
164
+ raise ValueError('Invalid GLM MLP layer types')
165
+ for i, typ in enumerate(types):
166
+ prefix = f'model.layers.{i}'
167
+ linear(prefix + '.self_attn.o_proj')
168
+ if typ == 'dense':
169
+ linear(prefix + '.mlp.down_proj')
170
+ else:
171
+ packed = prefix + '.mlp.experts.down_proj'
172
+ unpacked = [prefix + f'.mlp.experts.{j}.down_proj.weight'
173
+ for j in range(c['n_routed_experts'])]
174
+ if packed in tensors:
175
+ if any(key in tensors for key in unpacked):
176
+ raise ValueError('Ambiguous packed/unpacked GLM expert layout')
177
+ add(packed, 'expert_linear')
178
+ else:
179
+ for key in unpacked:
180
+ add(key, 'linear')
181
+ if tensors[key]['shape'] != [hidden, c['moe_intermediate_size']]:
182
+ raise ValueError(f'Unexpected expert writer shape: {key}')
183
+ linear(prefix + '.mlp.shared_experts.down_proj')
184
+ elif config['model_type'] == 'flint':
185
+ if include_embed:
186
+ add('model.embed_tokens.weight', 'embedding')
187
+ mlp_only = set(c.get('mlp_only_layers') or [])
188
+ step = int(c.get('decoder_sparse_step', 1))
189
+ n_experts = int(c.get('num_experts', 0))
190
+ if step <= 0 or n_experts < 0:
191
+ raise ValueError('Invalid Flint sparse MoE layer configuration')
192
+ for i in range(n):
193
+ prefix = f'model.layers.{i}'
194
+ linear(prefix + '.self_attn.o_proj')
195
+ is_moe = (i not in mlp_only) and (n_experts > 0) and ((i + 1) % step == 0)
196
+ if not is_moe:
197
+ linear(prefix + '.mlp.down_proj')
198
+ else:
199
+ packed = prefix + '.mlp.experts.down_proj'
200
+ unpacked = [prefix + f'.mlp.experts.{j}.down_proj.weight'
201
+ for j in range(n_experts)]
202
+ if packed in tensors:
203
+ if any(key in tensors for key in unpacked):
204
+ raise ValueError('Ambiguous packed/unpacked Flint expert layout')
205
+ add(packed, 'expert_linear')
206
+ else:
207
+ for key in unpacked:
208
+ add(key, 'linear')
209
+ if tensors[key]['shape'] != [hidden, c['moe_intermediate_size']]:
210
+ raise ValueError(f'Unexpected expert writer shape: {key}')
211
+ if prefix + '.mlp.shared_expert.down_proj.weight' in tensors:
212
+ linear(prefix + '.mlp.shared_expert.down_proj')
213
+ else:
214
+ if config['model_type'] == 'gemma3':
215
+ prefix = next((p for p in ('language_model.model', 'model.language_model')
216
+ if p + '.embed_tokens.weight' in tensors), None)
217
+ if prefix is None:
218
+ raise ValueError('Unrecognized Gemma text tensor layout')
219
+ else:
220
+ prefix = 'model'
221
+ if include_embed:
222
+ add(prefix + '.embed_tokens.weight', 'embedding')
223
+ for i in range(n):
224
+ linear(prefix + f'.layers.{i}.self_attn.o_proj')
225
+ linear(prefix + f'.layers.{i}.mlp.down_proj')
226
+ if config['model_type'] == 'gemma3':
227
+ projector = next((p for p in ('multi_modal_projector.mm_input_projection_weight',
228
+ 'model.multi_modal_projector.mm_input_projection_weight') if p in tensors), None)
229
+ if config.get('vision_config') and projector is None:
230
+ raise ValueError('Gemma multimodal projector is missing')
231
+ if projector:
232
+ add(projector, 'embedding') # Stored as (vision_hidden, text_hidden), right-multiplied.
233
+ normalization_scales(config, tensors) # Validate the post-writer normalization dependencies.
234
+ # Refuse unaccounted writer-like keys, including a new expert/layout variant.
235
+ writer_like = re.compile(r'(?:(?:\.down_proj|\.out_proj|\.o_proj|\.w2|\.merger\.linear_fc2)\.(?:weight|bias)|\.experts\.down_proj(?:_bias)?)$')
236
+ # Upstream GLM stores next-token-prediction modules after the decoder. They
237
+ # are preserved byte-for-byte, never edited or claimed as verified inference.
238
+ mtp_prefixes = ()
239
+ if config['model_type'] == 'glm4_moe_lite':
240
+ count = c.get('num_nextn_predict_layers', 0)
241
+ if not isinstance(count, int) or not 0 <= count <= 1:
242
+ raise ValueError('Unsupported GLM next-token-prediction layout')
243
+ mtp_prefixes = tuple(f'model.layers.{i}.' for i in range(n, n + count))
244
+ extras = [k for k in tensors if writer_like.search(k) and k not in modes and
245
+ not (mtp_prefixes and k.startswith(mtp_prefixes)) and
246
+ not k.startswith('mtp.') and not k.startswith('model.visual.blocks.') and
247
+ not k.startswith('vision_tower.') and not k.startswith('model.vision_tower.')]
248
+ if extras:
249
+ raise ValueError(f'Unmapped output projections: {extras[:5]}')
250
+ if band is not None:
251
+ start, end = band
252
+ modes = {
253
+ k: v for k, v in modes.items()
254
+ if (idx := layer_index(k)) is not None and start <= idx <= end
255
+ }
256
+ if not modes:
257
+ raise ValueError(f'layer_band {start}:{end} matched no residual writers')
258
+ return modes
259
+
260
+
261
+ def normalization_scales(config, tensors):
262
+ """Gemma normalizes/scales writer outputs before residual addition; raw W <- P W is insufficient."""
263
+ if config.get('model_type') != 'gemma3':
264
+ return {}
265
+ prefix = next((p for p in ('language_model.model', 'model.language_model')
266
+ if p + '.embed_tokens.weight' in tensors), None)
267
+ if prefix is None:
268
+ raise ValueError('Unrecognized Gemma text tensor layout')
269
+ c = config['text_config']
270
+ result = {}
271
+ for i in range(c['num_hidden_layers']):
272
+ for writer, norm in (('self_attn.o_proj', 'post_attention_layernorm'),
273
+ ('mlp.down_proj', 'post_feedforward_layernorm')):
274
+ key = prefix + f'.layers.{i}.{norm}.weight'
275
+ if key not in tensors or tensors[key]['shape'] != [c['hidden_size']]:
276
+ raise ValueError(f'Missing or invalid Gemma post-writer scale: {key}')
277
+ result[prefix + f'.layers.{i}.{writer}.weight'] = key
278
+ bias = prefix + f'.layers.{i}.{writer}.bias'
279
+ if bias in tensors:
280
+ result[bias] = key
281
+ return result