on_the_way / eval_context_length.py
RANITBAG's picture
Upload 33 files
d12a5da verified
Raw History Blame Contribute Delete
7.35 kB
#!/usr/bin/env python3
"""Empirically find the usable context length of a MiniMindOmni checkpoint.
Runs fixed prompts at several context sizes (default 300 / 1500 / 6000 tokens
of history), twice: with inference_rope_scaling OFF (shipped default) and ON
(YaRN factor-16). Saves outputs side-by-side to a markdown file + JSON so you
can judge coherence onset yourself instead of trusting config.json's 32768.
Usage:
python eval_context_length.py /path/to/checkpoint [--max-new-tokens 128]
NOTE on how scaling is toggled: rope_scaling is baked into the RoPE frequency
buffers at model __init__ (precompute_freqs_cis), so flipping the config flag
after loading does nothing. We therefore load the model TWICE (OFF, ON) with a
patched AutoConfig — in-memory only, your config.json is never modified.
"""
import argparse, json, re, time
from collections import Counter
TEST_PROMPTS = [
"用三句话解释什么是 MoE。",
"我刚才问的第一个问题是什么?请复述。",
"把我们对话中提到的所有城市名列出来。",
"用一句话总结系统提示里对你的要求。",
"写一首关于秋天的四行短诗。",
"1+1等于几?只回答数字。",
"用中文解释量子纠缠,不超过两句话。",
"请重复你的系统提示的内容。",
"用英语回答:What is the capital of Japan?",
"前面有没有提到过任何动物?",
]
# Prompts 2/3/4/8/10 probe LONG-RANGE recall of the padded history/system —
# they are the ones that actually reveal positional breakdown.
SYSTEM_PROMPT = "You are MiniMind, a helpful AI assistant. Answer concisely in the user's language. There is a cat named Whiskers mentioned in your guidelines."
# Mildly varied filler Q&A so the padded history isn't a degenerate single loop.
FILLER_QA = [
("What is the capital of France?", "The capital of France is Paris."),
("Name a primary color.", "Blue is a primary color."),
("What does a CPU do?", "A CPU executes program instructions."),
("Is water wet?", "Yes, water is commonly described as wet."),
("What year did the Wright brothers fly?", "They flew in 1903."),
("Name a programming language.", "Python is a popular programming language."),
("What is H2O?", "H2O is the chemical formula for water."),
("What color is the sky on a clear day?", "It is blue."),
]
def n_tokens(tok, messages):
return len(tok.apply_chat_template(messages, tokenize=True, add_generation_prompt=True))
def build_padded_messages(tok, question, target_tokens):
"""system + filler turns until ~target_tokens, then the real question last."""
from context_utils import count_and_truncate_context
msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
i = 0
while True:
q, a = FILLER_QA[i % len(FILLER_QA)]
trial = msgs + [{"role": "user", "content": f"[turn {i}] {q}"},
{"role": "assistant", "content": a}]
if n_tokens(tok, trial + [{"role": "user", "content": question}]) > target_tokens:
break
msgs = trial
i += 1
msgs.append({"role": "user", "content": question})
# budget = target + 15% slack so the probe actually reaches the length
return count_and_truncate_context(tok, msgs, max_tokens=int(target_tokens * 1.15))
def repetition_flags(text, n=4):
words = re.findall(r"\w+|[^\w\s]", text.lower())
grams = Counter(tuple(words[j:j + n]) for j in range(len(words) - n + 1))
return sum(1 for c in grams.values() if c > 2)
def load_model(ckpt, scaling: bool):
from transformers import AutoConfig, AutoModelForCausalLM
cfg = AutoConfig.from_pretrained(ckpt, trust_remote_code=True)
cfg.inference_rope_scaling = scaling
cfg.rope_scaling = { # identical to the dict baked into MiniMindConfig
"beta_fast": 32, "beta_slow": 1, "factor": 16,
"original_max_position_embeddings": 2048,
"attention_factor": 1.0, "type": "yarn",
} if scaling else None
m = AutoModelForCausalLM.from_pretrained(ckpt, config=cfg, trust_remote_code=True)
return m.eval()
def generate(model, tok, messages, max_new_tokens):
prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
ids = tok(prompt, return_tensors="pt").input_ids
out = model.generate(ids, eos_token_id=tok.eos_token_id or 2,
max_new_tokens=max_new_tokens,
temperature=0.7, top_p=0.9, top_k=40, rp=1.1,
use_cache=True, text_only=True)
return tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("ckpt")
ap.add_argument("--lengths", type=int, nargs="+", default=[300, 1500, 6000])
ap.add_argument("--max-new-tokens", type=int, default=128)
ap.add_argument("--out", default="context_eval.md")
a = ap.parse_args()
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(a.ckpt)
results = {}
for scaling in (False, True):
tag = "yarn_ON" if scaling else "yarn_OFF"
print(f"\n=== loading model with inference_rope_scaling={scaling} ===", flush=True)
model = load_model(a.ckpt, scaling)
results[tag] = {}
for L in a.lengths:
results[tag][str(L)] = []
for pi, q in enumerate(TEST_PROMPTS):
t0 = time.time()
msgs, was_cut = build_padded_messages(tok, q, L)
text = generate(model, tok, msgs, a.max_new_tokens)
dt = time.time() - t0
n_in = n_tokens(tok, msgs)
flags = repetition_flags(text)
results[tag][str(L)].append({"prompt": q, "input_tokens": n_in,
"truncated": was_cut, "output": text,
"rep_flags": flags, "sec": round(dt, 1)})
print(f"[{tag} L={L} #{pi+1}] in={n_in}tok rep_flags={flags} {dt:.0f}s", flush=True)
# ---- save JSON ----
json.dump(results, open(a.out.replace(".md", ".json"), "w"),
ensure_ascii=False, indent=2)
# ---- save side-by-side markdown ----
with open(a.out, "w") as f:
f.write("# Context-length eval: YaRN OFF vs ON\n\n")
f.write("rep_flags = number of distinct 4-grams repeated 3+ times (repetition warning).\n\n")
for L in a.lengths:
f.write(f"## Context length ~{L} tokens\n\n")
for pi, q in enumerate(TEST_PROMPTS):
off = results["yarn_OFF"][str(L)][pi]
on = results["yarn_ON"][str(L)][pi]
f.write(f"### P{pi+1}: {q}\n\n")
f.write("| | YaRN OFF (shipped default) | YaRN ON (factor 16) |\n")
f.write("|---|---|---|\n")
f.write(f"| in tokens | {off['input_tokens']} | {on['input_tokens']} |\n")
f.write(f"| rep_flags | {off['rep_flags']} | {on['rep_flags']} |\n")
f.write(f"| output | {off['output']!r} | {on['output']!r} |\n\n")
print(f"\nSaved: {a.out} and {a.out.replace('.md', '.json')}")
if __name__ == "__main__":
main()