File size: 12,509 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
2ad60ce
 
 
 
 
 
 
 
 
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from __future__ import annotations

from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import time

import numpy as np

from . import scene_store as store

LABEL_ID = 'gt_visibility_v2'
SCHEMA = 'gt_visibility_fullframe_v2'
SEMANTICS = 'camera-occluder only; scene self-occlusion not modelled'
RECIPE = 'camera_only_v2'
SOURCE_POLICY = 'occluder_policy_hard_v1'
OFFSET_RADIUS = 20
SOURCE = 'waymo'
DGGT_CHECKPOINT = 'https://huggingface.co/xiaomi-research/dggt/resolve/main/model_latest_waymo.pt'
DGGT_UNUSED_HEADS = ('point_head', 'semantic_head')
DGGT_PRECISION = {'matmul': False, 'cudnn': True}
SEED = 20260929


def digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()


def symmetric_offsets(radius):
    return tuple(range(-radius, 0)) + tuple(range(1, radius + 1))


def med(x):
    x = np.asarray(x); x = x[np.isfinite(x)]
    return float(np.median(x)) if x.size else float('nan')


def metric_depth(D, L, alpha, solid, sky):
    Z_MAX, MIN_PX = 75.0, 50
    clear = ((alpha < .05) & ~solid) & ~sky & (D > 0)
    valid = clear & (L > 0) & (L <= Z_MAX)
    a_clip = med(L[valid] / D[valid]) if valid.sum() >= MIN_PX else float('nan')
    a_f = [med(L[f][valid[f]] / D[f][valid[f]]) if valid[f].sum() >= MIN_PX else a_clip for f in range(len(D))]
    if not np.isfinite(a_clip) or not np.isfinite(a_f).all():
        raise ValueError('not enough LiDAR pixels for the visibility scale')
    return D * np.asarray(a_f)[:, None, None], {'a_clip': a_clip, 'a_frame': a_f,
        'clear_lidar_pixels': valid.sum((1, 2)).tolist(), 'fallback': [bool(v.sum() < MIN_PX) for v in valid]}


def metric_reference_depth(depth, lidar, layers, sky):
    return metric_depth(depth, lidar, layers['effective_alpha'].astype(np.float32),
                        layers['solid_mask_hard'].astype(bool), sky)


def blocks16(frame_count):
    if frame_count < 16:
        raise ValueError('scene has fewer than 16 frames')
    return [min(start, frame_count-16) for start in range(0, frame_count, 16)]


def pil_resize_tensor(frames_u8, width: int = 518, multiple: int = 14):
    import torch
    from PIL import Image
    from torchvision import transforms as TF
    frames = np.asarray(frames_u8)
    if frames.dtype != np.uint8 or frames.ndim != 4 or frames.shape[-1] != 3:
        raise ValueError('Expected (N, H, W, 3) uint8 frames')
    to_tensor, out = TF.ToTensor(), []
    for frame in frames:
        image = Image.fromarray(frame).convert('RGB')
        w, h = image.size
        image = image.resize((width, round(h * (width / w) / multiple) * multiple), Image.Resampling.BICUBIC)
        tensor = to_tensor(image)
        if tensor.shape[1] > width:
            start = (tensor.shape[1] - width) // 2
            tensor = tensor[:, start:start + width, :]
        out.append(tensor)
    return torch.stack(out)


def load_dggt(checkpoint, device='cuda'):
    import torch
    from agt.model.build import add_dggt_to_path
    add_dggt_to_path()
    from dggt.models.vggt import VGGT
    model = VGGT()
    state = torch.load(checkpoint, map_location='cpu', weights_only=False)
    model.load_state_dict(state, strict=True)
    del state
    for name in DGGT_UNUSED_HEADS:
        setattr(model, name, None)
    model = model.to(device)
    for param in model.parameters():
        param.requires_grad = False
    return model.eval()


def canonical_depth(model, clean, *, device='cuda'):
    import torch
    from .sky import precision
    count = len(clean)
    depth = np.empty((count, clean.shape[1], clean.shape[2]), np.float32)
    owners = np.full(count, -1, np.int32)
    for block, start in enumerate(blocks16(count)):
        images = pil_resize_tensor(clean[start:start+16])[None].to(device)
        with precision(**DGGT_PRECISION), torch.no_grad():
            pred = model(images)
        values = pred['depth'][0, ..., 0].float().cpu().numpy()
        pending = np.flatnonzero(owners[start:start+16] < 0)
        depth[start+pending] = values[pending]
        owners[start+pending] = block
        del pred, images
    assert (owners >= 0).all()
    if not np.isfinite(depth).all() or (depth <= 0).any():
        raise ValueError('invalid reference depth')
    return depth, owners


def lidar_depth(data_root, record, frames, timestamps_mid_us, *, shape=(294, 518)):
    import h5py
    path = Path(data_root) / 'labels/lidar_dggt_single_v2' / record.source_id / record.scene_id / 'depth.h5'
    frames = [int(f) for f in frames]
    with h5py.File(path, 'r') as f:
        stored = f['frame_indices'][:]
        if np.any(np.diff(stored) <= 0):
            raise ValueError(f'{path}: frame_indices are not strictly increasing')
        lookup = {int(frame): row for row, frame in enumerate(stored)}
        have = sorted((lookup[frame], i) for i, frame in enumerate(frames) if frame in lookup)
        data = np.zeros((len(frames), *f['depth'].shape[-2:]), np.float32)
        labelled = np.zeros(len(frames), bool)
        if have:
            rows, positions = map(list, zip(*have))
            np.testing.assert_array_equal(f['timestamp_mid_us'][rows], np.asarray(timestamps_mid_us)[positions])
            data[positions] = f['depth'][rows]
            labelled[positions] = True
    h, w = shape
    iy = np.floor(np.arange(h) * (data.shape[-2] / h)).astype(np.int64)
    ix = np.floor(np.arange(w) * (data.shape[-1] / w)).astype(np.int64)
    return data[..., iy[:, None], ix[None, :]], labelled


def scene_geometry(record, data_root, model):
    from agt.data.grid import ScoringGrid
    from agt.data.labels import CleanSkyStore
    from agt.data.scene import SceneSource
    source = SceneSource(record, ScoringGrid())
    try:
        prepared = source.template()
        start = time.perf_counter()
        frames = list(range(record.frame_count))
        clean = source.rgb('clean', frames)
        depth, owners = canonical_depth(model, clean)
        del clean
        sky_store = CleanSkyStore(Path(data_root) / 'labels/sky_v1' / record.source_id)
        sky = sky_store.read(record.scene_id, frames, record.frame_count, source.timestamps_start_us)['sky'] >= 127.5
        L, labelled = lidar_depth(data_root, record, frames, source.timestamps_mid_us)
        if not labelled.all():
            raise ValueError(f'{record.scene_id}: frames without LiDAR labels')
        metric, scales = metric_reference_depth(depth.astype(np.float64), L.astype(np.float64), prepared.layers, sky)
        camera = source.grid_camera
        K = np.repeat(np.asarray([[camera.fx, 0, camera.cx], [0, camera.fy, camera.cy], [0, 0, 1]], np.float64)[None],
                      len(frames), axis=0)
        c2w = source.poses(frames, reference=0).astype(np.float64)
        return metric, K, c2w, scales, owners, time.perf_counter() - start
    finally:
        source.close()


def pair_bits(depth, K, c2w, occluder, *, offsets, device='cuda'):
    import torch
    from agt.model.visibility import visibility_camera
    offsets = tuple(offsets)
    radius = max(offsets)
    depth = torch.as_tensor(depth, dtype=torch.float64, device=device)
    K = torch.as_tensor(K, dtype=torch.float64, device=device)
    c2w = torch.as_tensor(c2w, dtype=torch.float64, device=device)
    count, h, w = depth.shape
    source_occluder = torch.as_tensor(np.broadcast_to(occluder, (count, h, w)).copy(), dtype=torch.float64, device=device)
    pixels = np.arange(h*w, dtype=np.int32)
    packed = np.zeros((count, len(offsets), (len(pixels)+7)//8), np.uint8)
    for j in range(count):
        lo, hi = max(0, j-radius), min(count, j+radius+1)
        result = visibility_camera(depth[None, lo:hi], K[None, lo:hi], c2w[None, lo:hi],
            torch.ones((1, hi-lo, h, w), dtype=torch.bool, device=device), [j-lo],
            alpha=source_occluder[None, lo:hi])
        selected = result['bits'][0].reshape(hi-lo, h*w).cpu().numpy()
        bits = np.packbits(selected, axis=-1, bitorder='little')
        for t in range(lo, hi):
            if t != j:
                packed[t, offsets.index(j-t)] = bits[t-lo]
    return {'strict': packed}


def write_cache(path, identity, packed, scales, K, c2w, owners, *, timings=None):
    import h5py
    path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
    try:
        with h5py.File(temporary, 'w') as f:
            f.attrs.update(schema=SCHEMA, identity_json=json.dumps(identity, sort_keys=True),
                           identity_sha256=digest(identity), created_utc=datetime.now(timezone.utc).isoformat(),
                           scale_json=json.dumps(scales), timings_json=json.dumps(timings or {}))
            for name, array in packed.items():
                kwargs = dict(compression='gzip', compression_opts=4, chunks=(1, 1, array.shape[-1]), fletcher32=True) if array.shape[-1] else {}
                f.create_dataset(name, data=array, **kwargs)
            offsets = tuple(identity['offsets'])
            offset_dtype = np.int8 if max(offsets) <= np.iinfo(np.int8).max else np.int32
            for name, array in dict(frame_indices=np.arange(len(owners)), offsets=np.asarray(offsets, offset_dtype),
                                    a_f=np.asarray(scales['a_frame']), K=K, c2w=c2w, depth_block=owners).items():
                f.create_dataset(name, data=array)
            f.attrs['complete'] = True
        temporary.replace(path)
    finally:
        temporary.unlink(missing_ok=True)


def manifest(offsets) -> dict:
    return {'schema': SCHEMA, 'label_id': LABEL_ID, 'implementation_version': LABEL_ID, 'recipe': RECIPE,
            'visibility_semantics': SEMANTICS, 'depth_consistency': False,
            'source_alpha_tolerance': .1, 'source_filter_label': SOURCE_POLICY,
            'offsets_by_source': {SOURCE: list(offsets)},
            'storage': 'strict[frame, offset, ceil(H*W/8)] little bit order; all target pixels',
            'dggt_checkpoint': DGGT_CHECKPOINT}


def generate(data_root, records, checkpoint) -> int:
    import torch
    from agt.eval.labels import PolicyLabels
    data_root = Path(data_root)
    out = data_root / 'labels' / LABEL_ID
    offsets = symmetric_offsets(OFFSET_RADIUS)
    store.atomic_text(out / 'label_manifest.json', json.dumps(manifest(offsets), indent=1, sort_keys=True) + '\n')
    torch.set_num_threads(4); torch.manual_seed(SEED); np.random.seed(SEED)
    torch.backends.cudnn.benchmark = False
    model = None
    failed = 0
    for record in records:
        path = out / record.source_id / (record.scene_id + '.h5')
        started = time.perf_counter()
        if path.is_file():
            print(json.dumps({'scene': record.scene_id, 'status': 'skipped'}), flush=True)
            continue
        try:
            if model is None:
                model = load_dggt(checkpoint)
            occluder, _ = PolicyLabels(data_root).read(record.source_id, record.scene_id, list(range(record.frame_count)))
            depth, K, c2w, scales, owners, forward_seconds = scene_geometry(record, data_root, model)
            pairs_started = time.perf_counter()
            packed = pair_bits(depth, K, c2w, occluder, offsets=offsets)
            torch.cuda.synchronize()
            identity = {'schema': SCHEMA, 'implementation_version': LABEL_ID, 'recipe': RECIPE,
                        'visibility_semantics': SEMANTICS, 'depth_consistency': False,
                        'scene': {'source_id': record.source_id, 'scene_id': record.scene_id,
                                  'frame_count': record.frame_count, 'template_id': record.template_id},
                        'shape': list(occluder.shape[-2:]), 'offsets': list(offsets), 'blocks16': blocks16(record.frame_count),
                        'source_alpha': SOURCE_POLICY, 'dggt_checkpoint': DGGT_CHECKPOINT}
            write_cache(path, identity, packed, scales, K, c2w, owners,
                        timings=dict(forward_seconds=forward_seconds, pair_seconds=time.perf_counter() - pairs_started))
            row = {'scene': record.scene_id, 'status': 'written', 'frames': record.frame_count,
                   'seconds': round(time.perf_counter() - started, 1)}
        except Exception as error:
            failed += 1
            row = {'scene': record.scene_id, 'status': 'failed', 'error': f'{type(error).__name__}: {error}'}
        print(json.dumps(row), flush=True)
    return failed