Download apply_patch.py from yasserrmd/MiniCPM5-1B-WSP-NoLoop: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/yasserrmd/MiniCPM5-1B-WSP-NoLoop/resolve/main/apply_patch.py
- Command line
-
hf download hf://yasserrmd/MiniCPM5-1B-WSP-NoLoop/apply_patch.py
-
curl -L -o apply_patch.py https://huggingface.co/yasserrmd/MiniCPM5-1B-WSP-NoLoop/resolve/main/apply_patch.py
2.24 kB
| """ | |
| WSP NoLoop v2 patch for openbmb/MiniCPM5-1B (mean-replacement edit). | |
| For each of the 64 MLP neurons listed in neurons.json: | |
| * its column in model.layers[l].mlp.down_proj.weight is set to zero, and | |
| * its average contribution (column x mean activation) is added to a constant | |
| down_proj bias, | |
| so the neuron always outputs its average value instead of its input-dependent | |
| value. This removes the repetition-driving signal without shifting the | |
| residual stream, which is what cost math and knowledge in v1 (plain zeroing). | |
| The model is saved with config.mlp_bias = True. gate_proj / up_proj biases and | |
| the down_proj bias of untouched layers are all zero. | |
| Usage: | |
| python apply_patch.py --out ./MiniCPM5-1B-WSP-NoLoop-v2 | |
| """ | |
| import argparse | |
| import json | |
| from collections import defaultdict | |
| import torch | |
| from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer | |
| BASE = "openbmb/MiniCPM5-1B" | |
| def build(neurons_path, base=BASE): | |
| spec = json.load(open(neurons_path)) | |
| by_layer = defaultdict(list) | |
| for layer, neuron in spec["neurons"]: | |
| by_layer[layer].append(neuron) | |
| means = {tuple(map(int, k.split(","))): v for k, v in spec["neuron_means"].items()} | |
| cfg = AutoConfig.from_pretrained(base) | |
| cfg.mlp_bias = True | |
| model = AutoModelForCausalLM.from_pretrained(base, config=cfg, dtype=torch.bfloat16) | |
| for layer in model.model.layers: | |
| for lin in (layer.mlp.gate_proj, layer.mlp.up_proj, layer.mlp.down_proj): | |
| lin.bias.zero_() | |
| for l, idx in by_layer.items(): | |
| W = model.model.layers[l].mlp.down_proj.weight | |
| mu = torch.tensor([means[(l, n)] for n in idx], dtype=torch.float32) | |
| bias = (W[:, idx].float() * mu[None, :]).sum(1) | |
| model.model.layers[l].mlp.down_proj.bias.copy_(bias.to(W.dtype)) | |
| W[:, idx] = 0 | |
| return model | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--neurons", default="neurons.json") | |
| ap.add_argument("--out", required=True) | |
| a = ap.parse_args() | |
| model = build(a.neurons) | |
| model.save_pretrained(a.out, safe_serialization=True) | |
| AutoTokenizer.from_pretrained(BASE).save_pretrained(a.out) | |
| print(f"Patched model saved to {a.out}") | |