mirror of
https://github.com/p-e-w/heretic.git
synced 2026-12-03 18:42:57 +07:00
[GH-ISSUE #198] Qwen3.5 - Direct weight modification for fused MoE experts #113
Labels
No labels
bug
enhancement
enhancement
pull-request
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
p-e-w/heretic#113
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @timrohrbaugh on GitHub (Feb 27, 2026).
Original GitHub issue: https://github.com/p-e-w/heretic/issues/198
Some MoE architectures (e.g., Qwen3.5) store all routed expert weights in a single fused
nn.Parametertensor rather than as individualnn.Linearmodules qwen3.5-122b-A10B_config.json. For example,Qwen3_5MoeExperts.down_projhas shape[256, 3072, 1024](256 experts × hidden_size × intermediate_size) qwen3.5-122b-A10B_config.json. Since PEFT/LoRA can only wrapnn.Linearmodules, these fused experts are completely untouched by the existing abliteration pipeline.This is critical because the routed experts handle the vast majority of MLP computation (8 activated per token × 1024 intermediate dim = 8,192 total capacity vs the shared expert's 1,024) qwen3.5-122b-A10B_config.json. Without abliterating these experts, the model retains full refusal capability through its MLP pathway. On Qwen3.5-122B-A10B, abliterating only attention projections and the shared expert resulted in 98-100/100 refusals after 48 trials (essentially no effect). Adding fused expert abliteration reduced this to 7/100 refusals.
Changes to model.py
Add after the self._apply_lora() call:
self._apply_lora()
Cache original fused expert weights for in-place restoration during reset.
This avoids expensive full model reloads when abliterating fused MoE experts
whose weights are stored as batched nn.Parameter tensors (not nn.Linear modules)
and therefore cannot be handled by LoRA adapters.
self._original_expert_weights: dict[int, Tensor] = {}
for i, layer in enumerate(self.get_layers()):
with suppress(Exception):
fused = layer.mlp.experts.down_proj
if isinstance(fused, (Tensor, torch.nn.Parameter)) and fused.ndim == 3:
# Clone to CPU to avoid consuming GPU VRAM for the cache.
self._original_expert_weights[i] = fused.data.detach().clone().cpu()
# if you have enough room in VRAM you can avoid moving to RAM with this self.original_expert_weights[i] = fused.data.detach().clone()
2. reset_model() — Restore cached fused expert weights in the fast path:
In the fast path (after zeroing LoRA B weights), add restoration of fused expert weights:
def reset_model(self):
current_model = getattr(self.model.config, "name_or_path", None)
if current_model == self.settings.model and not self.needs_reload:
# Reset LoRA adapters to zero (identity transformation).
for name, module in self.model.named_modules():
if "lora_B" in name and hasattr(module, "weight"):
torch.nn.init.zeros(module.weight)
abliterate() — Add fused expert abliteration pass after the LoRA pass:
Add at the end of the abliterate() method, after the existing LoRA-based loop:
# === Direct weight modification for fused MoE experts ===
# Some MoE architectures (e.g. Qwen3.5) store all routed expert weights
# in a single fused nn.Parameter tensor (e.g. shape [256, 3072, 1024])
# rather than as individual nn.Linear modules. Since PEFT/LoRA cannot
# wrap raw nn.Parameter tensors, we apply the orthogonalization directly
# to the weight tensor using vectorized einsum operations.
if "mlp.down_proj" in parameters:
params = parameters["mlp.down_proj"]
NOTE:
Memory impact example Qwen3.5 The weight cache stores 48 layers ×
[256, 3072, 1024]× 2 bytes (BF16) ≈ 72.5 GB in system RAM for Qwen3.5-122B-A10B, or ~20 GB for the 35B-A3B variant. Models without fused experts have an empty cache dictionary with zero memory overhead.Backward compatibility:
The fused expert detection uses a triple
getattrchain withNonefallbacks — models withoutlayer.mlp.experts.down_projas a 3D tensor simply skip this code path entirely._original_expert_weightsis empty for models without fused experts, adding zero memory overhead.reset_model()restoration loop iterates over an empty dictionary for non-MoE models, adding zero overhead.@p-e-w commented on GitHub (Feb 27, 2026):
Code belongs in pull requests, not issues.