File size: 10,097 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
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
from __future__ import annotations

import io
import json
import time
from contextlib import contextmanager
from pathlib import Path

import numpy as np

from . import scene_store as store

SEGFORMER = 'nvidia/segformer-b5-finetuned-cityscapes-1024-1024'
SEGFORMER_REVISION = '2c6f153e4c23c229e2fa2b188eb250607e030cd8'
SKY_LABEL = 10
GRID = (518, 294)
FILE = 'sky.h5'
LABEL_DIR = Path('labels') / 'sky_v1'
WAYMO_FRONT = 1
WAYMO_NATIVE = (1920, 1280)
WAYMO_CROP_TOP = 100
MANIFEST = {
    'schema': 'amodaldrive_label_manifest_v1', 'name': 'sky', 'version': 1, 'source_id': 'waymo', 'file': FILE,
    'layers': ['sky'],
    'grid': {'name': '518x294_direct', 'width': 518, 'height': 294, 'geometry': 'direct_anisotropic_full_frame',
             'resampler': 'PIL_Image.Resampling.BICUBIC_on_uint8_0_255_binary (DGGT datasets/dataset.py:60-136)',
             'value': 'uint8 = BICUBIC(native binary sky * 255); loader value = uint8 / 255 (as ToTensor)'},
    'segmentation': f'SegFormer-B5 Cityscapes ({SEGFORMER}), slide inference, trainId 10 (sky), fp32, TF32 off',
    'inputs': {'sky': 'native clean frames the rgb.mp4 was converted from (Waymo v2.0.1 camera_image FRONT JPEG, '
                      'PIL RGB 1920x1280, rows [100, 1180))'},
}

SEMANTIC_CLASSES = [
    'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
    'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
    'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
    'bicycle'
]
IMG_SCALE = (2048, 1024)
CROP = (1024, 1024)
STRIDE = (768, 768)


def _check_labels(model):
    id2label = model.config.id2label
    got = [id2label[i] for i in range(len(SEMANTIC_CLASSES))]
    if got != SEMANTIC_CLASSES:
        raise RuntimeError(f'label order mismatch: expected {SEMANTIC_CLASSES}, got {got}')


def _resize_keep_ratio(img):
    h, w = img.shape[:2]
    long_edge, short_edge = max(IMG_SCALE), min(IMG_SCALE)
    scale = min(long_edge / max(h, w), short_edge / min(h, w))
    return int(w * scale + 0.5), int(h * scale + 0.5)


def slide_inference(model, img_bgr, device, dtype):
    import torch
    import torch.nn.functional as F
    mean = torch.tensor([123.675, 116.28, 103.53]).view(1, 3, 1, 1)
    std = torch.tensor([58.395, 57.12, 57.375]).view(1, 3, 1, 1)
    orig_h, orig_w = img_bgr.shape[:2]
    new_w, new_h = _resize_keep_ratio(img_bgr)

    x = torch.from_numpy(img_bgr[..., ::-1].copy()).permute(2, 0, 1)[None].float()
    x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", align_corners=False)
    x = ((x - mean) / std).to(device=device, dtype=dtype)

    n_cls = model.config.num_labels
    logits = torch.zeros((1, n_cls, new_h, new_w), device=device, dtype=torch.float32)
    count = torch.zeros((1, 1, new_h, new_w), device=device, dtype=torch.float32)

    ch, cw = CROP
    sh, sw = STRIDE
    n_rows = max(new_h - ch + sh - 1, 0) // sh + 1
    n_cols = max(new_w - cw + sw - 1, 0) // sw + 1
    for r in range(n_rows):
        for c in range(n_cols):
            y2 = min(r * sh + ch, new_h); x2 = min(c * sw + cw, new_w)
            y1 = max(y2 - ch, 0);         x1 = max(x2 - cw, 0)
            crop = x[:, :, y1:y2, x1:x2]
            out = model(pixel_values=crop).logits
            out = F.interpolate(out.float(), size=crop.shape[2:],
                                mode="bilinear", align_corners=False)
            logits[:, :, y1:y2, x1:x2] += out
            count[:, :, y1:y2, x1:x2] += 1

    logits = logits / count
    logits = F.interpolate(logits, size=(orig_h, orig_w),
                           mode="bilinear", align_corners=False)
    return logits.argmax(dim=1)[0].to(torch.uint8).cpu().numpy()


@contextmanager
def precision(matmul: bool, cudnn: bool):
    import torch
    old = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32
    torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = matmul, cudnn
    try:
        yield
    finally:
        torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = old


class Segmenter:
    def __init__(self, segformer: str = SEGFORMER, revision: str | None = SEGFORMER_REVISION):
        import torch
        from transformers import SegformerForSemanticSegmentation
        model, info = SegformerForSemanticSegmentation.from_pretrained(
            segformer, revision=revision if segformer == SEGFORMER else None, output_loading_info=True)
        if any(info[k] for k in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs')):
            raise SystemExit(f'SegFormer loading info {info}')
        self.model = model.cuda().eval().float()
        _check_labels(self.model)
        self.torch = torch

    def native(self, frame_rgb: np.ndarray) -> np.ndarray:
        torch = self.torch
        with precision(matmul=False, cudnn=False), torch.inference_mode():
            labels = slide_inference(self.model, frame_rgb[..., ::-1].copy(), 'cuda', torch.float32)
        return labels == SKY_LABEL


def bicubic_sky(binary: np.ndarray) -> np.ndarray:
    from PIL import Image
    return np.asarray(Image.fromarray(binary.astype(np.uint8) * 255).resize(GRID, Image.Resampling.BICUBIC))


def waymo_native_frames(raw: Path, camera_json: dict, frames: list):
    import pyarrow.parquet as pq
    from PIL import Image
    segment, split = camera_json['source']['segment'], camera_json['source']['split']
    path = Path(raw) / split / 'camera_image' / f'{segment}.parquet'
    t = pq.read_table(str(path), columns=['key.segment_context_name', 'key.frame_timestamp_micros', 'key.camera_name',
                                          '[CameraImageComponent].image']).to_pydict()
    if set(t['key.segment_context_name']) - {segment}:
        raise ValueError(f'{segment}: camera_image rows of another segment')
    jpeg = {}
    for stamp, cam, data in zip(t['key.frame_timestamp_micros'], t['key.camera_name'], t['[CameraImageComponent].image']):
        if int(cam) == WAYMO_FRONT:
            if int(stamp) in jpeg:
                raise ValueError(f'{segment}: repeated FRONT timestamp {stamp}')
            jpeg[int(stamp)] = data
    wanted = [int(f['frame_timestamp_us']) for f in frames]
    if sorted(jpeg) != sorted(wanted):
        raise ValueError(f'{segment}: FRONT rows {len(jpeg)} do not match frames.jsonl {len(wanted)}')
    del t
    for index, stamp in enumerate(wanted):
        with Image.open(io.BytesIO(jpeg[stamp])) as image:
            if image.format != 'JPEG':
                raise ValueError(f'{segment}: camera image is {image.format}')
            rgb = np.asarray(image.convert('RGB'))
        if rgb.shape != (WAYMO_NATIVE[1], WAYMO_NATIVE[0], 3):
            raise ValueError(f'{segment}: camera image {rgb.shape}')
        yield index, np.ascontiguousarray(rgb[WAYMO_CROP_TOP:WAYMO_NATIVE[1] - WAYMO_CROP_TOP])


def write_manifest(data_root: Path) -> Path:
    path = Path(data_root) / LABEL_DIR / 'waymo' / 'label_manifest.json'
    store.atomic_text(path, json.dumps(MANIFEST, indent=1, sort_keys=True) + '\n')
    return path


def label_scene(seg: Segmenter, data_root: Path, raw: Path, scene: str) -> dict:
    import h5py
    started = time.time()
    data_root = Path(data_root)
    out_dir = data_root / LABEL_DIR / 'waymo' / scene
    if (out_dir / 'complete.json').is_file() and (out_dir / FILE).is_file():
        marker = json.loads((out_dir / 'complete.json').read_text())
        if store.sha256_file(out_dir / FILE) == marker['files'][FILE]:
            return {'scene': scene, 'status': 'skipped'}
    scene_dir = data_root / 'scenes' / 'waymo' / scene
    camera_json = json.loads((scene_dir / 'camera.json').read_text())
    frames = [json.loads(line) for line in (scene_dir / 'frames.jsonl').read_text().splitlines() if line.strip()]
    n = len(frames)
    if [f['frame_index'] for f in frames] != list(range(n)):
        raise ValueError(f'{scene}: frames.jsonl does not hold frames 0..{n - 1}')
    out_dir.mkdir(parents=True, exist_ok=True)
    temp = out_dir / f'{FILE}.tmp'
    fraction = np.zeros(n, np.float64)
    decoded = 0
    with h5py.File(temp, 'w') as h:
        sky = h.create_dataset('sky', (n, GRID[1], GRID[0]), dtype='u1', chunks=(1, GRID[1], GRID[0]),
                               compression='gzip', compression_opts=4)
        for index, rgb in waymo_native_frames(raw, camera_json, frames):
            if index != decoded:
                raise ValueError(f'{scene}: frame {index} out of order')
            binary = seg.native(rgb)
            sky[index] = bicubic_sky(binary)
            fraction[index] = float(binary.mean())
            decoded += 1
        if decoded != n:
            raise ValueError(f'{scene}: decoded {decoded}/{n} frames')
        h.create_dataset('frame_indices', data=np.arange(n, dtype=np.int64))
        h.create_dataset('timestamp_start_us', data=np.array([f['timestamp_start_us'] for f in frames], np.int64))
        h.create_dataset('sky_fraction_native', data=fraction)
    temp.replace(out_dir / FILE)
    marker = {'name': 'sky', 'version': 1, 'layers': ['sky'], 'scene_id': scene, 'source_id': 'waymo', 'frame_count': n,
              'files': {FILE: store.sha256_file(out_dir / FILE)}, 'segmentation': MANIFEST['segmentation'],
              'sky_native_fraction_mean': float(fraction.mean()), 'seconds': round(time.time() - started, 1)}
    store.atomic_text(out_dir / 'complete.json', json.dumps(marker, indent=1, sort_keys=True) + '\n')
    return {'scene': scene, 'status': 'written', 'frames': n, 'seconds': marker['seconds']}


def generate(data_root: Path, raw: Path, scenes: list[str], *, segformer: str = SEGFORMER) -> int:
    import torch
    torch.backends.cudnn.benchmark = False
    write_manifest(data_root)
    seg = Segmenter(segformer)
    failed = 0
    for scene in scenes:
        try:
            result = label_scene(seg, data_root, raw, scene)
        except Exception as error:
            failed += 1
            result = {'scene': scene, 'status': 'failed', 'error': f'{type(error).__name__}: {error}'}
        print(json.dumps(result), flush=True)
    return failed