Buckets:
| """Generate model outputs for evaluation items and append them to a JSONL file, one line per prompt. | |
| Runs are resumable: items already in the output file are skipped. Scoring reads these files. | |
| """ | |
| import json | |
| import os | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from src import model as model_io | |
| PROGRESS_EVERY = 50 | |
| def load_items(path="data/eval_set.jsonl"): | |
| with open(path, encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def drop_partial_tail(out_path): | |
| """Cut a last line that a stopped process left without its newline, so new lines start clean.""" | |
| path = Path(out_path) | |
| if not path.exists(): | |
| return 0 | |
| data = path.read_bytes() | |
| if not data or data.endswith(b"\n"): | |
| return 0 | |
| keep = data.rfind(b"\n") + 1 | |
| path.write_bytes(data[:keep]) | |
| print(f"dropped a partial last line of {len(data) - keep} bytes from {out_path}", flush=True) | |
| return len(data) - keep | |
| def done_ids(out_path): | |
| if not Path(out_path).exists(): | |
| return set() | |
| with open(out_path, encoding="utf-8") as f: | |
| return {json.loads(line)["item_id"] for line in f if line.strip()} | |
| def generate_batch(model, tokenizer, prompts, max_new_tokens): | |
| """Greedy outputs for a batch of rendered prompts: (text, new tokens, hit the token limit).""" | |
| enc = tokenizer(prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device) | |
| with torch.inference_mode(): | |
| out = model.generate(**enc, do_sample=False, max_new_tokens=max_new_tokens, | |
| temperature=None, top_p=None, top_k=None, pad_token_id=tokenizer.pad_token_id) | |
| stop = model_io.eos_ids(model) | |
| results = [] | |
| for row in out[:, enc["input_ids"].shape[1]:].tolist(): | |
| end = next((i + 1 for i, t in enumerate(row) if t in stop), None) | |
| n = end if end is not None else len(row) | |
| results.append((tokenizer.decode(row[:n], skip_special_tokens=True), n, end is None)) | |
| return results | |
| def batches(items, size): | |
| for start in range(0, len(items), size): | |
| yield items[start:start + size] | |
| def output_line(item, prompt, result, settings, batch_size): | |
| text, n_new, hit = result | |
| return {"item_id": item["item_id"], **settings, "batch_size": batch_size, "rendered_prompt": prompt, | |
| "raw_output": text, "n_new_tokens": n_new, "hit_token_limit": hit} | |
| def run(items, out_path, model, tokenizer, settings, batch_size): | |
| """Append outputs for items not yet in out_path. Returns throughput numbers for this call.""" | |
| drop_partial_tail(out_path) | |
| already = done_ids(out_path) | |
| todo = [i for i in items if i["item_id"] not in already] | |
| rendered = {i["item_id"]: model_io.render(tokenizer, i["prompt"], i["system_prompt"]) for i in todo} | |
| todo.sort(key=lambda i: -len(tokenizer(rendered[i["item_id"]], add_special_tokens=False)["input_ids"])) | |
| Path(out_path).parent.mkdir(parents=True, exist_ok=True) | |
| n_done, n_tokens, start = len(already), 0, time.perf_counter() | |
| with open(out_path, "a", encoding="utf-8") as f: | |
| for batch in batches(todo, batch_size): | |
| prompts = [rendered[i["item_id"]] for i in batch] | |
| results = generate_batch(model, tokenizer, prompts, settings["max_new_tokens"]) | |
| for item, prompt, result in zip(batch, prompts, results): | |
| f.write(json.dumps(output_line(item, prompt, result, settings, batch_size), ensure_ascii=False) + "\n") | |
| n_tokens += result[1] | |
| f.flush() | |
| previous, n_done = n_done, n_done + len(batch) | |
| if n_done // PROGRESS_EVERY > previous // PROGRESS_EVERY or n_done == len(already) + len(todo): | |
| print(f"{n_done} done, {time.perf_counter() - start:.0f} s", flush=True) | |
| seconds = time.perf_counter() - start | |
| return {"prompts": len(todo), "new_tokens": n_tokens, "seconds": round(seconds, 1), | |
| "prompts_per_second": round(len(todo) / seconds, 3) if todo else 0, | |
| "tokens_per_second": round(n_tokens / seconds, 1) if todo else 0} | |
| def check_batching(items, model, tokenizer, settings, batch_size): | |
| """Compare batched against one-at-a-time outputs on the same prompts.""" | |
| prompts = [model_io.render(tokenizer, i["prompt"], i["system_prompt"]) for i in items] | |
| batched = [r[0] for b in batches(prompts, batch_size) for r in generate_batch(model, tokenizer, b, settings["max_new_tokens"])] | |
| single = [generate_batch(model, tokenizer, [p], settings["max_new_tokens"])[0][0] for p in prompts] | |
| rows = [{"item_id": i["item_id"], "same": b == s, "batched": b, "unbatched": s} for i, b, s in zip(items, batched, single)] | |
| return {"n": len(rows), "n_same": sum(r["same"] for r in rows), "batch_size": batch_size, "rows": rows} | |
| def settings_for(cfg, rt): | |
| if cfg["decoding"]["do_sample"] is not False: | |
| raise ValueError("the evaluation uses greedy decoding, set decoding.do_sample to false") | |
| return {"model_id": cfg["model"]["repo_id"], "revision": cfg["model"]["revision"], "dtype": rt["dtype"], | |
| "runtime": rt["runtime"], "code_bundle": os.environ.get("FIT_CODE_BUNDLE", ""), | |
| "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "", | |
| "do_sample": cfg["decoding"]["do_sample"], "max_new_tokens": cfg["decoding"]["eval_max_new_tokens"]} | |
Xet Storage Details
- Size:
- 5.38 kB
- Xet hash:
- 4a8ef4cbf04e8eb7a1990258ceb67ead3e035e5c7a973ce3d086b204ae4e8b1a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.