File size: 7,975 Bytes
85805ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""PyTorch Dataset over a manifest CSV. Deliverable for teammate A.

This module plus a manifest is the ENTIRE interface. Do not import build_sid.py, do not
touch HuggingFace, do not sample your own images -- if you do, your numbers stop being
comparable with everyone else's.

    from dataset import SidCropDataset, make_loader
    train_ds = SidCropDataset("manifests/train.csv", train=True)
    val_ds   = SidCropDataset("manifests/val.csv",   train=False)

__getitem__ returns (tensor[3,224,224], label_bin). Pass return_meta=True to also get
label_orig, which teammate C needs to report recall separately for full_synthetic vs
tampered.

WHY THE MODEL INPUT IS A CROP AND NOT A RESIZE
CLIP's stock preprocessing is Resize(224) + CenterCrop(224). That Resize is a low-pass
filter, and it throws away exactly the high-frequency generative artifacts that this whole
pipeline was built to preserve -- it would undo the crop-not-resize rule at the last step.
Going from our 256px crop to the model's 224px input is therefore a CENTER CROP.
If you swap in a backbone with a different input size, crop to it; do not resize to it.
"""

from __future__ import annotations

import csv
import sys
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler

sys.path.insert(0, str(Path(__file__).resolve().parent))
import common as C  # noqa: E402
from transforms import TrainAugment  # noqa: E402


def _center_crop(img: Image.Image, size: int) -> Image.Image:
    w, h = img.size
    if w == size and h == size:
        return img
    if w < size or h < size:
        raise ValueError("crop %dx%d is smaller than the model input %d; "
                         "resizing here would defeat the pipeline" % (w, h, size))
    x, y = (w - size) // 2, (h - size) // 2
    return img.crop((x, y, x + size, y + size))


class SidCropDataset(Dataset):
    def __init__(self, manifest, cfg=None, train: bool = False, augment=None,
                 return_meta: bool = False, input_size: int = None, normalize: bool = True):
        """
        manifest    path to manifests/train.csv or manifests/val.csv
        train       convenience flag; when augment is None it decides whether to augment
        augment     True/False to override, or your own callable(PIL) -> PIL
        return_meta also return {"img_id", "label_orig", "crop_idx", "source"}
        """
        self.cfg = cfg or C.load_config()
        self.root = Path(self.cfg["_root"])
        mp = Path(manifest)
        if not mp.is_absolute():
            mp = self.root / mp
        with open(mp, newline="", encoding="utf-8") as fh:
            self.rows = list(csv.DictReader(fh))
        if not self.rows:
            raise ValueError("empty manifest: %s" % mp)

        d = self.cfg["dataset"]
        self.input_size = int(input_size or d["model_input_size"])
        self.return_meta = return_meta
        self.normalize = normalize
        self.mean = torch.tensor(d["normalize_mean"], dtype=torch.float32).view(3, 1, 1)
        self.std = torch.tensor(d["normalize_std"], dtype=torch.float32).view(3, 1, 1)

        if augment is None:
            augment = bool(train)
        if augment is True:
            self.augment = TrainAugment(self.cfg)
        elif augment is False:
            self.augment = None
        else:
            self.augment = augment

    # -- helpers teammate A will want ------------------------------------------------
    def labels(self) -> np.ndarray:
        return np.array([int(r["label_bin"]) for r in self.rows])

    def labels_orig(self) -> np.ndarray:
        return np.array([int(r["label_orig"]) for r in self.rows])

    def pos_weight(self) -> torch.Tensor:
        """For BCEWithLogitsLoss(pos_weight=...) when the manifest is not 1:1.

        The shipped manifests are 1 real : 2 synthetic, so this returns ~0.5. Forgetting it
        biases the model toward predicting 'synthetic' and inflates apparent recall.
        """
        y = self.labels()
        n_pos, n_neg = int((y == 1).sum()), int((y == 0).sum())
        return torch.tensor([n_neg / max(n_pos, 1)], dtype=torch.float32)

    def balanced_sampler(self) -> WeightedRandomSampler:
        """The other way to handle the 1:2 ratio: sample it back to 1:1 each epoch."""
        y = self.labels()
        cnt = np.bincount(y, minlength=2).astype(np.float64)
        w = (1.0 / np.maximum(cnt, 1))[y]
        return WeightedRandomSampler(torch.as_tensor(w, dtype=torch.double), len(w), True)

    # -- Dataset ---------------------------------------------------------------------
    def __len__(self) -> int:
        return len(self.rows)

    def __getitem__(self, i: int):
        r = self.rows[i]
        p = Path(r["crop_path"])
        img = Image.open(p if p.is_absolute() else self.root / p)
        img.load()
        if img.mode != "RGB":
            img = img.convert("RGB")

        if self.augment is not None:
            img = self.augment(img)

        img = _center_crop(img, self.input_size)          # CROP, never resize -- see module docstring
        a = torch.from_numpy(np.asarray(img, dtype=np.uint8).copy())
        x = a.permute(2, 0, 1).float().div_(255.0)
        if self.normalize:
            x = (x - self.mean) / self.std

        y = int(r["label_bin"])
        if not self.return_meta:
            return x, y
        return x, y, {"img_id": r["img_id"], "label_orig": int(r["label_orig"]),
                      "crop_idx": int(r["crop_idx"]), "source": r["source"]}


def make_loader(manifest, batch_size: int = 64, train: bool = False, num_workers: int = 4,
                balanced: bool = False, cfg=None, **kw) -> DataLoader:
    ds = SidCropDataset(manifest, cfg=cfg, train=train, **kw)
    sampler = ds.balanced_sampler() if (train and balanced) else None
    return DataLoader(ds, batch_size=batch_size, shuffle=(train and sampler is None),
                      sampler=sampler, num_workers=num_workers,
                      pin_memory=torch.cuda.is_available(), drop_last=train,
                      persistent_workers=num_workers > 0)


# --------------------------------------------------------------------------------------

def _self_test() -> int:
    """python src/dataset.py [manifest]"""
    cfg = C.load_config()
    mp = sys.argv[1] if len(sys.argv) > 1 else "manifests/val.csv"
    if not (Path(cfg["_root"]) / mp).exists():
        print("manifest %s not built yet" % mp)
        return 1

    ds = SidCropDataset(mp, cfg=cfg, train=False, return_meta=True)
    x, y, m = ds[0]
    print("clean  : x%s %s  range [%.2f, %.2f]  y=%d  meta=%s"
          % (tuple(x.shape), x.dtype, x.min(), x.max(), y, m))
    assert tuple(x.shape) == (3, ds.input_size, ds.input_size)

    ds_a = SidCropDataset(mp, cfg=cfg, train=True, return_meta=False)
    xa, ya = ds_a[0]
    print("augment: x%s  differs from clean: %s" % (tuple(xa.shape), bool((xa - x).abs().max() > 0)))

    y_all = ds.labels()
    print("manifest: %d crops, %d images, label_bin 0/1 = %d/%d, pos_weight=%.3f"
          % (len(ds), len({r["img_id"] for r in ds.rows}),
             int((y_all == 0).sum()), int((y_all == 1).sum()), float(ds.pos_weight())))
    import collections
    print("label_orig:", dict(sorted(collections.Counter(ds.labels_orig().tolist()).items())))

    # both crops of one image must share a split -- verified here as "no img_id in two splits"
    splits = collections.defaultdict(set)
    for r in ds.rows:
        splits[r["img_id"]].add(r["split"])
    bad = [k for k, v in splits.items() if len(v) > 1]
    print("img_ids spanning >1 split: %d (must be 0)" % len(bad))
    assert not bad

    dl = make_loader(mp, batch_size=8, train=False, num_workers=0)
    xb, yb = next(iter(dl))
    print("loader : batch %s labels %s" % (tuple(xb.shape), yb.tolist()))
    print("ALL CHECKS PASSED")
    return 0


if __name__ == "__main__":
    raise SystemExit(_self_test())