File size: 5,529 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""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()