Download scripts/j2/fetch_weights_loadtest.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 6.52 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/24aaa767fa765a248ba6fb28e28bf8018edaba46/scripts/j2/fetch_weights_loadtest.py
- Command line
-
hf download hf://treoa/turkic-ocr-code@24aaa767fa765a248ba6fb28e28bf8018edaba46/scripts/j2/fetch_weights_loadtest.py
-
curl -L -o fetch_weights_loadtest.py https://huggingface.co/treoa/turkic-ocr-code/resolve/24aaa767fa765a248ba6fb28e28bf8018edaba46/scripts/j2/fetch_weights_loadtest.py
6.52 kB
| """J2 step 2b: fetch root-level safetensors weights of the run candidates and test the native weight load on CPU. | |
| No token, no .py file, trust_remote_code is never set. A model passes the load gate only if from_pretrained with the | |
| native class reports no missing key and no mismatched key; unexpected keys are listed for reading. | |
| usage: fetch_weights_loadtest.py MODELS_DIR OUT_DIR short [short ...] | |
| """ | |
| import json | |
| import os | |
| import struct | |
| import sys | |
| import time | |
| 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 = sys.argv[1:3] | |
| shorts = sys.argv[3:] | |
| 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", | |
| ] | |
| REPO = {} | |
| for line in open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "models.tsv"), encoding="utf-8").read().splitlines()[1:]: | |
| s, r, _, _ = line.split("\t") | |
| REPO[s] = r | |
| # class used for loading: the one the card names, else the auto class that maps the config's model_type | |
| CARD_CLASS = { | |
| "lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", | |
| "lightonocr_3_1b": "LightOnOcrForConditionalGeneration", | |
| } | |
| def header_params(path): | |
| """Total elements and tensor count from a safetensors header (data only).""" | |
| with open(path, "rb") as f: | |
| n = struct.unpack("<Q", f.read(8))[0] | |
| h = json.loads(f.read(n)) | |
| tot, cnt = 0, 0 | |
| for k, v in h.items(): | |
| if k == "__metadata__": | |
| continue | |
| p = 1 | |
| for d in v["shape"]: | |
| p *= d | |
| tot += p | |
| cnt += 1 | |
| return tot, cnt | |
| api = HfApi(token=False) | |
| for short in shorts: | |
| rec = {"short": short, "repo": REPO[short], "transformers": transformers.__version__, "errors": []} | |
| t0 = time.time() | |
| try: | |
| info = api.model_info(REPO[short], files_metadata=True, token=False) | |
| rec["revision"] = info.sha | |
| 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_files"] = [f"{n}:{s}" for n, s in root if n.endswith(".safetensors")] | |
| rec["root_safetensors_bytes"] = sum(s or 0 for n, s in root if n.endswith(".safetensors")) | |
| rec["root_pickle_or_other_weights_not_downloaded"] = [ | |
| f"{n}:{s}" for n, s in root if n.endswith((".bin", ".pt", ".pth", ".pdparams", ".ckpt", ".onnx", ".gguf"))] | |
| local = os.path.join(models_dir, short) | |
| snapshot_download(REPO[short], revision=info.sha, local_dir=local, allow_patterns=CFG + wl, 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 = [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"] = sorted(got) | |
| ck_params, ck_tensors = 0, 0 | |
| for g in got: | |
| if g.endswith(".safetensors") and "/" not in g: | |
| a, b = header_params(os.path.join(local, g)) | |
| ck_params += a | |
| ck_tensors += b | |
| rec["ckpt_params_header"] = ck_params | |
| rec["ckpt_tensors_header"] = ck_tensors | |
| 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) | |
| print(short, "FETCH ERROR", repr(e)[:300], flush=True) | |
| continue | |
| t1 = time.time() | |
| try: | |
| cls_name = CARD_CLASS.get(short) | |
| cls = getattr(transformers, cls_name, None) if cls_name else None | |
| rec["card_class"] = cls_name | |
| rec["card_class_in_transformers"] = cls is not None | |
| if cls is None: | |
| if cls_name: | |
| rec["errors"].append(f"card class {cls_name} is not in transformers {transformers.__version__}; using AutoModelForImageTextToText") | |
| 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"] = cls.__name__ + " -> " + type(model).__module__ + "." + type(model).__name__ | |
| rec["missing_keys"] = sorted(li.get("missing_keys", []))[:50] | |
| rec["n_missing_keys"] = len(li.get("missing_keys", [])) | |
| rec["unexpected_keys"] = sorted(li.get("unexpected_keys", []))[:50] | |
| rec["n_unexpected_keys"] = len(li.get("unexpected_keys", [])) | |
| rec["mismatched_keys"] = [str(x)[:200] for x in li.get("mismatched_keys", [])][:50] | |
| rec["n_mismatched_keys"] = len(li.get("mismatched_keys", [])) | |
| rec["error_msgs"] = [str(x)[:300] for x in li.get("error_msgs", [])][:20] | |
| seen, n = set(), 0 | |
| for p in model.parameters(): | |
| if id(p) in seen: | |
| continue | |
| seen.add(id(p)) | |
| n += p.numel() | |
| rec["model_params_unique"] = n | |
| rec["tied_weights_note"] = "checkpoint header total minus model unique params = %d" % (ck_params - n) | |
| rec["generation_config"] = model.generation_config.to_dict() if getattr(model, "generation_config", None) else None | |
| rec["load_gate"] = ("PASS" if rec["n_missing_keys"] == 0 and rec["n_mismatched_keys"] == 0 and not rec["error_msgs"] | |
| else "FAIL") | |
| rec["load_seconds"] = round(time.time() - t1, 1) | |
| 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, "gate", rec.get("load_gate"), "missing", rec.get("n_missing_keys"), "unexpected", rec.get("n_unexpected_keys"), | |
| "mismatched", rec.get("n_mismatched_keys"), "ckpt_params", rec.get("ckpt_params_header"), "model_params", rec.get("model_params_unique"), | |
| "errors", len(rec["errors"]), flush=True) | |