turkic-ocr-code / scripts /r5_vlma /fetch_pinned.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
7.6 kB
"""R5 VLMA: download root-level safetensors weights and configs at a PINNED revision, then run the native
weight-load gate (CPU) and the E3 tokenizer round trip.
No token, no .py file (allow_patterns has no *.py; a check fails the model if one appears), trust_remote_code is
never set. A model passes the load gate only if from_pretrained with the native class reports no missing and no
mismatched key.
usage: fetch_pinned.py MODELS_DIR OUT_DIR CODEC_JSON VAL_TSV spec [spec ...]
spec = short=repo@revision (revision = 40-hex commit; 'HEAD' pins the current commit and records it)
spec = short=repo@HEAD:info (record the pinned commit, config and file list only; no weights, no load)
"""
import json
import os
import struct
import sys
import time
import unicodedata
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
os.environ.pop(k, None)
models_dir, out_dir, codec_json, val_tsv = sys.argv[1:5]
specs = sys.argv[5:]
os.makedirs(out_dir, exist_ok=True)
import torch
import transformers
from huggingface_hub import HfApi, snapshot_download
CFG = ["config.json", "generation_config.json", "preprocessor_config.json", "processor_config.json",
"video_preprocessor_config.json", "tokenizer*", "special_tokens_map.json", "added_tokens.json",
"vocab*", "merges.txt", "chat_template*", "README.md"]
CARD_CLASS = {"lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", "lightonocr_3_1b": "LightOnOcrForConditionalGeneration"}
codec = json.load(open(codec_json, encoding="utf-8"))
symbols = [chr(int(c[2:], 16)) for c in codec["codepoints"]]
nonspace = [s for s in symbols if not s.isspace()]
labels = []
with open(val_tsv, encoding="utf-8", newline="") as f:
f.readline()
for line in f:
labels.append(unicodedata.normalize("NFC", line.rstrip("\n").split("\t")[2]))
labels = sorted(set(labels))
def roundtrip(tok, texts):
bad = []
for t in texts:
ids = tok.encode(t, add_special_tokens=False)
back = tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
if back != t:
bad.append((t, back))
return bad
def header_params(path):
with open(path, "rb") as f:
n = struct.unpack("<Q", f.read(8))[0]
h = json.loads(f.read(n))
tot = 0
for k, v in h.items():
if k == "__metadata__":
continue
p = 1
for d in v["shape"]:
p *= d
tot += p
return tot
api = HfApi(token=False)
for spec in specs:
short, rest = spec.split("=", 1)
info_only = rest.endswith(":info")
rest = rest[:-5] if info_only else rest
repo, rev = rest.split("@", 1)
rec = {"short": short, "repo": repo, "requested_revision": rev, "transformers": transformers.__version__,
"torch": torch.__version__, "errors": [], "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
t0 = time.time()
try:
info = api.model_info(repo, revision=None if rev == "HEAD" else rev, files_metadata=True, token=False)
rec["revision"] = info.sha
if rev != "HEAD":
assert info.sha == rev, f"pinned {rev} but hub returned {info.sha}"
rec["all_files"] = sorted(f"{s.rfilename}:{s.size}" for s in info.siblings)
rec["py_files_in_repo"] = sorted(s.rfilename for s in info.siblings if s.rfilename.endswith(".py"))
root = [(s.rfilename, s.size) for s in info.siblings if "/" not in s.rfilename]
wl = [n for n, _ in root if n.endswith(".safetensors") or n.endswith(".safetensors.index.json")]
rec["root_safetensors_bytes"] = sum(s or 0 for n, s in root if n.endswith(".safetensors"))
local = os.path.join(models_dir, short)
pats = CFG if info_only else CFG + wl
snapshot_download(repo, revision=info.sha, local_dir=local, allow_patterns=pats, token=False)
got = []
for r, _, fs in os.walk(local):
for fn in fs:
got.append(os.path.relpath(os.path.join(r, fn), local))
got = sorted(g for g in got if not g.startswith(".cache"))
assert not any(g.endswith(".py") for g in got), "a .py file is present"
rec["files_in_dir"] = got
cfg = json.load(open(os.path.join(local, "config.json"), encoding="utf-8"))
rec["config_architectures"] = cfg.get("architectures")
rec["config_model_type"] = cfg.get("model_type")
rec["config_auto_map"] = cfg.get("auto_map")
rec["ckpt_params_header"] = sum(header_params(os.path.join(local, g)) for g in got
if g.endswith(".safetensors") and "/" not in g)
rec["download_seconds"] = round(time.time() - t0, 1)
except Exception as e: # noqa: BLE001
rec["errors"].append("fetch: " + repr(e)[:400])
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str)
print(short, "FETCH ERROR", repr(e)[:300], flush=True)
continue
if info_only:
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str)
print(short, "info only", rec["revision"], rec["config_architectures"], rec["config_auto_map"], flush=True)
continue
try:
tok = transformers.AutoTokenizer.from_pretrained(local, trust_remote_code=False)
rec["tokenizer_class"] = type(tok).__module__ + "." + type(tok).__name__
bs = roundtrip(tok, nonspace)
bl = roundtrip(tok, labels)
rec["e3_symbols_bad_of_%d" % len(nonspace)] = len(bs)
rec["e3_labels_bad_of_%d" % len(labels)] = len(bl)
rec["e3_examples_bad"] = (bs + bl)[:10]
except Exception as e: # noqa: BLE001
rec["errors"].append("tokenizer: " + repr(e)[:300])
t1 = time.time()
try:
cls_name = CARD_CLASS.get(short)
cls = getattr(transformers, cls_name, None) if cls_name else None
if cls is None:
cls = transformers.AutoModelForImageTextToText
model, li = cls.from_pretrained(local, dtype=torch.bfloat16, trust_remote_code=False, use_safetensors=True,
output_loading_info=True)
rec["load_class_used"] = type(model).__module__ + "." + type(model).__name__
for key in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs"):
v = li.get(key, [])
rec["n_" + key] = len(v)
rec[key] = [str(x)[:200] for x in sorted(v, key=str)][:60]
seen, n = set(), 0
for p in model.parameters():
if id(p) not in seen:
seen.add(id(p))
n += p.numel()
rec["model_params_unique"] = n
rec["load_gate"] = "PASS" if rec["n_missing_keys"] == 0 and rec["n_mismatched_keys"] == 0 and not rec["n_error_msgs"] else "FAIL"
rec["load_seconds"] = round(time.time() - t1, 1)
proc = transformers.AutoProcessor.from_pretrained(local, trust_remote_code=False)
rec["processor_class"] = type(proc).__module__ + "." + type(proc).__name__
del model
except Exception as e: # noqa: BLE001
rec["load_gate"] = "FAIL"
rec["errors"].append("load: " + repr(e)[:500])
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str)
print(short, rec["revision"], "gate", rec.get("load_gate"), "missing", rec.get("n_missing_keys"), "unexpected",
rec.get("n_unexpected_keys"), "params", rec.get("model_params_unique"), "errors", rec["errors"], flush=True)