File size: 2,239 Bytes
0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 0c5dc21 91682c8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | """
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"
@torch.no_grad()
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}")
|