Download scripts/r5_release/rc1_a1_padding_diag.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 4.3 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_release/rc1_a1_padding_diag.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_release/rc1_a1_padding_diag.py
-
curl -L -o rc1_a1_padding_diag.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_release/rc1_a1_padding_diag.py
4.3 kB
| """rc1 diagnostic (A1): how much does the batch padding change the A1 reading of the KOHTD validation screen set V1? | |
| Why: the rc1 check found that the A1 package reads the same crops differently depending on the batch (alone, mixed widths, sorted by width, | |
| sorted by label length as in the evaluation). kraken's PPLCNetV4 backbone has squeeze-and-excitation layers whose global mean runs over the | |
| whole padded width (kraken/lib/ppocr/backbone.py SELayer.forward: x.mean(dim=(2, 3))), while only the neck masks padded columns | |
| (network.py _lengths_and_mask), so the amount of padding in a batch reaches the output. | |
| What: greedy reading of all 3,678 V1 rows (validation only) with the package's own functions (infer.py of the A1 package, imported by path), | |
| CPU float32, under these batches (all of size 32): manifest order; a seeded shuffle; sorted by width plus E extra zero columns on the right of | |
| the whole batch (the neck mask keeps the original widths), E in 0, 64, 128, 256, 512, 1024. Reports CER against the reference column of the | |
| recorded V1 file and the agreement with the recorded predictions (batches sorted by label length, GPU bfloat16). | |
| usage: rc1_a1_padding_diag.py PKG_DIR V1_MANIFEST RECORDED_V1_TSV OUT_JSON | |
| """ | |
| import csv | |
| import importlib.util | |
| import json | |
| import random | |
| import sys | |
| import time | |
| import unicodedata | |
| import torch | |
| import torch.nn.functional as F | |
| from PIL import Image | |
| from rapidfuzz.distance import Levenshtein | |
| csv.field_size_limit(10 ** 9) | |
| def cer(refs, hyps): | |
| return sum(Levenshtein.distance(a, b) for a, b in zip(refs, hyps)) / max(1, sum(len(a) for a in refs)) | |
| def main(): | |
| pkg, man, recp, outp = sys.argv[1:5] | |
| assert "test" not in man.lower().split("/")[-1] and "test" not in recp.lower().split("/")[-1] | |
| spec = importlib.util.spec_from_file_location("a1pkg", pkg + "/infer.py") | |
| mod = importlib.util.module_from_spec(spec) | |
| sys.modules["a1pkg"] = mod | |
| spec.loader.exec_module(mod) | |
| rows = list(csv.DictReader(open(man, encoding="utf-8", newline=""), delimiter="\t", quoting=csv.QUOTE_NONE)) | |
| assert all(r["split"] == "val" for r in rows) | |
| rec = {r["id"]: r for r in csv.DictReader(open(recp, encoding="utf-8", newline=""), delimiter="\t", quoting=csv.QUOTE_NONE)} | |
| ids = [r["id"] for r in rows] | |
| refs = [rec[i]["ref"] for i in ids] | |
| recorded = [rec[i]["hyp"] for i in ids] | |
| net = mod.Recognizer(pkg + "/model", "cpu", 16) | |
| tens = [mod.pil_tensor(Image.open(r["image"]).convert("RGB"), net.height) for r in rows] | |
| n = len(tens) | |
| def run(order, extra=0, bs=32): | |
| hyps = [None] * n | |
| t0 = time.time() | |
| for b in range(0, n, bs): | |
| idx = order[b:b + bs] | |
| x, sl = mod.collate([tens[i] for i in idx]) | |
| if extra: | |
| x = F.pad(x, (0, extra)) # padding of the whole batch; seq_lens keep the real widths | |
| lp, ol = net.log_probs(x, sl) | |
| res = net.greedy(lp, ol) | |
| for j, i in enumerate(idx): | |
| hyps[i] = unicodedata.normalize("NFC", res[j][0]) | |
| same = sum(1 for a, b in zip(hyps, recorded) if a == b) | |
| return {"cer": cer(refs, hyps), "identical_to_recorded": same, "rows": n, "agreement": same / n, "seconds": round(time.time() - t0, 1)} | |
| res = {"note": "validation V1 only; CER against the reference column of the recorded V1 file; recorded CER on the same rows given below", | |
| "recorded_cer": cer(refs, recorded), "conditions": {}} | |
| order_manifest = list(range(n)) | |
| order_shuffled = list(range(n)) | |
| random.Random(20261125).shuffle(order_shuffled) | |
| order_width = sorted(range(n), key=lambda i: tens[i].shape[-1]) | |
| res["conditions"]["manifest_order_batches_of_32"] = run(order_manifest) | |
| print("manifest order", res["conditions"]["manifest_order_batches_of_32"], flush=True) | |
| res["conditions"]["shuffled_batches_of_32"] = run(order_shuffled) | |
| print("shuffled", res["conditions"]["shuffled_batches_of_32"], flush=True) | |
| for e in (0, 64, 128, 256, 512, 1024): | |
| k = "sorted_by_width_plus_%d_extra_columns" % e | |
| res["conditions"][k] = run(order_width, e) | |
| print(k, res["conditions"][k], flush=True) | |
| with open(outp, "w", encoding="utf-8") as f: | |
| json.dump(res, f, indent=1) | |
| if __name__ == "__main__": | |
| main() | |