bloxy-data-v1 / code /scripts /check_format.py
Radinkazemian's picture
Update Bloxy training code
6da8440 verified
Raw History Blame Contribute Delete
3.82 kB
"""Checks the built dataset against the real Gemma 4 chat template (no GPU needed).
Renders every example exactly like train.py does, tokenizes it with the real
tokenizer, and reports real token counts, how many examples would be dropped
for being too long, and the training cost. Also writes masked samples so you
can see exactly which tokens Bloxy learns.
python scripts/check_format.py --data out/train.jsonl.gz
"""
from __future__ import annotations
import argparse
import json
import statistics
import sys
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from train import read_rows, render, tokenize_example # noqa: E402
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default=str(ROOT / "out" / "train.jsonl.gz"))
ap.add_argument("--tokenizer", default="unsloth/gemma-4-12b-it")
ap.add_argument("--max_len", type=int, default=4096)
ap.add_argument("--tps", type=float, default=2000, help="training tokens/sec on the rented GPU")
ap.add_argument("--price", type=float, default=0.59, help="$/hour of the GPU")
ap.add_argument("--out", default=str(ROOT / "out"))
args = ap.parse_args()
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(args.tokenizer)
rows = read_rows(args.data)
lens = defaultdict(list)
trained = Counter()
dropped = Counter()
errors = Counter()
samples = {}
for r in rows:
src = r.get("source", "?")
try:
text = render(tok, r)
except Exception as e:
errors[src] += 1
if errors[src] <= 2:
print(f"render error in {src}: {e!r}")
continue
ex = tokenize_example(tok, text, args.max_len)
if ex is None:
dropped[src] += 1
continue
lens[src].append(len(ex["input_ids"]))
trained[src] += sum(l != -100 for l in ex["labels"])
if src not in samples:
parts, cur, masked = [], [], None
for t, l in zip(ex["input_ids"], ex["labels"]):
m = l == -100
if masked is not None and m != masked:
s = tok.decode(cur)
parts.append(f"\x1b{s}\x1c" if masked else s)
cur = []
cur.append(t)
masked = m
if cur:
s = tok.decode(cur)
parts.append(f"\x1b{s}\x1c" if masked else s)
samples[src] = "".join(parts)
total = sum(sum(v) for v in lens.values())
hours = total / args.tps / 3600
report = {
"examples_kept": sum(len(v) for v in lens.values()),
"dropped_too_long_or_empty": dict(dropped),
"render_errors": dict(errors),
"tokens_total": total,
"trained_tokens": sum(trained.values()),
"by_source": {s: {"n": len(v), "mean_len": int(statistics.mean(v)), "max_len": max(v),
"tokens": sum(v)} for s, v in sorted(lens.items())},
"est_hours_1_epoch": round(hours, 2),
"est_cost_usd_1_epoch": round(hours * args.price, 2),
}
out = Path(args.out)
(out / "format_report.json").write_text(json.dumps(report, indent=2))
with open(out / "masked_samples.md", "w", encoding="utf-8") as f:
f.write("Text between ⟦ ⟧ is masked (not trained). Everything else is what Bloxy learns to write.\n")
for s, v in samples.items():
f.write(f"\n\n## {s}\n\n```\n{v.replace(chr(27), '⟦').replace(chr(28), '⟧')[:6000]}\n```\n")
print(json.dumps(report, indent=2))
if errors and sum(errors.values()) > 0.02 * len(rows):
sys.exit("too many render errors")
if __name__ == "__main__":
main()