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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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""
msc_data.py -- CIFAR-100, canonical ordering, and the Parquet schema.

Owns the single most dangerous invariant in the project: **row alignment**.
A per-sample table whose rows do not correspond to the same images across runs
destroys real correlations or manufactures fake ones, and nothing downstream
looks broken. Everything here exists to make that impossible rather than
unlikely.

Three independent defences:
    1. The ordering is defined by the ORIGINAL pickle, not by a directory walk.
    2. A dataset fingerprint is asserted equal across every run.
    3. `sample_idx` is written explicitly and asserted canonical at write time.

Contents
    1. sources     Kaggle mirrors, layout resolution, download fallbacks
    2. loading     raw pickle -> arrays, in canonical order
    3. fingerprint
    4. schema      the Parquet contract
    5. datasets    CPU reference pipeline and GPU fast pipeline
"""
from __future__ import annotations

import pickle
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple

import numpy as np

import msc_util as U

__version__ = "2.0.0"

CIFAR100_MEAN = (0.5071, 0.4865, 0.4409)
CIFAR100_STD = (0.2673, 0.2564, 0.2762)
N_CLASSES = 100
N_TRAIN = 50000
N_TEST = 10000


# ---------------------------------------------------------------------------
# 1. sources
# ---------------------------------------------------------------------------

KAGGLE_DATASETS = {
    "cifar100": "shanmuk4622/dataset-cifar100-python",
    "cifar10": "shanmuk4622/dataset-cifar10-python",
}
_PICKLE_DIR = {"cifar100": "cifar-100-python", "cifar10": "cifar-10-batches-py"}
_SPLIT_FILES = {"cifar100": ("train", "test"),
                "cifar10": ("data_batch_1", "test_batch")}


def _is_pickle_root(p: Path, which: str) -> bool:
    return p.is_dir() and all((p / f).exists() for f in _SPLIT_FILES[which])


def find_pickle_root(base: Path, which: str = "cifar100",
                     max_depth: int = 3) -> Optional[Path]:
    """Locate the directory holding the split files, whatever the nesting.

    Kaggle preserves whatever the uploader zipped, so all of these occur and
    all must work (failure D2):
        <base>/cifar-100-python/train
        <base>/train
        <base>/anything/cifar-100-python/train
    """
    if not base.exists():
        return None
    if _is_pickle_root(base, which):
        return base
    direct = base / _PICKLE_DIR[which]
    if _is_pickle_root(direct, which):
        return direct
    try:
        for p in sorted(base.rglob("*")):
            if (p.is_dir()
                    and len(p.relative_to(base).parts) <= max_depth
                    and _is_pickle_root(p, which)):
                return p
    except Exception:
        pass
    return None


def _extract_tarball(base: Path, which: str, scratch: Path) -> Optional[Path]:
    """Some uploads keep the .tar.gz. Extract to scratch, never to
    /kaggle/working -- that is 20 GB and it is the artifact space."""
    import tarfile
    if not base.exists():
        return None
    for tb in sorted(list(base.glob("*.tar.gz")) + list(base.glob("*.tgz"))):
        dest = U.ensure_dir(scratch / "data")
        print(f"[DATA] extracting {tb.name} -> {dest}")
        try:
            with tarfile.open(tb) as t:
                t.extractall(dest)
        except Exception as e:
            print(f"[DATA] extract failed: {e}")
            continue
        r = find_pickle_root(dest, which)
        if r is not None:
            return r
    return None


def locate_cifar(which: str = "cifar100",
                 scratch_dir: str = "/kaggle/temp") -> str:
    """Return the directory that DIRECTLY contains the CIFAR pickle splits.

    Resolution order, fastest first (failure D1):
        1. attached Kaggle dataset      -- no download at all
        2. kagglehub download           -- mirrors are public, no credentials
        3. tarball in an attached input -- extracted to scratch
        4. torchvision from origin      -- last resort

    We use the ORIGINAL pickle, never a train/<class>/*.png mirror. With a PNG
    layout the enumeration order depends on filenames and class-directory sort
    order, so two runs on different mirrors get different sample_idx -> image
    maps: row alignment broken at the source, with nothing downstream looking
    wrong. The fingerprint (failure D3) is the backstop for the case where the
    source changes underneath us.
    """
    assert which in KAGGLE_DATASETS, f"unknown dataset {which!r}"
    scratch = Path(scratch_dir)
    slug = KAGGLE_DATASETS[which]
    short = slug.split("/")[-1]
    inp = Path("/kaggle/input")

    for base in (inp / short, inp / short.replace("dataset-", ""),
                 inp / _PICKLE_DIR[which]):
        r = find_pickle_root(base, which)
        if r is not None:
            print(f"[DATA] attached Kaggle dataset: {r}")
            return str(r)
    if inp.exists():
        for base in sorted(inp.iterdir()):
            r = find_pickle_root(base, which)
            if r is not None:
                print(f"[DATA] attached Kaggle dataset: {r}")
                return str(r)

    try:
        import kagglehub
        print(f"[DATA] kagglehub download: {slug}")
        p = Path(kagglehub.dataset_download(slug))
        r = find_pickle_root(p, which) or _extract_tarball(p, which, scratch)
        if r is not None:
            print(f"[DATA] kagglehub -> {r}")
            return str(r)
        print(f"[DATA] kagglehub gave {p} but no pickle splits inside")
    except Exception as e:
        print(f"[DATA] kagglehub unavailable ({type(e).__name__}: {e})")

    if inp.exists():
        for base in sorted(inp.iterdir()):
            r = _extract_tarball(base, which, scratch)
            if r is not None:
                return str(r)

    r = find_pickle_root(scratch / "data", which)
    if r is not None:
        print(f"[DATA] cached in scratch: {r}")
        return str(r)

    root = U.ensure_dir(scratch / "data")
    print(f"[DATA] falling back to torchvision download of {which} "
          f"(slow; prefer attaching {slug})")
    from torchvision import datasets
    ds = datasets.CIFAR100 if which == "cifar100" else datasets.CIFAR10
    ds(root=str(root), train=True, download=True)
    ds(root=str(root), train=False, download=True)
    r = find_pickle_root(root, which)
    assert r is not None, f"{which} download did not produce the pickle splits"
    return str(r)


# ---------------------------------------------------------------------------
# 2. loading -- canonical order
# ---------------------------------------------------------------------------

def load_raw(root: str, train: bool) -> Tuple[np.ndarray, np.ndarray]:
    """Load straight from the pickle, so the ordering is canonically defined.

    `root` directly contains `train` and `test`; `locate_cifar` has already
    resolved whatever nesting the upload used. One stray extra level is
    tolerated because it costs nothing and removes a whole class of support
    questions.
    """
    name = "train" if train else "test"
    f = Path(root) / name
    if not f.exists():
        alt = Path(root) / _PICKLE_DIR["cifar100"] / name
        if alt.exists():
            f = alt
    with open(f, "rb") as fh:
        d = pickle.load(fh, encoding="bytes")
    data = d[b"data"].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)  # NHWC uint8
    labels = np.array(d[b"fine_labels"], dtype=np.int64)
    return np.ascontiguousarray(data), labels


# ---------------------------------------------------------------------------
# 3. fingerprint
# ---------------------------------------------------------------------------

def dataset_fingerprint(root: str) -> Dict[str, str]:
    """sha256 over labels and leading pixels, both splits.

    Asserted equal across all four runs. Catches a swapped mirror, a
    re-uploaded dataset, and a torchvision version change -- any of which
    would silently repermute sample_idx. Failures D3, D4.
    """
    fp: Dict[str, str] = {}
    for split, train in (("train", True), ("test", False)):
        data, labels = load_raw(root, train)
        fp[f"{split}_n"] = str(len(labels))
        fp[f"{split}_labels_sha256"] = U.sha256_bytes(
            labels.astype(np.int16).tobytes())
        fp[f"{split}_pixels_sha256"] = U.sha256_bytes(data[:100].tobytes())
    return fp


def assert_fingerprint(actual: Dict[str, str], expected: Dict[str, str],
                       context: str = "") -> None:
    if actual == expected:
        return
    diff = {k: (expected.get(k), actual.get(k))
            for k in set(expected) | set(actual)
            if expected.get(k) != actual.get(k)}
    raise AssertionError(
        f"DATASET FINGERPRINT MISMATCH {context}\n"
        f"  differing fields (expected, actual): {diff}\n"
        f"This run saw different data than the bootstrap. Row alignment across "
        f"runs would be void and every correlation silently wrong. Halting.")


def frozen_train_slice(n_total: int = N_TRAIN, n_slice: int = 5000,
                       master_seed: int = 0) -> List[int]:
    """A fixed slice of the TRAINING set that IS trained on.

    Identical across all four runs (failure D6). Trained on, not held out:
    EL2N, forgetting events and prediction depth are only defined on training
    examples, and holding 5,000 out would cost ~0.5-1 point of test accuracy
    and risk tripping the accuracy gate for a reason unrelated to the recipe.
    """
    rng = np.random.default_rng(U.derive_seed(master_seed, "train_seen_slice"))
    return sorted(rng.choice(n_total, size=min(n_slice, n_total),
                             replace=False).tolist())


# ---------------------------------------------------------------------------
# 4. schema -- the Parquet contract
# ---------------------------------------------------------------------------

RESOLUTIONS = (16, 20, 24, 28, 32)
K_DEPTH = 5
BATTERY = ("msp", "margin", "entropy", "ce_loss", "el2n", "forget_events",
           "pred_depth")


def schema_columns(resolutions: Sequence[int] = RESOLUTIONS,
                   k_depth: int = K_DEPTH,
                   include_upsample: bool = True,
                   include_probe_k: bool = True) -> List[str]:
    """The exact column list, in order. Owned here so the analysis driver and
    the emitter cannot disagree about it."""
    cols = ["sample_idx", "label"]
    for i in range(1, k_depth + 1):
        cols += [f"pred_d{i}", f"top1p_d{i}", f"top2p_d{i}"]
    for r in resolutions:
        cols += [f"pred_r{r}", f"top1p_r{r}", f"top2p_r{r}"]
    if include_upsample:
        for r in resolutions:
            cols += [f"pred_ru{r}", f"top1p_ru{r}", f"top2p_ru{r}"]
    cols += list(BATTERY)
    if include_probe_k:
        cols += ["pred_probeK", "top1p_probeK", "top2p_probeK"]
    return cols


def axis_columns(axis: str, resolutions: Sequence[int] = RESOLUTIONS,
                 k_depth: int = K_DEPTH) -> List[str]:
    """Column suffixes for one axis, ascending in cost."""
    if axis == "depth":
        return [f"d{i}" for i in range(1, k_depth + 1)]
    if axis == "resolution":
        return [f"r{r}" for r in resolutions]
    if axis == "resolution_upsample":
        return [f"ru{r}" for r in resolutions]
    raise ValueError(f"unknown axis {axis!r}")


def assert_canonical_index(sample_idx: np.ndarray, n_expected: Optional[int] = None) -> None:
    """Row alignment, enforced at write time. Failures D7, D8, I1."""
    sample_idx = np.asarray(sample_idx)
    n = len(sample_idx)
    if n_expected is not None and n != n_expected:
        raise AssertionError(
            f"expected {n_expected} rows, got {n}. A loader with "
            f"drop_last=True or a Subset would do this.")
    if not np.array_equal(sample_idx, np.arange(n)):
        bad = int(np.argmax(sample_idx != np.arange(n)))
        raise AssertionError(
            f"sample_idx is not the canonical 0..{n-1} ordering "
            f"(first mismatch at position {bad}: got {sample_idx[bad]}). "
            f"Evaluation loaders must be shuffle=False, drop_last=False, "
            f"sampler=None, with no Subset.")


# ---------------------------------------------------------------------------
# 5. datasets
# ---------------------------------------------------------------------------

class CifarCPU:
    """Reference pipeline: per-sample augmentation, torchvision semantics.

    Kept as the definition of correct. The GPU pipeline below is verified
    pixel-identical against these exact operations (AT-17).
    """

    def __init__(self, root: str, train: bool, augment: bool,
                 indices: Optional[Sequence[int]] = None):
        import torch
        data, labels = load_raw(root, train)
        idx = np.arange(len(labels)) if indices is None else np.asarray(indices)
        self.idx = idx
        self.data = torch.from_numpy(data[idx]).permute(0, 3, 1, 2).contiguous()
        self.labels = torch.from_numpy(labels[idx])
        self.augment = augment
        self.mean = torch.tensor(CIFAR100_MEAN).view(3, 1, 1)
        self.std = torch.tensor(CIFAR100_STD).view(3, 1, 1)

    def __len__(self) -> int:
        return len(self.labels)

    def __getitem__(self, i: int):
        import torch
        import torch.nn.functional as F
        img = self.data[i]
        if self.augment:
            # torchvision RandomCrop(32, padding=4): zero-pad the uint8 image,
            # THEN crop. Zero in pixel space is not zero after Normalize, so
            # padding a normalised tensor would train on different data.
            img = F.pad(img.unsqueeze(0), (4, 4, 4, 4), value=0).squeeze(0)
            top = int(torch.randint(0, 9, (1,)).item())
            left = int(torch.randint(0, 9, (1,)).item())
            img = img[:, top:top + 32, left:left + 32]
            if torch.rand(1).item() < 0.5:
                img = torch.flip(img, dims=[2])
        x = img.float().div(255.0).sub(self.mean).div(self.std)
        return x, self.labels[i], int(self.idx[i])


class CifarGPU:
    """The whole dataset resident on the GPU as uint8, augmented in batch.

    CIFAR ResNets at batch 64 are LATENCY bound, not compute bound: ~1.09 GMACs
    is single-digit ms on a T4, but a Python DataLoader doing per-sample
    pad/crop/flip/normalise on two Kaggle vCPUs cannot keep up and the GPU
    waits. Moving 150 MB of uint8 pixels onto the card removes the dataloader
    from the critical path entirely. Failure M7.

    This is a SPEED change and not a RECIPE change, and AT-17 proves it: given
    the same (top, left, flip) the batched path is pixel-identical to the
    torchvision ops in CifarCPU.

    Augmentation draws from the torch CUDA RNG, so it is captured by the
    checkpoint's RNG state and a resumed run replays the same augmentations.
    """

    def __init__(self, root: str, train: bool, device,
                 indices: Optional[Sequence[int]] = None):
        import torch
        data, labels = load_raw(root, train)
        idx = np.arange(len(labels)) if indices is None else np.asarray(indices)
        self.device = device
        self.n = len(idx)
        self.sample_idx = torch.from_numpy(idx.astype(np.int64)).to(device)
        self.x = torch.from_numpy(data[idx]).permute(0, 3, 1, 2).contiguous().to(device)
        self.y = torch.from_numpy(labels[idx]).to(device)
        self.mean = torch.tensor(CIFAR100_MEAN, device=device).view(1, 3, 1, 1) * 255.0
        self.std = torch.tensor(CIFAR100_STD, device=device).view(1, 3, 1, 1) * 255.0

    def __len__(self) -> int:
        return self.n

    def nbytes(self) -> int:
        return int(self.x.numel())

    def _normalise(self, xb):
        return (xb.float() - self.mean) / self.std

    def augment(self, xb_u8, gen=None):
        """Batched RandomCrop(32, pad=4) + RandomHorizontalFlip."""
        import torch
        import torch.nn.functional as F
        b = xb_u8.shape[0]
        xp = F.pad(xb_u8, (4, 4, 4, 4), mode="constant", value=0)  # uint8 space
        top = torch.randint(0, 9, (b,), device=self.device, generator=gen)
        left = torch.randint(0, 9, (b,), device=self.device, generator=gen)
        ar = torch.arange(32, device=self.device)
        rows = (top.view(b, 1) + ar.view(1, 32)).view(b, 1, 32, 1).expand(b, 3, 32, 40)
        xp = xp.gather(2, rows)
        cols = (left.view(b, 1) + ar.view(1, 32)).view(b, 1, 1, 32).expand(b, 3, 32, 32)
        xp = xp.gather(3, cols)
        flip = torch.rand(b, device=self.device, generator=gen) < 0.5
        xp = torch.where(flip.view(b, 1, 1, 1), xp.flip(3), xp)
        return self._normalise(xp)

    def train_batches(self, batch_size: int, gen=None):
        import torch
        perm = torch.randperm(self.n, device=self.device, generator=gen)
        for i in range(0, self.n, batch_size):
            sl = perm[i:i + batch_size]
            yield self.augment(self.x[sl], gen), self.y[sl], self.sample_idx[sl]

    def eval_batches(self, batch_size: int = 512, resolution: int = 32,
                     mode: str = "native"):
        """Deterministic order, no augmentation. THIS is the canonical
        sample_idx ordering every per-sample table refers to."""
        import torch.nn.functional as F
        for i in range(0, self.n, batch_size):
            xb = self._normalise(self.x[i:i + batch_size])
            if resolution != 32:
                xb = F.interpolate(xb, size=(resolution, resolution),
                                   mode="bilinear", align_corners=False)
                if mode == "upsample":
                    xb = F.interpolate(xb, size=(32, 32), mode="bilinear",
                                       align_corners=False)
            yield xb, self.y[i:i + batch_size], self.sample_idx[i:i + batch_size]

    def n_batches(self, batch_size: int) -> int:
        return (self.n + batch_size - 1) // batch_size