File size: 7,706 Bytes
920632c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6e1b8b
 
 
 
920632c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read sparse PointZero WebDataset shards without extracting any files.

Training intentionally samples with replacement, as the original PointZero
weighted dataset does. Evaluation traverses each shard exactly once globally.
"""
import io
import json
import multiprocessing
from pathlib import Path
import random
import tarfile

import numpy as np
from PIL import Image
import torch

COMPONENT_WEIGHTS = {
    'shorts_v7': 0.33, 'tshirt_v7': 0.33, 'towel_v7': 0.33,
    'genesis_partnet_50k': 1.0, 'kubric_50k_v2': 0.33,
}


def image_tensor(blob):
    with Image.open(io.BytesIO(blob)) as image:
        array = np.array(image)
    if array.ndim == 2:
        array = array[None]
    else:
        array = array.transpose(2, 0, 1)
    return torch.from_numpy(array)


def decode_sample(sample, load_images=True):
    metadata = json.loads(sample['json'])
    result = {'points': torch.from_numpy(np.load(io.BytesIO(sample['points.npy']), allow_pickle=False)),
              'graspers': None, 'dirs': np.array(metadata['timestep_names']),
              'pred_dir': metadata['key']}
    if 'graspers.npy' in sample:
        result['graspers'] = torch.from_numpy(np.load(io.BytesIO(sample['graspers.npy']), allow_pickle=False))
    if load_images:
        result['rgb'] = image_tensor(sample['rgb_000.png']).unsqueeze(0)
        result['segmentation'] = (image_tensor(sample['segmentation_000.png']).unsqueeze(0) > 0).bool()
    return {'current_scene': result, 'context': {}}


def iter_shard(path, all_images=False):
    """Iterate adjacent WebDataset members; retain only conditioning images by default."""
    key = None
    sample = {}
    wanted = {'points.npy', 'graspers.npy', 'json', 'rgb_000.png', 'segmentation_000.png'}
    with tarfile.open(path, 'r|') as archive:
        for member in archive:
            if not member.isfile():
                raise ValueError(f'Unexpected member: {member.name}')
            current, suffix = member.name.split('.', 1)
            if current != key:
                if sample:
                    yield sample
                key, sample = current, {'__key__': current}
            if suffix in wanted or all_images:
                sample[suffix] = archive.extractfile(member).read()
        if sample:
            yield sample


class PointZeroShardDataset(torch.utils.data.IterableDataset):
    """Local-shard training adapter with distributed/worker-aware iteration.

    `epoch_samples` is the number of training samples per distributed rank.
    Do not attach a DistributedSampler: this iterable manages partitioning.
    Call set_epoch(epoch) before each epoch, including with persistent workers.
    Download the shards with huggingface_hub.snapshot_download beforehand.
    """
    def __init__(self, root, split='train', components=None, training=None,
                 weights=None, epoch_samples=100000, shuffle_buffer=128,
                 load_images=True, seed=787, rank=None, world_size=None):
        super().__init__()
        self.root = Path(root)
        self.split = split
        self.components = list(components or COMPONENT_WEIGHTS)
        self.training = split == 'train' if training is None else training
        self.weights = weights or COMPONENT_WEIGHTS
        self.epoch_samples = epoch_samples
        self.shuffle_buffer = shuffle_buffer
        if epoch_samples <= 0 or shuffle_buffer <= 0:
            raise ValueError('epoch_samples and shuffle_buffer must be positive')
        self.load_images = load_images
        self.seed = seed
        self.epoch = multiprocessing.Value('q', 0)
        distributed = torch.distributed.is_available() and torch.distributed.is_initialized()
        self.rank = torch.distributed.get_rank() if rank is None and distributed else (rank or 0)
        self.world_size = (torch.distributed.get_world_size() if world_size is None and distributed
                           else (world_size or 1))
        self.shards = {}
        for component in self.components:
            files = sorted((self.root / 'data' / component / split).glob('shard-*.tar'))
            if not files:
                raise ValueError(f'No shards for {component}/{split}; select components with this split')
            self.shards[component] = files
        if self.training and any(self.weights.get(c, 0) <= 0 for c in self.components):
            raise ValueError('Every selected training component needs a positive sampling weight')

    def set_epoch(self, epoch):
        self.epoch.value = epoch

    def __len__(self):
        if self.training:
            return self.epoch_samples
        files = [p for c in self.components for p in self.shards[c]][self.rank::self.world_size]
        return sum(json.loads((self.root / 'manifests/shards' / p.relative_to(self.root / 'data'))
                              .with_suffix('.json').read_text())['trajectories'] for p in files)

    def __iter__(self):
        worker = torch.utils.data.get_worker_info()
        worker_id, workers = (worker.id, worker.num_workers) if worker else (0, 1)
        global_worker = self.rank * workers + worker_id
        rng = random.Random(self.seed + 1000003 * self.epoch.value + 1009 * global_worker)
        if not self.training:
            # Rank partition first makes __len__ agree with iteration regardless of worker count.
            files = [p for c in self.components for p in self.shards[c]]
            for shard in files[self.rank::self.world_size][worker_id::workers]:
                for sample in iter_shard(shard):
                    yield decode_sample(sample, self.load_images)
            return

        def component_stream(component):
            files = self.shards[component]
            while True:
                # Uniform shard choice followed by all samples gives uniform long-run
                # sample frequency. Variable shard size affects block length, not frequency.
                for sample in iter_shard(rng.choice(files)):
                    # Retain short source sequences in the release, but require
                    # the ten-frame horizon for default PointZero pretraining.
                    if len(json.loads(sample['json'])['timestep_names']) == 10:
                        yield sample

        streams = {c: component_stream(c) for c in self.components}
        probabilities = [self.weights[c] for c in self.components]
        budget = max(0, (self.epoch_samples + workers - 1 - worker_id) // workers)
        buffer = []
        for _ in range(min(self.shuffle_buffer, budget)):
            component = rng.choices(self.components, probabilities)[0]
            buffer.append(next(streams[component]))
        for i in range(budget):
            index = rng.randrange(len(buffer))
            sample = buffer[index]
            if i + len(buffer) < budget:
                component = rng.choices(self.components, probabilities)[0]
                buffer[index] = next(streams[component])
            else:
                buffer.pop(index)
            yield decode_sample(sample, self.load_images)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('root')
    parser.add_argument('--component', default='shorts_v7')
    parser.add_argument('--split', default='train')
    args = parser.parse_args()
    dataset = PointZeroShardDataset(args.root, components=[args.component], split=args.split,
                                   training=False)
    example = next(iter(dataset))['current_scene']
    print('points:', tuple(example['points'].shape))
    print('graspers:', None if example['graspers'] is None else tuple(example['graspers'].shape))
    print('rgb:', tuple(example['rgb'].shape))