File size: 9,726 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""RQ2 training image path (design 'common_image_path_training'), ordinal batch sampler and run hooks.

1. open the crop, RGB, resize to height H keeping the aspect ratio, Lanczos (as linedet.data.pil_tensor)
2. slot u in 0..6 from numpy default_rng([seed, 4242, sample ordinal]) (shared across arms)
3. the policy's op for slot u on the H px image; if the height changed, resize back to H (Lanczos, aspect kept)
4. 16 px white pad left and right, scale to [0, 1], invert with t.max() - t (exactly as linedet.data.pil_tensor)
5. too wide or CTC-infeasible after augmentation: the same sample without augmentation; infeasible (or unreadable) too:
   replacement drawn with default_rng([seed, 4343, ordinal, attempt]). Both cases are counted per component, slot and reason.
kraken's DefaultAugmenter is never used (LineDS.__getitem__ with its unseeded fallback is overridden, not called).
"""
import copy
import hashlib
import json
import os
import sys
import time

import numpy as np
import torch
from PIL import Image

from linedet import data as D

from .aug import REPLACE_SALT, Policy, resize_to_height, slot_rng

ST_AUG, ST_CLEAN, ST_REPLACED = 0, 1, 2
STATUS_NAMES = {ST_AUG: "augmented", ST_CLEAN: "augmentation_dropped_infeasible", ST_REPLACED: "replaced"}


def to_tensor_like_linedet(im):
    """linedet.data.pil_tensor after its resize, for fixed_width None and 3 channels."""
    arr = np.asarray(im, dtype=np.uint8)
    arr = np.pad(arr, ((0, 0), (D.PAD, D.PAD), (0, 0)), constant_values=255)
    t = torch.from_numpy(arr).permute(2, 0, 1).float().div_(255.0)
    t = t.max() - t
    return t


class Infeasible(Exception):
    pass


class RQ2LineDS(D.LineDS):
    """Training dataset of one RQ2 arm. Indexed by (gid, ordinal) pairs from OrdinalBS."""

    def __init__(self, flat, spec, codec, train, seed=0, policy="typical", height=64):
        super().__init__(flat, spec, codec, train, seed)
        if spec.height != int(height):
            raise ValueError("spec height %s != arm height %s" % (spec.height, height))
        self.height = int(height)
        self.policy = Policy(policy, height)

    def _aug(self):            # never kraken's DefaultAugmenter
        return None

    def load_h(self, path):
        im = Image.open(path).convert("RGB")
        return resize_to_height(im, self.height)

    def feasible(self, t, target):
        w = t.shape[-1]
        if w > self.spec.max_width:
            return "too_wide"
        if D.frames_needed(target) > w // self.spec.subsampling:
            return "ctc_frames"
        return ""

    def one(self, gid, ordinal):
        path, text, kind = self.flat.items[gid]
        target = self.codec.encode(text)
        im_h = self.load_h(path)
        im_a, op, params = self.policy(im_h, slot_rng(self.seed, ordinal))
        if im_a.size[1] != self.height:
            im_a = resize_to_height(im_a, self.height)
        t = to_tensor_like_linedet(im_a)
        why = self.feasible(t, target)
        if not why:
            return t, target, text, op, ST_AUG, ""
        t = to_tensor_like_linedet(im_h)
        why2 = self.feasible(t, target)
        if not why2:
            return t, target, text, op, ST_CLEAN, why
        raise Infeasible(why2)

    def __getitem__(self, key):
        gid, ordinal = int(key[0]), int(key[1])
        req = gid
        reason = ""
        for attempt in range(21):
            try:
                t, target, text, op, status, why = self.one(gid, ordinal)
                if attempt:
                    status, why = ST_REPLACED, reason
                return {"image": t, "target": target, "text": text,
                        "gid": (gid, ordinal, req, op, status, why)}
            except Infeasible as e:
                reason = reason or ("infeasible_" + str(e))
            except Exception as e:     # unreadable image or a character the codec cannot encode
                reason = reason or ("error_" + type(e).__name__)
                if attempt == 0:
                    sys.stderr.write("[rq2 data] sample %d failed: %s %s\n" % (gid, type(e).__name__, str(e)[:120]))
            gid = int(np.random.default_rng([int(self.seed), REPLACE_SALT, ordinal, attempt]).integers(0, len(self.flat)))
        raise RuntimeError("21 consecutive failures at ordinal %d" % ordinal)


class OrdinalBS:
    """Replaces linedet.train_arm._BS: yields lists of (gid, sample ordinal); the ordinal is the sample count of the
    stream, so the augmentation of a sample is a function of (seed, ordinal) and survives a resume."""

    def __init__(self, stream, start):
        self.stream, self.start = stream, int(start)

    def __iter__(self):
        o = self.start
        for b in self.stream.batches(self.start):
            yield [(int(g), o + j) for j, g in enumerate(b)]
            o += len(b)


def batches_digest(stream, n_batches, start=0):
    """sha256 over the first n batches of (gid, ordinal) pairs, and the ordinals' slot sequence."""
    h = hashlib.sha256()
    it = iter(OrdinalBS(stream, start))
    pairs = []
    for _ in range(n_batches):
        b = next(it)
        h.update(json.dumps(b).encode())
        pairs.extend(b)
    return h.hexdigest(), pairs


class RunHooks:
    """Wraps one arm's train_chunks/state/load_state: counts the image-path outcomes per component, slot and reason;
    saves and restores the torch RNG state with resume.pt (dropout in the neck and the NRTR head) so a resumed run
    continues on the same random stream; optional per-step trace (smoke tests) and a step limit (resume test)."""

    def __init__(self, comp_of, comp_names, out_dir, trace_path="", stop_at_step=0, stop_flag=None):
        self.comp_of = comp_of
        self.comp_names = comp_names
        self.out_dir = out_dir
        self.trace_path = trace_path
        self.stop_at_step = int(stop_at_step or 0)
        self.stop_flag = stop_flag
        self.step = 0
        self.pending_rng = None
        self.counters = {"samples": 0, "by_status": {}, "by_component": {}, "by_op": {}, "by_reason": {}}

    def _count(self, g):
        gid, ordinal, req, op, status, why = g
        c = self.counters
        c["samples"] += 1
        sn = STATUS_NAMES[status]
        c["by_status"][sn] = c["by_status"].get(sn, 0) + 1
        comp = self.comp_names[int(self.comp_of[req])]
        d = c["by_component"].setdefault(comp, {"samples": 0, "augmented": 0, "augmentation_dropped_infeasible": 0, "replaced": 0})
        d["samples"] += 1
        d[sn] += 1
        o = c["by_op"].setdefault(op, {"samples": 0, "augmented": 0, "augmentation_dropped_infeasible": 0, "replaced": 0})
        o["samples"] += 1
        o[sn] += 1
        if why:
            c["by_reason"][why] = c["by_reason"].get(why, 0) + 1

    def install(self, arm):
        orig_tc, orig_state, orig_load = arm.train_chunks, arm.state, arm.load_state
        hooks = self

        def train_chunks(chunks, B, device, lr):
            if hooks.pending_rng is not None:
                cpu_state, cuda_state = hooks.pending_rng
                torch.set_rng_state(cpu_state)
                if cuda_state is not None and torch.cuda.is_available():
                    torch.cuda.set_rng_state_all(cuda_state)
                hooks.pending_rng = None
            info = orig_tc(chunks, B, device, lr)
            gs = sorted((g for ch in chunks for g in ch["gid"]), key=lambda g: g[1])
            for g in gs:
                hooks._count(g)
            hooks.step += 1
            if hooks.trace_path:
                rec = {"step": hooks.step, "lr": lr, "loss": info.get("loss"), "ctc": info.get("ctc"), "nrtr": info.get("nrtr"),
                       "req": [g[2] for g in gs], "used": [g[0] for g in gs], "ord": [g[1] for g in gs],
                       "op": [g[3] for g in gs], "status": [g[4] for g in gs], "t": time.time()}
                with open(hooks.trace_path, "a") as f:
                    f.write(json.dumps(rec) + "\n")
            if hooks.stop_at_step and hooks.step >= hooks.stop_at_step and hooks.stop_flag is not None:
                hooks.stop_flag["flag"] = True
            return info

        def state():
            st = orig_state()
            st["rq2"] = {"counters": copy.deepcopy(hooks.counters), "step": hooks.step, "torch_rng": torch.get_rng_state(),
                         "cuda_rng": (torch.cuda.get_rng_state_all() if torch.cuda.is_available() and torch.cuda.is_initialized() else None)}
            hooks.write_counters()
            return st

        def load_state(st, with_opt=True):
            rq = st.get("rq2")
            if rq:
                hooks.counters = copy.deepcopy(rq["counters"])
                hooks.step = int(rq["step"])
                hooks.pending_rng = (rq["torch_rng"], rq.get("cuda_rng"))
            return orig_load(st, with_opt)

        arm.train_chunks, arm.state, arm.load_state = train_chunks, state, load_state
        arm.rq2_hooks = self
        return arm

    def write_counters(self):
        if not self.out_dir:
            return
        os.makedirs(self.out_dir, exist_ok=True)
        p = os.path.join(self.out_dir, "rq2_counters.json")
        tmp = p + ".tmp"
        with open(tmp, "w") as f:
            json.dump({"step": self.step, "counters": self.counters,
                       "status_meaning": {"augmented": "policy op applied", "augmentation_dropped_infeasible": "augmented sample too wide or CTC-infeasible: the same sample without augmentation (design step 5)",
                                          "replaced": "also infeasible or unreadable without augmentation: replaced by a sample drawn with default_rng([seed, 4343, ordinal, attempt])"}},
                      f, indent=1)
        os.replace(tmp, p)