Manitchahar's picture
Upload code_and_results/cpu_bench.py with huggingface_hub
596b047 verified
Raw History Blame Contribute Delete
2.8 kB
# CPU latency of the merged decision models, without importing unsloth (it needs a GPU).
# Uses the Clef reference code (joint_schema_model.py) saved inside each merged folder.
import glob, importlib.util, json, os, statistics, sys, time
os.environ["CUDA_VISIBLE_DEVICES"] = ""
import torch
from safetensors.torch import load_file
from transformers import AutoConfig, AutoTokenizer
torch.set_num_threads(os.cpu_count())
rows = [json.loads(l) for l in open("/kaggle/working/data/eval_synthetic.jsonl")][:30]
out = {}
for path in sorted(glob.glob("/kaggle/working/models/*")):
tag = os.path.basename(path)
try:
ref = glob.glob(f"{path}/joint_schema_model.py") or [
importlib.util.find_spec("unsloth").submodule_search_locations[0] + "/_vendor/clef/joint_schema_model.py"]
spec = importlib.util.spec_from_file_location("jsm_" + tag, ref[0])
jsm = importlib.util.module_from_spec(spec); spec.loader.exec_module(jsm)
cfg = AutoConfig.from_pretrained(path)
if getattr(cfg, "vision_config", None) is not None:
from transformers import AutoModelForImageTextToText as Auto
else:
from transformers import AutoModelForCausalLM as Auto
backbone = Auto.from_pretrained(path, dtype = torch.float32).eval()
head = jsm.JointSchemaHead(**json.load(open(f"{path}/joint_head_config.json")))
head.load_state_dict(load_file(f"{path}/joint_head.safetensors"), strict = True)
model = jsm.ClefModel(backbone, head.float().eval()).eval()
tok = AutoTokenizer.from_pretrained(path)
if tok.pad_token_id is None: tok.pad_token = tok.eos_token
ts, ntok = [], []
with torch.inference_mode():
for i, r in enumerate(rows):
t = time.perf_counter()
rec = jsm.encode_record(tok, {"state": r["state"], "questions": r["questions"]}, max_length = 4096)
model(jsm.collate_records([rec], tok.pad_token_id, torch.device("cpu")))
if i >= 2:
ts.append((time.perf_counter() - t) * 1000); ntok.append(len(rec.input_ids))
ts.sort()
out[tag] = {"p50_ms": round(statistics.median(ts)), "p95_ms": round(ts[int(0.95 * (len(ts) - 1))]),
"mean_tokens": round(statistics.mean(ntok)), "q_per_row": round(sum(len(r["questions"]) for r in rows) / len(rows), 1),
"threads": os.cpu_count(), "params_m": round(sum(p.numel() for p in model.parameters()) / 1e6)}
del model, backbone, head
except Exception as e:
import traceback; traceback.print_exc()
out[tag] = {"error": f"{type(e).__name__}: {str(e)[:300]}"}
print(tag, out[tag], flush = True)
json.dump(out, open("/kaggle/working/cpu_latency.json", "w"), indent = 1)