File size: 2,916 Bytes
ebc780a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | """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()
|