spreizzaehler-daten / code /amputate_model_final.py
Davidmg0815's picture
Add code/amputate_model_final.py
089042b verified
Raw History Blame Contribute Delete
7.56 kB
#!/usr/bin/env python3
"""Gehirnamputation Qwen2.5-7B-Instruct: Tokens mit Doppelzeichen entfernen.
Tokenizer (JSON-Roundtrip, tokenizers 0.22.2) + Tensor-Chirurgie (embed/lm_head).
keep_ids = Filter (auf dekodiertem Text) + WHITELIST (added_tokens + special ids).
"""
import os
import json
import shutil
from collections import Counter
from pathlib import Path
os.environ.setdefault("HF_HOME", "/home/david/Schreibtisch/Platte/cache/huggingface")
os.environ.setdefault("HF_HUB_CACHE", "/home/david/Schreibtisch/Platte/cache/huggingface/hub")
import torch
from tokenizers import Tokenizer
from transformers import AutoTokenizer, AutoModelForCausalLM
MODEL_NAME = "unsloth/Qwen2.5-7B-Instruct"
TARGET_DIR = Path("/mnt/models/graf_zahl/qwen_amputated_base")
EXPECTED_KEEP = 106915
def hat_doppelzeichen(text: str) -> bool:
counts = Counter(c.lower() for c in text if c.isalnum())
return any(n > 1 for n in counts.values())
def map_id(value, old_to_new):
if value is None:
return None
if isinstance(value, (list, tuple)):
return [old_to_new[v] for v in value]
return old_to_new[value]
def main():
print("=== [1/7] keep_ids bestimmen (Filter + Whitelist) ===", flush=True)
tok = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
vocab_size = len(tok)
d = json.loads(tok._tokenizer.to_str())
base_vocab = d["model"]["vocab"]
merges = d["model"]["merges"]
added_tokens = d["added_tokens"]
added_ids = {t["id"] for t in added_tokens}
special_ids = set(tok.all_special_ids)
decoded = {}
CHUNK = 20000
for i in range(0, vocab_size, CHUNK):
chunk = list(range(i, min(i + CHUNK, vocab_size)))
for tid, txt in zip(chunk, tok.batch_decode([[t] for t in chunk], skip_special_tokens=False)):
decoded[tid] = txt
keep_ids = [
oid for oid in range(vocab_size)
if (oid in added_ids) or (oid in special_ids) or not hat_doppelzeichen(decoded[oid])
]
n_keep = len(keep_ids)
print(f" Vokabular {vocab_size} -> {n_keep} (Verlust {(vocab_size - n_keep) / vocab_size * 100:.2f}%)")
assert n_keep == EXPECTED_KEEP, f"ERWARTET {EXPECTED_KEEP}, IST {n_keep}"
print("=== [2/7] Mapping old_to_new_id ===", flush=True)
old_to_new = {old: new for new, old in enumerate(keep_ids)}
keep_set = set(keep_ids)
assert all(old_to_new[k] == i for i, k in enumerate(keep_ids))
print("=== [3/7] Tokenizer-JSON umbauen ===", flush=True)
new_vocab = {raw: old_to_new[oid] for raw, oid in base_vocab.items() if oid in keep_set}
new_added = []
for t in added_tokens:
nt = dict(t)
nt["id"] = old_to_new[t["id"]]
new_added.append(nt)
new_merges = [
(a, b) for a, b in merges
if (a + b) in new_vocab and a in new_vocab and b in new_vocab
]
n_merge_result_only = sum(1 for a, b in merges if (a + b) in new_vocab)
print(f" Basis-Vokabular: {len(base_vocab)} -> {len(new_vocab)}")
print(f" Added Tokens: {len(added_tokens)} -> {len(new_added)}")
print(f" Merges: {len(merges)} -> {len(new_merges)} "
f"(nur Ergebnis-Regel haette {n_merge_result_only} behalten)")
d["model"]["vocab"] = new_vocab
d["model"]["merges"] = new_merges
d["added_tokens"] = new_added
new_raw = Tokenizer.from_str(json.dumps(d))
assert new_raw.get_vocab_size() == n_keep, f"{new_raw.get_vocab_size()} != {n_keep}"
print("=== [4/7] Tokenizer + Config-IDs speichern ===", flush=True)
TARGET_DIR.mkdir(parents=True, exist_ok=True)
tok.save_pretrained(TARGET_DIR)
new_raw.save(str(TARGET_DIR / "tokenizer.json"))
tc_path = TARGET_DIR / "tokenizer_config.json"
tc = json.loads(tc_path.read_text(encoding="utf-8"))
if "added_tokens_decoder" in tc:
tc["added_tokens_decoder"] = {
str(old_to_new[int(k)]): v for k, v in tc["added_tokens_decoder"].items()
}
tc_path.write_text(json.dumps(tc, ensure_ascii=False, indent=2), encoding="utf-8")
print(f" tokenizer_config.json: added_tokens_decoder auf neue IDs gemappt")
print("=== [5/7] Modell laden (CPU, bf16) ===", flush=True)
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME, device_map="cpu", dtype=torch.bfloat16, trust_remote_code=True,
)
print(f" embed_tokens {tuple(model.model.embed_tokens.weight.shape)}, "
f"lm_head {tuple(model.lm_head.weight.shape)}, "
f"tie_word_embeddings={model.config.tie_word_embeddings}")
assert not model.config.tie_word_embeddings, "Tied embeddings: Slicing muesste anders laufen"
print("=== [6/7] Tensor-Chirurgie + Config ===", flush=True)
keep_tensor = torch.tensor(keep_ids, dtype=torch.long)
with torch.no_grad():
model.model.embed_tokens.weight.data = model.model.embed_tokens.weight.data[keep_tensor].contiguous()
model.lm_head.weight.data = model.lm_head.weight.data[keep_tensor].contiguous()
model.model.embed_tokens.num_embeddings = n_keep
model.lm_head.out_features = n_keep
model.config.vocab_size = n_keep
for name in ("eos_token_id", "bos_token_id", "pad_token_id"):
for cfg in (model.config, model.generation_config):
old = getattr(cfg, name, None)
if old is not None:
new = map_id(old, old_to_new)
setattr(cfg, name, new)
print(f" {type(cfg).__name__}.{name}: {old} -> {new}")
assert model.model.embed_tokens.weight.shape[0] == n_keep
assert model.lm_head.weight.shape[0] == n_keep
print("=== [7/7] Modell speichern ===", flush=True)
model.save_pretrained(TARGET_DIR, safe_serialization=True)
print(f" Gespeichert in {TARGET_DIR}")
print("\n=== VERIFIKATION (frisch von Platte) ===", flush=True)
new_tok = AutoTokenizer.from_pretrained(TARGET_DIR, trust_remote_code=True)
assert len(new_tok) == n_keep, f"len(new_tok)={len(new_tok)} != {n_keep}"
for old_id, name in ((151643, "<|endoftext|>"), (151644, "<|im_start|>"), (151645, "<|im_end|>")):
new_id = old_to_new[old_id]
got = new_tok.convert_ids_to_tokens(new_id)
assert got == name, f"{name}: neue ID {new_id} liefert {got!r}"
print(f" {name}: {old_id} -> {new_id} OK")
for s in ["Hallo Welt", "Zaehl bitte: YYYYYYYYYY. Wie viele Y sind das?", "Ah ah ah! 1 2 3 4 5"]:
ids = new_tok.encode(s, add_special_tokens=False)
assert max(ids) < n_keep
back = new_tok.decode(ids)
print(f" {s!r} -> {len(ids)} Tokens -> {back!r} {'OK' if back == s else 'ABWEICHUNG'}")
assert back == s
msgs = [{"role": "user", "content": "Hi"}]
chat_text = new_tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
chat_ids = new_tok.encode(chat_text, add_special_tokens=False)
assert max(chat_ids) < n_keep
print(f" Chat-Template: {len(chat_ids)} Tokens, max ID {max(chat_ids)} < {n_keep}")
check = AutoModelForCausalLM.from_pretrained(TARGET_DIR, device_map="cpu", dtype=torch.bfloat16)
assert check.model.embed_tokens.weight.shape[0] == n_keep
assert check.lm_head.weight.shape[0] == n_keep
assert check.config.vocab_size == n_keep
ref = model.model.embed_tokens.weight[:5]
assert torch.equal(check.model.embed_tokens.weight[:5], ref)
print(f" Modell neu geladen: embed/lm_head {n_keep} x {check.config.hidden_size}, Gewichte identisch")
print("\nERFOLG: amputiertes Modell liegt unter", TARGET_DIR)
if __name__ == "__main__":
main()