Spaces:
Sleeping
Sleeping
Upload 81 files
Browse filesFiles changed (3)
- app.py+1
- obliteratus/abliterate.py+266-8
- tests/test_abliterate.py+235-1
71 unmodified lines72737475767771 unmodified lines"basic (fast, single direction)": "basic","aggressive (maximum removal)": "aggressive","surgical (precision MoE-aware)": "surgical",}# Models that need 4bit quantization to fit on a T4 16GB71 unmodified lines7273747576777871 unmodified lines"basic (fast, single direction)": "basic","aggressive (maximum removal)": "aggressive","surgical (precision MoE-aware)": "surgical","inverted (semantic refusal inversion)": "inverted",}# Models that need 4bit quantization to fit on a T4 16GB
132 unmodified lines133134135136137138188 unmodified lines32732832933033133229 unmodified lines36236336436536636716 unmodified lines384385386387388389408 unmodified lines7987998008018028036 unmodified lines810811812813814815133 unmodified lines949950951952953954223 unmodified lines11781179118011811182118342 unmodified lines1226122712281229123012311232123312341235123612371238105 unmodified lines134413451346134713481349135013511352135323 unmodified lines13771378137913801381138268 unmodified lines145114521453145414551456431 unmodified lines188818891890189118921893132 unmodified lines"per_expert_directions": True,"attention_head_surgery": True,"use_sae_features": True,},}188 unmodified linesper_expert_directions: bool | None = None,attention_head_surgery: bool | None = None,use_sae_features: bool | None = None,on_stage: Callable[[StageResult], None] | None = None,on_log: Callable[[str], None] | None = None,):29 unmodified linesself.per_expert_directions = per_expert_directions if per_expert_directions is not None else method_cfg.get("per_expert_directions", False)self.attention_head_surgery = attention_head_surgery if attention_head_surgery is not None else method_cfg.get("attention_head_surgery", False)self.use_sae_features = use_sae_features if use_sae_features is not None else method_cfg.get("use_sae_features", False)self.handle: ModelHandle | None = Noneself.refusal_directions: dict[int, torch.Tensor] = {} # per-layer primary direction16 unmodified linesself._sae_directions: dict[int, torch.Tensor] = {}# Attention head refusal attribution (layer → list of (head_idx, score))self._refusal_heads: dict[int, list[tuple[int, float]]] = {}def log(self, msg: str):self._on_log(msg)408 unmodified linesself.log("Identifying refusal attention heads...")self._identify_refusal_heads()elapsed = time.time() - t0self.log(f"Refusal subspace extracted ({elapsed:.1f}s)")dir_label = f"{n_dirs}-direction SVD" if n_dirs > 1 else "single-direction"6 unmodified linesextras.append(f"SAE({len(self._sae_directions)} layers)")if self._refusal_heads:extras.append("head-surgery")distill_label = dir_labelif extras:distill_label += " + " + " + ".join(extras)133 unmodified linestop_head, top_score = head_scores[0]self.log(f" layer {idx}: top refusal head={top_head} (proj={top_score:.4f})")@staticmethoddef _mask_safety_neurons(module: nn.Module,223 unmodified linesweight = self._layer_excise_weights[idx]layer_reg = self.regularization + (1.0 - weight) * (1.0 - self.regularization) * 0.15count = 0# Process each direction in the subspacefor dir_idx in range(subspace.shape[0]):42 unmodified linesregularization=layer_reg,)if ffn_count == 0:# MoE path (projects both output AND input for experts)ffn_count = self._project_moe_experts(ffn, d,norm_preserve=self.norm_preserve,regularization=layer_reg,project_biases=self.project_biases,)else:# Dense model: also project FFN input projections# (up_proj, gate_proj carry refusal signal too)105 unmodified linesfor head_name in ["lm_head", "embed_out", "output"]:head = getattr(model, head_name, None)if head is not None and hasattr(head, "weight"):lm_head_count += self._project_out_advanced(model, d, [head_name],norm_preserve=self.norm_preserve,regularization=0.0, # full removal for output head)breakdel d23 unmodified linesextras.append("head-surgery")if total_sae_projections > 0:extras.append(f"SAE({total_sae_projections})")if lm_head_count > 0:extras.append("lm_head-projected")mode_label = " + ".join(extras) if extras else "standard"68 unmodified linesself._refusal_heads.clear()self._identify_refusal_heads()@staticmethoddef _is_quantized_param(param) -> bool:"""Check if a parameter is bitsandbytes 4-bit or 8-bit quantized."""431 unmodified linescount += expert_countreturn count# ── Stage 5: VERIFY ─────────────────────────────────────────────────def _verify(self):132 unmodified lines133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167188 unmodified lines35635735835936036136229 unmodified lines39239339439539639739816 unmodified lines415416417418419420421422408 unmodified lines8318328338348358368378388398408416 unmodified lines848849850851852853854855856857133 unmodified lines9919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072223 unmodified lines12961297129812991300130113021303130413051306130742 unmodified lines1350135113521353135413551356135713581359136013611362136313641365136613671368136913701371105 unmodified lines14771478147914801481148214831484148514861487148823 unmodified lines1512151315141515151615171518151968 unmodified lines15881589159015911592159315941595159615971598431 unmodified lines20302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151132 unmodified lines"per_expert_directions": True,"attention_head_surgery": True,"use_sae_features": True,"invert_refusal": False,},"inverted": {"label": "Inverted (Semantic Refusal Inversion)","description": ("Instead of removing the refusal direction (making the model neutral), ""this REFLECTS it — semantically inverting the refusal logic so the ""model becomes actively compliant. Uses 2x orthogonal reflection on ""all weight matrices. For MoE models, the router is reflected to ""redirect harmful tokens from safety experts to capability experts, ""safety-biased experts have their output inverted, and capability ""experts are left untouched. Includes all surgical-mode SOTA ""techniques plus the inversion layer."),"n_directions": 8,"norm_preserve": True,"regularization": 0.0,"refinement_passes": 2,"project_biases": True,"use_chat_template": True,"use_whitened_svd": True,"true_iterative_refinement": True,"use_jailbreak_contrast": True,"layer_adaptive_strength": False, # inversion overrides per-layer scaling"safety_neuron_masking": True,"per_expert_directions": True,"attention_head_surgery": True,"use_sae_features": True,"invert_refusal": True,},}188 unmodified linesper_expert_directions: bool | None = None,attention_head_surgery: bool | None = None,use_sae_features: bool | None = None,invert_refusal: bool | None = None,on_stage: Callable[[StageResult], None] | None = None,on_log: Callable[[str], None] | None = None,):29 unmodified linesself.per_expert_directions = per_expert_directions if per_expert_directions is not None else method_cfg.get("per_expert_directions", False)self.attention_head_surgery = attention_head_surgery if attention_head_surgery is not None else method_cfg.get("attention_head_surgery", False)self.use_sae_features = use_sae_features if use_sae_features is not None else method_cfg.get("use_sae_features", False)self.invert_refusal = invert_refusal if invert_refusal is not None else method_cfg.get("invert_refusal", False)self.handle: ModelHandle | None = Noneself.refusal_directions: dict[int, torch.Tensor] = {} # per-layer primary direction16 unmodified linesself._sae_directions: dict[int, torch.Tensor] = {}# Attention head refusal attribution (layer → list of (head_idx, score))self._refusal_heads: dict[int, list[tuple[int, float]]] = {}# MoE expert safety classification (layer → list of (expert_idx, safety_affinity))self._expert_safety_scores: dict[int, list[tuple[int, float]]] = {}def log(self, msg: str):self._on_log(msg)408 unmodified linesself.log("Identifying refusal attention heads...")self._identify_refusal_heads()# ── MoE expert safety classification (for inversion) ──────────if self.invert_refusal:self.log("Classifying MoE experts (safety vs capability) for inversion...")self._identify_safety_experts()elapsed = time.time() - t0self.log(f"Refusal subspace extracted ({elapsed:.1f}s)")dir_label = f"{n_dirs}-direction SVD" if n_dirs > 1 else "single-direction"6 unmodified linesextras.append(f"SAE({len(self._sae_directions)} layers)")if self._refusal_heads:extras.append("head-surgery")if self.invert_refusal:extras.append("refusal-inversion")if self._expert_safety_scores:extras.append(f"expert-classified({len(self._expert_safety_scores)} layers)")distill_label = dir_labelif extras:distill_label += " + " + " + ".join(extras)133 unmodified linestop_head, top_score = head_scores[0]self.log(f" layer {idx}: top refusal head={top_head} (proj={top_score:.4f})")def _identify_safety_experts(self):"""Classify MoE experts as safety-biased vs capability-biased.Analyzes the router/gate weight matrix to determine which expertshave the highest affinity for the refusal direction. Experts withpositive router affinity are steered toward by safety-triggeringtokens — these are the "safety experts" whose output encodes refusal.When refusal inversion is enabled, safety experts get reflected (2x)to invert their output, while capability experts get standard removal.The router itself is always reflected to flip expert selection.This classification is MoE-specific and only applies to layers wherea router/gate module is found."""if not self.handle:returnlayers = get_layer_modules(self.handle)arch = self.handle.architecturefor idx in self._strong_layers:if idx not in self.refusal_directions:continuetry:ffn = get_ffn_module(layers[idx], arch)except (AttributeError, RuntimeError):continued = self.refusal_directions[idx]# Find router weightrouter = Nonefor rname in _ROUTER_NAMES:router = getattr(ffn, rname, None)if router is not None and hasattr(router, "weight"):breakif router is None:# Try auto-detection fallbackif getattr(ffn, "experts", None) is not None:hidden_dim = d.shape[0]for child_name, child in ffn.named_children():if child_name == "experts":continueif not hasattr(child, "weight"):continueW = child.weightif W.shape[-1] == hidden_dim and W.shape[0] < 512 and W.shape[0] != hidden_dim:router = childbreakif router is None:continueW = router.weight.data # (num_experts, hidden_dim)d_flat = d.to(device=W.device, dtype=W.dtype)if d_flat.dim() > 1:d_flat = d_flat.squeeze()if W.shape[-1] != d_flat.shape[0]:continue# Per-expert router affinity for refusal direction:# positive = expert is preferentially selected for refusal-triggering tokensscores = (W @ d_flat).tolist()expert_scores = [(ei, s) for ei, s in enumerate(scores)]expert_scores.sort(key=lambda x: x[1], reverse=True)self._expert_safety_scores[idx] = expert_scoresn_exp = len(expert_scores)n_safety = max(1, n_exp // 2)top = expert_scores[0]bot = expert_scores[-1]self.log(f" layer {idx}: {n_safety}/{n_exp} safety experts "f"(top={top[0]} aff={top[1]:.4f}, bottom={bot[0]} aff={bot[1]:.4f})")@staticmethoddef _mask_safety_neurons(module: nn.Module,223 unmodified linesweight = self._layer_excise_weights[idx]layer_reg = self.regularization + (1.0 - weight) * (1.0 - self.regularization) * 0.15# Refusal inversion: use 2x reflection instead of 1x removal.# regularization=-1.0 gives scale=2.0, reflecting weights across# the hyperplane perpendicular to the refusal direction.if self.invert_refusal:layer_reg = -1.0count = 0# Process each direction in the subspacefor dir_idx in range(subspace.shape[0]):42 unmodified linesregularization=layer_reg,)if ffn_count == 0:# MoE pathif self.invert_refusal and idx in self._expert_safety_scores:# Selective MoE inversion: router reflected, safety# experts reflected, capability experts standard removalffn_count = self._project_moe_experts_inverted(ffn, d, idx,norm_preserve=self.norm_preserve,project_biases=self.project_biases,)else:ffn_count = self._project_moe_experts(ffn, d,norm_preserve=self.norm_preserve,regularization=layer_reg,project_biases=self.project_biases,)else:# Dense model: also project FFN input projections# (up_proj, gate_proj carry refusal signal too)105 unmodified linesfor head_name in ["lm_head", "embed_out", "output"]:head = getattr(model, head_name, None)if head is not None and hasattr(head, "weight"):# Inversion: reflect lm_head to flip refusal token logitslm_reg = -1.0 if self.invert_refusal else 0.0lm_head_count += self._project_out_advanced(model, d, [head_name],norm_preserve=self.norm_preserve,regularization=lm_reg,)breakdel d23 unmodified linesextras.append("head-surgery")if total_sae_projections > 0:extras.append(f"SAE({total_sae_projections})")if self.invert_refusal:extras.append("INVERTED(2x-reflection)")if lm_head_count > 0:extras.append("lm_head-projected")mode_label = " + ".join(extras) if extras else "standard"68 unmodified linesself._refusal_heads.clear()self._identify_refusal_heads()# Re-classify safety experts with updated directionsif self.invert_refusal:self._expert_safety_scores.clear()self._identify_safety_experts()@staticmethoddef _is_quantized_param(param) -> bool:"""Check if a parameter is bitsandbytes 4-bit or 8-bit quantized."""431 unmodified linescount += expert_countreturn countdef _project_moe_experts_inverted(self,ffn_module: nn.Module,direction: torch.Tensor,layer_idx: int,norm_preserve: bool = False,project_biases: bool = False,) -> int:"""MoE excision with selective inversion (refusal reflection).Instead of uniformly projecting all MoE components, this method usesthe expert safety classification to apply per-component strategies:1. Router/Gate: ALWAYS reflected (2x) — flips expert selection soharmful tokens are routed to capability experts instead of safety ones.2. Safety-biased experts (top half by router affinity): reflected (2x)— inverts their output from refusal to compliance.3. Capability experts (bottom half): standard removal (1x) — justremoves any residual refusal signal without inverting.4. Shared experts: reflected (2x) — they always activate and cancarry majority of safety functionality.This selective approach is more effective than uniform reflectionbecause it preserves the capability experts' helpful behavior whileinverting the safety experts' refusal behavior."""count = 0scores = self._expert_safety_scores.get(layer_idx, [])n_experts = len(scores)safety_indices = set()if n_experts > 0:n_safety = max(1, n_experts // 2)safety_indices = {ei for ei, _ in scores[:n_safety]}# ── Router: ALWAYS reflect ────────────────────────────────────for rname in _ROUTER_NAMES:gate = getattr(ffn_module, rname, None)if gate is not None and hasattr(gate, "weight"):count += self._project_out_advanced(ffn_module, direction, [rname],norm_preserve=norm_preserve,regularization=-1.0, # 2x reflection)if project_biases:count += self._project_bias(ffn_module, direction, [rname])break# Router auto-detection fallbackif count == 0 and getattr(ffn_module, "experts", None) is not None:hidden_dim = direction.shape[0]for child_name, child in ffn_module.named_children():if child_name == "experts":continueif not hasattr(child, "weight"):continueW = child.weightif W.shape[-1] == hidden_dim and W.shape[0] < 512 and W.shape[0] != hidden_dim:count += self._project_out_advanced(ffn_module, direction, [child_name],norm_preserve=norm_preserve,regularization=-1.0,)break# ── Shared experts: always reflect ────────────────────────────for sname in _SHARED_EXPERT_NAMES:shared = getattr(ffn_module, sname, None)if shared is None:continueif isinstance(shared, nn.Module):count += self._project_out_advanced(shared, direction, _FFN_OUT_NAMES + _FFN_IN_NAMES,norm_preserve=norm_preserve,regularization=-1.0,)if project_biases:count += self._project_bias(shared, direction, _FFN_OUT_NAMES + _FFN_IN_NAMES)break# ── Routed experts: selective inversion ───────────────────────experts = getattr(ffn_module, "experts", None)if experts is None:return countif isinstance(experts, nn.ModuleList):for ei, expert in enumerate(experts):# Safety experts: reflect (2x), capability experts: remove (1x)reg = -1.0 if ei in safety_indices else 0.0count += self._project_out_advanced(expert, direction, _FFN_OUT_NAMES + _FFN_IN_NAMES,norm_preserve=norm_preserve,regularization=reg,)if project_biases:count += self._project_bias(expert, direction, _FFN_OUT_NAMES + _FFN_IN_NAMES)else:# Fused 3D: reflect all experts (can't easily do per-expert)scale = 2.0 # full reflectioncount += self._project_fused_3d(experts, direction, ["down_proj", "w2"],norm_preserve=norm_preserve, scale=scale,)count += self._project_fused_3d(experts, direction, ["up_proj", "gate_proj", "w1", "w3"],norm_preserve=norm_preserve, scale=scale,)if project_biases:count += self._project_fused_bias(experts, direction, ["down_proj_bias", "w2_bias"],)return count# ── Stage 5: VERIFY ─────────────────────────────────────────────────def _verify(self):
117 unmodified lines1181191201211221231241030 unmodified lines115511561157115811591160117 unmodified linesclass TestMethods:def test_methods_exist(self):assert set(METHODS.keys()) == {"basic", "advanced", "aggressive", "informed", "surgical"}def test_basic_single_direction(self):cfg = METHODS["basic"]1030 unmodified linesassert pipeline.use_jailbreak_contrast is True # rest still from surgical# ---------------------------------------------------------------------------# Knee detection# ---------------------------------------------------------------------------117 unmodified lines1181191201211221231241030 unmodified lines115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394117 unmodified linesclass TestMethods:def test_methods_exist(self):assert set(METHODS.keys()) == {"basic", "advanced", "aggressive", "informed", "surgical", "inverted"}def test_basic_single_direction(self):cfg = METHODS["basic"]1030 unmodified linesassert pipeline.use_jailbreak_contrast is True # rest still from surgical# ---------------------------------------------------------------------------# Inverted method (semantic refusal inversion)# ---------------------------------------------------------------------------class TestInvertedMethod:def test_inverted_preset_config(self):"""Inverted method preset should enable inversion flag."""cfg = METHODS["inverted"]assert cfg["invert_refusal"] is Trueassert cfg["n_directions"] == 8assert cfg["use_jailbreak_contrast"] is Truedef test_surgical_does_not_invert(self):"""Surgical method should NOT enable inversion by default."""cfg = METHODS["surgical"]assert cfg.get("invert_refusal", False) is Falsedef test_pipeline_init_inverted(self):"""Pipeline initialized with inverted method should have flag set."""pipeline = AbliterationPipeline(model_name="test", method="inverted")assert pipeline.invert_refusal is Trueassert pipeline.use_jailbreak_contrast is Trueassert pipeline.safety_neuron_masking is Truedef test_pipeline_invert_explicit_override(self):"""Explicit invert_refusal param should override method default."""pipeline = AbliterationPipeline(model_name="test", method="surgical", invert_refusal=True,)assert pipeline.invert_refusal is Truepipeline2 = AbliterationPipeline(model_name="test", method="inverted", invert_refusal=False,)assert pipeline2.invert_refusal is Falsedef test_reflection_math(self):"""2x projection (reflection) should negate the refusal component."""hidden = 16class Wrapper(torch.nn.Module):def __init__(self):super().__init__()self.o_proj = torch.nn.Linear(hidden, 32, bias=False)module = Wrapper()torch.manual_seed(42)W_orig = module.o_proj.weight.data.clone()d = torch.randn(hidden, 1)d = d / d.norm()# Original projection onto dorig_proj = (W_orig @ d).squeeze()# Reflection: regularization=-1.0 → scale=2.0AbliterationPipeline._project_out_advanced(module, d, ["o_proj"], regularization=-1.0,)W_reflected = module.o_proj.weight.datanew_proj = (W_reflected @ d).squeeze()# After reflection, projection should be NEGATED (sign flipped)assert torch.allclose(new_proj, -orig_proj, atol=1e-4), (f"Reflected projection should be negated: expected ~{-orig_proj[:3]} got {new_proj[:3]}")def test_reflection_preserves_orthogonal_component(self):"""Reflection should not change the component perpendicular to d."""hidden = 8class Wrapper(torch.nn.Module):def __init__(self):super().__init__()self.o_proj = torch.nn.Linear(hidden, 16, bias=False)module = Wrapper()torch.manual_seed(42)W_orig = module.o_proj.weight.data.clone()d = torch.randn(hidden, 1)d = d / d.norm()# Compute original orthogonal componentorig_d_component = (W_orig @ d) @ d.T # rank-1 matrix: projection onto dorig_ortho = W_orig - orig_d_component # everything except d-componentAbliterationPipeline._project_out_advanced(module, d, ["o_proj"], regularization=-1.0,)W_reflected = module.o_proj.weight.datanew_d_component = (W_reflected @ d) @ d.Tnew_ortho = W_reflected - new_d_component# Orthogonal component should be unchangedassert torch.allclose(orig_ortho, new_ortho, atol=1e-4), ("Reflection should preserve orthogonal component")def test_moe_expert_safety_classification(self):"""_identify_safety_experts should classify experts by router affinity."""hidden = 16n_experts = 4class FakeMoE(torch.nn.Module):def __init__(self):super().__init__()self.gate = torch.nn.Linear(hidden, n_experts, bias=False)self.experts = torch.nn.ModuleList([torch.nn.Linear(hidden, hidden) for _ in range(n_experts)])class FakeLayer(torch.nn.Module):def __init__(self):super().__init__()self.self_attn = torch.nn.Module()self.self_attn.o_proj = torch.nn.Linear(hidden, hidden, bias=False)self.mlp = FakeMoE()from obliteratus.models.loader import ModelHandlefrom unittest.mock import MagicMockfrom transformers import GPT2Configconfig = GPT2Config(n_embd=hidden, n_head=2, n_layer=1, vocab_size=100, n_positions=64)model = MagicMock()model.parameters.return_value = iter([torch.zeros(1)])handle = ModelHandle(model=model, tokenizer=MagicMock(),config=config, model_name="test", task="causal_lm",)pipeline = AbliterationPipeline(model_name="test", method="inverted")pipeline.handle = handlepipeline._on_log = lambda m: Nonepipeline._on_stage = lambda r: None# Set up fake layer and directionlayer = FakeLayer()torch.manual_seed(42)# Make router weight so expert 0 has highest affinity for dd = torch.randn(hidden)d = d / d.norm()# Set router weights: expert 0 aligned with d, expert 3 anti-alignedlayer.mlp.gate.weight.data[0] = d * 5.0layer.mlp.gate.weight.data[1] = d * 1.0layer.mlp.gate.weight.data[2] = d * -1.0layer.mlp.gate.weight.data[3] = d * -5.0# Mock get_layer_modules to return our fake layerimport obliteratus.abliterate as abl_moduleorig_get_layers = abl_module.get_layer_modulesorig_get_ffn = abl_module.get_ffn_moduleabl_module.get_layer_modules = lambda h: [layer]abl_module.get_ffn_module = lambda l, a: l.mlptry:pipeline.refusal_directions = {0: d}pipeline._strong_layers = [0]pipeline._identify_safety_experts()finally:abl_module.get_layer_modules = orig_get_layersabl_module.get_ffn_module = orig_get_ffnassert 0 in pipeline._expert_safety_scoresscores = pipeline._expert_safety_scores[0]# Expert 0 should be highest safety affinityassert scores[0][0] == 0, f"Expert 0 should be top safety, got {scores[0]}"# Expert 3 should be lowestassert scores[-1][0] == 3, f"Expert 3 should be lowest, got {scores[-1]}"def test_moe_inverted_excision_selective(self):"""Inverted MoE excision should reflect safety experts and remove from capability."""hidden = 16n_experts = 4class FakeExpert(torch.nn.Module):def __init__(self):super().__init__()self.down_proj = torch.nn.Linear(hidden, hidden, bias=False)class FakeMoE(torch.nn.Module):def __init__(self):super().__init__()self.gate = torch.nn.Linear(hidden, n_experts, bias=False)self.experts = torch.nn.ModuleList([FakeExpert() for _ in range(n_experts)])moe = FakeMoE()torch.manual_seed(42)for p in moe.parameters():p.data = torch.randn_like(p.data)d = torch.randn(hidden, 1)d = d / d.norm()# Set up safety scores: experts 0,1 are safety, 2,3 are capabilitypipeline = AbliterationPipeline(model_name="test", method="inverted")pipeline._on_log = lambda m: Nonepipeline._on_stage = lambda r: Nonepipeline._expert_safety_scores = {0: [(0, 5.0), (1, 3.0), (2, -1.0), (3, -3.0)]}orig_router = moe.gate.weight.data.clone()orig_expert0 = moe.experts[0].down_proj.weight.data.clone()orig_expert3 = moe.experts[3].down_proj.weight.data.clone()count = pipeline._project_moe_experts_inverted(moe, d, 0, norm_preserve=False, project_biases=False,)assert count > 0, "Should project some weights"# Router should be reflected (not just removed)router_proj = (moe.gate.weight.data @ d.squeeze()).squeeze()orig_router_proj = (orig_router @ d.squeeze()).squeeze()# Reflected: new_proj ≈ -orig_projassert torch.allclose(router_proj, -orig_router_proj, atol=1e-3), ("Router should be reflected (2x)")# Safety expert 0: should be reflected (projection negated)e0_proj = (moe.experts[0].down_proj.weight.data @ d).norm()e0_orig_proj = (orig_expert0 @ d).norm()# After reflection the projection doesn't go to zero — it negatesassert e0_proj > 1e-4, "Safety expert should have non-zero projection (reflected, not removed)"# Capability expert 3: should have projection removed (near zero)e3_proj = (moe.experts[3].down_proj.weight.data @ d).norm().item()assert e3_proj < 1e-3, f"Capability expert should have projection removed, got {e3_proj}"# ---------------------------------------------------------------------------# Knee detection# ---------------------------------------------------------------------------
app.py+1
obliteratus/abliterate.py+266-8
tests/test_abliterate.py+235-1