turkic-ocr-code / scripts /j2 /eligibility.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
11.9 kB
"""J2 step 2: eligibility facts for the 20 models of screen.list_S. Runs on a ZEN4 node with .venv_vlm.
Downloads (no token, no .py file) only config, tokenizer, processor, chat template and README files and
reads the file list with sizes from the Hub API. Then, with the pinned transformers release only:
- checks that model_type and architecture are native classes (trust_remote_code is never set),
- builds the native model class on the meta device (no weights) and counts parameters,
- loads the tokenizer and the processor with trust_remote_code=False,
- round-trips the 238 project symbols and all validation labels through the tokenizer (E3).
usage: eligibility.py MODELS_TSV CODEC_JSON VALIDATION_TSV MODELS_DIR OUT_DIR [only_short ...]
"""
import collections
import json
import os
import sys
import traceback
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_tsv, codec_json, val_tsv, models_dir, out_dir = sys.argv[1:6]
only = set(sys.argv[6:])
os.makedirs(out_dir, exist_ok=True)
import huggingface_hub
import torch
import transformers
from huggingface_hub import HfApi, snapshot_download
ALLOW = [
"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*", "*.jinja", "README.md", "*.safetensors.index.json",
]
WEIGHT_EXT_PICKLE = (".bin", ".pt", ".pth", ".pdparams", ".ckpt", ".pkl", ".msgpack", ".h5", ".onnx", ".gguf")
codec = json.load(open(codec_json, encoding="utf-8"))
symbols = [chr(int(c[2:], 16)) for c in codec["codepoints"]]
assert len(symbols) == 238
labels = []
with open(val_tsv, encoding="utf-8", newline="") as f:
f.readline()
for line in f:
parts = line.rstrip("\n").split("\t")
labels.append(unicodedata.normalize("NFC", parts[2]))
labels = sorted(set(labels))
api = HfApi(token=False)
def roundtrip(tok, texts, kind):
"""kind 'hf' (transformers tokenizer) or 'raw' (tokenizers.Tokenizer)."""
bad, unk = [], 0
unk_id = getattr(tok, "unk_token_id", None) if kind == "hf" else None
for t in texts:
if kind == "hf":
ids = tok.encode(t, add_special_tokens=False)
back = tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
else:
enc = tok.encode(t, add_special_tokens=False)
ids = enc.ids
back = tok.decode(ids, skip_special_tokens=True)
if unk_id is not None:
unk += sum(1 for i in ids if i == unk_id)
if back != t:
bad.append((t, back))
return bad, unk
def native_info(cfg_dict):
from transformers.models.auto import configuration_auto, modeling_auto
info = {}
mt = cfg_dict.get("model_type")
info["model_type"] = mt
info["config_native"] = mt in configuration_auto.CONFIG_MAPPING_NAMES
for sub in ("text_config", "vision_config", "llm_config", "language_config"):
if isinstance(cfg_dict.get(sub), dict) and cfg_dict[sub].get("model_type"):
smt = cfg_dict[sub]["model_type"]
info[sub + "_type"] = smt
info[sub + "_native"] = smt in configuration_auto.CONFIG_MAPPING_NAMES
maps = {}
for name in ("MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES",
"MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "MODEL_MAPPING_NAMES"):
m = getattr(modeling_auto, name, None)
if m is not None and mt in m:
maps[name.replace("MODEL_FOR_", "").replace("_MAPPING_NAMES", "").replace("MODEL_MAPPING_NAMES", "BASE")] = m[mt]
info["auto_model_mappings"] = maps
return info
rows = []
with open(models_tsv, encoding="utf-8") as f:
f.readline()
for line in f:
short, repo, dp, sc = line.rstrip("\n").split("\t")
if only and short not in only:
continue
rows.append((short, repo, int(dp), sc))
for short, repo, design_params, size_class in rows:
rec = {"short": short, "repo": repo, "design_unique_params": design_params, "size_class_design": size_class,
"transformers": transformers.__version__, "errors": []}
try:
info = api.model_info(repo, files_metadata=True, token=False)
rec["revision"] = info.sha
rec["gated"] = info.gated
rec["license_tag"] = (info.card_data.get("license") if info.card_data else None)
rec["last_modified"] = str(info.last_modified)
files = [(s.rfilename, s.size) for s in (info.siblings or [])]
rec["n_files"] = len(files)
st = [(n, s) for n, s in files if n.endswith(".safetensors")]
pk = [(n, s) for n, s in files if n.endswith(WEIGHT_EXT_PICKLE)]
rec["safetensors_files"] = len(st)
rec["safetensors_bytes"] = sum(s or 0 for n, s in st)
rec["other_weight_files"] = [f"{n}:{s}" for n, s in pk][:20]
rec["other_weight_bytes"] = sum(s or 0 for n, s in pk)
rec["py_files_in_repo_not_downloaded"] = [n for n, s in files if n.endswith(".py")]
rec["weight_format"] = ("safetensors" if st and not pk else "safetensors+other" if st and pk
else "pickle/other only" if pk else "none found")
if info.gated:
rec["errors"].append("repo is gated: " + str(info.gated))
local = os.path.join(models_dir, short)
os.makedirs(local, exist_ok=True)
snapshot_download(repo, revision=info.sha, local_dir=local, allow_patterns=ALLOW, token=False)
got = []
for root, _, fs in os.walk(local):
for fn in fs:
got.append(os.path.relpath(os.path.join(root, fn), local))
rec["downloaded_files"] = sorted(g for g in got if not g.startswith(".cache"))
assert not any(g.endswith(".py") for g in got), "a .py file was downloaded"
except Exception as e: # noqa: BLE001
rec["errors"].append("fetch: " + repr(e)[:300])
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
print(short, "FETCH ERROR", repr(e)[:200], flush=True)
continue
local = os.path.join(models_dir, short)
cfg_path = os.path.join(local, "config.json")
try:
cfg_dict = json.load(open(cfg_path, encoding="utf-8"))
rec["architectures"] = cfg_dict.get("architectures")
rec["auto_map"] = cfg_dict.get("auto_map")
rec.update(native_info(cfg_dict))
archs = cfg_dict.get("architectures") or []
rec["arch_class_in_transformers"] = [bool(getattr(transformers, a, None)) for a in archs]
except Exception as e: # noqa: BLE001
rec["errors"].append("config read: " + repr(e)[:300])
cfg_dict = {}
# native config load, trust_remote_code=False
cfg = None
try:
cfg = transformers.AutoConfig.from_pretrained(local, trust_remote_code=False)
rec["autoconfig_class"] = type(cfg).__module__ + "." + type(cfg).__name__
rec["autoconfig_native"] = type(cfg).__module__.startswith("transformers.")
except Exception as e: # noqa: BLE001
rec["autoconfig_native"] = False
rec["errors"].append("AutoConfig: " + repr(e)[:300])
# meta-device construction of the native class (no weights, no code of the vendor)
try:
if cfg is not None and rec.get("autoconfig_native"):
archs = cfg_dict.get("architectures") or []
cls = None
for a in archs:
cls = getattr(transformers, a, None)
if cls is not None:
rec["native_model_class"] = a
break
if cls is None:
from transformers import AutoModelForImageTextToText
cls = AutoModelForImageTextToText
rec["native_model_class"] = "AutoModelForImageTextToText(fallback)"
with torch.device("meta"):
if hasattr(cls, "_from_config"):
m = cls._from_config(cfg, dtype=torch.bfloat16)
else:
m = cls.from_config(cfg, trust_remote_code=False)
n = 0
seen = set()
for p in m.parameters():
if id(p) in seen:
continue
seen.add(id(p))
n += p.numel()
rec["meta_params_unique"] = n
rec["meta_construct_ok"] = True
del m
except Exception as e: # noqa: BLE001
rec["meta_construct_ok"] = False
rec["errors"].append("meta construct: " + repr(e)[:300])
# tokenizer, trust_remote_code=False
tok, kind = None, None
try:
tok = transformers.AutoTokenizer.from_pretrained(local, trust_remote_code=False)
kind = "hf"
rec["tokenizer_class"] = type(tok).__module__ + "." + type(tok).__name__
rec["tokenizer_native"] = type(tok).__module__.startswith("transformers.")
except Exception as e: # noqa: BLE001
rec["errors"].append("AutoTokenizer: " + repr(e)[:300])
tj = os.path.join(local, "tokenizer.json")
if os.path.exists(tj):
try:
from tokenizers import Tokenizer
tok = Tokenizer.from_file(tj)
kind = "raw"
rec["tokenizer_class"] = "tokenizers.Tokenizer(from tokenizer.json, data only)"
rec["tokenizer_native"] = True
except Exception as e2: # noqa: BLE001
rec["errors"].append("tokenizers.from_file: " + repr(e2)[:300])
rec["tokenizer_kind"] = kind
if tok is not None:
try:
nonspace = [s for s in symbols if s != " "]
bad_s, unk_s = roundtrip(tok, nonspace, kind)
bad_sp, _ = roundtrip(tok, ["а б"], kind)
joined = "".join(nonspace)
bad_j, _ = roundtrip(tok, [joined], kind)
bad_l, unk_l = roundtrip(tok, labels, kind)
rec["e3_symbols_tested"] = len(nonspace)
rec["e3_symbols_bad"] = len(bad_s)
rec["e3_symbols_bad_examples"] = [[a, b] for a, b in bad_s[:12]]
rec["e3_space_in_context_ok"] = not bad_sp
rec["e3_joined_string_ok"] = not bad_j
rec["e3_unk_ids_symbols"] = unk_s
rec["e3_labels_tested"] = len(labels)
rec["e3_labels_bad"] = len(bad_l)
rec["e3_labels_bad_examples"] = [[a, b] for a, b in bad_l[:12]]
rec["e3_labels_bad_strip_equal"] = sum(1 for a, b in bad_l if a.strip() == b.strip())
rec["e3_unk_ids_labels"] = unk_l
except Exception as e: # noqa: BLE001
rec["errors"].append("roundtrip: " + repr(e)[:300] + traceback.format_exc()[-300:])
# processor, trust_remote_code=False
try:
proc = transformers.AutoProcessor.from_pretrained(local, trust_remote_code=False)
rec["processor_class"] = type(proc).__module__ + "." + type(proc).__name__
rec["processor_native"] = type(proc).__module__.startswith("transformers.")
tmpl = getattr(proc, "chat_template", None)
rec["chat_template_present"] = bool(tmpl) or bool(getattr(getattr(proc, "tokenizer", None), "chat_template", None))
except Exception as e: # noqa: BLE001
rec["processor_native"] = False
rec["errors"].append("AutoProcessor: " + repr(e)[:300])
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False)
print(short, rec.get("model_type"), rec.get("weight_format"), "native_cfg", rec.get("autoconfig_native"),
"meta", rec.get("meta_construct_ok"), "tok_sym_bad", rec.get("e3_symbols_bad"), "labels_bad",
rec.get("e3_labels_bad"), "proc", rec.get("processor_native"), "errors", len(rec["errors"]), flush=True)