import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src")) sys.path.insert(0, HERE) import pytest # noqa: E402 pytest.importorskip("PIL") from dwd_klein.data import BucketLoader, iter_val, parse_bucket # noqa: E402 from tiny import write_shards # noqa: E402 def _keys(loader, start, n, accum=1): loader.start(start, accum) out = [] for s in range(start, start + n): for m in range(accum): b = loader.next(s, m) out.append((b.bucket, tuple(b.keys), tuple(b.images.shape))) state = b.state loader.stop() return out, state def test_buckets_shapes_and_epochs(tmp_path): write_shards(str(tmp_path), shards=2, per_shard=5) ld = BucketLoader(str(tmp_path), micro_batch=3, seed=0) out, _ = _keys(ld, 0, 12) for bucket, keys, shape in out: W, H = parse_bucket(bucket) assert shape == (3, 3, H, W) and all(k.startswith(bucket) for k in keys) assert {b for b, _, _ in out} == {"32x32", "48x32"} # both buckets drawn seen = [k for b, ks, _ in out if b == "32x32" for k in ks] first_epoch = seen[:10] assert len(set(first_epoch)) == 10 # a full pass over the bucket before any repeat def test_resume_reproduces_stream(tmp_path): write_shards(str(tmp_path), shards=3, per_shard=4) full, _ = _keys(BucketLoader(str(tmp_path), micro_batch=2, seed=3), 0, 10, accum=2) first, state = _keys(BucketLoader(str(tmp_path), micro_batch=2, seed=3), 0, 4, accum=2) ld = BucketLoader(str(tmp_path), micro_batch=2, seed=3) ld.load_state_dict(state) rest, _ = _keys(ld, 4, 6, accum=2) assert first + rest == full def test_rank_split_disjoint(tmp_path): write_shards(str(tmp_path), buckets=("32x32",), shards=4, per_shard=3) keys = [] for r in range(2): out, _ = _keys(BucketLoader(str(tmp_path), micro_batch=2, rank=r, world=2, seed=0), 0, 3) keys.append({k for _, ks, _ in out for k in ks}) assert not keys[0] & keys[1] # fewer shards than ranks: sample-strided, still disjoint write_shards(str(tmp_path / "b"), buckets=("32x32",), shards=1, per_shard=6) keys = [] for r in range(3): out, _ = _keys(BucketLoader(str(tmp_path / "b"), micro_batch=2, rank=r, world=3, seed=0), 0, 1) keys.append({k for _, ks, _ in out for k in ks}) assert not (keys[0] & keys[1]) and not (keys[1] & keys[2]) and len(set.union(*keys)) == 6 def test_manifest_and_multiple_captions(tmp_path): from dwd_klein.data import bucket_counts, list_buckets write_shards(str(tmp_path), buckets=("32x32", "48x32"), shards=3, per_shard=4, manifest=True, captions=True) lb = list_buckets(str(tmp_path), "train") assert sorted(lb) == ["32x32", "48x32"] and all(len(v) == 3 for v in lb.values()) assert bucket_counts(str(tmp_path)) == {"32x32": 12.0, "48x32": 12.0} ld = BucketLoader(str(tmp_path), micro_batch=4, seed=0) ld.start(0, 1) caps = [c for s in range(6) for c in ld.next(s, 0).captions] ld.stop() assert any(c.startswith("alt") for c in caps) and any(c.startswith("caption") for c in caps) def test_val_iter(tmp_path): write_shards(str(tmp_path), buckets=("48x32",), shards=1, per_shard=4, split="val") v = list(iter_val(str(tmp_path), "48x32", 3)) assert len(v) == 3 and v[0][1].shape == (3, 32, 48) and v[0][2].startswith("caption") def _corrupt_member(path: str, key: str): """Rewrite the tar with key.jpg replaced by bytes that are not an image.""" import io import tarfile with tarfile.open(path) as tf: members = [(m, tf.extractfile(m).read()) for m in tf if m.isfile()] with tarfile.open(path, "w") as tf: for m, data in members: if m.name == f"{key}.jpg": data = b"\xff\xd8 not a jpeg" m.size = len(data) tf.addfile(m, io.BytesIO(data)) def test_bad_sample_and_bad_shard_are_skipped_deterministically(tmp_path): write_shards(str(tmp_path), buckets=("32x32",), shards=3, per_shard=4) d = tmp_path / "train" / "32x32" _corrupt_member(str(d / "shard-0001.tar"), "32x32_01_002") (d / "shard-0002.tar").write_bytes(b"truncated garbage, not a tar") full, _ = _keys(BucketLoader(str(tmp_path), micro_batch=3, seed=0), 0, 6) keys = [k for _, ks, _ in full for k in ks] assert "32x32_01_002" not in keys and not any(k.startswith("32x32_02") for k in keys) assert len(set(keys[:7])) == 7 # one epoch = the 7 good samples # and resume stays exact across the skips first, state = _keys(BucketLoader(str(tmp_path), micro_batch=3, seed=0), 0, 2) ld = BucketLoader(str(tmp_path), micro_batch=3, seed=0) ld.load_state_dict(state) rest, _ = _keys(ld, 2, 4) assert first + rest == full def test_val_subset_is_stratified(tmp_path): """Val shards hold one source after another: the subset must still cover every (source, bucket).""" import io import json import tarfile import numpy as np from PIL import Image from dwd_klein.data import val_subset for b, W, H in (("32x32", 32, 32), ("48x32", 48, 32)): os.makedirs(tmp_path / "val" / b, exist_ok=True) with tarfile.open(tmp_path / "val" / b / f"val-{b}-000.tar", "w") as tf: for src, prefix, n in (("alpha", "a", 10), ("beta", "b", 3), ("gamma", "g", 2)): for i in range(n): key = f"{prefix}-{b}-{i}" bio = io.BytesIO() Image.fromarray(np.full((H, W, 3), i, np.uint8)).save(bio, format="JPEG") for ext, data in (("jpg", bio.getvalue()), ("txt", f"cap {key}".encode()), ("json", json.dumps({"key": key, "source": src}).encode())): ti = tarfile.TarInfo(f"{key}.{ext}") ti.size = len(data) tf.addfile(ti, io.BytesIO(data)) v = val_subset(str(tmp_path), 6, seed=0) assert len(v) == 6 and {(s, b) for _, _, _, s, b in v} == {(s, b) for s in ("alpha", "beta", "gamma") for b in ("32x32", "48x32")} assert v[0][1].shape == (3, 32, 32) and [x[0] for x in val_subset(str(tmp_path), 6, seed=0)] == [x[0] for x in v] assert len(val_subset(str(tmp_path), 100, seed=0)) == 30 # capped at what exists def test_read_ahead_same_stream(tmp_path): """Reading the next shard group in the background gives exactly the stream of a plain read (resume unaffected).""" from dwd_klein.data import BucketStream, list_buckets write_shards(str(tmp_path), buckets=("32x32",), shards=5, per_shard=3) shards = list_buckets(str(tmp_path))["32x32"] a = BucketStream("32x32", shards, seed=3, group=2, read_ahead=True) b = BucketStream("32x32", shards, seed=3, group=2, read_ahead=False) ka = [a.next()["key"] for _ in range(40)] kb = [b.next()["key"] for _ in range(40)] assert ka == kb and len(set(ka[:15])) == 15