Download scripts/r5_release/rc1_prep_a1.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 5.53 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_release/rc1_prep_a1.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_release/rc1_prep_a1.py
-
curl -L -o rc1_prep_a1.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_release/rc1_prep_a1.py
5.53 kB
| """rc1 prep, step A1: turn the long2x training checkpoint (a pickle) into safetensors + codec JSON + config JSON. | |
| Run with CODE/.venv_kraken/bin/python -I (kraken 7.2, torch). Reads the checkpoint of our own training run (weights_only=False is needed | |
| for that pickle; it holds plain Python objects and tensors) and writes into the package folder: | |
| model/model.safetensors the network state dict (ck["state"]["net"]), every tensor cloned and contiguous | |
| model/codec.json {"c2l": {char: [labels]}} from ck["codec_c2l"] | |
| model/config.json the numbers needed to build the network without the training code | |
| Then it checks: codec equals DATA/outputs/r5/linedet/codec_union.json (the one lm_decode.py used), the network rebuilt from the | |
| files loads strictly and every tensor equals the pickle's tensor, parameter counts. Writes a JSON report (not into the package). | |
| usage: rc1_prep_a1.py CKPT OUT_MODEL_DIR CODEC_UNION_JSON REPORT_JSON | |
| """ | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| import torch | |
| from safetensors.torch import load_file, save_file | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for b in iter(lambda: f.read(1 << 20), b""): | |
| h.update(b) | |
| return h.hexdigest() | |
| def main(): | |
| ck_path, out_dir, codec_union_path, report_path = sys.argv[1:5] | |
| rep = {"checkpoint": ck_path, "checkpoint_sha256": sha256(ck_path), "checkpoint_bytes": os.path.getsize(ck_path)} | |
| ck = torch.load(ck_path, map_location="cpu", weights_only=False) | |
| rep["ck_keys"] = sorted(ck.keys()) | |
| for k in ("samples_seen", "lr_peak", "recipe", "opts", "wall_train_seconds"): | |
| rep["ck_" + k] = ck.get(k) | |
| st = ck["state"] | |
| rep["state_keys"] = sorted(st.keys()) | |
| net = st["net"] | |
| rep["n_state_tensors"] = len(net) | |
| bad = [k for k, v in net.items() if not torch.is_tensor(v)] | |
| rep["non_tensor_entries"] = bad | |
| rep["dtypes"] = sorted({str(v.dtype) for v in net.values() if torch.is_tensor(v)}) | |
| rep["state_numel_total"] = int(sum(v.numel() for v in net.values() if torch.is_tensor(v))) | |
| ptrs = {} | |
| for k, v in net.items(): | |
| if torch.is_tensor(v): | |
| ptrs.setdefault(v.data_ptr(), []).append(k) | |
| rep["shared_storage_groups"] = [g for g in ptrs.values() if len(g) > 1][:10] | |
| rep["first_keys"] = list(net.keys())[:6] | |
| c2l = {k: [int(x) for x in v] for k, v in ck["codec_c2l"].items()} | |
| union = json.load(open(codec_union_path, encoding="utf-8"))["c2l"] | |
| union = {k: [int(x) for x in v] for k, v in union.items()} | |
| rep["codec_n_chars"] = len(c2l) | |
| rep["codec_equals_codec_union_json"] = (c2l == union) | |
| rep["codec_union_sha256"] = sha256(codec_union_path) | |
| from kraken.lib.codec import PytorchCodec | |
| from kraken.lib.ppocr import PPOCRv6Model | |
| codec = PytorchCodec(c2l) | |
| n_cls = codec.max_label + 1 | |
| rep["codec_max_label"] = codec.max_label | |
| rep["num_classes"] = n_cls | |
| single = {v[0]: k for k, v in c2l.items() if len(v) == 1} | |
| rep["l2c_single_equals_codec_l2c_single"] = (single == dict(codec.l2c_single)) | |
| os.makedirs(out_dir, exist_ok=True) | |
| tens = {k: v.detach().clone().contiguous() for k, v in net.items()} | |
| out_st = os.path.join(out_dir, "model.safetensors") | |
| save_file(tens, out_st, metadata={"format": "pt", "source": "long2x checkpoint of the A1 line recognizer, state_dict of the network"}) | |
| with open(os.path.join(out_dir, "codec.json"), "w", encoding="utf-8") as f: | |
| json.dump({"c2l": c2l}, f, ensure_ascii=False, indent=1, sort_keys=True) | |
| cfg = {"architecture": "kraken PPOCRv6Model", "kraken_version": "7.2", "variant": "medium", "height": 96, "num_classes": n_cls, | |
| "input_channels": 3, "pad_px": 16, "seg_type": "baselines", "one_channel_mode": "RGB", "legacy_polygons": False, | |
| "ctc_blank_label": 0, "label_form": "NFD (the codec is over NFD characters; output is written as NFC)"} | |
| with open(os.path.join(out_dir, "config.json"), "w", encoding="utf-8") as f: | |
| json.dump(cfg, f, indent=1) | |
| # rebuild from the written files only | |
| model = PPOCRv6Model(variant="medium", num_classes=n_cls, height=96, codec=codec.c2l, seg_type="baselines", | |
| one_channel_mode="RGB", legacy_polygons=False) | |
| sd = load_file(out_st) | |
| res = model.load_state_dict(sd, strict=True) | |
| rep["strict_load"] = {"missing": list(res.missing_keys), "unexpected": list(res.unexpected_keys)} | |
| equal = all(torch.equal(model.state_dict()[k], net[k]) for k in net) | |
| rep["all_tensors_equal_to_pickle"] = bool(equal) | |
| seen = set() | |
| n = 0 | |
| for p in model.parameters(): | |
| if id(p) not in seen: | |
| seen.add(id(p)) | |
| n += p.numel() | |
| rep["parameters_network_unique"] = n | |
| seen = set() | |
| n2 = 0 | |
| for p in model.nn.parameters(): | |
| if id(p) not in seen: | |
| seen.add(id(p)) | |
| n2 += p.numel() | |
| rep["parameters_model_nn_unique"] = n2 | |
| rep["safetensors_sha256"] = sha256(out_st) | |
| rep["safetensors_bytes"] = os.path.getsize(out_st) | |
| rep["codec_json_sha256"] = sha256(os.path.join(out_dir, "codec.json")) | |
| with open(report_path, "w", encoding="utf-8") as f: | |
| json.dump(rep, f, indent=1, ensure_ascii=False, default=str) | |
| print(json.dumps({k: rep[k] for k in ("codec_equals_codec_union_json", "all_tensors_equal_to_pickle", "strict_load", | |
| "parameters_network_unique", "parameters_model_nn_unique", "num_classes")}, default=str)) | |
| if __name__ == "__main__": | |
| main() | |