File size: 3,697 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Runtime checks for all shards, original bytes, score, and runnable loaders."""

import json
import math
from pathlib import Path
import re
import subprocess
import sys
import tarfile
import tempfile
import shutil

from PIL import Image


ROOT = Path.cwd()


def run(workspace, *args):
    result = subprocess.run([sys.executable, *args], cwd=workspace, capture_output=True, text=True, timeout=60)
    assert result.returncode == 0, f"{' '.join(args)} failed: {result.stderr or result.stdout}"
    return result.stdout


def expected(workspace):
    dataset = workspace / "data" / "dataset"
    images = {p.stem for p in dataset.glob("*.jpg")}
    captions = {p.stem for p in dataset.glob("*.txt")}
    for path in dataset.glob("*.jpg"):
        with Image.open(path) as image:
            image.verify()
    return sorted(images & captions), len(images | captions)


def check_workspace(workspace):
    pairs, total = expected(workspace)
    assert pairs, "no complete image-caption pairs"
    run(workspace, "solve.py")
    score = (workspace / "score.txt").read_text(encoding="utf-8")
    match = re.search(r"(\d+)\s*/\s*(\d+)", score)
    assert match and (int(match[1]), int(match[2])) == (len(pairs), total), "incorrect score numerator/denominator"
    shards = sorted((workspace / "shards").glob("dataset-*.tar"))
    assert len(shards) == math.ceil(len(pairs) / 6), "incorrect shard count"
    assert [p.name for p in shards] == [f"dataset-{i:06d}.tar" for i in range(len(shards))], "shard naming gap"
    all_keys = []
    for shard_index, path in enumerate(shards):
        group = pairs[shard_index * 6:(shard_index + 1) * 6]
        with tarfile.open(path) as archive:
            members = archive.getmembers()
            names = [m.name for m in members]
            expected_names = [f"{key}.{suffix}" for key in group for suffix in ("jpg", "txt")]
            assert sorted(names) == sorted(expected_names), f"wrong pair membership in {path.name}"
            assert len(names) == len(set(names)), "duplicate tar member"
            for member in members:
                assert member.isfile() and "/" not in member.name and ".." not in member.name
                assert archive.extractfile(member).read() == (workspace / "data" / "dataset" / member.name).read_bytes(), f"payload changed: {member.name}"
        all_keys.extend(group)
    assert all_keys == pairs
    # Consumers must read packaged shards even if the raw source is unavailable.
    with tempfile.TemporaryDirectory(prefix='raw-pairs-') as directory:
        dataset = workspace / 'data' / 'dataset'
        saved = Path(directory) / 'dataset'
        shutil.move(str(dataset), str(saved))
        try:
            for batch_size in (1, 4, 7):
                lines = run(workspace, "dataloader_demo.py", "--batch-size", str(batch_size)).splitlines()
                batches = [json.loads(line) for line in lines]
                assert batches == [pairs[offset:offset+batch_size] for offset in range(0, len(pairs), batch_size)], 'batch loader must honor batch size and include the final remainder'
            for world_size in (1, 2, 3, len(pairs) + 1):
                ranks = range(world_size) if world_size <= 3 else (0, world_size - 1)
                for rank in ranks:
                    got = run(workspace, "distributed_demo.py", "--rank", str(rank), "--world-size", str(world_size)).splitlines()
                    assert got == pairs[rank::world_size], f"rank {rank}/{world_size} partition wrong"
        finally:
            shutil.move(str(saved), str(dataset))
    return pairs


if __name__ == "__main__":
    check_workspace(ROOT)
    print("all shard, JPEG, batch, and rank checks passed")