ml-intern-iac-sharechat-repro / tokenize_trace.py
Googlu15's picture
Llama-3 tokenization
ebc780a verified
Raw History Blame Contribute Delete
2.92 kB
"""Stage 2a: tokenize the ShareChat replay trace with a Llama-3.1 chat template."""
from __future__ import annotations
import json
import os
import sys
import time
import numpy as np
REPO_DIR = os.environ.get("IAC_REPO", "/work/iac-repo")
sys.path.insert(0, REPO_DIR)
from iac.data import Trace # noqa: E402
OUT = "/work/artifacts/tokens_llama3.npz"
CANDIDATES = [
("NousResearch/Meta-Llama-3.1-70B-Instruct", False),
("NousResearch/Meta-Llama-3.1-70B", True),
("unsloth/Meta-Llama-3.1-70B", True),
("Qwen/Qwen3-8B", False),
]
def get_tokenizer():
from transformers import AutoTokenizer
last = None
for name, sub in CANDIDATES:
try:
tok = AutoTokenizer.from_pretrained(name)
_ = tok.apply_chat_template(
[{"role": "user", "content": "hi"}], tokenize=True, add_generation_prompt=True
)
if sub:
print(f"FLAG: tokenizer substitution — using {name}", flush=True)
else:
print(f"tokenizer: {name}", flush=True)
return tok, name
except Exception as e: # noqa: BLE001
last = e
print(f" {name} failed: {type(e).__name__}", flush=True)
raise RuntimeError(f"no tokenizer available: {last}")
def main():
os.makedirs(os.path.dirname(OUT), exist_ok=True)
trace = Trace.load("/work/traces/sharechat_r3")
reqs = sorted(trace.requests, key=lambda r: r.req_id)
n = len(reqs)
tok, tok_name = get_tokenizer()
ids_parts = []
offsets = np.zeros(n + 1, dtype=np.int64)
pos = 0
CHUNK = 512
t0 = time.time()
for start in range(0, n, CHUNK):
batch = reqs[start : start + CHUNK]
encs = [
tok.apply_chat_template(trace.messages(r), tokenize=True, add_generation_prompt=True)
for r in batch
]
for r, enc in zip(batch, encs):
if not isinstance(enc, (list, tuple, np.ndarray)):
enc = enc["input_ids"]
arr = np.asarray(enc, dtype=np.int32).ravel()
ids_parts.append(arr)
pos += arr.size
offsets[r.req_id + 1] = pos
if (start // CHUNK) % 20 == 0:
print(f" {start + len(batch)}/{n} ({time.time() - t0:.0f}s)", flush=True)
ids = np.concatenate(ids_parts)
np.savez(OUT, ids=ids, offsets=offsets)
lens = np.diff(offsets)
stats = {
"tokenizer": tok_name,
"requests": n,
"total_tokens": int(ids.size),
"mean": float(lens.mean()),
"median": float(np.median(lens)),
"p90": float(np.percentile(lens, 90)),
"max": int(lens.max()),
"seconds": round(time.time() - t0, 1),
}
with open("/work/artifacts/tokens_llama3.stats.json", "w") as f:
json.dump(stats, f, indent=1)
print(json.dumps(stats, indent=1), flush=True)
if __name__ == "__main__":
main()