Spaces:
Running on Zero
Running on Zero
Upload 81 files
Browse filesFiles changed (2)
230 unmodified lines231232233234235236616 unmodified lines853854855856857858859860307 unmodified lines11681169117011711172117311744 unmodified lines117911801181118211831184118511861187118811891 unmodified line11911192119311941195119611971198119912001201120212031204120510 unmodified lines1216121712181219122012211 unmodified line1223122412251226122712281229123073 unmodified lines13041305130613071308130916 unmodified lines1326132713281329133013315 unmodified lines133713381339134013411342134329 unmodified lines13731374137513761377137876 unmodified lines14551456145714581459146019 unmodified lines148014811482148314841485148611 unmodified lines149814991500150115021503150415051506230 unmodified lines# Common output projection attribute names per sub-module type_ATTN_OUT_NAMES = ["o_proj", "out_proj", "dense", "c_proj", "wo"]_FFN_OUT_NAMES = ["down_proj", "c_proj", "dense_4h_to_h", "fc_out", "fc2", "w2"]# Expert input projections — early computation that can encode refusal_FFN_IN_NAMES = ["up_proj", "gate_proj", "w1", "w3", "fc1"]616 unmodified linesbest_dist = distbest_k = i + 1 # include points up to and including the knee# Ensure at least 1 layer, and apply minimum threshold of 10% to avoid noisemin_threshold = max_n * 0.1selected = [idx for idx, norm in sorted_layers[:best_k] if norm >= min_threshold]return selected if selected else [sorted_layers[0][0]]307 unmodified lines# Reduce regularization for strong-signal layers (project more),# increase for weak-signal layers (project less, preserve capability)weight = self._layer_excise_weights[idx]layer_reg = self.regularization + (1.0 - weight) * (1.0 - self.regularization) * 0.5count = 0# Process each direction in the subspace4 unmodified lines# ── Attention projection ──────────────────────────try:attn = get_attention_module(layers[idx], arch)if (self.attention_head_surgeryand idx in self._refusal_headsand n_headsand n_heads > 1):# Selective head surgery: only target top refusal headscount += self._project_head_selective(attn, d, self._refusal_heads[idx],n_heads=n_heads,1 unmodified linenorm_preserve=self.norm_preserve,regularization=layer_reg,)else:# Standard: project from full o_projcount += self._project_out_advanced(attn, d, _ATTN_OUT_NAMES,norm_preserve=self.norm_preserve,regularization=layer_reg,)if self.project_biases:count += self._project_bias(attn, d, _ATTN_OUT_NAMES)except (AttributeError, RuntimeError) as e:warnings.warn(f"Layer {idx}: attention projection failed ({type(e).__name__}: {e}). "10 unmodified linesregularization=layer_reg,)if ffn_count == 0:ffn_count = self._project_moe_experts(ffn, d,norm_preserve=self.norm_preserve,1 unmodified lineproject_biases=self.project_biases,)else:if self.project_biases:ffn_count += self._project_bias(ffn, d, _FFN_OUT_NAMES)# Safety-neuron masking (applied after projection for# complementary effect — projection reduces refusal component,73 unmodified linestotal_modified += modified_this_passself.log(f" Pass {pass_num + 1}: modified {modified_this_pass} weight matrices")grad_ctx.__exit__(None, None, None)elapsed = time.time() - t016 unmodified linesextras.append("head-surgery")if total_sae_projections > 0:extras.append(f"SAE({total_sae_projections})")mode_label = " + ".join(extras) if extras else "standard"self.log(f"Excised refusal from {total_modified} matrices [{mode_label}] ({elapsed:.1f}s)")5 unmodified lines)def _distill_inner(self):"""Re-run distillation without emitting stage events (for iterative refinement)."""n_layers = len(self._harmful_means)norms: dict[int, float] = {}n_dirs = self.n_directions29 unmodified linessorted_layers = sorted(norms.items(), key=lambda x: x[1], reverse=True)self._strong_layers = self._select_layers_knee(sorted_layers)@staticmethoddef _is_quantized_param(param) -> bool:"""Check if a parameter is bitsandbytes 4-bit or 8-bit quantized."""76 unmodified linesin-place operations on packed NF4 storage are silent no-ops."""scale = 1.0 - regularizationfor name in candidate_names:proj = getattr(module, name, None)19 unmodified linesif is_quantized:AbliterationPipeline._replace_quantized_weight(proj, W)return 1elif W.shape[0] == d.shape[0]:# Transposed (e.g. GPT-2 Conv1D): W is (hidden_dim, out_features)11 unmodified linesif is_quantized:AbliterationPipeline._replace_quantized_weight(proj, W)return 1return 0@staticmethoddef _project_bias(230 unmodified lines231232233234235236237238239240241242243244616 unmodified lines861862863864865866867868307 unmodified lines11761177117811791180118111824 unmodified lines11871188118911901191119211931194119511961197119811991200120112021203120412051206120712081 unmodified line12101211121212131214121510 unmodified lines12261227122812291230123112321 unmodified line1234123512361237123812391240124112421243124412451246124712481249125073 unmodified lines132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136016 unmodified lines137713781379138013811382138313845 unmodified lines1390139113921393139413951396139713981399140029 unmodified lines14301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145676 unmodified lines153315341535153615371538153919 unmodified lines155915601561156215631564156511 unmodified lines157715781579158015811582158315841585230 unmodified lines# Common output projection attribute names per sub-module type_ATTN_OUT_NAMES = ["o_proj", "out_proj", "dense", "c_proj", "wo"]# Attention input projections — q/k/v carry significant refusal signal and MUST be projected_ATTN_IN_NAMES = ["q_proj", "k_proj", "v_proj", # LLaMA, Mistral, Qwen, GPT-OSS"qkv_proj", "Wqkv", # Fused QKV (various architectures)"c_attn", # GPT-2 fused QKV"query_key_value", # Falcon, BLOOM"W_pack", # Baichuan]_FFN_OUT_NAMES = ["down_proj", "c_proj", "dense_4h_to_h", "fc_out", "fc2", "w2"]# Expert input projections — early computation that can encode refusal_FFN_IN_NAMES = ["up_proj", "gate_proj", "w1", "w3", "fc1"]616 unmodified linesbest_dist = distbest_k = i + 1 # include points up to and including the knee# Ensure at least 1 layer, and apply minimum threshold of 5% to avoid noisemin_threshold = max_n * 0.05selected = [idx for idx, norm in sorted_layers[:best_k] if norm >= min_threshold]return selected if selected else [sorted_layers[0][0]]307 unmodified lines# Reduce regularization for strong-signal layers (project more),# increase for weak-signal layers (project less, preserve capability)weight = self._layer_excise_weights[idx]layer_reg = self.regularization + (1.0 - weight) * (1.0 - self.regularization) * 0.15count = 0# Process each direction in the subspace4 unmodified lines# ── Attention projection ──────────────────────────try:attn = get_attention_module(layers[idx], arch)# Project refusal from ALL attention weight matrices:# output (o_proj) AND input (q_proj, k_proj, v_proj)count += self._project_out_advanced(attn, d, _ATTN_OUT_NAMES + _ATTN_IN_NAMES,norm_preserve=self.norm_preserve,regularization=layer_reg,)if self.project_biases:count += self._project_bias(attn, d, _ATTN_OUT_NAMES + _ATTN_IN_NAMES)# Additional head surgery: second-pass precision targeting# on the top safety heads to remove residual refusal signalif (self.attention_head_surgeryand idx in self._refusal_headsand n_headsand n_heads > 1):count += self._project_head_selective(attn, d, self._refusal_heads[idx],n_heads=n_heads,1 unmodified linenorm_preserve=self.norm_preserve,regularization=layer_reg,)except (AttributeError, RuntimeError) as e:warnings.warn(f"Layer {idx}: attention projection failed ({type(e).__name__}: {e}). "10 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,1 unmodified lineproject_biases=self.project_biases,)else:# Dense model: also project FFN input projections# (up_proj, gate_proj carry refusal signal too)ffn_count += self._project_out_advanced(ffn, d, _FFN_IN_NAMES,norm_preserve=self.norm_preserve,regularization=layer_reg,)if self.project_biases:ffn_count += self._project_bias(ffn, d, _FFN_OUT_NAMES + _FFN_IN_NAMES,)# Safety-neuron masking (applied after projection for# complementary effect — projection reduces refusal component,73 unmodified linestotal_modified += modified_this_passself.log(f" Pass {pass_num + 1}: modified {modified_this_pass} weight matrices")# ── lm_head projection ────────────────────────────────────────# The language model head converts hidden states to token logits.# Even if all internal layers are projected, lm_head can still# "read" the refusal direction and produce refusal tokens.# Project using the direction from the last strong layer (closest# to the output).lm_head_count = 0if self._strong_layers and self.handle:last_strong = max(self._strong_layers)model = self.handle.modelif last_strong in self.refusal_subspaces:subspace = self.refusal_subspaces[last_strong]for dir_idx in range(subspace.shape[0]):direction = subspace[dir_idx]lm_device = next(model.parameters()).deviced = direction.to(lm_device).unsqueeze(-1)# Try common lm_head attribute namesfor 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 dif lm_head_count > 0:total_modified += lm_head_countself.log(f" lm_head: {lm_head_count} projections")grad_ctx.__exit__(None, None, None)elapsed = time.time() - t016 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"self.log(f"Excised refusal from {total_modified} matrices [{mode_label}] ({elapsed:.1f}s)")5 unmodified lines)def _distill_inner(self):"""Re-run distillation without emitting stage events (for iterative refinement).Includes jailbreak-contrastive blending and head re-identificationto keep directions fresh after weight modifications."""n_layers = len(self._harmful_means)norms: dict[int, float] = {}n_dirs = self.n_directions29 unmodified linessorted_layers = sorted(norms.items(), key=lambda x: x[1], reverse=True)self._strong_layers = self._select_layers_knee(sorted_layers)# Re-apply jailbreak-contrastive blending on updated directionsif self.use_jailbreak_contrast and self._jailbreak_means:blend_alpha = 0.5for idx in self._strong_layers:if idx not in self._jailbreak_means:continuejb_diff = (self._harmful_means[idx] - self._jailbreak_means[idx]).squeeze(0)jb_norm = jb_diff.norm()if jb_norm > 0:jb_dir = jb_diff / jb_normstd_dir = self.refusal_directions[idx]blended = (1 - blend_alpha) * std_dir + blend_alpha * jb_dirblended = blended / blended.norm()self.refusal_directions[idx] = blendedself.refusal_subspaces[idx][0] = blended# Re-identify refusal heads with updated directionsif self.attention_head_surgery:self._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."""76 unmodified linesin-place operations on packed NF4 storage are silent no-ops."""scale = 1.0 - regularizationcount = 0for name in candidate_names:proj = getattr(module, name, None)19 unmodified linesif is_quantized:AbliterationPipeline._replace_quantized_weight(proj, W)count += 1elif W.shape[0] == d.shape[0]:# Transposed (e.g. GPT-2 Conv1D): W is (hidden_dim, out_features)11 unmodified linesif is_quantized:AbliterationPipeline._replace_quantized_weight(proj, W)count += 1return count@staticmethoddef _project_bias(
310 unmodified lines311312313314315316310 unmodified linesassert abs(original_norm - new_norm) < 1e-4# ---------------------------------------------------------------------------# MoE projection (router, shared expert, input/output, fused)# ---------------------------------------------------------------------------310 unmodified lines311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426310 unmodified linesassert abs(original_norm - new_norm) < 1e-4# ---------------------------------------------------------------------------# Full attention projection (q/k/v + o_proj)# ---------------------------------------------------------------------------class TestAttentionFullProjection:"""Test that ALL attention weight matrices are projected (not just o_proj)."""def test_qkv_all_projected(self):"""q_proj, k_proj, v_proj should all be projected alongside o_proj."""hidden = 16class FakeAttn(torch.nn.Module):def __init__(self):super().__init__()self.q_proj = torch.nn.Linear(hidden, hidden, bias=False)self.k_proj = torch.nn.Linear(hidden, hidden, bias=False)self.v_proj = torch.nn.Linear(hidden, hidden, bias=False)self.o_proj = torch.nn.Linear(hidden, hidden, bias=False)attn = FakeAttn()torch.manual_seed(42)for p in attn.parameters():p.data = torch.randn_like(p.data)originals = {name: getattr(attn, name).weight.data.clone()for name in ["q_proj", "k_proj", "v_proj", "o_proj"]}d = torch.randn(hidden, 1)d = d / d.norm()from obliteratus.abliterate import _ATTN_OUT_NAMES, _ATTN_IN_NAMEScount = AbliterationPipeline._project_out_advanced(attn, d, _ATTN_OUT_NAMES + _ATTN_IN_NAMES,)assert count == 4, f"Should project 4 weights (q/k/v/o), got {count}"for name in ["q_proj", "k_proj", "v_proj", "o_proj"]:assert not torch.allclose(getattr(attn, name).weight.data, originals[name]), f"{name} should be modified"def test_project_all_does_not_early_return(self):"""_project_out_advanced should project ALL matching weights, not just first."""hidden = 16class FakeModule(torch.nn.Module):def __init__(self):super().__init__()self.up_proj = torch.nn.Linear(hidden, 32, bias=False)self.gate_proj = torch.nn.Linear(hidden, 32, bias=False)mod = FakeModule()torch.manual_seed(42)orig_up = mod.up_proj.weight.data.clone()orig_gate = mod.gate_proj.weight.data.clone()d = torch.randn(hidden, 1)d = d / d.norm()from obliteratus.abliterate import _FFN_IN_NAMEScount = AbliterationPipeline._project_out_advanced(mod, d, _FFN_IN_NAMES)assert count == 2, f"Should project both up_proj and gate_proj, got {count}"assert not torch.allclose(mod.up_proj.weight.data, orig_up), "up_proj should be modified"assert not torch.allclose(mod.gate_proj.weight.data, orig_gate), "gate_proj should be modified"def test_lm_head_projection(self):"""lm_head should be projectable via _project_out_advanced."""hidden = 16vocab = 100class FakeModel(torch.nn.Module):def __init__(self):super().__init__()self.lm_head = torch.nn.Linear(hidden, vocab, bias=False)model = FakeModel()torch.manual_seed(42)orig = model.lm_head.weight.data.clone()d = torch.randn(hidden, 1)d = d / d.norm()count = AbliterationPipeline._project_out_advanced(model, d, ["lm_head"], regularization=0.0,)assert count == 1, "Should project lm_head"assert not torch.allclose(model.lm_head.weight.data, orig), "lm_head should be modified"# Verify refusal direction is removed from lm_headproj = (model.lm_head.weight.data @ d).norm().item()assert proj < 1e-4, f"Refusal direction should be removed from lm_head, proj={proj}"class TestKneeDetectionThreshold:"""Test that knee detection uses 5% threshold to include more layers."""def test_five_percent_threshold_includes_more(self):"""Layers between 5% and 10% of max should now be included."""# Layer norms: max=10.0, then several between 5%-10%sorted_layers = [(0, 10.0), (1, 8.0), (2, 6.0), (3, 0.7), (4, 0.6)]selected = AbliterationPipeline._select_layers_knee(sorted_layers)# 0.7 and 0.6 are 7% and 6% of max — should now be included (> 5% threshold)assert 3 in selected or 4 in selected, (f"Layers with 6-7% of max signal should be included, got {selected}")# ---------------------------------------------------------------------------# MoE projection (router, shared expert, input/output, fused)# ---------------------------------------------------------------------------
obliteratus/abliterate.py+97-18
tests/test_abliterate.py+110