1
0
Fork 0
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

Closed
opened 2026-11-01 04:17:39 +07:00 by bsakaguchi · 1 comment
Owner

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.Parameter tensor rather than as individual nn.Linear modules qwen3.5-122b-A10B_config.json. For example, Qwen3_5MoeExperts.down_proj has shape [256, 3072, 1024] (256 experts × hidden_size × intermediate_size) qwen3.5-122b-A10B_config.json. Since PEFT/LoRA can only wrap nn.Linear modules, 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

  1. init() — Cache original fused expert weights after _apply_lora():
    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)

    # Restore fused expert weights that were modified in-place.
    # These cannot be reset via LoRA because they are raw nn.Parameter
    # tensors, not nn.Linear modules.
    for i, original in self._original_expert_weights.items():
        layer = self.get_layers()[i]
        with suppress(Exception):
            fused = layer.mlp.experts.down_proj
            if isinstance(fused, (Tensor, torch.nn.Parameter)):
                fused.data.copy_(original.to(fused.device))

    return

# ... rest of slow-path reload unchanged ...
  1. 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"]

         for layer_index in range(len(self.get_layers())):
             distance = cast(
                 float, abs(layer_index - params.max_weight_position)
             )
             if distance > params.min_weight_distance:
                 continue
    
             weight = params.max_weight + (
                 distance / params.min_weight_distance
             ) * (params.min_weight - params.max_weight)
    
             if refusal_direction is None:
                 layer_refusal_direction = refusal_directions[layer_index + 1]
             else:
                 layer_refusal_direction = refusal_direction
    
             layer = self.get_layers()[layer_index]
    
             # Access the fused experts' down_proj parameter directly.
             fused_down_proj = getattr(
                 getattr(getattr(layer, "mlp", None), "experts", None),
                 "down_proj",
                 None,
             )
    
             if fused_down_proj is None:
                 continue
             if not isinstance(
                 fused_down_proj, (Tensor, torch.nn.Parameter)
             ):
                 continue
             if fused_down_proj.ndim != 3:
                 continue
    
             # fused_down_proj shape: [num_experts, hidden_size, intermediate_size]
             # e.g., [256, 3072, 1024] for Qwen3.5-122B-A10B
             v = layer_refusal_direction.to(fused_down_proj.device).to(
                 torch.float32
             )
             W = fused_down_proj.data.to(torch.float32)
    
             # Vectorized orthogonalization across all experts:
             # W_new = W - weight * v ⊗ (v^T @ W) for each expert
             proj = torch.einsum("h,ehd->ed", v, W)  # [num_experts, intermediate]
             delta = weight * torch.einsum(
                 "h,ed->ehd", v, proj
             )  # [num_experts, hidden, intermediate]
    
             fused_down_proj.data -= delta.to(fused_down_proj.dtype)
    

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 getattr chain with None fallbacks — models without layer.mlp.experts.down_proj as a 3D tensor simply skip this code path entirely.

  • The weight cache dictionary _original_expert_weights is empty for models without fused experts, adding zero memory overhead.
  • The reset_model() restoration loop iterates over an empty dictionary for non-MoE models, adding zero overhead.
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.Parameter` tensor rather than as individual `nn.Linear` modules qwen3.5-122b-A10B_config.json. For example, `Qwen3_5MoeExperts.down_proj` has shape `[256, 3072, 1024]` (256 experts × hidden_size × intermediate_size) qwen3.5-122b-A10B_config.json. Since PEFT/LoRA can only wrap `nn.Linear` modules, 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 1. __init__() — Cache original fused expert weights after _apply_lora(): 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) # Restore fused expert weights that were modified in-place. # These cannot be reset via LoRA because they are raw nn.Parameter # tensors, not nn.Linear modules. for i, original in self._original_expert_weights.items(): layer = self.get_layers()[i] with suppress(Exception): fused = layer.mlp.experts.down_proj if isinstance(fused, (Tensor, torch.nn.Parameter)): fused.data.copy_(original.to(fused.device)) return # ... rest of slow-path reload unchanged ... 3. 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"] for layer_index in range(len(self.get_layers())): distance = cast( float, abs(layer_index - params.max_weight_position) ) if distance > params.min_weight_distance: continue weight = params.max_weight + ( distance / params.min_weight_distance ) * (params.min_weight - params.max_weight) if refusal_direction is None: layer_refusal_direction = refusal_directions[layer_index + 1] else: layer_refusal_direction = refusal_direction layer = self.get_layers()[layer_index] # Access the fused experts' down_proj parameter directly. fused_down_proj = getattr( getattr(getattr(layer, "mlp", None), "experts", None), "down_proj", None, ) if fused_down_proj is None: continue if not isinstance( fused_down_proj, (Tensor, torch.nn.Parameter) ): continue if fused_down_proj.ndim != 3: continue # fused_down_proj shape: [num_experts, hidden_size, intermediate_size] # e.g., [256, 3072, 1024] for Qwen3.5-122B-A10B v = layer_refusal_direction.to(fused_down_proj.device).to( torch.float32 ) W = fused_down_proj.data.to(torch.float32) # Vectorized orthogonalization across all experts: # W_new = W - weight * v ⊗ (v^T @ W) for each expert proj = torch.einsum("h,ehd->ed", v, W) # [num_experts, intermediate] delta = weight * torch.einsum( "h,ed->ehd", v, proj ) # [num_experts, hidden, intermediate] fused_down_proj.data -= delta.to(fused_down_proj.dtype) 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 `getattr` chain with `None` fallbacks — models without `layer.mlp.experts.down_proj` as a 3D tensor simply skip this code path entirely. - The weight cache dictionary `_original_expert_weights` is empty for models without fused experts, adding zero memory overhead. - The `reset_model()` restoration loop iterates over an empty dictionary for non-MoE models, adding zero overhead.
Author
Owner

@p-e-w commented on GitHub (Feb 27, 2026):

Code belongs in pull requests, not issues.

<!-- gh-comment-id:3970699924 --> @p-e-w commented on GitHub (Feb 27, 2026): Code belongs in pull requests, not issues.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
p-e-w/heretic#113
No description provided.