Download scripts/r5_vlma/check_inputs.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 3.94 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlma/check_inputs.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_vlma/check_inputs.py
-
curl -L -o check_inputs.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlma/check_inputs.py
3.94 kB
| """R5 VLMA CPU check (processor and tokenizer only, no model weights): for every model, the rendered prompt, the | |
| template kwargs, the answer-end suffix and stop ids, and a 4-row training batch whose loss positions are decoded and | |
| compared with label + suffix. Writes one JSON per model. | |
| usage: check_inputs.py REGISTRY MODELS_DIR SMOKE_SEQ OUT_DIR short [short ...] | |
| """ | |
| import json | |
| import os | |
| import sys | |
| import traceback | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import vlm_common as vc # noqa: E402 | |
| import transformers # noqa: E402 | |
| from PIL import Image # noqa: E402 | |
| registry, models_dir, seq, out_dir = sys.argv[1:5] | |
| shorts = sys.argv[5:] | |
| os.makedirs(out_dir, exist_ok=True) | |
| rows = [] | |
| with open(seq, encoding="utf-8") as f: | |
| hdr = f.readline().rstrip("\n").split("\t") | |
| ix = {h: i for i, h in enumerate(hdr)} | |
| for line in f: | |
| p = line.rstrip("\n").split("\t") | |
| rows.append((p[ix["id"]], p[ix["image"]], p[ix["text"]])) | |
| if len(rows) >= 4: | |
| break | |
| rows[3] = (rows[3][0] + ":EMPTY", rows[3][1], "") # an empty label (clutter case) must train on the end token only | |
| for short in shorts: | |
| rec = {"short": short, "errors": []} | |
| try: | |
| path = os.path.join(models_dir, short) | |
| proc, tok = vc.load_processor(short, path) | |
| gcfg = transformers.GenerationConfig.from_pretrained(path) if os.path.exists(os.path.join(path, "generation_config.json")) else transformers.GenerationConfig() | |
| kw = vc.template_kwargs(proc, tok) | |
| rec["template_kwargs"] = kw | |
| rec["rendered_prompt"] = vc.rendered_prompt(short, proc, kw) | |
| sfx, how, sfx_text = vc.answer_suffix(short, proc, tok, gcfg, kw) | |
| rec["answer_suffix_ids"] = sfx | |
| rec["answer_suffix_tokens"] = [tok.decode([i], skip_special_tokens=False) for i in sfx] | |
| rec["answer_suffix_how"] = how | |
| rec["template_suffix_text"] = sfx_text | |
| rec["stop_ids"] = sorted(vc.stop_ids(gcfg, tok)) | |
| rec["stop_tokens"] = [tok.decode([i], skip_special_tokens=False) for i in rec["stop_ids"]] | |
| rec["pad_token"] = [tok.pad_token, tok.pad_token_id] | |
| imgs = [Image.open(r[1]).convert("RGB") for r in rows] | |
| labs = [r[2] for r in rows] | |
| inp, lab, ntok = vc.build_train_batch(short, proc, tok, imgs, labs, sfx, kw) | |
| rec["batch_keys"] = {k: (list(v.shape), str(v.dtype)) if hasattr(v, "shape") else type(v).__name__ for k, v in inp.items()} | |
| rec["n_target_tokens"] = ntok | |
| checks = [] | |
| for i in range(lab.shape[0]): | |
| pos = lab[i] != -100 | |
| got = lab[i][pos].tolist() | |
| exp = vc.target_ids(tok, labs[i], sfx) | |
| ids_ok = got == exp | |
| first = int(pos.nonzero()[0]) if pos.any() else -1 | |
| seq_ok = inp["input_ids"][i][pos].tolist() == got | |
| dec = tok.decode(got[: len(got) - len(sfx)], skip_special_tokens=False) | |
| prompt_tail = tok.decode(inp["input_ids"][i][max(0, first - 6):first].tolist(), skip_special_tokens=False) | |
| checks.append({"id": rows[i][0], "label": labs[i], "ids_equal": ids_ok, "input_ids_match_labels": seq_ok, | |
| "label_part_decoded": dec, "label_part_equal": dec == labs[i], "prompt_tail": prompt_tail, | |
| "prompt_tokens": first, "seq_len": int(inp["attention_mask"][i].sum())}) | |
| rec["label_checks"] = checks | |
| rec["ok"] = all(c["ids_equal"] and c["input_ids_match_labels"] and c["label_part_equal"] for c in checks) | |
| except Exception as e: # noqa: BLE001 | |
| rec["ok"] = False | |
| rec["errors"].append(repr(e)[:400] + " | " + traceback.format_exc()[-800:]) | |
| json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False) | |
| print(short, "OK" if rec["ok"] else "FAIL", rec.get("answer_suffix_tokens"), rec.get("template_kwargs"), | |
| rec.get("batch_keys"), rec["errors"][:1], flush=True) | |