Download conversion/check_coreml.py from masahiroid/LFM3-1.7B-CoreML: direct link, hf CLI and curl.
- Browser
- Download file 2.15 kB
-
https://huggingface.co/masahiroid/LFM3-1.7B-CoreML/resolve/main/conversion/check_coreml.py
- Command line
-
hf download hf://masahiroid/LFM3-1.7B-CoreML/conversion/check_coreml.py
-
curl -L -o check_coreml.py https://huggingface.co/masahiroid/LFM3-1.7B-CoreML/resolve/main/conversion/check_coreml.py
2.15 kB
| """Compare the Core ML model against HF fp32: greedy tokens, logit cosine, speed.""" | |
| import sys | |
| import time | |
| import coremltools as ct | |
| import numpy as np | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| path = sys.argv[1] | |
| units = {"gpu": ct.ComputeUnit.CPU_AND_GPU, "ane": ct.ComputeUnit.CPU_AND_NE, "all": ct.ComputeUnit.ALL}[ | |
| sys.argv[2] if len(sys.argv) > 2 else "gpu" | |
| ] | |
| NEW = 32 | |
| torch.set_grad_enabled(False) | |
| tok = AutoTokenizer.from_pretrained("src") | |
| prompts = [ | |
| "日本の首都はどこですか?一文で答えてください。", | |
| "Write a haiku about the sea, then explain it in two sentences.", | |
| ] | |
| hf = AutoModelForCausalLM.from_pretrained("src", dtype=torch.float32, trust_remote_code=True).eval() | |
| t0 = time.time() | |
| ml = ct.models.MLModel(path, compute_units=units) | |
| print(f"load {time.time()-t0:.1f}s") | |
| for p in prompts: | |
| ids = tok.apply_chat_template( | |
| [{"role": "user", "content": p}], add_generation_prompt=True, return_tensors="pt", return_dict=True | |
| )["input_ids"] | |
| ref = hf.generate(ids, max_new_tokens=NEW, do_sample=False)[0, ids.shape[1]:].tolist() | |
| ref_logits = hf(ids).logits[0, -1].numpy() | |
| state = ml.make_state() | |
| n = ids.shape[1] | |
| t0 = time.time() | |
| out = ml.predict({"input_ids": ids.numpy().astype(np.int32), "position": np.array([0], np.int32)}, state) | |
| pre = time.time() - t0 | |
| lg = out["logits"][0].astype(np.float32) | |
| cos = float(lg @ ref_logits / (np.linalg.norm(lg) * np.linalg.norm(ref_logits))) | |
| toks, pos = [], n | |
| t0 = time.time() | |
| for _ in range(NEW): | |
| nxt = int(lg.argmax()) | |
| toks.append(nxt) | |
| out = ml.predict({"input_ids": np.array([[nxt]], np.int32), "position": np.array([pos], np.int32)}, state) | |
| lg = out["logits"][0].astype(np.float32) | |
| pos += 1 | |
| dec = time.time() - t0 | |
| k = next((i for i, (a, b) in enumerate(zip(toks, ref)) if a != b), NEW) | |
| print(f"\nprompt tokens={n} prefill {pre*1000:.0f}ms decode {NEW/dec:.1f} tok/s") | |
| print(f"logit cos={cos:.6f} first divergence at token {k}/{NEW}") | |
| print("HF :", tok.decode(ref)) | |
| print("CML:", tok.decode(toks)) | |