TurkLM-scratch-0.3B / eval /bpc_two_sets.py
eademir's picture
Model card, config, tokenizer and evaluation bundle
f354976 verified
Raw History Blame Contribute Delete
3.39 kB
"""
Bits-per-character (BPC) of a causal LM on two sets of Turkish Wikipedia articles.
overlap : Wikipedia articles #5,001-5,200 of the 20231101 dump (data/bpc_docs.json, cached).
WARNING: this slice lies inside the TurkLM training stream - it is NOT held out. It is kept only because the
first published numbers used it; it rewards models that saw it. Do not use it to compare TurkLM with other models.
fresh : articles created AFTER the training cutoff (data/fresh_wiki.json, built by fetch_fresh_wiki.py). Use this one.
BPC = total negative log-likelihood (bits) / number of characters. It is comparable across tokenizers (perplexity is not).
Method: each document is cut into windows of 1,024 tokens; a window needs >= 2 tokens; loss is the mean token NLL of the window.
IMPORTANT (macOS / Apple GPU): the default sdpa attention on MPS (macOS 27, torch 2.12.1) is not causal and gives wrong,
far too low BPC. This script always uses attn_implementation="eager", which matches CPU fp32 and CUDA.
usage: python bpc_two_sets.py --model-path MODEL_DIR_OR_HF_ID [--json out.json] [--device cpu|cuda|mps]
"""
import argparse, json, math
from pathlib import Path
import torch
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
HERE = Path(__file__).parent
MAX_SEQ_LEN = 1024
@torch.no_grad()
def doc_nats_chars(model, tok, text, device):
text = text.strip()
ids = tok.encode(text, add_special_tokens=False)
nats = 0.0
for i in range(0, len(ids), MAX_SEQ_LEN):
chunk = ids[i:i + MAX_SEQ_LEN]
if len(chunk) < 2:
continue
x = torch.tensor([chunk], device=device)
nats += model(input_ids=x, labels=x).loss.item() * (len(chunk) - 1)
return nats, len(text)
def bpc(model, tok, texts, device, desc):
per_doc = [doc_nats_chars(model, tok, t, device) for t in tqdm(texts, desc=desc)]
return sum(n for n, _ in per_doc) / (math.log(2) * sum(c for _, c in per_doc)), per_doc
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model-path", required=True)
ap.add_argument("--json", default="")
ap.add_argument("--device", default="")
ap.add_argument("--sets", default="overlap,fresh")
a = ap.parse_args()
device = torch.device(a.device or ("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"))
tok = AutoTokenizer.from_pretrained(a.model_path)
model = AutoModelForCausalLM.from_pretrained(a.model_path, dtype=torch.bfloat16, attn_implementation="eager").to(device).eval()
out = {"model": a.model_path}
if "overlap" in a.sets:
texts = json.loads((HERE / "data" / "bpc_docs.json").read_text())
out["overlap"], per = bpc(model, tok, texts, device, "overlap set")
out["overlap_n"] = len(texts)
print(f"BPC overlap set ({len(texts)} articles, inside the training stream): {out['overlap']:.4f}")
if "fresh" in a.sets:
docs = json.loads((HERE / "data" / "fresh_wiki.json").read_text())
out["fresh"], per = bpc(model, tok, [d["text"] for d in docs], device, "fresh set")
out["fresh_n"] = len(docs)
print(f"BPC fresh set ({len(docs)} articles created after the cutoff): {out['fresh']:.4f}")
if a.json:
Path(a.json).write_text(json.dumps(out, indent=1))
if __name__ == "__main__":
main()