Spaces:
Running on Zero
Running on Zero
Upload 81 files
Browse filesFiles changed (2)
165 unmodified lines1661671681691701711721731741751761771781791801811821831841851865 unmodified lines192193194195196197198199200201389 unmodified lines59159259359459559659735 unmodified lines6336346356366376386391823 unmodified lines246324642465246624672468246924702471247224732474247524762477247835 unmodified lines25142515251625172518251925202521252225232524252525262527252825292530253125324 unmodified lines253725382539254025412542254325442 unmodified lines2547254825492550255125522553165 unmodified lines"nuclear": {"label": "Nuclear (Maximum Force Combo)","description": ("The ultimate abliteration mode for the most stubborn models. ""Combines ALL techniques at maximum strength: 16 SVD directions, ""3 refinement passes with true iterative re-probing, 2.5x ""reflection (stronger than standard 2x inversion), input ""embedding projection, expert weight transplant (overwrites ""safety expert weights with capability expert weights), and ""inference-time activation steering hooks that continuously ""subtract the refusal direction from hidden states during ""generation. Designed to break through models like GPT-OSS 20B ""where standard methods plateau."),"n_directions": 16,"norm_preserve": True,"regularization": 0.0,"refinement_passes": 3,"project_biases": True,"use_chat_template": True,"use_whitened_svd": True,5 unmodified lines"attention_head_surgery": True,"use_sae_features": True,"invert_refusal": True,"reflection_strength": 2.5,"project_embeddings": True,"activation_steering": True,"expert_transplant": True,},}389 unmodified linesreflection_strength: float | None = None,project_embeddings: bool | None = None,activation_steering: bool | None = None,expert_transplant: bool | None = None,on_stage: Callable[[StageResult], None] | None = None,on_log: Callable[[str], None] | None = None,):35 unmodified linesself.reflection_strength = reflection_strength if reflection_strength is not None else method_cfg.get("reflection_strength", 2.0)self.project_embeddings = project_embeddings if project_embeddings is not None else method_cfg.get("project_embeddings", False)self.activation_steering = activation_steering if activation_steering is not None else method_cfg.get("activation_steering", False)self.expert_transplant = expert_transplant if expert_transplant is not None else method_cfg.get("expert_transplant", False)self.handle: ModelHandle | None = Noneself.refusal_directions: dict[int, torch.Tensor] = {} # per-layer primary direction1823 unmodified lines# ── Nuclear-mode helpers ─────────────────────────────────────────────def _transplant_expert_weights(self, layers: nn.ModuleList) -> int:"""Overwrite safety expert down_proj weights with capability expert averages.For each MoE layer, computes the mean of capability experts' down_projweights and copies it into each safety expert's down_proj. This is moreaggressive than reflection — it completely replaces the refusal-encodingoutput path with the capability-encoding one.Returns the number of weight matrices transplanted."""arch = self.handle.architecturecount = 0for idx in self._strong_layers:35 unmodified lines# Compute mean of capability expert weightscap_mean = torch.stack(cap_weights).mean(dim=0)# Transplant into safety expertsfor ei in safety_indices:if ei >= len(experts):continuetarget = getattr(experts[ei], wname, None)if target is not None and hasattr(target, "weight"):if target.weight.data.shape == cap_mean.shape:target.weight.data.copy_(cap_mean)count += 1del cap_weights, cap_meanself.log(f" layer {idx}: transplanted capability weights into {len(safety_indices)} safety experts")return count4 unmodified linescontinuously steering the model away from the refusal direction.This catches residual signal that static weight surgery may have missed.The steering strength scales with the reflection_strength parameter:standard (2.0) = subtract 1x direction, boosted (2.5) = 1.5x, etc.Returns the number of hooks installed."""2 unmodified lineshook.remove()self._steering_hooks.clear()steering_scale = self.reflection_strength - 1.0 # 2.0→1.0, 2.5→1.5, 3.0→2.0for idx in self._strong_layers:if idx not in self.refusal_directions:165 unmodified lines1661671681691701711721731741751761771781791801811821831841855 unmodified lines191192193194195196197198199200201202389 unmodified lines59259359459559659759859960035 unmodified lines6366376386396406416426436441823 unmodified lines24682469247024712472247324742475247624772478247924802481248224832484248524862487248835 unmodified lines252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525464 unmodified lines25512552255325542555255625572558255925602 unmodified lines256325642565256625672568256925702571165 unmodified lines"nuclear": {"label": "Nuclear (Maximum Force Combo)","description": ("Comprehensive combo mode for stubborn MoE models. Combines ALL ""techniques with calibrated intensity: 10 SVD directions, 2 ""refinement passes, standard 2x reflection, input embedding ""projection, partial expert weight transplant (blends 30%% ""capability weights into safety experts), and light inference-""time activation steering (0.3x residual cleanup). Designed ""to break through models like GPT-OSS 20B without causing ""decoherence — every technique fires at moderate power so they ""complement rather than compound."),"n_directions": 10,"norm_preserve": True,"regularization": 0.0,"refinement_passes": 2,"project_biases": True,"use_chat_template": True,"use_whitened_svd": True,5 unmodified lines"attention_head_surgery": True,"use_sae_features": True,"invert_refusal": True,"reflection_strength": 2.0,"project_embeddings": True,"activation_steering": True,"steering_strength": 0.3,"expert_transplant": True,"transplant_blend": 0.3,},}389 unmodified linesreflection_strength: float | None = None,project_embeddings: bool | None = None,activation_steering: bool | None = None,steering_strength: float | None = None,expert_transplant: bool | None = None,transplant_blend: float | None = None,on_stage: Callable[[StageResult], None] | None = None,on_log: Callable[[str], None] | None = None,):35 unmodified linesself.reflection_strength = reflection_strength if reflection_strength is not None else method_cfg.get("reflection_strength", 2.0)self.project_embeddings = project_embeddings if project_embeddings is not None else method_cfg.get("project_embeddings", False)self.activation_steering = activation_steering if activation_steering is not None else method_cfg.get("activation_steering", False)self.steering_strength = steering_strength if steering_strength is not None else method_cfg.get("steering_strength", 0.3)self.expert_transplant = expert_transplant if expert_transplant is not None else method_cfg.get("expert_transplant", False)self.transplant_blend = transplant_blend if transplant_blend is not None else method_cfg.get("transplant_blend", 0.3)self.handle: ModelHandle | None = Noneself.refusal_directions: dict[int, torch.Tensor] = {} # per-layer primary direction1823 unmodified lines# ── Nuclear-mode helpers ─────────────────────────────────────────────def _transplant_expert_weights(self, layers: nn.ModuleList) -> int:"""Blend capability expert weights into safety expert down_proj.For each MoE layer, computes the mean of capability experts' down_projweights and blends it into each safety expert's down_proj using thetransplant_blend ratio. A blend of 0.3 means:new_weight = 0.7 * original_safety + 0.3 * capability_meanThis preserves most of the safety expert's general language modelingability while nudging its output toward the capability distribution.Full overwrite (blend=1.0) causes decoherence.Returns the number of weight matrices blended."""arch = self.handle.architectureblend = self.transplant_blendcount = 0for idx in self._strong_layers:35 unmodified lines# Compute mean of capability expert weightscap_mean = torch.stack(cap_weights).mean(dim=0)# Partial blend into safety expertsfor ei in safety_indices:if ei >= len(experts):continuetarget = getattr(experts[ei], wname, None)if target is not None and hasattr(target, "weight"):if target.weight.data.shape == cap_mean.shape:# Blend: (1-blend) * original + blend * capability_meantarget.weight.data.mul_(1.0 - blend).add_(cap_mean * blend)count += 1del cap_weights, cap_meanself.log(f" layer {idx}: blended {blend:.0%} capability weights "f"into {len(safety_indices)} safety experts")return count4 unmodified linescontinuously steering the model away from the refusal direction.This catches residual signal that static weight surgery may have missed.Uses the dedicated steering_strength parameter (default 0.3) insteadof coupling to reflection_strength. A light touch (0.3) works asresidual cleanup without causing decoherence — the weight surgeryalready handles the bulk of the removal.Returns the number of hooks installed."""2 unmodified lineshook.remove()self._steering_hooks.clear()# Use only the primary refusal direction (not full subspace) to# minimize interference with the model's representation spacesteering_scale = self.steering_strengthfor idx in self._strong_layers:if idx not in self.refusal_directions:
1408 unmodified lines1409141014111412141314141415141614171418141914201 unmodified line142214231424142514261427142814291430143114321433147 unmodified lines1581158215831584158515861587158815891590159115921408 unmodified lines"""Nuclear method should have all techniques enabled at maximum."""cfg = METHODS["nuclear"]assert cfg["invert_refusal"] is Trueassert cfg["n_directions"] == 16assert cfg["refinement_passes"] == 3assert cfg["reflection_strength"] == 2.5assert cfg["project_embeddings"] is Trueassert cfg["activation_steering"] is Trueassert cfg["expert_transplant"] is Trueassert cfg["use_jailbreak_contrast"] is Trueassert cfg["attention_head_surgery"] is True1 unmodified line"""Pipeline initialized with nuclear method should have all flags set."""pipeline = AbliterationPipeline(model_name="test", method="nuclear")assert pipeline.invert_refusal is Trueassert pipeline.reflection_strength == 2.5assert pipeline.project_embeddings is Trueassert pipeline.activation_steering is Trueassert pipeline.expert_transplant is Trueassert pipeline.n_directions == 16assert pipeline.refinement_passes == 3def test_reflection_strength_configurable(self):"""reflection_strength should be explicitly overridable."""147 unmodified linesfinally:abl_module.get_ffn_module = orig_get_ffnassert count >= 2, f"Should transplant at least 2 weights (safety experts), got {count}"# Safety expert 0 should now have the capability meantransplanted = layer.mlp.experts[0].down_proj.weight.dataassert torch.allclose(transplanted, expected_mean, atol=1e-4), ("Safety expert weight should match capability expert mean after transplant")# Capability expert 2 should be unchanged1408 unmodified lines140914101411141214131414141514161417141814191420142114221 unmodified line14241425142614271428142914301431143214331434143514361437147 unmodified lines158515861587158815891590159115921593159415951596159715981408 unmodified lines"""Nuclear method should have all techniques enabled at maximum."""cfg = METHODS["nuclear"]assert cfg["invert_refusal"] is Trueassert cfg["n_directions"] == 10assert cfg["refinement_passes"] == 2assert cfg["reflection_strength"] == 2.0assert cfg["project_embeddings"] is Trueassert cfg["activation_steering"] is Trueassert cfg["steering_strength"] == 0.3assert cfg["expert_transplant"] is Trueassert cfg["transplant_blend"] == 0.3assert cfg["use_jailbreak_contrast"] is Trueassert cfg["attention_head_surgery"] is True1 unmodified line"""Pipeline initialized with nuclear method should have all flags set."""pipeline = AbliterationPipeline(model_name="test", method="nuclear")assert pipeline.invert_refusal is Trueassert pipeline.reflection_strength == 2.0assert pipeline.steering_strength == 0.3assert pipeline.transplant_blend == 0.3assert pipeline.project_embeddings is Trueassert pipeline.activation_steering is Trueassert pipeline.expert_transplant is Trueassert pipeline.n_directions == 10assert pipeline.refinement_passes == 2def test_reflection_strength_configurable(self):"""reflection_strength should be explicitly overridable."""147 unmodified linesfinally:abl_module.get_ffn_module = orig_get_ffnassert count >= 2, f"Should blend at least 2 weights (safety experts), got {count}"# Safety expert 0 should be a 30% blend toward capability mean# new = 0.7 * original + 0.3 * capability_meanexpected_blend = 0.7 * orig_safety0 + 0.3 * expected_meantransplanted = layer.mlp.experts[0].down_proj.weight.dataassert torch.allclose(transplanted, expected_blend, atol=1e-4), ("Safety expert weight should be 30% blended toward capability mean")# Capability expert 2 should be unchanged
obliteratus/abliterate.py+42-24
tests/test_abliterate.py+16-10