Datasets:
Download code/compare_intelligence_v4.py from Davidmg0815/spreizzaehler-daten: direct link, hf CLI and curl.
- Browser
- Download file 7.76 kB
-
https://huggingface.co/datasets/Davidmg0815/spreizzaehler-daten/resolve/main/code/compare_intelligence_v4.py
- Command line
-
hf download hf://datasets/Davidmg0815/spreizzaehler-daten/code/compare_intelligence_v4.py
-
curl -L -o compare_intelligence_v4.py https://huggingface.co/datasets/Davidmg0815/spreizzaehler-daten/resolve/main/code/compare_intelligence_v4.py
7.76 kB
| #!/usr/bin/env python3 | |
| """Intelligenz- und Mathetests: Original Qwen2.5-7B-Instruct gegen geheiltes Modell gegen Hardcore-Modell. | |
| Gleiche Aufgaben, gleiche Einstellungen (bf16, GPU 0, Greedy, repetition_penalty 1.0, Standard-Chat-Template): | |
| GSM8K (100, Rechenaufgaben, Antwort per Text) | MMLU (100, Multiple Choice, Logits ueber A-D) | |
| ARC-Challenge (100, Multiple Choice) | Arithmetik (40, selbst erzeugt). | |
| """ | |
| import os | |
| os.environ["CUDA_VISIBLE_DEVICES"] = "0" | |
| PLATTE = "/home/david/Schreibtisch/Platte" | |
| os.environ.setdefault("HF_HOME", f"{PLATTE}/cache/huggingface") | |
| os.environ.setdefault("HF_HUB_CACHE", f"{PLATTE}/cache/huggingface/hub") | |
| os.environ["HF_HUB_OFFLINE"] = "1" | |
| import gc | |
| import json | |
| import random | |
| import re | |
| import time | |
| import torch | |
| from datasets import load_dataset | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| MODELS = [ | |
| ("v4", f"{PLATTE}/models/graf_zahl/qwen_graf_zahl_v4_merged"), | |
| ] | |
| RESULTS = f"{PLATTE}/models/graf_zahl/compare_intelligence_v4_results.json" | |
| N_GSM, N_MMLU, N_ARC = 100, 100, 100 | |
| SEED = 3407 | |
| BATCH = 16 | |
| def build_tasks(): | |
| rng = random.Random(SEED) | |
| g = load_dataset("openai/gsm8k", "main", split="test") | |
| gsm = [{"q": g[i]["question"], "a": float(g[i]["answer"].split("####")[-1].strip().replace(",", ""))} | |
| for i in rng.sample(range(len(g)), N_GSM)] | |
| m = load_dataset("cais/mmlu", "all", split="test") | |
| mmlu = [] | |
| for i in rng.sample(range(len(m)), N_MMLU): | |
| r = m[i] | |
| opts = "\n".join(f"{l}. {c}" for l, c in zip("ABCD", r["choices"])) | |
| mmlu.append({"q": f"The following is a multiple choice question about {r['subject'].replace('_', ' ')}.\n\n" | |
| f"{r['question']}\n{opts}\n\nAnswer with only the letter of the correct option.", | |
| "a": "ABCD"[r["answer"]], "labels": "ABCD", "subject": r["subject"]}) | |
| a = load_dataset("allenai/ai2_arc", "ARC-Challenge", split="test") | |
| arc = [] | |
| for i in rng.sample(range(len(a)), N_ARC): | |
| r = a[i] | |
| labels = r["choices"]["label"] | |
| opts = "\n".join(f"{l}. {t}" for l, t in zip(labels, r["choices"]["text"])) | |
| arc.append({"q": f"The following is a multiple choice science question.\n\n{r['question']}\n{opts}\n\n" | |
| "Answer with only the letter of the correct option.", "a": r["answerKey"], "labels": "".join(labels)}) | |
| ar = [] | |
| for _ in range(10): x, y = rng.randint(10000, 99999), rng.randint(10000, 99999); ar.append((f"{x} + {y}", x + y, "add")) | |
| for _ in range(10): x, y = rng.randint(50000, 99999), rng.randint(10000, 49999); ar.append((f"{x} - {y}", x - y, "sub")) | |
| for _ in range(10): x, y = rng.randint(100, 999), rng.randint(11, 99); ar.append((f"{x} * {y}", x * y, "mul 3x2")) | |
| for _ in range(5): x, y = rng.randint(100, 999), rng.randint(100, 999); ar.append((f"{x} * {y}", x * y, "mul 3x3")) | |
| for _ in range(5): y, q = rng.randint(12, 99), rng.randint(100, 999); ar.append((f"{y * q} / {y}", q, "div")) | |
| arith = [{"q": f"Berechne: {e} = ?\nAntworte nur mit der Zahl.", "a": float(v), "typ": t} for e, v, t in ar] | |
| return {"GSM8K": gsm, "MMLU": mmlu, "ARC-Challenge": arc, "Arithmetik": arith} | |
| def to_prompt(tok, text): | |
| return tok.apply_chat_template([{"role": "user", "content": text}], tokenize=False, add_generation_prompt=True) | |
| def last_number(s): | |
| nums = re.findall(r"-?\d[\d,]*\.?\d*", s.replace("$", "")) | |
| return float(nums[-1].replace(",", "").rstrip(".")) if nums else None | |
| def gsm_number(s): | |
| m = re.findall(r"Answer:\s*\$?\s*(-?\d[\d,]*\.?\d*)", s) | |
| return float(m[-1].replace(",", "").rstrip(".")) if m else last_number(s) | |
| def generate_batch(model, tok, prompts, max_new): | |
| outs = [] | |
| order = sorted(range(len(prompts)), key=lambda i: len(prompts[i])) | |
| res = [None] * len(prompts) | |
| for s in range(0, len(order), BATCH): | |
| idx = order[s:s + BATCH] | |
| enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True, add_special_tokens=False).to("cuda") | |
| out = model.generate(**enc, max_new_tokens=max_new, do_sample=False, repetition_penalty=1.0, | |
| eos_token_id=tok.eos_token_id, pad_token_id=tok.pad_token_id) | |
| for j, i in enumerate(idx): | |
| res[i] = tok.decode(out[j][enc["input_ids"].shape[1]:], skip_special_tokens=True) | |
| return res | |
| def choose_letters(model, tok, prompts, labels_list): | |
| letter_ids = {} | |
| for l in set("".join(labels_list)): | |
| ids = tok.encode(l, add_special_tokens=False) | |
| assert len(ids) == 1, (l, ids) | |
| letter_ids[l] = ids[0] | |
| res = [None] * len(prompts) | |
| order = sorted(range(len(prompts)), key=lambda i: len(prompts[i])) | |
| for s in range(0, len(order), BATCH): | |
| idx = order[s:s + BATCH] | |
| enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True, add_special_tokens=False).to("cuda") | |
| logits = model(**enc).logits[:, -1, :].float() | |
| for j, i in enumerate(idx): | |
| res[i] = max(labels_list[i], key=lambda l: logits[j, letter_ids[l]].item()) | |
| return res | |
| def main(): | |
| tasks = build_tasks() | |
| print({k: len(v) for k, v in tasks.items()}, flush=True) | |
| results = {} | |
| for name, path in MODELS: | |
| t0 = time.time() | |
| tok = AutoTokenizer.from_pretrained(path) | |
| tok.padding_side = "left" | |
| model = AutoModelForCausalLM.from_pretrained(path, dtype=torch.bfloat16, device_map={"": 0}).eval() | |
| print(f"\n===== {name} geladen ({len(tok)} Tokens im Vokabular, {time.time() - t0:.0f}s) =====", flush=True) | |
| r = {} | |
| outs = generate_batch(model, tok, [to_prompt(tok, t["q"] + "\nSolve the problem step by step. End your reply with 'Answer: <number>'.") | |
| for t in tasks["GSM8K"]], 512) | |
| ok = [gsm_number(o) is not None and abs(gsm_number(o) - t["a"]) < 1e-6 for o, t in zip(outs, tasks["GSM8K"])] | |
| r["GSM8K"] = {"richtig": sum(ok), "n": len(ok), "beispiel_antwort": outs[0][-300:]} | |
| print(f" GSM8K: {sum(ok)}/{len(ok)} ({time.time() - t0:.0f}s)", flush=True) | |
| for key in ("MMLU", "ARC-Challenge"): | |
| pick = choose_letters(model, tok, [to_prompt(tok, t["q"]) for t in tasks[key]], [t["labels"] for t in tasks[key]]) | |
| ok = [p == t["a"] for p, t in zip(pick, tasks[key])] | |
| r[key] = {"richtig": sum(ok), "n": len(ok)} | |
| print(f" {key}: {sum(ok)}/{len(ok)} ({time.time() - t0:.0f}s)", flush=True) | |
| outs = generate_batch(model, tok, [to_prompt(tok, t["q"]) for t in tasks["Arithmetik"]], 40) | |
| ok = [last_number(o) is not None and abs(last_number(o) - t["a"]) < 1e-6 for o, t in zip(outs, tasks["Arithmetik"])] | |
| by = {} | |
| for t, k in zip(tasks["Arithmetik"], ok): | |
| by.setdefault(t["typ"], []).append(k) | |
| r["Arithmetik"] = {"richtig": sum(ok), "n": len(ok), "je_typ": {k: f"{sum(v)}/{len(v)}" for k, v in by.items()}} | |
| print(f" Arithmetik: {sum(ok)}/{len(ok)} {r['Arithmetik']['je_typ']} ({time.time() - t0:.0f}s)", flush=True) | |
| results[name] = r | |
| json.dump(results, open(RESULTS, "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| del model | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| print("\n===== AUSWERTUNG =====") | |
| names = list(results) | |
| print(f"{'Test':16} " + " ".join(f"{n[:28]:>30}" for n in names)) | |
| for key in ("GSM8K", "MMLU", "ARC-Challenge", "Arithmetik"): | |
| print(f"{key:16} " + " ".join(f"{results[n][key]['richtig']:>4}/{results[n][key]['n']:<3} = {results[n][key]['richtig'] / results[n][key]['n'] * 100:5.1f} %".rjust(30) for n in names)) | |
| print(f"\nErgebnisse: {RESULTS}") | |
| if __name__ == "__main__": | |
| main() | |