Download lib/msc_data.py from Shanmuk4622/msc-kd-data: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/datasets/Shanmuk4622/msc-kd-data/resolve/main/lib/msc_data.py
- Command line
-
hf download hf://datasets/Shanmuk4622/msc-kd-data/lib/msc_data.py
-
curl -L -o msc_data.py https://huggingface.co/datasets/Shanmuk4622/msc-kd-data/resolve/main/lib/msc_data.py
17.9 kB
| """ | |
| 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 | |