s23dr
hoho22k
research-only
non-commercial
File size: 8,304 Bytes
932f501
 
 
 
 
 
 
 
 
d5467ee
932f501
d5467ee
 
 
 
 
932f501
 
 
 
 
 
 
d5467ee
932f501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5467ee
 
932f501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5467ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5467ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5467ee
 
 
932f501
 
d5467ee
 
 
 
932f501
 
 
 
 
d5467ee
932f501
 
 
 
 
d5467ee
 
 
 
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
"""Per-epoch augmentation + subsampling for cached scene samples.

These transforms apply to the dict returned by `HoHoCachedDataset` *after* it
has been loaded from a semantic cache shard. They mutate `scene_xyz`, the per-point
parallel arrays, and `verts_gt[:, :3]` in place-equivalent ways (returning
new tensors) so that:

  - Random 3D rotation: rotate scene + GT vertices by a random 3D rotation matrix.
  - Random horizontal flip: optional Xβ†’βˆ’X mirror, applied to scene + GT.
  - Random scale (Building3D): isotropic or per-axis factor on scene + GT.
  - Random XYZ jitter: small Gaussian noise on `scene_xyz` only.
  - Random point dropout (Building3D) before the subsample to `n_pts`; both only
    change anything when the cache holds more points than the model input
    (raw-point `b3d_v2` caches). At eval time the resample is deterministic:
    a prefix slice for the fixed-size S23DR caches, a permutation seeded by the
    building id for raw-point caches.

All operations are torch-native to keep work on whichever device the
DataLoader returns; in practice they run on CPU before the batch ships to
the GPU.
"""
from __future__ import annotations

import zlib
from typing import Optional

import torch


# Per-point arrays that must be co-permuted when subsampling/dropping points.
POINT_KEYS = (
    "scene_xyz",
    "scene_type_ids",
    "scene_gestalt_ids",
    "scene_gestalt_id2",
    "scene_gestalt_w1",
    "scene_ade_ids",
    "scene_geom_conf",
    "scene_sem_conf",
    "scene_rgb",
    "scene_nir",        # Building3D caches only
    "scene_intensity",  # Building3D caches only
)


def _yaw_rotation_matrix(theta: torch.Tensor) -> torch.Tensor:
    """3x3 rotation around Y (Y-up). theta: scalar tensor in radians."""
    c = torch.cos(theta)
    s = torch.sin(theta)
    R = torch.eye(3, dtype=torch.float32, device=theta.device)
    R[0, 0] = c
    R[0, 2] = s
    R[2, 0] = -s
    R[2, 2] = c
    return R


def random_yaw_rotation(sample: dict, generator: Optional[torch.Generator] = None) -> dict:
    """Rotate scene_xyz and verts_gt[:, :3] by the same random Y-axis angle."""
    theta = torch.rand((), generator=generator) * (2.0 * torch.pi)
    R = _yaw_rotation_matrix(theta)

    sample["scene_xyz"] = sample["scene_xyz"] @ R.T
    if "verts_gt" in sample:
        v = sample["verts_gt"]
        # v[:, :3] only β€” keep the validity flag at column 3 untouched.
        v_xyz = v[:, :3] @ R.T
        sample["verts_gt"] = torch.cat([v_xyz, v[:, 3:4]], dim=-1)
    return sample


def random_horizontal_flip(sample: dict, p: float = 0.5,
                            generator: Optional[torch.Generator] = None) -> dict:
    """With probability `p`, mirror the scene along X (X β†’ βˆ’X)."""
    if torch.rand((), generator=generator).item() >= p:
        return sample
    sample["scene_xyz"] = sample["scene_xyz"] * torch.tensor([-1.0, 1.0, 1.0])
    if "verts_gt" in sample:
        v = sample["verts_gt"]
        v_xyz = v[:, :3] * torch.tensor([-1.0, 1.0, 1.0])
        sample["verts_gt"] = torch.cat([v_xyz, v[:, 3:4]], dim=-1)
    return sample


def random_xyz_jitter(sample: dict, sigma: float = 0.01,
                       generator: Optional[torch.Generator] = None) -> dict:
    """Add small Gaussian noise to scene_xyz only (verts_gt stays clean)."""
    if sigma <= 0.0:
        return sample
    noise = torch.randn(sample["scene_xyz"].shape, generator=generator) * sigma
    sample["scene_xyz"] = sample["scene_xyz"] + noise
    return sample


def random_scale(sample: dict, lo: float, hi: float, anisotropic: bool,
                 generator: Optional[torch.Generator] = None) -> dict:
    """Scale scene and GT by a factor drawn from [lo, hi] (one per axis when `anisotropic`,
    which varies the roof pitch; an isotropic factor keeps every angle)."""
    if hi <= lo:
        return sample
    s = torch.rand(3 if anisotropic else 1, generator=generator) * (hi - lo) + lo
    sample["scene_xyz"] = sample["scene_xyz"] * s
    v = sample["verts_gt"]
    sample["verts_gt"] = torch.cat([v[:, :3] * s, v[:, 3:4]], dim=-1)
    return sample


def random_point_dropout(sample: dict, p: float,
                         generator: Optional[torch.Generator] = None) -> dict:
    """Drop a fraction `p` of the cached points (before `random_point_subsample`, so it removes
    distinct measurements rather than duplicates)."""
    n = sample["scene_xyz"].shape[0]
    n_keep = max(int(round(n * (1.0 - p))), 1)
    if n_keep >= n:
        return sample
    idx = torch.randperm(n, generator=generator)[:n_keep]
    for k in POINT_KEYS:
        if k in sample:
            sample[k] = sample[k][idx]
    return sample


def random_point_subsample(sample: dict, n_pts: int,
                            generator: Optional[torch.Generator] = None) -> dict:
    """Randomly keep `n_pts` of the cached points (training augmentation)."""
    n_cache = sample["scene_xyz"].shape[0]
    if n_cache == n_pts:
        return sample
    if n_cache < n_pts:
        # Pad with random repeats β€” should be rare since cache is built oversized.
        extra = torch.randint(0, n_cache, (n_pts - n_cache,), generator=generator)
        idx = torch.cat([torch.arange(n_cache), extra])
    else:
        idx = torch.randperm(n_cache, generator=generator)[:n_pts]
    for k in POINT_KEYS:
        if k in sample:
            sample[k] = sample[k][idx]
    return sample


def seeded_point_resample(sample: dict, n_pts: int) -> dict:
    """Resample a raw-point cache row to exactly `n_pts`, identically on every run: a permutation
    (or random duplicates when short) seeded by crc32(order_id), so the choice does not depend on
    the LiDAR scan order, the rank or the shard layout."""
    n_cache = sample["scene_xyz"].shape[0]
    if n_cache == n_pts:
        return sample
    g = torch.Generator().manual_seed(zlib.crc32(str(sample["order_id"]).encode()) & 0x7FFFFFFF)
    if n_cache < n_pts:
        idx = torch.cat([torch.arange(n_cache), torch.randint(0, n_cache, (n_pts - n_cache,), generator=g)])
    else:
        idx = torch.randperm(n_cache, generator=g)[:n_pts]
    for k in POINT_KEYS:
        if k in sample:
            sample[k] = sample[k][idx]
    return sample


def deterministic_point_slice(sample: dict, n_pts: int) -> dict:
    """Take the first `n_pts` cached points (eval/inference use)."""
    n_cache = sample["scene_xyz"].shape[0]
    if n_cache == n_pts:
        return sample
    if n_cache < n_pts:
        # Cache shorter than expected β€” pad by repeating the last point.
        last = n_cache - 1
        pad = torch.full((n_pts - n_cache,), last, dtype=torch.long)
        idx = torch.cat([torch.arange(n_cache), pad])
    else:
        idx = torch.arange(n_pts)
    for k in POINT_KEYS:
        if k in sample:
            sample[k] = sample[k][idx]
    return sample


def apply_train_transforms(
    sample: dict,
    n_pts: int,
    yaw: bool = True,
    flip: bool = True,
    jitter_sigma: float = 0.01,
    point_dropout: float = 0.0,
    scale_range: tuple[float, float] = (1.0, 1.0),
    scale_anisotropic: bool = False,
    generator: Optional[torch.Generator] = None,
) -> dict:
    """Training-time pipeline: dropout β†’ subsample β†’ flip β†’ yaw β†’ scale β†’ jitter. With the defaults
    (no dropout, unit scale) it is exactly subsample β†’ flip β†’ yaw β†’ jitter."""
    if point_dropout > 0.0:
        sample = random_point_dropout(sample, point_dropout, generator=generator)
    sample = random_point_subsample(sample, n_pts, generator=generator)
    if flip:
        sample = random_horizontal_flip(sample, generator=generator)
    if yaw:
        sample = random_yaw_rotation(sample, generator=generator)
    sample = random_scale(sample, *scale_range, anisotropic=scale_anisotropic, generator=generator)
    if jitter_sigma > 0.0:
        sample = random_xyz_jitter(sample, sigma=jitter_sigma, generator=generator)
    return sample


def apply_eval_transforms(sample: dict, n_pts: int, seeded: bool = False) -> dict:
    """Eval/inference-time pipeline: deterministic resample, no rotation, no jitter. `seeded`
    selects `seeded_point_resample` (raw-point caches) instead of the prefix slice."""
    return seeded_point_resample(sample, n_pts) if seeded else deterministic_point_slice(sample, n_pts)