diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4c9ad980682246bd6ab0d2bae82232be6dbdcbd4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 5d3912aa756d561ed2e437a91d790db40c14dec9..999ee8f594b48792c390d161181daf1593acb896 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,32 @@ --- -title: Lidarverse -emoji: 🐨 -colorFrom: indigo -colorTo: yellow +title: LidarVerse +emoji: 🛰️ +colorFrom: pink +colorTo: green sdk: gradio sdk_version: 6.30.0 -python_version: '3.12' app_file: app.py -pinned: false +short_description: Generate LiDAR sweeps from a road scene you design +python_version: "3.12" +startup_duration_timeout: 1h +license: apache-2.0 +models: + - nvidia/lidarverse --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# LidarVerse: HD map → LiDAR world generation + +Demo for [nvidia/lidarverse](https://huggingface.co/nvidia/lidarverse) ("Into the LidarVerse: A Real-Time Unified +LiDAR World Model Across Tasks and Sensors", [arXiv 2610.19201](https://arxiv.org/abs/2610.19201)). + +* Uses the released **Stage-3 SF-DMD EMA** package (4 SDE steps, CFG 1, four-frame causal blocks, 9-frame K/V + cache incl. sink, persistent spatial cache with 0.10 m voxels) and the FP32 PAI range tokenizer, following the + official `scripts/diffusion/getting_started.sh STAGE=3` quickstart. +* The HD map is built procedurally (lanes, curbs, crosswalks, stop lines, poles, moving / parked vehicles, ego motion) + in the prepared-PAI sample format and conditioned through the official raw-HDMap rasterizer + (`RAW_HDMAP_CONDITION_RASTERIZE=1`, 3x3 bbox dilation, 0.1 m segment spacing). +* Inference code is from [nv-tlabs/LidarVerse](https://github.com/nv-tlabs/LidarVerse) (Apache-2.0). Transformer + Engine, Megatron, Apex and NATTEN are replaced by small pure-PyTorch equivalents in `shims/` (RMSNorm, RoPE, + exact neighborhood attention with NATTEN's window clamping) so the app runs on ZeroGPU. + +Model weights are under the NVIDIA Open Model License (research and development only). diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d1df9eb500ef727e02344dfdf656b181acb94b --- /dev/null +++ b/app.py @@ -0,0 +1,205 @@ +import os +import sys + +os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") +os.environ.setdefault("MPLCONFIGDIR", "/tmp/lidarverse-matplotlib") +ROOT = os.path.dirname(os.path.abspath(__file__)) +# Pure-PyTorch stand-ins for Transformer Engine / Megatron / Apex / NATTEN come first on the path. +sys.path[:0] = [os.path.join(ROOT, "shims"), ROOT] + +import spaces # noqa: E402 (must precede torch) +import tempfile # noqa: E402 +import time # noqa: E402 +from pathlib import Path # noqa: E402 +from types import SimpleNamespace # noqa: E402 + +import gradio as gr # noqa: E402 +import numpy as np # noqa: E402 +import plotly.graph_objects as go # noqa: E402 +import torch # noqa: E402 +from huggingface_hub import snapshot_download # noqa: E402 + +from diffusion.inference.pai import MODES, load_model, load_package, load_sample, preview # noqa: E402 +from scene import LAYOUTS, build_scene # noqa: E402 +from utils import inference as common # noqa: E402 +from utils.visualize.hdmap import render_hdmap # noqa: E402 + +# ----------------------------------------------------------------------------- model (Stage 3, SF-DMD EMA) +CKPT = Path(snapshot_download("nvidia/lidarverse", + allow_patterns=["lidarverse-sfdmd-pai/*", "lidarverse-tokenizer-pai/*"])) +CHECKPOINT = CKPT / "lidarverse-sfdmd-pai" / "ema_model.pt" +PACKAGE = load_package(CHECKPOINT, 3) +MODEL = load_model(CHECKPOINT, CKPT / "lidarverse-tokenizer-pai" / "ckpt.pt", + CKPT / "lidarverse-tokenizer-pai" / "latent_stats.pt", stage=3, package=PACKAGE) +ARGS = SimpleNamespace(stage=3, kv_cache_frames=9, num_steps=4, sde_eta=1.0, sampler="sde", guidance=1.0) + + +@spaces.GPU(duration=90) +def _run_model(sample: dict, mode: str, seed: int): + """Raw-HDMap rasterization (world mode) + Stage-3 causal 4-step sampling, all on GPU.""" + from diffusion.inference.causal import generate + from diffusion.inference.raw_hdmap import rasterize_raw_hdmap + + t0 = time.perf_counter() + with torch.inference_mode(): + if mode == "world" and "map_vertices" in sample and len(sample.get("map_offsets", [])) > 1: + condition, _ = rasterize_raw_hdmap(sample, bbox_dilation=3, seg_interval=0.1) + sample["hdmap"] = condition + generated, valid = generate(MODEL, sample, mode, ARGS, int(seed), sys.stdout) + torch.cuda.synchronize() + return generated, valid, sample.get("hdmap"), time.perf_counter() - t0 + + +def _scatter3d(points: np.ndarray, title: str) -> go.Figure: + if len(points) > 60000: + points = points[np.random.default_rng(0).choice(len(points), 60000, replace=False)] + fig = go.Figure(go.Scatter3d( + x=points[:, 0], y=points[:, 1], z=points[:, 2], mode="markers", + marker=dict(size=1.2, color=np.clip(points[:, 2], -3, 5), colorscale="Viridis", opacity=0.9), + )) + fig.update_layout( + title=title, height=520, margin=dict(l=0, r=0, t=40, b=0), + scene=dict(aspectmode="data", xaxis_visible=False, yaxis_visible=False, zaxis_visible=False, + camera=dict(eye=dict(x=-0.9, y=0, z=0.55), center=dict(x=0.15, y=0, z=-0.1))), + ) + return fig + + +def _finish(sample, generated, valid, mode, seed, elapsed): + out = Path(tempfile.mkdtemp(prefix="lidarverse-")) + video = out / "generation.mp4" + common.write_video(video, preview(sample, generated, valid, mode, out), 10) + npz = out / f"lidarverse_{mode}_seed{seed}.npz" + np.savez_compressed(npz, range_m=generated, valid_mask=valid, ray_directions=sample["ray_directions"], + pose_sensor_start_end=sample["pose_sensor_start_end"][:len(generated)], fps=np.float32(10), + known_frame_mask=np.arange(len(generated)) < MODES[mode]["input_frames"]) + last = len(generated) - 1 + pts = common.points_from_ranges(generated[last], valid[last], sample["ray_directions"]) + fig = _scatter3d(pts, f"Generated sweep {last} (sensor frame, {len(pts):,} points)") + status = (f"**{mode}** | {len(generated)} sweeps @ 10 Hz | 4-step SF-DMD causal sampling | " + f"GPU time {elapsed:.1f}s | seed {seed}") + return str(video), fig, str(npz), status + + +def generate_scene(layout: str, lanes_per_direction: int = 2, ego_speed_kmh: float = 30.0, + num_vehicles: int = 8, parked_cars: bool = True, seed: int = 0): + """Generate a 21-sweep LiDAR sequence (2 s @ 10 Hz) from a procedurally built HD map. + + Args: + layout: "Straight road", "Four-way intersection" or "Curved road". + lanes_per_direction: lanes in each driving direction (1-3). + ego_speed_kmh: speed of the ego vehicle carrying the LiDAR. + num_vehicles: number of other moving vehicles on the road. + parked_cars: whether to park cars along the curbs. + seed: random seed for both the scene layout and the diffusion sampler. + + Returns: + Side-by-side video (HD map | generated LiDAR), a 3D plot of the last sweep, + the generated range sequence as .npz, and a status line. + """ + seed = int(seed) + sample = build_scene(layout, int(lanes_per_direction), float(ego_speed_kmh), int(num_vehicles), + bool(parked_cars), seed) + generated, valid, hdmap, elapsed = _run_model(sample, "world", seed) + sample["hdmap"] = hdmap + return _finish(sample, generated, valid, "world", seed, elapsed) + + +def generate_from_npz(npz_file: str, mode: str = "world", seed: int = 0): + """Run world generation / forecasting / resimulation on a prepared NVIDIA PAI clip. + + Args: + npz_file: an NPZ produced by LidarVerse's scripts/data/prepare_pai_bidir.py (128x1024, 10 Hz). + mode: "world" (HD map -> LiDAR), "forecast" (10 observed -> 11 future sweeps) or + "resim" (15 observed sweeps + future actor poses -> 5 sweeps). + seed: sampler seed. + """ + if not npz_file: + raise gr.Error("Upload a prepared PAI .npz clip first.") + try: + sample = load_sample(npz_file, [mode], 3) + except ValueError as e: + raise gr.Error(str(e)) + seed = int(seed) + generated, valid, hdmap, elapsed = _run_model(sample, mode, seed) + if hdmap is not None: + sample["hdmap"] = hdmap + if mode == "world" and "map_kinds" not in sample: + raise gr.Error("World-mode previews need the raw vector map (map_vertices/map_offsets/map_kinds).") + return _finish(sample, generated, valid, mode, seed, elapsed) + + +def preview_scene(layout, lanes_per_direction=2, ego_speed_kmh=30.0, num_vehicles=8, parked_cars=True, seed=0): + """Render the procedural HD map + actor boxes (first sweep) from the LiDAR's viewpoint.""" + sample = build_scene(layout, int(lanes_per_direction), float(ego_speed_kmh), int(num_vehicles), + bool(parked_cars), int(seed)) + return render_hdmap(sample, 0)[..., ::-1] + + +CSS = """ +#col-container { max-width: 1200px; margin: 0 auto; } +.dark .gradio-container { color: var(--body-text-color); } +""" + +with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo: + with gr.Column(elem_id="col-container"): + gr.Markdown( + "# LidarVerse: HD map → LiDAR world generation\n" + "Design a road scene. NVIDIA's [LidarVerse](https://huggingface.co/nvidia/lidarverse) " + "Stage-3 self-forcing model (2B DiT, 4 denoising steps, rolling K/V + spatial cache) then generates " + "2 s of 128-beam LiDAR sweeps conditioned on the HD map and actor boxes. " + "[Paper](https://arxiv.org/abs/2610.19201) · [Code](https://github.com/nv-tlabs/LidarVerse) · " + "[Project page](https://research.nvidia.com/labs/sil/projects/lidarverse/)" + ) + with gr.Row(): + with gr.Column(scale=2): + layout = gr.Radio(list(LAYOUTS), value="Four-way intersection", label="Road layout") + with gr.Row(): + lanes = gr.Slider(1, 3, value=2, step=1, label="Lanes per direction") + speed = gr.Slider(0, 60, value=30, step=5, label="Ego speed (km/h)") + with gr.Row(): + vehicles = gr.Slider(0, 16, value=8, step=1, label="Moving vehicles") + parked = gr.Checkbox(value=True, label="Parked cars along the curb") + seed = gr.Number(value=0, precision=0, label="Seed (scene + sampler)") + run = gr.Button("Generate LiDAR", variant="primary") + with gr.Column(scale=3): + scene_img = gr.Image(label="HD-map condition preview (first sweep)", interactive=False) + status = gr.Markdown() + video = gr.Video(label="HD map | generated LiDAR (10 Hz)", autoplay=True, loop=True) + with gr.Row(): + plot = gr.Plot(label="Last generated sweep (drag to orbit)") + npz_out = gr.File(label="Generated range sequence (.npz)") + + with gr.Accordion("Advanced: run on your own prepared NVIDIA PAI clip (forecast / resimulate)", open=False): + gr.Markdown( + "Upload a clip prepared with `scripts/data/prepare_pai_bidir.py` from the LidarVerse repo " + "(128x1024 Pandar128 range images, 10 Hz, 21 sweeps). **forecast** observes 10 sweeps and " + "predicts 11; **resim** observes 15 and re-simulates 5 under the given actor poses." + ) + with gr.Row(): + npz_in = gr.File(label="Prepared PAI clip (.npz)", file_types=[".npz"], type="filepath") + mode = gr.Radio(["world", "forecast", "resim"], value="forecast", label="Task") + seed2 = gr.Number(value=0, precision=0, label="Seed") + run2 = gr.Button("Run on uploaded clip") + + gr.Examples( + examples=[ + ["Four-way intersection", 2, 30, 8, True, 0], + ["Straight road", 3, 50, 12, False, 3], + ["Curved road", 1, 25, 4, True, 7], + ["Four-way intersection", 1, 0, 3, True, 11], + ], + inputs=[layout, lanes, speed, vehicles, parked, seed], + outputs=[video, plot, npz_out, status], + fn=generate_scene, cache_examples=True, cache_mode="lazy", + ) + + scene_inputs = [layout, lanes, speed, vehicles, parked, seed] + for comp in scene_inputs: + comp.change(preview_scene, scene_inputs, scene_img, api_name=False, show_progress="hidden") + demo.load(preview_scene, scene_inputs, scene_img, api_name=False) + run.click(generate_scene, scene_inputs, [video, plot, npz_out, status], api_name="generate") + run2.click(generate_from_npz, [npz_in, mode, seed2], [video, plot, npz_out, status], api_name="generate_from_npz") + +if __name__ == "__main__": + demo.launch(mcp_server=True) diff --git a/assets/lidar/lidar_model.yaml b/assets/lidar/lidar_model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51625ad677537fbf675cad95952a4307e5bb0cdd --- /dev/null +++ b/assets/lidar/lidar_model.yaml @@ -0,0 +1,536 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +lidar_models: + spinning: + # https://www.hesaitech.com/product/at128/ + # Manu: HESAI Device: AT128 + # Params is derived from https://www.hesaitech.com/wp-content/uploads/2023/03/PandarView2_User_Manual_PV2-en-230810-1.pdf + HESAI-AT128: {n_vertical_bins: 128, frequency: 10, horizontal_fov: 120, n_horizontal_bins: 1200, + sync_angle_deg: 0, # always zero for AT128. + azimuths_deg_offset: [ + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.659, + -2.4, + 0.659, + -2.4, + 0.659, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + 2.4, + -0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + -2.4, + 0.65, + ], + inclinations_deg: [ + 12.93, + 12.73, + 12.53, + 12.33, + 12.13, + 11.93, + 11.73, + 11.53, + 11.33, + 11.13, + 10.93, + 10.73, + 10.53, + 10.33, + 10.13, + 9.93, + 9.73, + 9.53, + 9.33, + 9.13, + 8.93, + 8.73, + 8.53, + 8.33, + 8.13, + 7.93, + 7.73, + 7.53, + 7.33, + 7.13, + 6.93, + 6.73, + 6.53, + 6.33, + 6.13, + 5.93, + 5.73, + 5.53, + 5.33, + 5.13, + 4.93, + 4.73, + 4.53, + 4.33, + 4.13, + 3.93, + 3.73, + 3.53, + 3.33, + 3.13, + 2.93, + 2.73, + 2.53, + 2.33, + 2.13, + 1.93, + 1.73, + 1.53, + 1.33, + 1.13, + 0.93, + 0.73, + 0.53, + 0.33, + 0.13, + -0.07, + -0.27, + -0.47, + -0.67, + -0.87, + -1.07, + -1.27, + -1.47, + -1.67, + -1.87, + -2.07, + -2.27, + -2.47, + -2.67, + -2.87, + -3.07, + -3.27, + -3.47, + -3.67, + -3.87, + -4.07, + -4.27, + -4.47, + -4.67, + -4.87, + -5.07, + -5.27, + -5.47, + -5.67, + -5.87, + -6.07, + -6.27, + -6.47, + -6.67, + -6.87, + -7.07, + -7.27, + -7.47, + -7.67, + -7.87, + -8.07, + -8.27, + -8.47, + -8.67, + -8.87, + -9.07, + -9.27, + -9.47, + -9.67, + -9.87, + -10.07, + -10.27, + -10.47, + -10.67, + -10.87, + -11.07, + -11.27, + -11.47, + -11.67, + -11.87, + -12.07, + -12.27, + -12.47, + ]} + + # https://www.hesaitech.com/product/pandar128/ + # Manu: HESAI Device: Pandar128 + # Params is derived from https://www.hesaitech.com/wp-content/uploads/2023/03/PandarView2_User_Manual_PV2-en-230810-1.pdf + HESAI-Pandar128: {n_vertical_bins: 128, frequency: 10, horizontal_fov: 360, n_horizontal_bins: 3600, + sync_angle_deg: 0, + azimuths_deg_offset: [ + 3.257, + 3.263, + 1.091, + 3.268, + 1.093, + 3.273, + 1.094, + 3.278, + 1.095, + 3.283, + 1.096, + 3.288, + 1.097, + 3.291, + 1.098, + -1.101, + 1.100, + -1.104, + -3.306, + -1.106, + -3.311, + -1.109, + -3.318, + -1.111, + -3.324, + -1.113, + 7.72, + 5.535, + 3.325, + -3.33, + 1.107, + -5.538, + -7.726, + -1.115, + 7.731, + 5.543, + 3.329, + -3.336, + 1.108, + -5.547, + -7.738, + -1.117, + 7.743, + 5.551, + 3.335, + -3.342, + 1.110, + -5.555, + -7.750, + -1.119, + 7.757, + 5.560, + 3.340, + -3.347, + 1.111, + -5.564, + -7.762, + -1.121, + 7.768, + 5.569, + 3.345, + -3.353, + 1.113, + -5.573, + -7.775, + -1.123, + 7.780, + 5.578, + 3.351, + -3.358, + 1.115, + -5.582, + -7.787, + -1.125, + 7.792, + 5.586, + 3.356, + -3.363, + 1.116, + -5.591, + -7.799, + -1.127, + 7.804, + 5.595, + 3.360, + -3.369, + 1.118, + -5.599, + -7.811, + -1.129, + -3.374, + -1.130, + -3.379, + -1.132, + -3.383, + 3.381, + -3.388, + 3.386, + 1.129, + 3.390, + 1.129, + 3.395, + 1.131, + 3.401, + 1.133, + 3.406, + 1.135, + 3.410, + 1.137, + 3.416, + 1.139, + -1.142, + 1.142, + -1.143, + -3.426, + -1.143, + -3.429, + -1.145, + -3.433, + -1.145, + -3.436, + -1.146, + -3.440, + -1.146, + -3.443, + -1.146, + -3.446, + -3.449, + ], + inclinations_deg: [ + 14.436, + 13.535, + 13.082, + 12.624, + 12.165, + 11.702, + 11.239, + 10.771, + 10.305, + 9.830, + 9.356, + 8.880, + 8.401, + 7.921, + 7.438, + 6.953, + 6.467, + 5.978, + 5.487, + 4.996, + 4.501, + 4.007, + 3.509, + 3.013, + 2.512, + 2.013, + 1.885, + 1.761, + 1.637, + 1.511, + 1.386, + 1.258, + 1.13, + 1.008, + 0.88, + 0.756, + 0.63, + 0.505, + 0.379, + 0.251, + 0.124, + 0.000, + -0.129, + -0.254, + -0.380, + -0.506, + -0.632, + -0.760, + -0.887, + -1.012, + -1.141, + -1.266, + -1.393, + -1.519, + -1.646, + -1.773, + -1.901, + -2.027, + -2.155, + -2.282, + -2.409, + -2.535, + -2.663, + -2.789, + -2.916, + -3.044, + -3.172, + -3.299, + -3.425, + -3.552, + -3.680, + -3.806, + -3.933, + -4.062, + -4.190, + -4.318, + -4.444, + -4.571, + -4.699, + -4.824, + -4.951, + -5.081, + -5.209, + -5.336, + -5.463, + -5.589, + -5.718, + -5.843, + -5.968, + -6.100, + -6.607, + -7.117, + -7.624, + -8.134, + -8.640, + -9.149, + -9.652, + -10.160, + -10.665, + -11.170, + -11.672, + -12.174, + -12.673, + -13.173, + -13.67, + -14.166, + -14.66, + -15.154, + -15.645, + -16.135, + -16.622, + -17.106, + -17.592, + -18.072, + -18.548, + -19.030, + -19.501, + -19.978, + -20.445, + -20.918, + -21.379, + -21.848, + -22.304, + -22.768, + -23.219, + -23.678, + -24.123, + -25.016, + ]} diff --git a/assets/lidar/sensors.yaml b/assets/lidar/sensors.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ee251cd2cc3759e0becfc84d10efdb6bc90c9fd --- /dev/null +++ b/assets/lidar/sensors.yaml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Public sensor contracts. Per-sequence calibration remains authoritative for +# NCore-backed datasets; this file records the grids consumed by LidarVerse. +sensors: + nvidia_pai: + model: HESAI-AT128 + grid: [128, 1200] + cadence_hz: 10 + calibration: assets/lidar/lidar_model.yaml + pandaset: + model: HESAI-Pandar64 + grid: [64, 1024] + cadence_hz: 10 + calibration: tokenizer/training/datasets/lidar_datasets/pandaset.py + nuscenes: + model: HDL-32E + grid: [32, 1024] + native_cadence_hz: 20 + world_model_cadence_hz: 2 + calibration: per-sequence NCore metadata + waymo: + model: TOP + grid: [64, 1024] + cadence_hz: 10 + calibration: per-sequence NCore metadata diff --git a/diffusion/checkpointers/ema_fsdp_checkpointer.py b/diffusion/checkpointers/ema_fsdp_checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..e71430697c29b4b0651ae5b2c073dd683368a97d --- /dev/null +++ b/diffusion/checkpointers/ema_fsdp_checkpointer.py @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings + +import attrs + +from utils import log +from utils.config import CheckpointConfig as BaseCheckpointConfig +from utils.config import make_freezable +from utils.fsdp_checkpointer import FSDPCheckpointer as BaseFSDPCheckpointer + + +@make_freezable +@attrs.define(slots=False) +class CheckpointConfig(BaseCheckpointConfig): + load_ema_to_reg: bool = False + + +class FSDPCheckpointer(BaseFSDPCheckpointer): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not isinstance(self.config_checkpoint, CheckpointConfig): + warnings.warn( + "The 'config_checkpoint' is not an instance of 'CheckpointConfig'. " + "This behavior is deprecated and will not be supported in future versions. " + "Please update 'config_checkpoint' to be of type 'CheckpointConfig'.", + DeprecationWarning, + ) + + self.load_ema_to_reg = False + else: + self.load_ema_to_reg = self.config_checkpoint.load_ema_to_reg + + log.critical(f"load_ema_to_reg: {self.load_ema_to_reg}", rank0_only=False) + + def load_model_during_init(self, model, is_ema: bool = False, ema_id: int = 0): + if self.load_ema_to_reg and is_ema is False: + is_ema = True + ema_id = 0 + log.critical("Loading EMA model to regular model during initialization.", rank0_only=False) + super().load_model_during_init(model, is_ema, ema_id) diff --git a/diffusion/conditioner.py b/diffusion/conditioner.py new file mode 100644 index 0000000000000000000000000000000000000000..96542249a79b9af849a2a5faa0764b9f0d903245 --- /dev/null +++ b/diffusion/conditioner.py @@ -0,0 +1,340 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from abc import ABC, abstractmethod +from collections import defaultdict +from dataclasses import dataclass, fields +from enum import Enum +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn + +from utils import log +from utils.lazy_config import instantiate + + +class BaseConditionEntry(nn.Module): + def __init__(self): + super().__init__() + + self._dropout_rate = None + self._input_key = None + self._return_dict = False + + @property + def dropout_rate(self) -> Union[float, torch.Tensor]: + return self._dropout_rate + + @property + def input_key(self) -> str: + return self._input_key + + @property + def is_return_dict(self) -> bool: + return self._return_dict + + @dropout_rate.setter + def dropout_rate(self, value: Union[float, torch.Tensor]): + self._dropout_rate = value + + @input_key.setter + def input_key(self, value: str): + self._input_key = value + + @is_return_dict.setter + def is_return_dict(self, value: bool): + self._return_dict = value + + @dropout_rate.deleter + def dropout_rate(self): + del self._dropout_rate + + @input_key.deleter + def input_key(self): + del self._input_key + + @is_return_dict.deleter + def is_return_dict(self): + del self._return_dict + + def random_dropout_input( + self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None + ) -> torch.Tensor: + del key + dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate + bernoulli = torch.bernoulli((1.0 - dropout_rate) * torch.ones(len(in_tensor))).type_as(in_tensor) + bernoulli_expand = bernoulli.view((-1,) + (1,) * (in_tensor.dim() - 1)) + return bernoulli_expand * in_tensor + + def summary(self) -> str: + pass + + +class DataType(Enum): + IMAGE = "image" + VIDEO = "video" + + +class TextAttr(BaseConditionEntry): + def __init__(self): + super().__init__() + + def forward(self, token: torch.Tensor, mask: torch.Tensor): + return {"crossattn_emb": token, "crossattn_mask": mask} + + def random_dropout_input( + self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None + ) -> torch.Tensor: + if key is not None and "mask" in key: + return in_tensor + return super().random_dropout_input(in_tensor, dropout_rate, key) + + +@dataclass +class BaseVideoCondition: + crossattn_emb: torch.Tensor + crossattn_mask: torch.Tensor + data_type: DataType = DataType.VIDEO + padding_mask: Optional[torch.Tensor] = None + fps: Optional[torch.Tensor] = None + num_frames: Optional[torch.Tensor] = None + image_size: Optional[torch.Tensor] = None + scalar_feature: Optional[torch.Tensor] = None + frame_repeat: Optional[torch.Tensor] = None + + def to_dict(self) -> Dict[str, Optional[torch.Tensor]]: + return {f.name: getattr(self, f.name) for f in fields(self)} + + +@dataclass +class VideoExtendCondition(BaseVideoCondition): + video_cond_bool: Optional[torch.Tensor] = None # whether or not it conditioned on video + gt_latent: Optional[torch.Tensor] = None + condition_video_indicator: Optional[torch.Tensor] = None # 1 for condition region + + # condition_video_input_mask will concat to the input of network, along channel dim; + # Will be concat with the input tensor + condition_video_input_mask: Optional[torch.Tensor] = None + # condition_video_augment_sigma: (B, T) tensor of sigma value for the conditional input augmentation, only valid when apply_corruption_to_condition_region is "noise_with_sigma" or "noise_with_sigma_fixed" + condition_video_augment_sigma: Optional[torch.Tensor] = None + # pose conditional input, will be concat with the input tensor + condition_video_pose: Optional[torch.Tensor] = None + + +@dataclass +class ViewConditionedVideoExtendCondition(VideoExtendCondition): + # view index indicating camera, used to index nn.Embedding + view_indices_B_T: Optional[torch.Tensor] = None + + +class GeneralConditioner(nn.Module, ABC): + """ + An abstract module designed to handle various embedding models with conditional and + unconditional configurations. This abstract base class initializes and manages a collection + of embedders that can dynamically adjust their dropout rates based on conditioning. + + Attributes: + KEY2DIM (dict): A mapping from output keys to dimensions used for concatenation. + embedders (nn.ModuleDict): A dictionary containing all embedded models initialized and + configured based on the provided configurations. + + Parameters: + emb_models (Union[List, Any]): A dictionary where keys are embedder names and values + are configurations for initializing the embedders. + + """ + + KEY2DIM = {"crossattn_emb": 1, "crossattn_mask": 1} + + def __init__(self, **emb_models: Union[List, Any]): + super().__init__() + self.embedders = nn.ModuleDict() + for n, (emb_name, embconfig) in enumerate(emb_models.items()): + embedder = instantiate(embconfig.obj) + assert isinstance( + embedder, BaseConditionEntry + ), f"embedder model {embedder.__class__.__name__} has to inherit from BaseConditionEntry" + embedder.dropout_rate = getattr(embconfig, "dropout_rate", 0.0) + + if hasattr(embconfig, "input_key"): + embedder.input_key = embconfig.input_key + elif hasattr(embconfig, "input_keys"): + embedder.input_keys = embconfig.input_keys + else: + raise KeyError(f"need either 'input_key' or 'input_keys' for embedder {embedder.__class__.__name__}") + + log.debug(f"Initialized embedder #{n}-{emb_name}: \n {embedder.summary()}") + self.embedders[emb_name] = embedder + + @abstractmethod + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> Any: + """Should be implemented in subclasses to handle conditon datatype""" + raise NotImplementedError + + def _forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> Dict: + """ + Processes the input batch through all configured embedders, applying conditional dropout rates if specified. + Output tensors for each key are concatenated along the dimensions specified in KEY2DIM. + + Parameters: + batch (Dict): The input data batch to process. + override_dropout_rate (Optional[Dict[str, float]]): Optional dictionary to override default dropout rates + per embedder key. + + Returns: + Dict: A dictionary of output tensors concatenated by specified dimensions. + + Note: + In case the network code is sensitive to the order of concatenation, you can either control the order via \ + config file or make sure the embedders return a unique key for each output. + """ + output = defaultdict(list) + if override_dropout_rate is None: + override_dropout_rate = {} + + # make sure emb_name in override_dropout_rate is valid + for emb_name in override_dropout_rate.keys(): + assert emb_name in self.embedders, f"invalid name found {emb_name}" + + for emb_name, embedder in self.embedders.items(): + with torch.no_grad(): + if hasattr(embedder, "input_key") and (embedder.input_key is not None): + emb_out = embedder( + embedder.random_dropout_input( + batch[embedder.input_key], override_dropout_rate.get(emb_name, None) + ) + ) + elif hasattr(embedder, "input_keys"): + emb_out = embedder( + *[ + embedder.random_dropout_input(batch[k], override_dropout_rate.get(emb_name, None), k) + for k in embedder.input_keys + ] + ) + for k, v in emb_out.items(): + output[k].append(v) + # Concatenate the outputs + return {k: torch.cat(v, dim=self.KEY2DIM.get(k, -1)) for k, v in output.items()} + + def get_condition_uncondition( + self, + data_batch: Dict, + ) -> Tuple[Any, Any]: + """ + Processes the provided data batch to generate conditioned and unconditioned outputs. + + This method manipulates dropout rates to simulate two scenarios: + 1. All conditions applied (conditioned) + 2. Conditions removed/reduced to minimum (unconditioned) + + This method sets dropout rates to zero for the conditioned scenario to fully apply + embedders' effects. For unconditioned, it sets rates to 1 (or 0 if initial rate is + insignificant) to minimize embedder influences. + + Parameters: + data_batch (Dict): Input data batch containing all necessary information for + embedding processing. + + Returns: + Tuple[Any, Any]: A tuple containing: + - Outputs with all embedders fully applied (conditioned) + - Outputs with embedders minimized/not applied (unconditioned) + """ + cond_dropout_rates, dropout_rates = {}, {} + for emb_name, embedder in self.embedders.items(): + cond_dropout_rates[emb_name] = 0.0 + dropout_rates[emb_name] = 1.0 if embedder.dropout_rate > 1e-4 else 0.0 + + condition: Any = self(data_batch, override_dropout_rate=cond_dropout_rates) + un_condition: Any = self(data_batch, override_dropout_rate=dropout_rates) + return condition, un_condition + + def get_condition_with_negative_prompt( + self, + data_batch: Dict, + ) -> Tuple[Any, Any]: + """ + Similar functionality as get_condition_uncondition + But use negative prompts for unconditon + """ + cond_dropout_rates, uncond_dropout_rates = {}, {} + for emb_name, embedder in self.embedders.items(): + cond_dropout_rates[emb_name] = 0.0 + if isinstance(embedder, TextAttr): + uncond_dropout_rates[emb_name] = 0.0 + else: + uncond_dropout_rates[emb_name] = 1.0 if embedder.dropout_rate > 1e-4 else 0.0 + + data_batch_neg_prompt = copy.deepcopy(data_batch) + if "neg_t5_text_embeddings" in data_batch_neg_prompt: + if isinstance(data_batch_neg_prompt["neg_t5_text_embeddings"], torch.Tensor): + data_batch_neg_prompt["t5_text_embeddings"] = data_batch_neg_prompt["neg_t5_text_embeddings"] + data_batch_neg_prompt["t5_text_mask"] = data_batch_neg_prompt["neg_t5_text_mask"] + + condition: Any = self(data_batch, override_dropout_rate=cond_dropout_rates) + un_condition: Any = self(data_batch_neg_prompt, override_dropout_rate=uncond_dropout_rates) + + return condition, un_condition + + +@dataclass +class CosmosCondition: + crossattn_emb: torch.Tensor + crossattn_mask: torch.Tensor + padding_mask: Optional[torch.Tensor] = None + scalar_feature: Optional[torch.Tensor] = None + + def to_dict(self) -> Dict[str, Optional[torch.Tensor]]: + return {f.name: getattr(self, f.name) for f in fields(self)} + + +class VideoConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> BaseVideoCondition: + output = super()._forward(batch, override_dropout_rate) + return BaseVideoCondition(**output) + + +class VideoExtendConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> VideoExtendCondition: + output = super()._forward(batch, override_dropout_rate) + return VideoExtendCondition(**output) + + +class ViewConditionedVideoExtendConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> ViewConditionedVideoExtendCondition: + output = super()._forward(batch, override_dropout_rate) + return ViewConditionedVideoExtendCondition(**output) diff --git a/diffusion/config/__init__.py b/diffusion/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/diffusion/config/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/diffusion/config/base/__init__.py b/diffusion/config/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/diffusion/config/base/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/diffusion/config/base/conditioner.py b/diffusion/config/base/conditioner.py new file mode 100644 index 0000000000000000000000000000000000000000..f5392eda15b99d0151b55a6e52c660bc80db0b81 --- /dev/null +++ b/diffusion/config/base/conditioner.py @@ -0,0 +1,261 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Dict, List, Optional + +import attrs +import torch + +from diffusion.conditioner import ( + BaseConditionEntry, + TextAttr, + VideoConditioner, + VideoExtendConditioner, + ViewConditionedVideoExtendConditioner, +) +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +@attrs.define(slots=False) +class TextConfig: + obj: LazyDict = L(TextAttr)() # No arguments + dropout_rate: float = 0.2 + input_keys: List[str] = attrs.field(factory=lambda: ["t5_text_embeddings", "t5_text_mask"]) + + +class BooleanFlag(BaseConditionEntry): + def __init__(self, output_key: Optional[str] = None): + super().__init__() + self.output_key = output_key + + def forward(self, *args, **kwargs) -> Dict[str, torch.Tensor]: + del args, kwargs + key = self.output_key if self.output_key else self.input_key + return {key: self.flag} + + def random_dropout_input( + self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None + ) -> torch.Tensor: + del key + dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate + self.flag = torch.bernoulli((1.0 - dropout_rate) * torch.ones(1)).bool().to(device=in_tensor.device) + return in_tensor + + +class ReMapkey(BaseConditionEntry): + def __init__(self, output_key: Optional[str] = None, dtype: Optional[str] = None): + super().__init__() + self.output_key = output_key + self.dtype = { + None: None, + "float": torch.float32, + "bfloat16": torch.bfloat16, + "half": torch.float16, + "float16": torch.float16, + "int": torch.int32, + "long": torch.int64, + }[dtype] + + def forward(self, element: torch.Tensor) -> Dict[str, torch.Tensor]: + key = self.output_key if self.output_key else self.input_key + if isinstance(element, torch.Tensor): + element = element.to(dtype=self.dtype) + return {key: element} + + +class FrameRepeatAttr(BaseConditionEntry): + def __init__(self): + super().__init__() + + def forward(self, frame_repeat: torch.Tensor) -> Dict[str, torch.Tensor]: + return { + "frame_repeat": frame_repeat / 10.0, + } + + +@attrs.define(slots=False) +class FPSConfig: + """ + Remap the key from the input dictionary to the output dictionary. For `fps`. + """ + + obj: LazyDict = L(ReMapkey)(output_key="fps", dtype=None) + dropout_rate: float = 0.0 + input_key: str = "fps" + + +@attrs.define(slots=False) +class PaddingMaskConfig: + """ + Remap the key from the input dictionary to the output dictionary. For `padding_mask`. + """ + + obj: LazyDict = L(ReMapkey)(output_key="padding_mask", dtype=None) + dropout_rate: float = 0.0 + input_key: str = "padding_mask" + + +@attrs.define(slots=False) +class ImageSizeConfig: + """ + Remap the key from the input dictionary to the output dictionary. For `image_size`. + """ + + obj: LazyDict = L(ReMapkey)(output_key="image_size", dtype=None) + dropout_rate: float = 0.0 + input_key: str = "image_size" + + +@attrs.define(slots=False) +class NumFramesConfig: + """ + Remap the key from the input dictionary to the output dictionary. For `num_frames`. + """ + + obj: LazyDict = L(ReMapkey)(output_key="num_frames", dtype=None) + dropout_rate: float = 0.0 + input_key: str = "num_frames" + + +@attrs.define(slots=False) +class FrameRepeatConfig: + """ + Remap and process key from the input dictionary to the output dictionary. For `frame_repeat`. + """ + + obj: LazyDict = L(FrameRepeatAttr)() + dropout_rate: float = 0.0 + input_key: str = "frame_repeat" + + +@attrs.define(slots=False) +class VideoCondBoolConfig: + obj: LazyDict = L(BooleanFlag)(output_key="video_cond_bool") + dropout_rate: float = 0.2 + input_key: str = "fps" # This is a placeholder, we never use this value + # Config below are for long video generation only + compute_loss_for_condition_region: bool = False # Compute loss for condition region + + # How to sample condition region during training. "first_random_n" set the first n frames to be condition region, n is random, "random" set the condition region to be random, + condition_location: str = "first_random_n" + random_conditon_rate: float = 0.5 # The rate to sample the condition region randomly + first_random_n_num_condition_t_max: int = 4 # The maximum number of frames to sample as condition region, used when condition_location is "first_random_n" + first_random_n_num_condition_t_min: int = 0 # The minimum number of frames to sample as condition region, used when condition_location is "first_random_n" + + # How to dropout value of the conditional input frames + cfg_unconditional_type: str = "zero_condition_region_condition_mask" # Unconditional type. "zero_condition_region_condition_mask" set the input to zero for condition region, "noise_x_condition_region" set the input to x_t, same as the base model + + # How to corrupt the condition region + apply_corruption_to_condition_region: str = "noise_with_sigma" # Apply corruption to condition region, option: "gaussian_blur", "noise_with_sigma", "clean" (inference), "noise_with_sigma_fixed" (inference) + # Inference only option: list of sigma value for the corruption at different chunk id, used when apply_corruption_to_condition_region is "noise_with_sigma" or "noise_with_sigma_fixed" + apply_corruption_to_condition_region_sigma_value: list[float] = [0.001, 0.2] + [ + 0.5 + ] * 10 # Sigma value for the corruption, used when apply_corruption_to_condition_region is "noise_with_sigma_fixed" + + # Add augment_sigma condition to the network + condition_on_augment_sigma: bool = False + # The following arguments is to match with previous implementation where we use train sde to sample augment sigma (with adjust video noise turn on) + augment_sigma_sample_p_mean: float = 0.0 # Mean of the augment sigma + augment_sigma_sample_p_std: float = 1.0 # Std of the augment sigma + augment_sigma_sample_multiplier: float = 4.0 # Multipler of augment sigma + + # Add pose condition to the network + add_pose_condition: bool = False + + # Sample PPP... from IPPP... sequence + sample_tokens_start_from_p_or_i: bool = False + + # Normalize the input condition latent + normalize_condition_latent: bool = False + + +@attrs.define(slots=False) +class MVVideoCondBoolConfig(VideoCondBoolConfig): + n_cond_view_max: int = 1 # The max number of camera views as condition region + n_cond_view_min: int = 1 # The min number of camera views as condition region + + +@attrs.define(slots=False) +class LatentConditionConfig: + """ + Remap the key from the input dictionary to the output dictionary. For `latent condition`. + """ + + obj: LazyDict = L(ReMapkey)(output_key="latent_condition", dtype=None) + dropout_rate: float = 0.0 + input_key: str = "latent_condition" + + +@attrs.define(slots=False) +class LatentConditionSigmaConfig: + """ + Remap the key from the input dictionary to the output dictionary. For `latent condition`. + """ + + obj: LazyDict = L(ReMapkey)(output_key="latent_condition_sigma", dtype=None) + dropout_rate: float = 0.0 + input_key: str = "latent_condition_sigma" + + +BaseVideoConditionerConfig: LazyDict = L(VideoConditioner)( + text=TextConfig(), +) + +VideoConditionerFpsSizePaddingConfig: LazyDict = L(VideoConditioner)( + text=TextConfig(), + fps=FPSConfig(), + num_frames=NumFramesConfig(), + image_size=ImageSizeConfig(), + padding_mask=PaddingMaskConfig(), +) + +VideoExtendConditionerConfig: LazyDict = L(VideoExtendConditioner)( + text=TextConfig(), + fps=FPSConfig(), + num_frames=NumFramesConfig(), + image_size=ImageSizeConfig(), + padding_mask=PaddingMaskConfig(), + video_cond_bool=VideoCondBoolConfig(), +) + +VideoConditionerFpsSizePaddingFrameRepeatConfig: LazyDict = L(VideoConditioner)( + text=TextConfig(), + fps=FPSConfig(), + num_frames=NumFramesConfig(), + image_size=ImageSizeConfig(), + padding_mask=PaddingMaskConfig(), + frame_repeat=FrameRepeatConfig(), +) + +VideoExtendConditionerFrameRepeatConfig: LazyDict = L(VideoExtendConditioner)( + text=TextConfig(), + fps=FPSConfig(), + num_frames=NumFramesConfig(), + image_size=ImageSizeConfig(), + padding_mask=PaddingMaskConfig(), + video_cond_bool=VideoCondBoolConfig(), + frame_repeat=FrameRepeatConfig(), +) + +ViewConditionedVideoExtendConditionerFrameRepeatConfig: LazyDict = L(ViewConditionedVideoExtendConditioner)( + text=TextConfig(), + fps=FPSConfig(), + num_frames=NumFramesConfig(), + image_size=ImageSizeConfig(), + padding_mask=PaddingMaskConfig(), + video_cond_bool=MVVideoCondBoolConfig(), + frame_repeat=FrameRepeatConfig(), +) diff --git a/diffusion/functional/batch_ops.py b/diffusion/functional/batch_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a72b24097f7cc9e7e6a8b324919455131bf84d47 --- /dev/null +++ b/diffusion/functional/batch_ops.py @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Functions for performing operations with broadcasting to the right axis +# +# Example +# input1: tensor of size (N1, N2) +# input2: tensor of size (N1, N2, N3, N4) +# batch_mul(input1, input2) = input1[:, :, None, None] * input2 +# +# If the common dimensions don't match, we raise an assertion error. + +from torch import Tensor + + +def common_broadcast(x: Tensor, y: Tensor) -> tuple[Tensor, Tensor]: + ndims1 = x.ndim + ndims2 = y.ndim + + common_ndims = min(ndims1, ndims2) + for axis in range(common_ndims): + assert x.shape[axis] == y.shape[axis], "Dimensions not equal at axis {}".format(axis) + + if ndims1 < ndims2: + x = x.reshape(x.shape + (1,) * (ndims2 - ndims1)) + elif ndims2 < ndims1: + y = y.reshape(y.shape + (1,) * (ndims1 - ndims2)) + + return x, y + + +def batch_add(x: Tensor, y: Tensor) -> Tensor: + x, y = common_broadcast(x, y) + return x + y + + +def batch_mul(x: Tensor, y: Tensor) -> Tensor: + x, y = common_broadcast(x, y) + return x * y + + +def batch_sub(x: Tensor, y: Tensor) -> Tensor: + x, y = common_broadcast(x, y) + return x - y + + +def batch_div(x: Tensor, y: Tensor) -> Tensor: + x, y = common_broadcast(x, y) + return x / y diff --git a/diffusion/functional/multi_step.py b/diffusion/functional/multi_step.py new file mode 100644 index 0000000000000000000000000000000000000000..a3aed694a5fc15fc2341bf95e3efff93ff551187 --- /dev/null +++ b/diffusion/functional/multi_step.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Impl of multistep methods to solve the ODE in the diffusion model. +""" + +from typing import Callable, List, Tuple + +import torch + +from diffusion.functional.runge_kutta import reg_x0_euler_step, res_x0_rk2_step + + +def order2_fn( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_s: torch.Tensor, x0_preds: torch.Tensor +) -> Tuple[torch.Tensor, List[torch.Tensor]]: + """ + impl the second order multistep method in https://arxiv.org/pdf/2308.02157 + Adams Bashforth approach! + """ + if x0_preds: + x0_s1, s1 = x0_preds[0] + x_t = res_x0_rk2_step(x_s, t, s, x0_s, s1, x0_s1) + else: + x_t = reg_x0_euler_step(x_s, s, t, x0_s)[0] + return x_t, [(x0_s, s)] + + +# key: method name, value: method function +# key: order + algorithm name +MULTISTEP_FNs = { + "2ab": order2_fn, +} + + +def get_multi_step_fn(name: str) -> Callable: + if name in MULTISTEP_FNs: + return MULTISTEP_FNs[name] + methods = "\n\t".join(MULTISTEP_FNs.keys()) + raise RuntimeError("Only support multistep method\n" + methods) + + +def is_multi_step_fn_supported(name: str) -> bool: + """ + Check if the multistep method is supported. + """ + return name in MULTISTEP_FNs diff --git a/diffusion/functional/runge_kutta.py b/diffusion/functional/runge_kutta.py new file mode 100644 index 0000000000000000000000000000000000000000..4764c17e0b5b4a7516786ae16a259cf08ef6a1d4 --- /dev/null +++ b/diffusion/functional/runge_kutta.py @@ -0,0 +1,333 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Callable, Tuple + +import torch + +from diffusion.functional.batch_ops import batch_mul + + +def phi1(t: torch.Tensor) -> torch.Tensor: + """ + Compute the first order phi function: (exp(t) - 1) / t. + + Args: + t: Input tensor. + + Returns: + Tensor: Result of phi1 function. + """ + input_dtype = t.dtype + t = t.to(dtype=torch.float64) + return (torch.expm1(t) / t).to(dtype=input_dtype) + + +def phi2(t: torch.Tensor) -> torch.Tensor: + """ + Compute the second order phi function: (phi1(t) - 1) / t. + + Args: + t: Input tensor. + + Returns: + Tensor: Result of phi2 function. + """ + input_dtype = t.dtype + t = t.to(dtype=torch.float64) + return ((phi1(t) - 1.0) / t).to(dtype=input_dtype) + + +def res_x0_rk2_step( + x_s: torch.Tensor, + t: torch.Tensor, + s: torch.Tensor, + x0_s: torch.Tensor, + s1: torch.Tensor, + x0_s1: torch.Tensor, +) -> torch.Tensor: + """ + Perform a residual-based 2nd order Runge-Kutta step. + + Args: + x_s: Current state tensor. + t: Target time tensor. + s: Current time tensor. + x0_s: Prediction at current time. + s1: Intermediate time tensor. + x0_s1: Prediction at intermediate time. + + Returns: + Tensor: Updated state tensor. + + Raises: + AssertionError: If step size is too small. + """ + s = -torch.log(s) + t = -torch.log(t) + m = -torch.log(s1) + + dt = t - s + assert not torch.any(torch.isclose(dt, torch.zeros_like(dt), atol=1e-6)), "Step size is too small" + assert not torch.any(torch.isclose(m - s, torch.zeros_like(dt), atol=1e-6)), "Step size is too small" + + c2 = (m - s) / dt + phi1_val, phi2_val = phi1(-dt), phi2(-dt) + + # Handle edge case where t = s = m + b1 = torch.nan_to_num(phi1_val - 1.0 / c2 * phi2_val, nan=0.0) + b2 = torch.nan_to_num(1.0 / c2 * phi2_val, nan=0.0) + + return batch_mul(torch.exp(-dt), x_s) + batch_mul(dt, batch_mul(b1, x0_s) + batch_mul(b2, x0_s1)) + + +def reg_x0_euler_step( + x_s: torch.Tensor, + s: torch.Tensor, + t: torch.Tensor, + x0_s: torch.Tensor, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a regularized Euler step based on x0 prediction. + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_s: Prediction at current time. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and current prediction. + """ + coef_x0 = (s - t) / s + coef_xs = t / s + return batch_mul(coef_x0, x0_s) + batch_mul(coef_xs, x_s), x0_s + + +def reg_eps_euler_step( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, eps_s: torch.Tensor +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a regularized Euler step based on epsilon prediction. + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + eps_s: Epsilon prediction at current time. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and current x0 prediction. + """ + return x_s + batch_mul(eps_s, t - s), x_s + batch_mul(eps_s, 0 - s) + + +def rk1_euler( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a first-order Runge-Kutta (Euler) step. + + Recommended for diffusion models with guidance or model undertrained + Usually more stable at the cost of a bit slower convergence. + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_fn: Function to compute x0 prediction. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and x0 prediction. + """ + x0_s = x0_fn(x_s, s) + return reg_x0_euler_step(x_s, s, t, x0_s) + + +def rk2_mid_stable( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a stable second-order Runge-Kutta (midpoint) step. + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_fn: Function to compute x0 prediction. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and x0 prediction. + """ + s1 = torch.sqrt(s * t) + x_s1, _ = rk1_euler(x_s, s, s1, x0_fn) + + x0_s1 = x0_fn(x_s1, s1) + return reg_x0_euler_step(x_s, s, t, x0_s1) + + +def rk2_mid(x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a second-order Runge-Kutta (midpoint) step. + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_fn: Function to compute x0 prediction. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and x0 prediction. + """ + s1 = torch.sqrt(s * t) + x_s1, x0_s = rk1_euler(x_s, s, s1, x0_fn) + + x0_s1 = x0_fn(x_s1, s1) + + return res_x0_rk2_step(x_s, t, s, x0_s, s1, x0_s1), x0_s1 + + +def rk_2heun_naive( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a naive second-order Runge-Kutta (Heun's method) step. + Impl based on rho-rk-deis solvers, https://github.com/qsh-zh/deis + Recommended for diffusion models without guidance and relative large NFE + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_fn: Function to compute x0 prediction. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and current state. + """ + x_t, x0_s = rk1_euler(x_s, s, t, x0_fn) + eps_s = batch_mul(1.0 / s, x_t - x0_s) + x0_t = x0_fn(x_t, t) + eps_t = batch_mul(1.0 / t, x_t - x0_t) + + avg_eps = (eps_s + eps_t) / 2 + + return reg_eps_euler_step(x_s, s, t, avg_eps) + + +def rk_2heun_edm( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a naive second-order Runge-Kutta (Heun's method) step. + Impl based no EDM second order Heun method + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_fn: Function to compute x0 prediction. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and current state. + """ + x_t, x0_s = rk1_euler(x_s, s, t, x0_fn) + x0_t = x0_fn(x_t, t) + + avg_x0 = (x0_s + x0_t) / 2 + + return reg_x0_euler_step(x_s, s, t, avg_x0) + + +def rk_3kutta_naive( + x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Perform a naive third-order Runge-Kutta step. + Impl based on rho-rk-deis solvers, https://github.com/qsh-zh/deis + Recommended for diffusion models without guidance and relative large NFE + + Args: + x_s: Current state tensor. + s: Current time tensor. + t: Target time tensor. + x0_fn: Function to compute x0 prediction. + + Returns: + Tuple[Tensor, Tensor]: Updated state tensor and current state. + """ + c2, c3 = 0.5, 1.0 + a31, a32 = -1.0, 2.0 + b1, b2, b3 = 1.0 / 6, 4.0 / 6, 1.0 / 6 + + delta = t - s + + s1 = c2 * delta + s + s2 = c3 * delta + s + x_s1, x0_s = rk1_euler(x_s, s, s1, x0_fn) + eps_s = batch_mul(1.0 / s, x_s - x0_s) + x0_s1 = x0_fn(x_s1, s1) + eps_s1 = batch_mul(1.0 / s1, x_s1 - x0_s1) + + _eps = a31 * eps_s + a32 * eps_s1 + x_s2, _ = reg_eps_euler_step(x_s, s, s2, _eps) + + x0_s2 = x0_fn(x_s2, s2) + eps_s2 = batch_mul(1.0 / s2, x_s2 - x0_s2) + + avg_eps = b1 * eps_s + b2 * eps_s1 + b3 * eps_s2 + return reg_eps_euler_step(x_s, s, t, avg_eps) + + +# key : order + name +RK_FNs = { + "1euler": rk1_euler, + "2mid": rk2_mid, + "2mid_stable": rk2_mid_stable, + "2heun_edm": rk_2heun_edm, + "2heun_naive": rk_2heun_naive, + "3kutta_naive": rk_3kutta_naive, +} + + +def get_runge_kutta_fn(name: str) -> Callable: + """ + Get the specified Runge-Kutta function. + + Args: + name: Name of the Runge-Kutta method. + + Returns: + Callable: The specified Runge-Kutta function. + + Raises: + RuntimeError: If the specified method is not supported. + """ + if name in RK_FNs: + return RK_FNs[name] + methods = "\n\t".join(RK_FNs.keys()) + raise RuntimeError(f"Only support the following Runge-Kutta methods:\n\t{methods}") + + +def is_runge_kutta_fn_supported(name: str) -> bool: + """ + Check if the specified Runge-Kutta function is supported. + + Args: + name: Name of the Runge-Kutta method. + + Returns: + bool: True if the method is supported, False otherwise. + """ + return name in RK_FNs diff --git a/diffusion/inference/__init__.py b/diffusion/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..527febe5bf36c9e3ff72fda40d5818a8b155183f --- /dev/null +++ b/diffusion/inference/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""HDMap-conditioned LiDAR inference.""" diff --git a/diffusion/inference/causal.py b/diffusion/inference/causal.py new file mode 100644 index 0000000000000000000000000000000000000000..753d4ed0b6a4ba4588d2f6fe5f7a1f9323953e28 --- /dev/null +++ b/diffusion/inference/causal.py @@ -0,0 +1,162 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Causal P1B4 sampling with clean K/V commits and streaming spatial memory.""" + +import torch +from tqdm import tqdm + +from diffusion.inference.hdmap import _metric_ranges +from diffusion.inference.pai import SPATIAL_CACHE, make_batch, mode_spec +from diffusion.training.datasets.lidar_dataset.forecast_warp import TorchSpatialPointMap +from utils import misc + + +def _spatial_map(model, batch): + rays, elev, azim, row_off = model._stage2_spatial_map_geometry(batch["video"]) + policy = {key: getattr(model.config, f"blockwise_spatial_map_{key}") for key in SPATIAL_CACHE} + policy["voxel_size_m"] = policy.pop("voxel_m") + return TorchSpatialPointMap( + ray_dirs=rays, row_elevations_rad=elev, column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, device=rays.device, + min_range=2.5, max_range=100, min_value=-1, inverse_depth=False, + **policy, + ) + + +def _commit(model, latent, condition): + model._current_sfdmd_store_self_attn_kv = True + try: + velocity = model._rf_network_forward( + latent.to(**model.tensor_kwargs), + torch.zeros((1, latent.shape[2]), device=latent.device), condition, + ) + if not torch.isfinite(velocity).all(): + raise FloatingPointError("Clean K/V commit produced non-finite values") + finally: + model._current_sfdmd_store_self_attn_kv = False + + +def generate(model, sample, mode, args, seed, console): + spec = mode_spec(mode, args.stage) + length = spec["input_frames"] + spec["output_frames"] + # Complete P1+4N blocks using the extra supplied pose, then crop for display. + padded_length = 1 + ((length - 1 + 3) // 4) * 4 + batch = make_batch(sample, mode, args.stage, length=padded_length) + video = batch["video"] + known = torch.arange(padded_length, device=video.device) < spec["input_frames"] + torch.manual_seed(seed) + model._current_stage2_data_batch = batch + model._current_stage2_geometry_source_mask = known + model._current_sensor_dataset_ids = batch["sensor_dataset_id"] + model._current_stage2_geometry_mode = "frozen_object" if mode == "resim" else "rolling_static" + model.factorized_static_only_geometry = False + model._hdmap_force_zero_latent = spec["hdmap"] == "null" + model._current_sfdmd_self_attn_kv_cache = model.new_teacher_forcing_kv_cache() + model._current_sfdmd_self_attn_kv_max_frames = args.kv_cache_frames + model._current_sfdmd_self_attn_kv_sink_frames = 1 + model._current_sfdmd_store_self_attn_kv = False + model._current_sfdmd_detach_self_attn_kv = True + model._current_sfdmd_return_self_attn_kv = False + + blocks = [(0, 1)] + [(start, start + 4) for start in range(1, padded_length, 4)] + spatial_map = _spatial_map(model, batch) if mode != "resim" else None + frozen = None + if mode == "resim": + # The training builder reads points only from the observed prefix. + # Target actor poses place the observed canonical object clouds. + frozen, _, _ = model._build_torch_spatial_map_history(video, batch["lidar_to_world"]) + elif mode == "forecast": + # Prefill all supplied observations, then append only newly generated sweeps. + for start, end in blocks: + end = min(end, spec["input_frames"]) + if start >= end: + break + spatial_map.append_token_block( + video[0, :, start:end], batch["lidar_to_world"][0, start:end], start, + input_has_prepend=False, + token_pose_sensor_start_end=batch["pose_sensor_start_end"][0, start:end], + ) + observed = torch.zeros((1, 64, padded_length, 16, 128), device=video.device) + observed_cache = None + for t in range(spec["input_frames"]): + latent, observed_cache = model.encode_stream( + video[:, :, t:t + 1].float(), temporal_kv_cache=observed_cache, max_cache_frames=9, + ) + if not torch.isfinite(latent).all(): + raise FloatingPointError(f"Non-finite observed latent at frame {t}") + observed[:, :, t:t + 1] = latent.float() + del observed_cache + + condition_cache = decoder_cache = None + decoded_blocks = [] + try: + for block_index, (start, end) in enumerate(tqdm( + blocks, desc=f"{mode} causal sampling", unit="block", file=console, + leave=False, disable=not console.isatty(), + )): + poses = batch["lidar_to_world"][0, start:end] + motion = batch["pose_sensor_start_end"][0, start:end] + if spatial_map is not None: + geometry, _ = spatial_map.render(poses, target_pose_sensor_start_end=motion) + geometry = geometry[None] + else: + geometry = frozen[:, :, start:end] + active = dict(batch) + active.update( + video=torch.full_like(video[:, :, start:end], -1), + lidar_hdmap=batch["lidar_hdmap"][:, :, start:end], + lidar_blockwise_warped_history=geometry, + num_frames=batch["num_frames"].new_tensor([end - start]), + ) + model._current_sfdmd_temporal_positions = torch.arange(start, end, device=video.device) + model._current_stage2_known_frame_mask = known[start:end] + with torch.autocast("cuda", dtype=torch.bfloat16): + condition, condition_cache = model.get_online_condition_stream( + active, temporal_kv_cache=condition_cache, max_cache_frames=9, + ) + block_known = known[start:end] + known_latents = observed[:, :, start:end] + if bool(block_known.all()): + sampled = known_latents + else: + noise = misc.arch_invariant_rand( + (1, 64, end - start, 16, 128), torch.float32, "cuda", seed + block_index, + ) + sampled = model._generate_sde( + latents=noise, condition=condition, uncondition=None, + guidance=1.0, use_cfg=False, B=1, num_steps=args.num_steps, + shift=5, seed=seed + block_index, sde_eta=args.sde_eta, + known_latents=known_latents if bool(block_known.any()) else None, + known_mask=block_known if bool(block_known.any()) else None, + known_latents_mode="clean_mask", + ) + if not torch.isfinite(sampled).all(): + raise FloatingPointError(f"Non-finite latents in block {block_index}") + if bool(block_known.any()) and not torch.equal( + sampled[:, :, block_known].float(), known_latents[:, :, block_known].float(), + ): + raise RuntimeError(f"Clean-prefix replacement failed in block {block_index}") + # Commit once after denoising, synchronously, before the next block. + _commit(model, sampled, condition) + decoded, decoder_cache = model.decode_stream( + sampled.float(), temporal_kv_cache=decoder_cache, max_cache_frames=30, + ) + if decoded.shape != video[:, :, start:end].shape or not torch.isfinite(decoded).all(): + raise RuntimeError(f"Invalid decoded LiDAR in block {block_index}") + decoded = torch.where(block_known[None, None, :, None, None], video[:, :, start:end], decoded) + decoded_blocks.append(decoded) + new_start = max(start, spec["input_frames"]) + if spatial_map is not None and new_start < end: + # No current-block or future GT points can enter its own condition. + offset = new_start - start + spatial_map.append_token_block( + decoded[0, :, offset:], poses[offset:], new_start, input_has_prepend=False, + token_pose_sensor_start_end=motion[offset:], + ) + finally: + model._current_sfdmd_temporal_positions = None + model._current_sfdmd_self_attn_kv_cache = None + model._current_sfdmd_store_self_attn_kv = False + model._current_stage2_data_batch = None + return _metric_ranges(torch.cat(decoded_blocks, dim=2)[:, :, :length]) diff --git a/diffusion/inference/hdmap.py b/diffusion/inference/hdmap.py new file mode 100644 index 0000000000000000000000000000000000000000..60492c3edb7e5a0a97d09915eb52a4d48455594d --- /dev/null +++ b/diffusion/inference/hdmap.py @@ -0,0 +1,305 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""HDMap-only diffusion loading, sampling, and output for native sensor grids.""" + +from __future__ import annotations + +import json +import os +import time +from collections import Counter +from copy import deepcopy +from datetime import timedelta +from pathlib import Path + +import numpy as np +import torch +from tqdm import tqdm + +from utils import inference as common +from utils.lidar_rangemap import unnormalize_and_reduce_channels + + +# Dataset-ID order is a checkpoint contract, not inferred from grid dimensions. +SENSORS = { + 0: ("pandar", 128, 1024, 10.0), + 1: ("pandaset", 64, 1024, 10.0), + 2: ("nuscenes", 32, 1024, 20.0), +} + + +def resolve_checkpoint(path: Path) -> Path: + if path.is_file(): + return path.resolve() + folder = path / "checkpoints" if (path / "checkpoints").is_dir() else path + marker = folder / "latest_checkpoint.txt" + stem = marker.read_text().strip().removesuffix(".pt") + if not stem.startswith("iter_") or not stem[5:].isdigit(): + raise ValueError(f"Invalid checkpoint marker in {marker}: {stem!r}") + source = folder / f"{stem}_ema_model.pt" + if not source.is_file() or source.stat().st_size == 0: + raise FileNotFoundError(f"No complete EMA checkpoint: {source}") + # Match the research launcher: pin the EMA before training retention unlinks it. + snapshot_dir = folder.parent / "eval_snapshots" + snapshot_dir.mkdir(parents=True, exist_ok=True) + snapshot = snapshot_dir / source.name + try: + os.link(source, snapshot) + except FileExistsError: + pass + return snapshot.resolve() + + +def load_model(checkpoint: Path, tokenizer_checkpoint: Path, latent_stats: Path): + from diffusion.training.config.base.lidarverse_vae import get_lidarverse_tokenizer + from diffusion.training.config.base.model import LidarModelConfig + from diffusion.training.config.text2world.registry import ( + MININET_2B_Config, VideoConditionerFpsSizePaddingConfig, + ) + from diffusion.training.models.hdmaptolidar_model_rf import HdmapToLidarRectifiedFlowModel + from utils.lazy_config import LazyDict + + net = deepcopy(MININET_2B_Config) + net.update( + in_channels=128, out_channels=64, patch_spatial=(1, 1), + rope_scale_positions_by_patch=True, num_dataset_embeddings=3, + timestep_scale=0.001, rope_h_extrapolation_ratio=3.0, + rope_w_extrapolation_ratio=3.0, rope_t_extrapolation_ratio=1.0, + rope_enable_fps_modulation=False, use_wan_fp32_strategy=True, + ) + net.sac_config.mode = "none" + vae = get_lidarverse_tokenizer() + vae.update(checkpoint_path=str(tokenizer_checkpoint), mean_std_fp=str(latent_stats), + strict_checkpoint=True, use_ema=False) + # No training experiment registration, dataloaders, FSDP, or extra EMA model. + config = LidarModelConfig( + net=net, vae=vae, conditioner=deepcopy(VideoConditionerFpsSizePaddingConfig), + ema=LazyDict(dict(enabled=False)), latent_shape=[64, 21, 16, 128], + hdmap_channels=3, additional_concat_ch=64, encode_hdmap_with_vae=True, + hdmap_dropout_prob=0.1, sigma_data=1.0, shift=5, + shift_clamp_percentiles=(0.5, 99.9), rf_prediction_type="velocity", + loss_reduce="mean", input_video_has_prepend=True, + ) + model = HdmapToLidarRectifiedFlowModel(config) + model.model.to(dtype=torch.bfloat16) + # Local/trusted PyTorch checkpoints only. Load strictly: never adapt a head. + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + state = payload.get("model", payload) + if isinstance(payload.get("ema"), dict): + state = payload["ema"] + model.model.load_state_dict(state, strict=True) + del state, payload + model.cuda().eval() + model.vae.float() + print(f"Loaded all diffusion weights strictly: {checkpoint}", flush=True) + return model + + +def load_hdmap_sample(path: Path, num_frames: int) -> dict: + with np.load(path, allow_pickle=False) as payload: + sample = {key: payload[key] for key in payload.files} + for key in ("hdmap", "ray_directions", "sensor_dataset_id", "fps"): + if key not in sample: + raise ValueError(f"{path}: missing {key}; tokenizer-only NPZs have no HDMap condition") + dataset_id = int(sample["sensor_dataset_id"]) + if dataset_id not in SENSORS: + raise ValueError(f"{path}: unknown sensor_dataset_id {dataset_id}") + sensor, height, width, fps = SENSORS[dataset_id] + hdmap = np.asarray(sample["hdmap"], dtype=np.float32) + if hdmap.shape != (num_frames, height, width): + raise ValueError(f"{path}: expected {num_frames} real {height}x{width} HDMap frames; got {hdmap.shape}") + if bool(sample.get("has_prepend", False)): + raise ValueError(f"{path}: store only real frames, not the duplicated VAE prefix") + if str(sample.get("dataset", sensor)) != sensor or float(sample["fps"]) != fps: + raise ValueError(f"{path}: sensor name/FPS does not match dataset ID {dataset_id}") + if float(sample.get("min_range_m", 2.5)) != 2.5 or float(sample.get("max_range_m", 100.0)) != 100.0: + raise ValueError(f"{path}: this checkpoint uses 2.5--100 m") + if not np.isfinite(hdmap).all() or hdmap.min() < -1 or hdmap.max() > 1: + raise ValueError(f"{path}: hdmap must be normalized to [-1,1], invalid cells=-1") + rays = np.asarray(sample["ray_directions"], dtype=np.float32) + if rays.shape not in ((height, width, 3), (num_frames, height, width, 3)): + raise ValueError(f"{path}: rays do not match the native HDMap grid: {rays.shape}") + if not np.isfinite(rays).all() or not np.allclose(np.linalg.norm(rays, axis=-1), 1, atol=1e-4): + raise ValueError(f"{path}: ray_directions must be finite unit vectors") + sample.update(hdmap=hdmap, ray_directions=rays, dataset=sensor, + visualization_yaw_deg=common.display_yaw(path, sensor)) + return sample + + +def _metric_ranges(video): + # Same validity cutoff (including near/far buffers) as the working launcher. + ranges, valid = unnormalize_and_reduce_channels( + video, max_range=100.0, min_range=2.5, min_value=-1.0, + inverse_depth=False, process_output="mono", + ) + return ranges[0].float().cpu().numpy(), valid[0].cpu().numpy() + + +def _preview_frames(sample, generated, valid, output): + hdmap, hd_valid = _metric_ranges(torch.from_numpy(sample["hdmap"])[None, None]) + rays = np.broadcast_to(sample["ray_directions"], hdmap.shape + (3,)) + for index in range(len(generated)): + panels = [] + clouds = [("hdmap", "HDMap", hdmap, hd_valid), + ("generation", "Generated", generated, valid)] + for name, title, values, mask in clouds: + points = common.points_from_ranges(values[index], mask[index], rays[index]) + common.write_ply(output / "ply" / f"{name}_{index:03d}.ply", points) + panels.append(common.label_image( + common.render_points(points, yaw_deg=sample["visualization_yaw_deg"]), + f"{sample['dataset']} | {title}", + )) + yield np.concatenate(panels, axis=1) + + +def _generate_sequence(model, sample, args, seed, console, label): + dataset_id = int(sample["sensor_dataset_id"]) + torch.cuda.synchronize() + phase_started = time.perf_counter() + # The diffusion path sees HDMap + null text, never GT. + video = torch.from_numpy(sample["hdmap"])[None, None].cuda() + video = torch.cat([video[:, :, :1], video], dim=2) + _, _, _, height, width = video.shape + batch = { + # The shared preparation API encodes a target to obtain its latent shape. + # Supply an empty target, never GT. Its latent is not a sampling condition. + "video": torch.full_like(video, -1), + "lidar_hdmap": video, + "is_preprocessed": True, + "sensor_dataset_id": torch.tensor([dataset_id], device="cuda", dtype=torch.long), + "fps": torch.tensor([float(sample["fps"])], device="cuda"), + "num_frames": torch.tensor([args.sample_n_frames], device="cuda"), + "image_size": torch.tensor([[height, width]], device="cuda"), + "padding_mask": torch.zeros(1, 1, height, width, device="cuda"), + "t5_text_embeddings": torch.zeros(1, 512, 1024, device="cuda"), + "t5_text_mask": torch.zeros(1, 512, device="cuda"), + } + batch["t5_text_mask"][:, 0] = 1 + # The VAE samples a Gaussian posterior even in eval mode. Seed preparation + # too, retaining the reference target-then-HDMap encode/RNG order. + torch.manual_seed(seed) + with torch.autocast("cuda", dtype=torch.bfloat16): + _, shape_latent, _ = model.get_data_and_condition(batch) + torch.cuda.synchronize() + encode_seconds = time.perf_counter() - phase_started + phase_started = time.perf_counter() + # Both supported samplers make one velocity query per step. Ordinary + # CFG makes two DiT forwards; CFG=0/1 makes one. The hook observes only + # completion and MUST return None so it cannot replace network outputs. + forwards_per_step = 1 if args.guidance in (0.0, 1.0) else 2 + forwards = 0 + with tqdm(total=args.num_steps, desc=f"{label} sampling", unit="step", + file=console, dynamic_ncols=True, leave=False, + disable=not console.isatty()) as progress: + def on_forward(_module, _inputs, _output): + nonlocal forwards + forwards += 1 + if forwards % forwards_per_step == 0: + progress.update(1) + + hook = model.net.register_forward_hook(on_forward) + try: + with torch.autocast("cuda", dtype=torch.bfloat16): + latent = model.generate_samples_from_batch( + batch, state_shape=shape_latent.shape[1:], n_sample=1, + guidance=args.guidance, seed=seed, num_steps=args.num_steps, + sampler=args.sampler, sde_eta=args.sde_eta, + ) + torch.cuda.synchronize() + finally: + hook.remove() + sampling_seconds = time.perf_counter() - phase_started + phase_started = time.perf_counter() + decoded = model.decode(latent.float()) + if decoded.shape != video.shape or not torch.isfinite(decoded).all(): + raise RuntimeError(f"Invalid decoded range video: {tuple(decoded.shape)}") + generated, valid = _metric_ranges(decoded[:, :, 1:]) + torch.cuda.synchronize() + decode_seconds = time.perf_counter() - phase_started + return generated, valid, { + "encode_seconds": encode_seconds, + "sampling_seconds": sampling_seconds, + "decode_seconds": decode_seconds, + } + + +@torch.inference_mode() +def run(args, console, say, started): + sample_root, output_root = args.sample_path.resolve(), args.output_folder + # Count selected clips without decompressing their range videos. Preserve + # the original file order and per-sensor seed/index convention. + samples, selected_counts = [], Counter() + for path in common.sample_paths(sample_root): + with np.load(path, allow_pickle=False) as payload: + dataset_id = int(payload["sensor_dataset_id"]) + if dataset_id not in SENSORS: + raise ValueError(f"{path}: unknown sensor_dataset_id {dataset_id}") + if selected_counts[dataset_id] < args.num_samples: + samples.append(path) + selected_counts[dataset_id] += 1 + if not torch.cuda.is_available(): + raise RuntimeError("A CUDA GPU is required; use the diffusion-capable container") + checkpoint = resolve_checkpoint(args.checkpoint.resolve()) + model = load_model(checkpoint, args.tokenizer_checkpoint.resolve(), args.latent_stats.resolve()) + torch.cuda.synchronize() + startup_seconds = time.perf_counter() - started + say(f"Ready in {startup_seconds:.1f}s | {checkpoint.name} | {len(samples)} clips, {args.sample_n_frames} frames each") + metadata = {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()} + metadata.update(resolved_checkpoint=str(checkpoint), shift=5, dataset_ids={k: v[0] for k, v in SENSORS.items()}) + (output_root / "run.json").write_text(json.dumps(metadata, indent=2) + "\n") + counts = {key: 0 for key in SENSORS} + sensor_seconds = Counter() + records = [] + timing_path = output_root / "timings.json" + for clip_index, path in enumerate(samples, 1): + clip_started = time.perf_counter() + sample = load_hdmap_sample(path, args.sample_n_frames) + dataset_id = int(sample["sensor_dataset_id"]) + seed = args.seed + int(sample.get("sample_index", counts[dataset_id])) + counts[dataset_id] += 1 + label = f"[{clip_index:02d}/{len(samples):02d}] {sample['dataset']}/{path.stem}" + say(f"{label} | encoding, {sample['hdmap'].shape[1]}x{sample['hdmap'].shape[2]}, seed {seed}") + generated, valid, generation_timing = _generate_sequence( + model, sample, args, seed, console, label + ) + encode_seconds = generation_timing["encode_seconds"] + sampling_seconds = generation_timing["sampling_seconds"] + decode_seconds = generation_timing["decode_seconds"] + phase_started = time.perf_counter() + output = common.sample_output(path, sample_root, output_root) + output.mkdir(parents=True, exist_ok=True) + saved = {key: sample[key] for key in ( + "ray_directions", "fps", "sensor_dataset_id", "dataset", "clip_name", + "lidar_to_world", "pose_sensor_start_end", "frame_indices", + ) if key in sample} + np.savez_compressed(output / "generation.npz", range_m=generated, valid_mask=valid, + seed=np.int64(seed), **saved) + save_seconds = time.perf_counter() - phase_started + phase_started = time.perf_counter() + if args.vis_pcd: + with tqdm(_preview_frames(sample, generated, valid, output), total=len(generated), + desc=f"{label} rendering", unit="frame", file=console, + dynamic_ncols=True, leave=False, disable=not console.isatty()) as preview: + common.write_video(output / "generation.mp4", preview, float(sample["fps"])) + render_seconds = time.perf_counter() - phase_started if args.vis_pcd else 0.0 + total_seconds = time.perf_counter() - clip_started + sensor_seconds[dataset_id] += total_seconds + remaining = selected_counts[dataset_id] - counts[dataset_id] + eta = sensor_seconds[dataset_id] / counts[dataset_id] * remaining + generation_seconds = encode_seconds + sampling_seconds + decode_seconds + records.append(dict(sample=str(path), dataset=sample["dataset"], seed=seed, + encode_seconds=encode_seconds, sampling_seconds=sampling_seconds, + decode_seconds=decode_seconds, save_seconds=save_seconds, + render_seconds=render_seconds, total_seconds=total_seconds, + generation_fps=args.sample_n_frames / generation_seconds)) + report = dict(startup_seconds=startup_seconds, elapsed_seconds=time.perf_counter() - started, + completed_clips=len(records), selected_clips=len(samples), samples=records) + timing_path.with_suffix(".json.tmp").write_text(json.dumps(report, indent=2) + "\n") + timing_path.with_suffix(".json.tmp").replace(timing_path) + say(f" Done {total_seconds:.1f}s | encode {encode_seconds:.1f}s | sample {sampling_seconds:.1f}s" + f" | decode {decode_seconds:.1f}s | save/render {save_seconds + render_seconds:.1f}s" + f" | {sample['dataset']} remaining ~{timedelta(seconds=round(eta))}") + model._store_hdmap_latent(None) + say(f"Finished {len(records)} clips in {timedelta(seconds=round(time.perf_counter() - started))} (including loading and rendering).") + say(f"Outputs: {output_root}\nTimings: {timing_path}") diff --git a/diffusion/inference/pai.py b/diffusion/inference/pai.py new file mode 100644 index 0000000000000000000000000000000000000000..808593b4119d672cac51f9b98f1f82e437bf1cfb --- /dev/null +++ b/diffusion/inference/pai.py @@ -0,0 +1,366 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Shared PAI package loading, conditioning, and quickstart outputs.""" + +from copy import deepcopy +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch +from tqdm import tqdm + +from diffusion.inference.hdmap import _metric_ranges +from utils import inference as common + +# No duplicate first frame: this DiT was trained on 21 unique sweeps. +MODES = { + "world": dict(input_frames=0, output_frames=20, geometry_frames=0, + hdmap="full", geometry="null"), + "forecast": dict(input_frames=10, output_frames=11, geometry_frames=10, + hdmap="null", geometry="frozen_static"), + "resim": dict(input_frames=15, output_frames=5, geometry_frames=15, + hdmap="null", geometry="frozen_object"), +} +SPATIAL_CACHE = dict( + voxel_policy="persistent_static", voxel_m=0.15, radius_m=100.0, + observation_unit="frame", static_min_observations=2, include_latest=False, + candidate_ttl_updates=1, free_space_clear=True, free_space_margin_m=0.75, + free_space_misses_to_remove=2, +) + + +def mode_spec(mode, stage=1): + spec = dict(MODES[mode]) + if mode == "world" and stage != 1: + spec["output_frames"] = 21 + spec["geometry"] = "rolling_generated" + if mode == "forecast" and stage != 1: + spec["geometry"] = "rolling_observed_then_generated" + return spec + + +def load_package(checkpoint, stage): + config_path = checkpoint.with_name("config.json") + config = json.loads(config_path.read_text()) + architecture = {1: "bidir", 2: "causal", 3: "sfdmd"}[stage] + expected = dict( + architecture=f"pai_factorized_{architecture}_p1x2", stage=f"stage{stage}", + weights="ema", input_channels=193, output_channels=64, + patch_spatial=[1, 2], model_channels=2048, num_blocks=28, num_heads=16, + num_dataset_embeddings=3, sensor_dataset_id=0, resolution=[128, 1024], + min_range_m=2.5, max_range_m=100, input_has_prepend=False, + shift=5, shift_clamp_percentiles=None, precision="bfloat16", + tokenizer="transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema", + tokenizer_encoder_dtype="bfloat16" if stage == 3 else "float32", + tokenizer_decoder_dtype="float32", + ) + if stage != 1: + expected.update(temporal_block_size=4, temporal_prefix_frames=1) + if stage == 3: + encoder_dtype = config.get("tokenizer_encoder_dtype") + if encoder_dtype not in ("float32", "bfloat16"): + raise ValueError(f"{config_path}: unsupported tokenizer encoder dtype {encoder_dtype!r}") + spatial_cache = config.get("spatial_cache") + if not isinstance(spatial_cache, dict): + raise ValueError(f"{config_path}: missing spatial_cache configuration") + voxel_m = spatial_cache.get("voxel_m") + if not isinstance(voxel_m, (int, float)) or not np.isfinite(voxel_m) or voxel_m <= 0: + raise ValueError(f"{config_path}: voxel_m must be finite and positive") + expected.update(tokenizer_encoder_dtype=encoder_dtype, + spatial_cache={**SPATIAL_CACHE, "voxel_m": voxel_m}, stream_condition_vae_encode=True, + condition_vae_cache_frames=9, clean_x0_kv_commit=True) + for key, value in expected.items(): + actual = config.get(key) + if key == "tokenizer" and actual == "transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema40k": + actual = value + if key not in config or actual != value: + raise ValueError(f"{config_path}: expected {key}={value!r}, got {config.get(key)!r}") + return config + + +def load_model(checkpoint, tokenizer_checkpoint, latent_stats, stage=1, package=None): + package = load_package(checkpoint, stage) if package is None else package + from diffusion.training.config.base.lidarverse_vae import get_lidarverse_tokenizer + from diffusion.training.config.base.model import LidarModelConfig + from diffusion.training.config.text2world.registry import ( + MININET_2B_Config, VideoConditionerFpsSizePaddingConfig, + ) + from diffusion.training.models.hdmaptolidar_model_rf import ( + HdmapToLidarFactorizedBidirectionalRFModel, + HdmapToLidarFactorizedTeacherForcingRFModel, + ) + from tokenizer.training.configs.base.nets.lidarverse import PAI_TOKENIZER_NAME + from utils.lazy_config import LazyDict + + net = deepcopy(MININET_2B_Config) + net.update( + in_channels=193, out_channels=64, patch_spatial=(1, 2), + num_dataset_embeddings=3, num_frame_type_embeddings=0, + temporal_block_size=0 if stage == 1 else 4, + temporal_prefix_frames=0 if stage == 1 else 1, side_condition_channels=0, + atten_backend="minimal_a2a" if stage == 1 else "torch-flex", + rope_scale_positions_by_patch=True, timestep_scale=0.001, + rope_h_extrapolation_ratio=3.0, rope_w_extrapolation_ratio=3.0, + rope_t_extrapolation_ratio=1.0, rope_enable_fps_modulation=False, + use_wan_fp32_strategy=True, + ) + net.sac_config.mode = "none" + vae = get_lidarverse_tokenizer() + vae.update( + experiment_name=PAI_TOKENIZER_NAME, checkpoint_path=str(tokenizer_checkpoint), + mean_std_fp=str(latent_stats), strict_checkpoint=True, use_ema=False, + is_bf16=False, encoder_is_bf16=package["tokenizer_encoder_dtype"] == "bfloat16", decoder_is_bf16=False, + ) + config = LidarModelConfig( + net=net, vae=vae, conditioner=deepcopy(VideoConditionerFpsSizePaddingConfig), + ema=LazyDict(dict(enabled=False)), fsdp_enabled=False, + latent_shape=[64, package.get("window_frames", 21), 16, 128], input_video_has_prepend=False, + hdmap_channels=1, additional_concat_ch=64, encode_hdmap_with_vae=True, + hdmap_dropout_prob=0.0, sigma_data=1.0, shift=5, + shift_clamp_percentiles=None, enable_shift_stretch=False, + rf_prediction_type="velocity", loss_reduce="mean", + diffusion_forcing_block_size=21 if stage == 1 else 4, + teacher_forcing_prefix_frames=0 if stage == 1 else 1, + factorized_bidirectional_stage1=stage == 1, + blockwise_warped_history_condition=True, blockwise_warped_history_concat=True, + blockwise_warped_history_backend="torch_spatial_map", + blockwise_spatial_map_max_range=100.0, blockwise_spatial_map_min_range=2.5, + **{f"blockwise_spatial_map_{key}": value for key, value in package.get("spatial_cache", SPATIAL_CACHE).items()}, + blockwise_spatial_map_geometry_root_path="", blockwise_spatial_map_geometry_filter_list_path="", + stage2_known_mask_concat=True, + stage2_factorized_prefix_frames=[0, 1, 2, 4, 8, 10, 12, 16], + stage2_factorized_prefix_probs=[0.5] + [1 / 14] * 7, + stage2_factorized_hdmap_modes=["null", "full"], stage2_factorized_hdmap_probs=[0.5, 0.5], + stage2_factorized_geometry_modes_k0=["null", "rolling_static", "frozen_object"], + stage2_factorized_geometry_probs_k0=[0.1, 0.45, 0.45], + stage2_factorized_geometry_modes_known=["null", "rolling_static", "frozen_object"], + stage2_factorized_geometry_probs_known=[0.1, 0.45, 0.45], + factorized_decouple_geometry_observations=True, + factorized_geometry_observation_frames=[1, 2, 4, 8, 10, 12, 16, 20], + factorized_geometry_observation_probs=[0.125] * 8, + factorized_geometry_rolling_shutter=True, factorized_geometry_actor_box_time_mode="frame", + ) + model_type = (HdmapToLidarFactorizedBidirectionalRFModel if stage == 1 + else HdmapToLidarFactorizedTeacherForcingRFModel) + model = model_type(config) + model.model.to(dtype=torch.bfloat16) + payload = torch.load(str(checkpoint), map_location="cpu", weights_only=True, mmap=True) + model.model.load_state_dict(payload["model"], strict=True) + del payload + model.cuda().eval() + if stage != 1: + model.net.set_cached_inference_self_attention_backend("sdpa-flash") + print(f"Loaded PAI Stage {stage} EMA strictly: {checkpoint}", flush=True) + return model + + +def load_sample(path, modes, stage=1): + with np.load(path, allow_pickle=False) as data: + sample = {key: data[key] for key in data.files} + ranges, valid, _, rays = common.load_sample(path) + sample.update(range_m=ranges, valid_mask=valid, ray_directions=rays) + frames = max(sum(mode_spec(mode, stage)[key] for key in ("input_frames", "output_frames")) for mode in modes) + if stage != 1: + frames = 1 + ((frames - 1 + 3) // 4) * 4 + if sample["range_m"].shape[1:] != (128, 1024) or len(sample["range_m"]) < frames: + raise ValueError(f"{path}: need at least {frames} real 128x1024 sweeps") + if int(sample.get("sensor_dataset_id", -1)) != 0 or str(sample.get("dataset", "")) != "pandar": + raise ValueError(f"{path}: this checkpoint is NVIDIA PAI only (dataset ID 0)") + if float(sample.get("fps", 0)) != 10 or bool(sample.get("has_prepend", False)): + raise ValueError(f"{path}: expected 10 Hz real sweeps without a duplicated prefix") + if float(sample.get("min_range_m", 0)) != 2.5 or float(sample.get("max_range_m", 0)) != 100: + raise ValueError(f"{path}: expected range support [2.5,100] m") + rays = sample["ray_directions"] + if rays.shape != (128, 1024, 3) or not np.isfinite(rays).all() or not np.allclose(np.linalg.norm(rays, axis=-1), 1, atol=1e-4): + raise ValueError(f"{path}: expected a calibrated 128x1024 unit-ray grid") + if "world" in modes: + hdmap = sample.get("hdmap") + if hdmap is None or hdmap.shape != sample["range_m"].shape or not np.isfinite(hdmap).all() or hdmap.min() < -1 or hdmap.max() > 1: + raise ValueError(f"{path}: world generation needs aligned HDMap ranges normalized to [-1,1]") + poses = sample.get("pose_sensor_start_end") + if poses is None or poses.shape != (len(sample["range_m"]), 2, 4, 4) or not np.isfinite(poses).all(): + raise ValueError(f"{path}: missing aligned sensor-to-world start/end poses") + if "resim" in modes or ("forecast" in modes and stage == 1): + for key in ("box_object_to_world", "box_lwh", "box_valid", "box_is_moving", "box_track_id"): + if key not in sample or len(sample[key]) != len(sample["range_m"]): + raise ValueError(f"{path}: forecast/resim need aligned {key}; use prepare_pai_bidir.py") + shape = sample["box_valid"].shape + if len(shape) != 2 or sample["box_track_id"].shape != shape or sample["box_is_moving"].shape != shape: + raise ValueError(f"{path}: box masks and track IDs must be (T,M)") + if sample["box_object_to_world"].shape != shape + (4, 4) or sample["box_lwh"].shape != shape + (3,): + raise ValueError(f"{path}: box poses/sizes do not match the mask") + active = sample["box_valid"].astype(bool) + if not np.isfinite(sample["box_object_to_world"][active]).all() or not np.isfinite(sample["box_lwh"][active]).all(): + raise ValueError(f"{path}: non-finite actor annotations") + if (sample["box_lwh"][active] <= 0).any() or (sample["box_track_id"][active] < 0).any(): + raise ValueError(f"{path}: actor sizes must be positive and track IDs nonnegative") + return sample + + +def make_batch(sample, mode, stage=1, length=None): + from utils.pai_batch import make_pai_batch + + spec = mode_spec(mode, stage) + length = spec["input_frames"] + spec["output_frames"] if length is None else length + return make_pai_batch(sample, length, input_frames=spec["input_frames"], + hdmap=spec["hdmap"] == "full", + boxes=mode == "resim" or (mode == "forecast" and stage == 1), device="cuda") + + +def generate_bidir(model, sample, mode, args, seed, console): + spec = MODES[mode] + model.stage2_factorized_force_prefix_k = spec["input_frames"] + model.stage2_factorized_force_hdmap_mode = spec["hdmap"] + # frozen_object + static_only is exactly the frozen_static builder branch. + model.stage2_factorized_force_geometry_mode = "null" if mode == "world" else "frozen_object" + model.factorized_static_only_geometry = mode == "forecast" + model.factorized_force_geometry_observations = spec["geometry_frames"] if mode != "world" else -1 + torch.manual_seed(seed) + batch = make_batch(sample, mode) + with torch.autocast("cuda", dtype=torch.bfloat16): + _, latent, _ = model.get_data_and_condition(batch) + known_mask = model._current_stage2_known_frame_mask + kwargs = dict(known_latents=latent, known_mask=known_mask, known_latents_mode="clean_mask") if spec["input_frames"] else {} + with tqdm(total=args.num_steps, desc=f"{mode} sampling", file=console, + unit="step", leave=False, disable=not console.isatty()) as progress: + calls = 0 + def on_forward(_module, _inputs, _output): + nonlocal calls + calls += 1 + if calls % (1 if args.guidance in (0, 1) else 2) == 0: + progress.update(1) + hook = model.net.register_forward_hook(on_forward) + try: + with torch.autocast("cuda", dtype=torch.bfloat16): + result = model.generate_samples_from_batch( + batch, state_shape=latent.shape[1:], n_sample=1, + guidance=args.guidance, seed=seed, num_steps=args.num_steps, + sampler=args.sampler, sde_eta=args.sde_eta, **kwargs, + ) + finally: + hook.remove() + if not torch.isfinite(result).all(): + raise FloatingPointError("Sampling produced non-finite latents") + if spec["input_frames"] and not torch.equal(result[:, :, :spec["input_frames"]], latent[:, :, :spec["input_frames"]].float()): + raise RuntimeError("Clean-prefix latents were not preserved") + decoded = model.decode(result.float()) + if decoded.shape != batch["video"].shape or not torch.isfinite(decoded).all(): + raise RuntimeError("Invalid decoded LiDAR sequence") + return _metric_ranges(decoded) + + +def _preview_label(image, title, frame, length, input_frames, is_input): + image = image.copy() + cv2.rectangle(image, (0, 0), (image.shape[1] - 1, 80), (255, 255, 255), -1) + color = (175, 90, 35) if is_input else (30, 30, 30) + cv2.putText(image, title, (20, 33), cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2, cv2.LINE_AA) + detail = f"Frame {frame} / {length - 1}" + if input_frames: + detail += f" | Input: 0-{input_frames - 1} | Generated: {input_frames}-{length - 1}" + cv2.putText(image, detail, (20, 64), cv2.FONT_HERSHEY_SIMPLEX, .7, (65, 65, 65), 1, cv2.LINE_AA) + return image + + +def preview(sample, generated, valid, mode, output): + from utils.visualize.hdmap import render_hdmap + + spec = MODES[mode] + length = len(generated) + if mode == "world": + source, source_valid = _metric_ranges(torch.from_numpy(sample["hdmap"][:length])[None, None]) + source_title = "Input HDMap" + else: + source, source_valid = sample["range_m"][:length], sample["valid_mask"][:length] + for t in range(length): + is_input = t < spec["input_frames"] + if mode != "world": + source_title = "INPUT | Observed GT" if is_input else "GT | Reference only (not input)" + generated_title = "INPUT | Observed GT" if is_input else { + "world": "GENERATION | HDMap-conditioned", + "forecast": "GENERATION | Forecasting", + "resim": "GENERATION | Resimulation", + }[mode] + # Display the actual provided sweep, not its tokenizer reconstruction. + values, mask = (source[t], source_valid[t]) if is_input else (generated[t], valid[t]) + clouds = (("input" if mode == "world" else "gt", source_title, source[t], source_valid[t]), + ("generation", generated_title, values, mask)) + panels = [] + for name, title, ranges, hits in clouds: + points = common.points_from_ranges(ranges, hits, sample["ray_directions"]) + common.write_ply(output / "ply" / f"{name}_{t:03d}.ply", points) + rendered = render_hdmap(sample, t) if mode == "world" and name == "input" else common.render_points(points, yaw_deg=0) + panels.append(_preview_label(rendered, title, t, length, spec["input_frames"], is_input)) + yield np.concatenate(panels, axis=1) + + +@torch.inference_mode() +def run(args, console, say): + package = load_package(args.checkpoint, args.stage) + modes = list(MODES) if args.mode == "all" else [args.mode] + paths = common.sample_paths(args.sample_path.resolve())[:args.num_samples] + if len(paths) < args.num_samples: + raise ValueError(f"Requested {args.num_samples} clips, found only {len(paths)}") + # Validate all requested annotations before allocating the diffusion model. + for path in paths: + sample = load_sample(path, modes, args.stage) + if args.raw_hdmap_condition_rasterize and "world" in modes: + from diffusion.inference.raw_hdmap import validate_raw_hdmap + validate_raw_hdmap(sample) + if args.vis_pcd and "world" in modes: + for key in ("map_vertices", "map_offsets", "map_kinds", "box_class"): + if key not in sample: + raise ValueError(f"{path}: missing {key}; rerun prepare_pai_bidir.py") + if not torch.cuda.is_available(): + raise RuntimeError("Run this quickstart on a CUDA GPU in the diffusion environment") + model = load_model(args.checkpoint, args.tokenizer_checkpoint, args.latent_stats, args.stage, package) + generate = generate_bidir + if args.stage != 1: + from diffusion.inference.causal import generate + metadata = {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()} + metadata.update(checkpoint_config=package, + modes={mode: mode_spec(mode, args.stage) for mode in modes}, shift=5, + shift_clamp_percentiles=None, input_has_prepend=False, + tokenizer_encoder_dtype=package["tokenizer_encoder_dtype"], tokenizer_decoder_dtype="float32") + if args.stage != 1: + metadata.update(kv_cache_frames=args.kv_cache_frames, kv_sink_frames=1, + attention_backend="sdpa-flash", + kv_budget_includes_sink=True, clean_kv_commit="synchronous_blockwise", + condition_vae_cache_frames=9, decoder_cache_frames=30, + observed_latent_encoding="causal_observed_only_stream", + spatial_cache=package.get("spatial_cache", SPATIAL_CACHE)) + (args.output_folder / "run.json").write_text(json.dumps(metadata, indent=2) + "\n") + for mode in modes: + for index, path in enumerate(paths): + seed = args.seed + index + say(f"{mode} [{index + 1}/{len(paths)}] {path.stem} | seed {seed}") + sample = load_sample(path, [mode], args.stage) + output = common.sample_output(path, args.sample_path.resolve(), args.output_folder / mode) + output.mkdir(parents=True, exist_ok=True) + if args.raw_hdmap_condition_rasterize and mode == "world": + from diffusion.inference.raw_hdmap import rasterize_raw_hdmap + say(" Rasterizing raw map and boxes with rolling-shutter poses...") + condition, stats = rasterize_raw_hdmap( + sample, bbox_dilation=args.raw_hdmap_condition_bbox_dilation, + seg_interval=args.raw_hdmap_seg_interval, + ) + sample["hdmap"] = condition + np.savez_compressed(output / "hdmap_condition.npz", normalized_range=condition, + frame_indices=sample["frame_indices"], + pose_sensor_start_end=sample["pose_sensor_start_end"], + ray_directions=sample["ray_directions"]) + (output / "raw_hdmap_condition.json").write_text(json.dumps(stats, indent=2) + "\n") + say(f" HDMap coverage: {stats['original_hit_fraction']:.3%} -> {stats['condition_hit_fraction']:.3%}") + generated, valid = generate(model, sample, mode, args, seed, console) + length = len(generated) + np.savez_compressed(output / "generation.npz", range_m=generated, valid_mask=valid, + ray_directions=sample["ray_directions"], fps=np.float32(10), + pose_sensor_start_end=sample["pose_sensor_start_end"][:length], + frame_indices=sample["frame_indices"][:length], clip_name=sample["clip_name"], + known_frame_mask=np.arange(length) < MODES[mode]["input_frames"], seed=np.int64(seed)) + if args.vis_pcd: + common.write_video(output / "generation.mp4", preview(sample, generated, valid, mode, output), 10) + say(f" Saved {output}") + say(f"Finished. Outputs: {args.output_folder}") diff --git a/diffusion/inference/raw_hdmap.py b/diffusion/inference/raw_hdmap.py new file mode 100644 index 0000000000000000000000000000000000000000..2546e967b175e4d93a2b05eb01cc838c2b0b8bac --- /dev/null +++ b/diffusion/inference/raw_hdmap.py @@ -0,0 +1,122 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inference-only raw-vector HDMap conditioning for prepared PAI samples.""" + +import numpy as np +import torch +import torch.nn.functional as F + + +def validate_raw_hdmap(sample): + required = ("map_vertices", "map_offsets", "box_valid", "box_lwh", "box_object_to_world") + for key in required: + if key not in sample: + raise ValueError(f"Missing {key}; rerun scripts/data/prepare_pai_bidir.py") + vertices, offsets = sample["map_vertices"], sample["map_offsets"] + if vertices.ndim != 2 or vertices.shape[1:] != (3,) or not np.isfinite(vertices).all(): + raise ValueError("Raw map vertices must be finite (N,3) world points") + if (offsets.ndim != 1 or len(offsets) < 2 or offsets.dtype.kind not in "iu" + or offsets[0] != 0 or offsets[-1] != len(vertices) or (np.diff(offsets) < 2).any()): + raise ValueError("Raw map offsets must delimit nonempty polylines of at least two vertices") + shape = sample["box_valid"].shape + if len(shape) != 2 or shape[0] != len(sample["range_m"]): + raise ValueError("Raw box masks must be (T,M), aligned with the real sweeps") + if sample["box_lwh"].shape != shape + (3,) or sample["box_object_to_world"].shape != shape + (4, 4): + raise ValueError("Raw box sizes/poses do not match the box mask") + active = sample["box_valid"].astype(bool) + if (not np.isfinite(sample["box_object_to_world"][active]).all() + or not np.isfinite(sample["box_lwh"][active]).all() + or (sample["box_lwh"][active] <= 0).any()): + raise ValueError("Active boxes must have finite poses and positive finite sizes") + + +def _sample_polyline(vertices, spacing): + # Match LiDARGen's raw-MADS densification, including endpoint handling. + vertices = np.asarray(vertices, dtype=np.float64) + points = [] + for start, end in zip(vertices[:-1], vertices[1:]): + distance = np.linalg.norm(end - start) + count = int(np.clip(np.floor(distance / spacing), 2, 10000)) + fractions = np.linspace(0, 1, count)[:-1] + points.append(start + fractions[:, None] * (end - start)) + points.append(vertices[-1:]) + return np.concatenate(points).astype(np.float32) + + +def _box_points(sample, frame, spacing): + signs = np.array([[1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1], + [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1]], dtype=np.float64) + wireframe = [0, 1, 2, 3, 0, 4, 5, 6, 7, 4, 5, 1, 2, 6, 7, 3] + points = [] + for index in np.flatnonzero(sample["box_valid"][frame]): + corners = signs * sample["box_lwh"][frame, index] / 2 + pose = sample["box_object_to_world"][frame, index].astype(np.float64) + corners = corners @ pose[:3, :3].T + pose[:3, 3] + points.append(_sample_polyline(corners[wireframe], spacing)) + return np.concatenate(points) if points else np.empty((0, 3), np.float32) + + +def _dilate_nearest(normalized, kernel_size): + """Widen bbox pixels without averaging ranges or filling empty neighborhoods.""" + if kernel_size < 1 or kernel_size % 2 != 1: + raise ValueError("BBox dilation must be a positive odd integer") + if kernel_size == 1: + return normalized + valid = torch.isfinite(normalized) & (normalized > -1 + 1e-5) + work = normalized[:, None].masked_fill(~valid[:, None], torch.inf) + nearest = -F.max_pool2d(-work, kernel_size, stride=1, padding=kernel_size // 2) + return torch.where(torch.isfinite(nearest), nearest, -1.)[:, 0] + + +@torch.inference_mode() +def rasterize_raw_hdmap(sample, *, bbox_dilation=1, seg_interval=0.1): + """Return a (T,H,W) normalized condition and provenance, without GT LiDAR.""" + from diffusion.training.datasets.lidar_dataset.forecast_warp import ( + TorchSpatialPointMap, compose_normalized_range_channels, + ) + from diffusion.training.models.hdmaptolidar_model_rf import _sensor_tables_from_ray_directions + + validate_raw_hdmap(sample) + if not np.isfinite(seg_interval) or seg_interval <= 0: + raise ValueError("Raw HDMap segment spacing must be positive and finite") + if bbox_dilation < 1 or bbox_dilation % 2 != 1: + raise ValueError("BBox dilation must be a positive odd integer") + rays = torch.as_tensor(sample["ray_directions"], dtype=torch.float32, device="cuda") + elevations, azimuths, offsets = _sensor_tables_from_ray_directions(rays, allow_approximate=True) + renderer = TorchSpatialPointMap( + ray_dirs=rays, row_elevations_rad=elevations, column_azimuths_rad=azimuths, + row_azimuth_offsets_rad=offsets, min_range=2.5, max_range=100, + min_value=-1, inverse_depth=False, radius_m=100, voxel_size_m=0.2, device="cuda", + ) + vertices, offsets = sample["map_vertices"], sample["map_offsets"] + static_points = np.concatenate([_sample_polyline(vertices[a:b], seg_interval) + for a, b in zip(offsets[:-1], offsets[1:])]) + poses = sample["pose_sensor_start_end"].astype(np.float32) + motions = np.linalg.inv(poses[:, 1]) @ poses[:, 0] + static, static_hit = renderer.render_points_world( + static_points, poses[:, 0], target_pose_sensor_start_end=motions, + ) + boxes, box_hits = [], [] + for t, pose in enumerate(poses): + ranges, hits = renderer.render_points_world( + _box_points(sample, t, seg_interval), pose[None, 0], + target_pose_sensor_start_end=motions[t:t + 1], + ) + boxes.append(ranges[0, 0]) + box_hits.append(hits[0]) + thick_boxes = _dilate_nearest(torch.stack(boxes), bbox_dilation) + condition = compose_normalized_range_channels( + torch.stack((static[0], thick_boxes)), channel_dim=0, min_value=-1, inverse_depth=False, + )[0].cpu().numpy() + stats = dict( + source="prepared_raw_vectors", bbox_dilation_kernel=bbox_dilation, + map_dilation_kernel=1, segment_spacing_m=seg_interval, + rolling_shutter=True, min_range_m=2.5, max_range_m=100, + static_hit_fraction=float(static_hit.float().mean()), + bbox_hit_fraction_before_dilation=float(torch.stack(box_hits).float().mean()), + bbox_hit_fraction_after_dilation=float((thick_boxes > -1 + 1e-5).float().mean()), + original_hit_fraction=float((sample["hdmap"] > -1 + 1e-5).mean()), + condition_hit_fraction=float((condition > -1 + 1e-5).mean()), + ) + return condition, stats diff --git a/diffusion/module/__init__.py b/diffusion/module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/diffusion/module/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/diffusion/module/attention.py b/diffusion/module/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0a4b02dea9adbb9a320ed2631014d4102ed288 --- /dev/null +++ b/diffusion/module/attention.py @@ -0,0 +1,313 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List, Optional + +import numpy as np +import torch +import transformer_engine as te +from einops import rearrange +from torch import nn +from torch.utils.checkpoint import checkpoint +from transformer_engine.pytorch.attention import DotProductAttention, apply_rotary_pos_emb + +# ---------------------- Feed Forward Network ----------------------- + + +class FeedForward(nn.Module): + """ + Transformer FFN with optional gating + + Parameters: + d_model (int): Dimensionality of input features. + d_ff (int): Dimensionality of the hidden layer. + dropout (float, optional): Dropout rate applied after the activation function. Defaults to 0.1. + activation (callable, optional): The activation function applied after the first linear layer. + Defaults to nn.ReLU(). + is_gated (bool, optional): If set to True, incorporates gating mechanism to the feed-forward layer. + Defaults to False. + bias (bool, optional): If set to True, adds a bias to the linear layers. Defaults to True. + + Example: + >>> ff = FeedForward(d_model=512, d_ff=2048) + >>> x = torch.randn(64, 10, 512) # Example input tensor + >>> output = ff(x) + >>> print(output.shape) # Expected shape: (64, 10, 512) + """ + + def __init__( + self, + d_model: int, + d_ff: int, + dropout: float = 0.1, + activation=nn.ReLU(), + is_gated: bool = False, + bias: bool = False, + ) -> None: + super().__init__() + + self.layer1 = nn.Linear(d_model, d_ff, bias=bias) + self.layer2 = nn.Linear(d_ff, d_model, bias=bias) + + self.dropout = nn.Dropout(dropout) + self.activation = activation + self.is_gated = is_gated + if is_gated: + self.linear_gate = nn.Linear(d_model, d_ff, bias=False) + + def forward(self, x: torch.Tensor): + g = self.activation(self.layer1(x)) + if self.is_gated: + x = g * self.linear_gate(x) + else: + x = g + assert self.dropout.p == 0.0, "we skip dropout" + return self.layer2(x) + + +class GPT2FeedForward(FeedForward): + def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1, bias: bool = False): + super().__init__( + d_model=d_model, + d_ff=d_ff, + dropout=dropout, + activation=nn.GELU(), + is_gated=False, + bias=bias, + ) + + def forward(self, x: torch.Tensor): + assert self.dropout.p == 0.0, "we skip dropout" + + x = self.layer1(x) + + def activation_layer2_forward(x): + x = self.activation(x) + x = self.layer2(x) + return x + + x = checkpoint(activation_layer2_forward, x, use_reentrant=False) + return x + + +# ---------------------- Normalization Layer ----------------------- + + +def normalize(x: torch.Tensor, dim: Optional[List[int]] = None, eps: float = 0) -> torch.Tensor: + """ + Normalizes the input tensor along specified dimensions such that the average square norm of elements is adjusted. + + Args: + x (torch.Tensor): The input tensor to normalize. + dim (list, optional): The dimensions over which to normalize. If None, normalizes over all dimensions except the first. + eps (float, optional): A small constant to ensure numerical stability during division. + + Returns: + torch.Tensor: The normalized tensor. + """ + if dim is None: + dim = list(range(1, x.ndim)) + norm = torch.linalg.vector_norm(x, dim=dim, keepdim=True, dtype=torch.float32) + norm = torch.add(eps, norm, alpha=np.sqrt(norm.numel() / x.numel())) + return x / norm.to(x.dtype) + + +def get_normalization(name: str, channels: int): + if name == "I": + return nn.Identity() + elif name == "R": + return te.pytorch.RMSNorm(channels, eps=1e-6) + else: + raise ValueError(f"Normalization {name} not found") + + +class BaseAttentionOp(nn.Module): + def __init__(self): + super().__init__() + + +class Attention(nn.Module): + """ + Generalized attention impl. + + Allowing for both self-attention and cross-attention configurations depending on whether a `context_dim` is provided. + If `context_dim` is None, self-attention is assumed. + + Parameters: + query_dim (int): Dimension of each query vector. + context_dim (int, optional): Dimension of each context vector. If None, self-attention is assumed. + heads (int, optional): Number of attention heads. Defaults to 8. + dim_head (int, optional): Dimension of each head. Defaults to 64. + dropout (float, optional): Dropout rate applied to the output of the attention block. Defaults to 0.0. + attn_op (BaseAttentionOp, optional): Custom attention operation to be used instead of the default. + qkv_bias (bool, optional): If True, adds a learnable bias to query, key, and value projections. Defaults to False. + out_bias (bool, optional): If True, adds a learnable bias to the output projection. Defaults to False. + qkv_norm (str, optional): A string representing normalization strategies for query, key, and value projections. + Defaults to "SSI". + qkv_norm_mode (str, optional): A string representing normalization mode for query, key, and value projections. + Defaults to 'per_head'. Only support 'per_head'. + + Examples: + >>> attn = Attention(query_dim=128, context_dim=256, heads=4, dim_head=32, dropout=0.1) + >>> query = torch.randn(10, 128) # Batch size of 10 + >>> context = torch.randn(10, 256) # Batch size of 10 + >>> output = attn(query, context) # Perform the attention operation + + Note: + https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/cosmos_predict1/attention.py#L223 + """ + + def __init__( + self, + query_dim: int, + context_dim=None, + heads=8, + dim_head=64, + dropout=0.0, + attn_op: Optional[BaseAttentionOp] = None, + qkv_bias: bool = False, + out_bias: bool = False, + qkv_norm: str = "SSI", + qkv_norm_mode: str = "per_head", + backend: str = "transformer_engine", + qkv_format: str = "bshd", + ) -> None: + super().__init__() + + self.is_selfattn = context_dim is None # self attention + + inner_dim = dim_head * heads + context_dim = query_dim if context_dim is None else context_dim + + self.heads = heads + self.dim_head = dim_head + self.qkv_norm_mode = qkv_norm_mode + self.qkv_format = qkv_format + + if self.qkv_norm_mode == "per_head": + norm_dim = dim_head + else: + raise ValueError(f"Normalization mode {self.qkv_norm_mode} not found, only support 'per_head'") + + self.backend = backend + self.tp_size = 1 # TP is not included in this Attention implementation. + + self.to_q = nn.Sequential( + nn.Linear(query_dim, inner_dim, bias=qkv_bias), + get_normalization(qkv_norm[0], norm_dim), + ) + self.to_k = nn.Sequential( + nn.Linear(context_dim, inner_dim, bias=qkv_bias), + get_normalization(qkv_norm[1], norm_dim), + ) + self.to_v = nn.Sequential( + nn.Linear(context_dim, inner_dim, bias=qkv_bias), + get_normalization(qkv_norm[2], norm_dim), + ) + + self.to_out = nn.Sequential( + nn.Linear(inner_dim, query_dim, bias=out_bias), + nn.Dropout(dropout), + ) + + if attn_op: # use what is given + self.attn_op = attn_op + elif self.backend == "transformer_engine": + self.attn_op: BaseAttentionOp = DotProductAttention( + self.heads, + self.dim_head, + num_gqa_groups=self.heads, + attention_dropout=0, + qkv_format=qkv_format, + attn_mask_type="no_mask", + tp_size=self.tp_size, + tp_group=None, + sequence_parallel=False, + ) + elif self.backend == "torch": + self.attn_op = torch.nn.functional.scaled_dot_product_attention + else: + raise ValueError(f"Backend {backend} not found") + self.query_dim = query_dim + self.context_dim = context_dim + self.inner_dim = inner_dim + + def cal_qkv( + self, x, context=None, mask=None, rope_emb=None, **kwargs + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + del kwargs + + """ + self.to_q, self.to_k, self.to_v are nn.Sequential with projection + normalization layers. + Before 07/24/2024, these modules normalize across all heads. + After 07/24/2024, to support tensor parallelism and follow the common practice in the community, + we support to normalize per head. + To keep the checkpoint copatibility with the previous code, + we keep the nn.Sequential but call the projection and the normalization layers separately. + We use a flag `self.qkv_norm_mode` to control the normalization behavior. + The default value of `self.qkv_norm_mode` is "per_head", which means we normalize per head. + """ + if self.qkv_norm_mode == "per_head": + q = self.to_q[0](x) + context = x if context is None else context + k = self.to_k[0](context) + v = self.to_v[0](context) + q, k, v = map( + lambda t: rearrange(t, "b ... (n c) -> b ... n c", n=self.heads, c=self.dim_head), + (q, k, v), + ) + else: + raise ValueError(f"Normalization mode {self.qkv_norm_mode} not found, only support 'per_head'") + + q = self.to_q[1](q) + k = self.to_k[1](k) + v = self.to_v[1](v) + if self.is_selfattn and rope_emb is not None: # only apply to self-attention! + q = apply_rotary_pos_emb(q, rope_emb, tensor_format=self.qkv_format, fused=True) + k = apply_rotary_pos_emb(k, rope_emb, tensor_format=self.qkv_format, fused=True) + return q, k, v + + def cal_attn(self, q, k, v, mask=None): + if self.backend == "transformer_engine": + seq_dim = self.qkv_format.index("s") + assert ( + q.shape[seq_dim] > 1 and k.shape[seq_dim] > 1 + ), "Seqlen must be larger than 1 for TE Attention starting with 1.8 TE version." + out = self.attn_op(q, k, v, core_attention_bias_type="no_bias", core_attention_bias=None) # [B, Mq, H, V] + return self.to_out(out) + elif self.backend == "torch": + q = rearrange(q, "s b h d -> b h s d") + k = rearrange(k, "s b h d -> b h s d") + v = rearrange(v, "s b h d -> b h s d") + out = self.attn_op(q, k, v) # [B, Mq, H, V] + return self.to_out(rearrange(out, " b h s d -> s b (h d)")) + else: + raise ValueError(f"Backend {self.backend} not found") + + def forward( + self, + x, + context=None, + mask=None, + rope_emb=None, + **kwargs, + ): + """ + Args: + x (Tensor): The query tensor of shape [B, Mq, K] + context (Optional[Tensor]): The key tensor of shape [B, Mk, K] or use x as context [self attention] if None + """ + q, k, v = self.cal_qkv(x, context, mask, rope_emb=rope_emb, **kwargs) + return self.cal_attn(q, k, v, mask) diff --git a/diffusion/module/blocks.py b/diffusion/module/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..1f8f9228b523a88c98e0fddc6e2dd8c86a909e06 --- /dev/null +++ b/diffusion/module/blocks.py @@ -0,0 +1,558 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Optional + +import numpy as np +import torch +from einops import rearrange, repeat +from einops.layers.torch import Rearrange +from torch import nn + +from diffusion.module.attention import Attention, GPT2FeedForward +from utils import log + + +def modulate(x, shift, scale): + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + +class Timesteps(nn.Module): + def __init__(self, num_channels): + super().__init__() + self.num_channels = num_channels + + def forward(self, timesteps): + in_dype = timesteps.dtype + half_dim = self.num_channels // 2 + exponent = -math.log(10000) * torch.arange(half_dim, dtype=torch.float32, device=timesteps.device) + exponent = exponent / (half_dim - 0.0) + + emb = torch.exp(exponent) + emb = timesteps[:, None].float() * emb[None, :] + + sin_emb = torch.sin(emb) + cos_emb = torch.cos(emb) + emb = torch.cat([cos_emb, sin_emb], dim=-1) + + return emb.to(in_dype) + + +class TimestepEmbedding(nn.Module): + def __init__(self, in_features: int, out_features: int, use_adaln_lora: bool = False): + super().__init__() + log.debug( + f"Using AdaLN LoRA Flag: {use_adaln_lora}. We enable bias if no AdaLN LoRA for backward compatibility." + ) + self.linear_1 = nn.Linear(in_features, out_features, bias=not use_adaln_lora) + self.activation = nn.SiLU() + self.use_adaln_lora = use_adaln_lora + if use_adaln_lora: + self.linear_2 = nn.Linear(out_features, 3 * out_features, bias=False) + else: + self.linear_2 = nn.Linear(out_features, out_features, bias=True) + + def forward(self, sample: torch.Tensor) -> torch.Tensor: + emb = self.linear_1(sample) + emb = self.activation(emb) + emb = self.linear_2(emb) + + if self.use_adaln_lora: + adaln_lora_B_3D = emb + emb_B_D = sample + else: + emb_B_D = emb + adaln_lora_B_3D = None + + return emb_B_D, adaln_lora_B_3D + + +class FourierFeatures(nn.Module): + """ + Implements a layer that generates Fourier features from input tensors, based on randomly sampled + frequencies and phases. This can help in learning high-frequency functions in low-dimensional problems. + + [B] -> [B, D] + + Parameters: + num_channels (int): The number of Fourier features to generate. + bandwidth (float, optional): The scaling factor for the frequency of the Fourier features. Defaults to 1. + normalize (bool, optional): If set to True, the outputs are scaled by sqrt(2), usually to normalize + the variance of the features. Defaults to False. + + Example: + >>> layer = FourierFeatures(num_channels=256, bandwidth=0.5, normalize=True) + >>> x = torch.randn(10, 256) # Example input tensor + >>> output = layer(x) + >>> print(output.shape) # Expected shape: (10, 256) + """ + + def __init__(self, num_channels, bandwidth=1, normalize=False): + super().__init__() + self.register_buffer("freqs", 2 * np.pi * bandwidth * torch.randn(num_channels), persistent=True) + self.register_buffer("phases", 2 * np.pi * torch.rand(num_channels), persistent=True) + self.gain = np.sqrt(2) if normalize else 1 + + def forward(self, x, gain: float = 1.0): + """ + Apply the Fourier feature transformation to the input tensor. + + Args: + x (torch.Tensor): The input tensor. + gain (float, optional): An additional gain factor applied during the forward pass. Defaults to 1. + + Returns: + torch.Tensor: The transformed tensor, with Fourier features applied. + """ + in_dtype = x.dtype + x = x.to(torch.float32).ger(self.freqs.to(torch.float32)).add(self.phases.to(torch.float32)) + x = x.cos().mul(self.gain * gain).to(in_dtype) + return x + + +class PatchEmbed(nn.Module): + """ + PatchEmbed is a module for embedding patches from an input tensor by applying either 3D or 2D convolutional layers, + depending on the . This module can process inputs with temporal (video) and spatial (image) dimensions, + making it suitable for video and image processing tasks. It supports dividing the input into patches + and embedding each patch into a vector of size `out_channels`. + + Parameters: + - spatial_patch_size (int): The size of each spatial patch. + - temporal_patch_size (int): The size of each temporal patch. + - in_channels (int): Number of input channels. Default: 3. + - out_channels (int): The dimension of the embedding vector for each patch. Default: 768. + - bias (bool): If True, adds a learnable bias to the output of the convolutional layers. Default: True. + """ + + def __init__( + self, + spatial_patch_size, + temporal_patch_size, + in_channels=3, + out_channels=768, + bias=True, + ): + super().__init__() + self.spatial_patch_size = spatial_patch_size + self.temporal_patch_size = temporal_patch_size + + self.proj = nn.Sequential( + Rearrange( + "b c (t r) (h m) (w n) -> b t h w (c r m n)", + r=temporal_patch_size, + m=spatial_patch_size, + n=spatial_patch_size, + ), + nn.Linear( + in_channels * spatial_patch_size * spatial_patch_size * temporal_patch_size, out_channels, bias=bias + ), + ) + self.out = nn.Identity() + + def forward(self, x): + """ + Forward pass of the PatchEmbed module. + + Parameters: + - x (torch.Tensor): The input tensor of shape (B, C, T, H, W) where + B is the batch size, + C is the number of channels, + T is the temporal dimension, + H is the height, and + W is the width of the input. + + Returns: + - torch.Tensor: The embedded patches as a tensor, with shape b t h w c. + """ + assert x.dim() == 5 + _, _, T, H, W = x.shape + assert H % self.spatial_patch_size == 0 and W % self.spatial_patch_size == 0 + assert T % self.temporal_patch_size == 0 + x = self.proj(x) + return self.out(x) + + +class FinalLayer(nn.Module): + """ + The final layer of video DiT. + """ + + def __init__( + self, + hidden_size, + spatial_patch_size, + temporal_patch_size, + out_channels, + use_adaln_lora: bool = False, + adaln_lora_dim: int = 256, + ): + super().__init__() + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.linear = nn.Linear( + hidden_size, spatial_patch_size * spatial_patch_size * temporal_patch_size * out_channels, bias=False + ) + self.hidden_size = hidden_size + self.n_adaln_chunks = 2 + self.use_adaln_lora = use_adaln_lora + if use_adaln_lora: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, adaln_lora_dim, bias=False), + nn.Linear(adaln_lora_dim, self.n_adaln_chunks * hidden_size, bias=False), + ) + else: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(hidden_size, self.n_adaln_chunks * hidden_size, bias=False) + ) + + def forward( + self, + x_BT_HW_D, + emb_B_D, + adaln_lora_B_3D: Optional[torch.Tensor] = None, + ): + if self.use_adaln_lora: + assert adaln_lora_B_3D is not None + shift_B_D, scale_B_D = (self.adaLN_modulation(emb_B_D) + adaln_lora_B_3D[:, : 2 * self.hidden_size]).chunk( + 2, dim=1 + ) + else: + shift_B_D, scale_B_D = self.adaLN_modulation(emb_B_D).chunk(2, dim=1) + + B = emb_B_D.shape[0] + T = x_BT_HW_D.shape[0] // B + shift_BT_D, scale_BT_D = repeat(shift_B_D, "b d -> (b t) d", t=T), repeat(scale_B_D, "b d -> (b t) d", t=T) + x_BT_HW_D = modulate(self.norm_final(x_BT_HW_D), shift_BT_D, scale_BT_D) + + x_BT_HW_D = self.linear(x_BT_HW_D) + return x_BT_HW_D + + +class VideoAttn(nn.Module): + """ + Implements video attention with optional cross-attention capabilities. + + This module processes video features while maintaining their spatio-temporal structure. It can perform + self-attention within the video features or cross-attention with external context features. + + Parameters: + x_dim (int): Dimension of input feature vectors + context_dim (Optional[int]): Dimension of context features for cross-attention. None for self-attention + num_heads (int): Number of attention heads + bias (bool): Whether to include bias in attention projections. Default: False + qkv_norm_mode (str): Normalization mode for query/key/value projections. Must be "per_head". Default: "per_head" + x_format (str): Format of input tensor. Must be "BTHWD". Default: "BTHWD" + n_views (int): Extra parameter used in multi-view diffusion model. It indicated total number of view we model together. + + Input shape: + - x: (T, H, W, B, D) video features + - context (optional): (M, B, D) context features for cross-attention + where: + T: temporal dimension + H: height + W: width + B: batch size + D: feature dimension + M: context sequence length + """ + + def __init__( + self, + x_dim: int, + context_dim: Optional[int], + num_heads: int, + bias: bool = False, + qkv_norm_mode: str = "per_head", + x_format: str = "BTHWD", + n_views: int = 1, + ) -> None: + super().__init__() + self.x_format = x_format + self.n_views = n_views + self.attn = Attention( + x_dim, + context_dim, + num_heads, + x_dim // num_heads, + qkv_bias=bias, + qkv_norm="RRI", + out_bias=bias, + qkv_norm_mode=qkv_norm_mode, + qkv_format="sbhd", + ) + + def forward( + self, + x: torch.Tensor, + context: Optional[torch.Tensor] = None, + crossattn_mask: Optional[torch.Tensor] = None, + rope_emb_L_1_1_D: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """ + Forward pass for video attention. + + Args: + x (Tensor): Input tensor of shape (B, T, H, W, D) or (T, H, W, B, D) representing batches of video data. + context (Tensor): Context tensor of shape (B, M, D) or (M, B, D), + where M is the sequence length of the context. + crossattn_mask (Optional[Tensor]): An optional mask for cross-attention mechanisms. + rope_emb_L_1_1_D (Optional[Tensor]): + Rotary positional embedding tensor of shape (L, 1, 1, D). L == THW for current video training. + + Returns: + Tensor: The output tensor with applied attention, maintaining the input shape. + """ + if context is not None and self.n_views > 1: + x_T_H_W_B_D = rearrange(x, "(v t) h w b d -> t h w (v b) d", v=self.n_views) + context_M_B_D = rearrange(context, "(v m) b d -> m (v b) d", v=self.n_views) + else: + x_T_H_W_B_D = x + context_M_B_D = context + T, H, W, B, D = x_T_H_W_B_D.shape + x_THW_B_D = rearrange(x_T_H_W_B_D, "t h w b d -> (t h w) b d") + x_THW_B_D = self.attn( + x_THW_B_D, + context_M_B_D, + crossattn_mask, + rope_emb=rope_emb_L_1_1_D, + ) + x_T_H_W_B_D = rearrange(x_THW_B_D, "(t h w) b d -> t h w b d", h=H, w=W) + if context is not None and self.n_views > 1: + x_T_H_W_B_D = rearrange(x_T_H_W_B_D, "t h w (v b) d -> (v t) h w b d", v=self.n_views) + return x_T_H_W_B_D + + +def adaln_norm_state(norm_state, x, scale, shift): + normalized = norm_state(x) + return normalized * (1 + scale) + shift + + +class DITBuildingBlock(nn.Module): + """ + A building block for the DiT (Diffusion Transformer) architecture that supports different types of + attention and MLP operations with adaptive layer normalization. + + Parameters: + block_type (str): Type of block - one of: + - "cross_attn"/"ca": Cross-attention + - "full_attn"/"fa": Full self-attention + - "mlp"/"ff": MLP/feedforward block + x_dim (int): Dimension of input features + context_dim (Optional[int]): Dimension of context features for cross-attention + num_heads (int): Number of attention heads + mlp_ratio (float): MLP hidden dimension multiplier. Default: 4.0 + bias (bool): Whether to use bias in layers. Default: False + mlp_dropout (float): Dropout rate for MLP. Default: 0.0 + qkv_norm_mode (str): QKV normalization mode. Default: "per_head" + x_format (str): Input tensor format. Default: "BTHWD" + use_adaln_lora (bool): Whether to use AdaLN-LoRA. Default: False + adaln_lora_dim (int): Dimension for AdaLN-LoRA. Default: 256 + n_views (int): Extra parameter used in multi-view diffusion model. It indicated total number of view we model together. + """ + + def __init__( + self, + block_type: str, + x_dim: int, + context_dim: Optional[int], + num_heads: int, + mlp_ratio: float = 4.0, + bias: bool = False, + mlp_dropout: float = 0.0, + qkv_norm_mode: str = "per_head", + x_format: str = "BTHWD", + use_adaln_lora: bool = False, + adaln_lora_dim: int = 256, + n_views: int = 1, + ) -> None: + block_type = block_type.lower() + + super().__init__() + self.x_format = x_format + if block_type in ["cross_attn", "ca"]: + self.block = VideoAttn( + x_dim, + context_dim, + num_heads, + bias=bias, + qkv_norm_mode=qkv_norm_mode, + x_format=self.x_format, + n_views=n_views, + ) + elif block_type in ["full_attn", "fa"]: + self.block = VideoAttn( + x_dim, None, num_heads, bias=bias, qkv_norm_mode=qkv_norm_mode, x_format=self.x_format + ) + elif block_type in ["mlp", "ff"]: + self.block = GPT2FeedForward(x_dim, int(x_dim * mlp_ratio), dropout=mlp_dropout, bias=bias) + else: + raise ValueError(f"Unknown block type: {block_type}") + + self.block_type = block_type + self.use_adaln_lora = use_adaln_lora + + self.norm_state = nn.LayerNorm(x_dim, elementwise_affine=False, eps=1e-6) + self.n_adaln_chunks = 3 + if use_adaln_lora: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(x_dim, adaln_lora_dim, bias=False), + nn.Linear(adaln_lora_dim, self.n_adaln_chunks * x_dim, bias=False), + ) + else: + self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(x_dim, self.n_adaln_chunks * x_dim, bias=False)) + + def forward( + self, + x: torch.Tensor, + emb_B_D: torch.Tensor, + crossattn_emb: torch.Tensor, + crossattn_mask: Optional[torch.Tensor] = None, + rope_emb_L_1_1_D: Optional[torch.Tensor] = None, + adaln_lora_B_3D: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """ + Forward pass for dynamically configured blocks with adaptive normalization. + + Args: + x (Tensor): Input tensor of shape (B, T, H, W, D) or (T, H, W, B, D). + emb_B_D (Tensor): Embedding tensor for adaptive layer normalization modulation. + crossattn_emb (Tensor): Tensor for cross-attention blocks. + crossattn_mask (Optional[Tensor]): Optional mask for cross-attention. + rope_emb_L_1_1_D (Optional[Tensor]): + Rotary positional embedding tensor of shape (L, 1, 1, D). L == THW for current video training. + + Returns: + Tensor: The output tensor after processing through the configured block and adaptive normalization. + """ + if self.use_adaln_lora: + shift_B_D, scale_B_D, gate_B_D = (self.adaLN_modulation(emb_B_D) + adaln_lora_B_3D).chunk( + self.n_adaln_chunks, dim=1 + ) + else: + shift_B_D, scale_B_D, gate_B_D = self.adaLN_modulation(emb_B_D).chunk(self.n_adaln_chunks, dim=1) + + shift_1_1_1_B_D, scale_1_1_1_B_D, gate_1_1_1_B_D = ( + shift_B_D.unsqueeze(0).unsqueeze(0).unsqueeze(0), + scale_B_D.unsqueeze(0).unsqueeze(0).unsqueeze(0), + gate_B_D.unsqueeze(0).unsqueeze(0).unsqueeze(0), + ) + + if self.block_type in ["mlp", "ff"]: + x = x + gate_1_1_1_B_D * self.block( + adaln_norm_state(self.norm_state, x, scale_1_1_1_B_D, shift_1_1_1_B_D), + ) + elif self.block_type in ["full_attn", "fa"]: + x = x + gate_1_1_1_B_D * self.block( + adaln_norm_state(self.norm_state, x, scale_1_1_1_B_D, shift_1_1_1_B_D), + context=None, + rope_emb_L_1_1_D=rope_emb_L_1_1_D, + ) + elif self.block_type in ["cross_attn", "ca"]: + x = x + gate_1_1_1_B_D * self.block( + adaln_norm_state(self.norm_state, x, scale_1_1_1_B_D, shift_1_1_1_B_D), + context=crossattn_emb, + crossattn_mask=crossattn_mask, + rope_emb_L_1_1_D=rope_emb_L_1_1_D, + ) + else: + raise ValueError(f"Unknown block type: {self.block_type}") + + return x + + +class GeneralDITTransformerBlock(nn.Module): + """ + A wrapper module that manages a sequence of DITBuildingBlocks to form a complete transformer layer. + Each block in the sequence is specified by a block configuration string. + + Parameters: + x_dim (int): Dimension of input features + context_dim (int): Dimension of context features for cross-attention blocks + num_heads (int): Number of attention heads + block_config (str): String specifying block sequence (e.g. "ca-fa-mlp" for cross-attention, + full-attention, then MLP) + mlp_ratio (float): MLP hidden dimension multiplier. Default: 4.0 + x_format (str): Input tensor format. Default: "BTHWD" + use_adaln_lora (bool): Whether to use AdaLN-LoRA. Default: False + adaln_lora_dim (int): Dimension for AdaLN-LoRA. Default: 256 + n_views (int): Extra parameter used in multi-view diffusion model. Default: 1 + + The block_config string uses "-" to separate block types: + - "ca"/"cross_attn": Cross-attention block + - "fa"/"full_attn": Full self-attention block + - "mlp"/"ff": MLP/feedforward block + + Example: + block_config = "ca-fa-mlp" creates a sequence of: + 1. Cross-attention block + 2. Full self-attention block + 3. MLP block + """ + + def __init__( + self, + x_dim: int, + context_dim: int, + num_heads: int, + block_config: str, + mlp_ratio: float = 4.0, + x_format: str = "BTHWD", + use_adaln_lora: bool = False, + adaln_lora_dim: int = 256, + n_views: int = 1, + ): + super().__init__() + self.blocks = nn.ModuleList() + self.x_format = x_format + for block_type in block_config.split("-"): + self.blocks.append( + DITBuildingBlock( + block_type, + x_dim, + context_dim, + num_heads, + mlp_ratio, + x_format=self.x_format, + use_adaln_lora=use_adaln_lora, + adaln_lora_dim=adaln_lora_dim, + n_views=n_views, + ) + ) + + def forward( + self, + x: torch.Tensor, + emb_B_D: torch.Tensor, + crossattn_emb: torch.Tensor, + crossattn_mask: Optional[torch.Tensor] = None, + rope_emb_L_1_1_D: Optional[torch.Tensor] = None, + adaln_lora_B_3D: Optional[torch.Tensor] = None, + extra_per_block_pos_emb: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + if extra_per_block_pos_emb is not None: + x = x + extra_per_block_pos_emb + for block in self.blocks: + x = block( + x, + emb_B_D, + crossattn_emb, + crossattn_mask, + rope_emb_L_1_1_D=rope_emb_L_1_1_D, + adaln_lora_B_3D=adaln_lora_B_3D, + ) + return x diff --git a/diffusion/modules/denoiser_scaling.py b/diffusion/modules/denoiser_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fb3df0f38d52de317177c248e22707a899beb4 --- /dev/null +++ b/diffusion/modules/denoiser_scaling.py @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Tuple + +import torch + + +class EDMScaling: + def __init__(self, sigma_data: float = 0.5): + self.sigma_data = sigma_data + + def __call__(self, sigma: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + c_skip = self.sigma_data**2 / (sigma**2 + self.sigma_data**2) + c_out = sigma * self.sigma_data / (sigma**2 + self.sigma_data**2) ** 0.5 + c_in = 1 / (sigma**2 + self.sigma_data**2) ** 0.5 + c_noise = 0.25 * sigma.log() + return c_skip, c_out, c_in, c_noise diff --git a/diffusion/modules/res_sampler.py b/diffusion/modules/res_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..336ebfee74e88d5692a64d9085af8c350f55bebd --- /dev/null +++ b/diffusion/modules/res_sampler.py @@ -0,0 +1,283 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +A general framework for various sampling algorithm from a diffusion model. +Impl based on +* Refined Exponential Solver (RES) in https://arxiv.org/pdf/2308.02157 +* also clude other impl, DDIM, DEIS, DPM-Solver, EDM sampler. +Most of sampling algorihtm, Runge-Kutta, Multi-step, etc, can be impl in this framework by \ + adding new step function in get_runge_kutta_fn or get_multi_step_fn. +""" + +import math +from typing import Any, Callable, List, Literal, Optional, Tuple, Union + +import attrs +import torch + +from diffusion.functional.multi_step import get_multi_step_fn, is_multi_step_fn_supported +from diffusion.functional.runge_kutta import get_runge_kutta_fn, is_runge_kutta_fn_supported +from utils.config import make_freezable + +COMMON_SOLVER_OPTIONS = Literal["2ab", "2mid", "1euler"] + + +@make_freezable +@attrs.define(slots=False) +class SolverConfig: + is_multi: bool = False + rk: str = "2mid" + multistep: str = "2ab" + # following parameters control stochasticity, see EDM paper + # BY default, we use deterministic with no stochasticity + s_churn: float = 0.0 + s_t_max: float = float("inf") + s_t_min: float = 0.05 + s_noise: float = 1.0 + + +@make_freezable +@attrs.define(slots=False) +class SolverTimestampConfig: + nfe: int = 50 + t_min: float = 0.002 + t_max: float = 80.0 + order: float = 7.0 + is_forward: bool = False # whether generate forward or backward timestamps + + +@make_freezable +@attrs.define(slots=False) +class SamplerConfig: + solver: SolverConfig = attrs.field(factory=SolverConfig) + timestamps: SolverTimestampConfig = attrs.field(factory=SolverTimestampConfig) + sample_clean: bool = True # whether run one last step to generate clean image + + +def get_rev_ts( + t_min: float, t_max: float, num_steps: int, ts_order: Union[int, float], is_forward: bool = False +) -> torch.Tensor: + """ + Generate a sequence of reverse time steps. + + Args: + t_min (float): The minimum time value. + t_max (float): The maximum time value. + num_steps (int): The number of time steps to generate. + ts_order (Union[int, float]): The order of the time step progression. + is_forward (bool, optional): If True, returns the sequence in forward order. Defaults to False. + + Returns: + torch.Tensor: A tensor containing the generated time steps in reverse or forward order. + + Raises: + ValueError: If `t_min` is not less than `t_max`. + TypeError: If `ts_order` is not an integer or float. + """ + if t_min >= t_max: + raise ValueError("t_min must be less than t_max") + + if not isinstance(ts_order, (int, float)): + raise TypeError("ts_order must be an integer or float") + + step_indices = torch.arange(num_steps + 1, dtype=torch.float64) + time_steps = ( + t_max ** (1 / ts_order) + step_indices / num_steps * (t_min ** (1 / ts_order) - t_max ** (1 / ts_order)) + ) ** ts_order + + if is_forward: + return time_steps.flip(dims=(0,)) + + return time_steps + + +class Sampler(torch.nn.Module): + def __init__(self, cfg: Optional[SamplerConfig] = None): + super().__init__() + if cfg is None: + cfg = SamplerConfig() + self.cfg = cfg + + @torch.no_grad() + def forward( + self, + x0_fn: Callable, + x_sigma_max: torch.Tensor, + num_steps: int = 35, + sigma_min: float = 0.002, + sigma_max: float = 80, + rho: float = 7, + S_churn: float = 0, + S_min: float = 0, + S_max: float = float("inf"), + S_noise: float = 1, + solver_option: str = "2ab", + ) -> torch.Tensor: + in_dtype = x_sigma_max.dtype + + def float64_x0_fn(x_B_StateShape: torch.Tensor, t_B: torch.Tensor) -> torch.Tensor: + return x0_fn(x_B_StateShape.to(in_dtype), t_B.to(in_dtype)).to(torch.float64) + + is_multistep = is_multi_step_fn_supported(solver_option) + is_rk = is_runge_kutta_fn_supported(solver_option) + assert is_multistep or is_rk, f"Only support multistep or Runge-Kutta method, got {solver_option}" + + solver_cfg = SolverConfig( + s_churn=S_churn, + s_t_max=S_max, + s_t_min=S_min, + s_noise=S_noise, + is_multi=is_multistep, + rk=solver_option, + multistep=solver_option, + ) + timestamps_cfg = SolverTimestampConfig(nfe=num_steps, t_min=sigma_min, t_max=sigma_max, order=rho) + sampler_cfg = SamplerConfig(solver=solver_cfg, timestamps=timestamps_cfg, sample_clean=True) + + return self._forward_impl(float64_x0_fn, x_sigma_max, sampler_cfg).to(in_dtype) + + @torch.no_grad() + def _forward_impl( + self, + denoiser_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], + noisy_input_B_StateShape: torch.Tensor, + sampler_cfg: Optional[SamplerConfig] = None, + callback_fns: Optional[List[Callable]] = None, + ) -> torch.Tensor: + """ + Internal implementation of the forward pass. + + Args: + denoiser_fn: Function to denoise the input. + noisy_input_B_StateShape: Input tensor with noise. + sampler_cfg: Configuration for the sampler. + callback_fns: List of callback functions to be called during sampling. + + Returns: + torch.Tensor: Denoised output tensor. + """ + sampler_cfg = self.cfg if sampler_cfg is None else sampler_cfg + solver_order = 1 if sampler_cfg.solver.is_multi else int(sampler_cfg.solver.rk[0]) + num_timestamps = sampler_cfg.timestamps.nfe // solver_order + + sigmas_L = get_rev_ts( + sampler_cfg.timestamps.t_min, sampler_cfg.timestamps.t_max, num_timestamps, sampler_cfg.timestamps.order + ).to(noisy_input_B_StateShape.device) + + denoised_output = differential_equation_solver( + denoiser_fn, sigmas_L, sampler_cfg.solver, callback_fns=callback_fns + )(noisy_input_B_StateShape) + + if sampler_cfg.sample_clean: + # Override denoised_output with fully denoised version + ones = torch.ones(denoised_output.size(0), device=denoised_output.device, dtype=denoised_output.dtype) + denoised_output = denoiser_fn(denoised_output, sigmas_L[-1] * ones) + + return denoised_output + + +def fori_loop(lower: int, upper: int, body_fun: Callable[[int, Any], Any], init_val: Any) -> Any: + """ + Implements a for loop with a function. + + Args: + lower: Lower bound of the loop (inclusive). + upper: Upper bound of the loop (exclusive). + body_fun: Function to be applied in each iteration. + init_val: Initial value for the loop. + + Returns: + The final result after all iterations. + """ + val = init_val + for i in range(lower, upper): + val = body_fun(i, val) + return val + + +def differential_equation_solver( + x0_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], + sigmas_L: torch.Tensor, + solver_cfg: SolverConfig, + callback_fns: Optional[List[Callable]] = None, +) -> Callable[[torch.Tensor], torch.Tensor]: + """ + Creates a differential equation solver function. + + Args: + x0_fn: Function to compute x0 prediction. + sigmas_L: Tensor of sigma values with shape [L,]. + solver_cfg: Configuration for the solver. + callback_fns: Optional list of callback functions. + + Returns: + A function that solves the differential equation. + """ + num_step = len(sigmas_L) - 1 + + if solver_cfg.is_multi: + update_step_fn = get_multi_step_fn(solver_cfg.multistep) + else: + update_step_fn = get_runge_kutta_fn(solver_cfg.rk) + + eta = min(solver_cfg.s_churn / (num_step + 1), math.sqrt(1.2) - 1) + + def sample_fn(input_xT_B_StateShape: torch.Tensor) -> torch.Tensor: + """ + Samples from the differential equation. + + Args: + input_xT_B_StateShape: Input tensor with shape [B, StateShape]. + + Returns: + Output tensor with shape [B, StateShape]. + """ + ones_B = torch.ones(input_xT_B_StateShape.size(0), device=input_xT_B_StateShape.device, dtype=torch.float64) + + def step_fn( + i_th: int, state: Tuple[torch.Tensor, Optional[List[torch.Tensor]]] + ) -> Tuple[torch.Tensor, Optional[List[torch.Tensor]]]: + input_x_B_StateShape, x0_preds = state + sigma_cur_0, sigma_next_0 = sigmas_L[i_th], sigmas_L[i_th + 1] + + # algorithm 2: line 4-6 + if solver_cfg.s_t_min < sigma_cur_0 < solver_cfg.s_t_max: + hat_sigma_cur_0 = sigma_cur_0 + eta * sigma_cur_0 + input_x_B_StateShape = input_x_B_StateShape + ( + hat_sigma_cur_0**2 - sigma_cur_0**2 + ).sqrt() * solver_cfg.s_noise * torch.randn_like(input_x_B_StateShape) + sigma_cur_0 = hat_sigma_cur_0 + + if solver_cfg.is_multi: + x0_pred_B_StateShape = x0_fn(input_x_B_StateShape, sigma_cur_0 * ones_B) + output_x_B_StateShape, x0_preds = update_step_fn( + input_x_B_StateShape, sigma_cur_0 * ones_B, sigma_next_0 * ones_B, x0_pred_B_StateShape, x0_preds + ) + else: + output_x_B_StateShape, x0_preds = update_step_fn( + input_x_B_StateShape, sigma_cur_0 * ones_B, sigma_next_0 * ones_B, x0_fn + ) + + if callback_fns: + for callback_fn in callback_fns: + callback_fn(**locals()) + + return output_x_B_StateShape, x0_preds + + x_at_eps, _ = fori_loop(0, num_step, step_fn, [input_xT_B_StateShape, None]) + return x_at_eps + + return sample_fn diff --git a/diffusion/training/conditioner.py b/diffusion/training/conditioner.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e1071a4f776d78671db981dbe6eb4e6eefb12c --- /dev/null +++ b/diffusion/training/conditioner.py @@ -0,0 +1,333 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, fields +from typing import Any, Dict, Optional, Tuple, Union + +import torch +import torch.nn as nn + +from diffusion.conditioner import DataType, GeneralConditioner +from diffusion.functional.batch_ops import batch_mul +from diffusion.training.context_parallel import split_inputs_cp +from utils.misc import count_params + + +class AbstractEmbModel(nn.Module): + def __init__(self): + super().__init__() + + self._is_trainable = None + self._dropout_rate = None + self._input_key = None + self._return_dict = False + + @property + def is_trainable(self) -> bool: + return self._is_trainable + + @property + def dropout_rate(self) -> Union[float, torch.Tensor]: + return self._dropout_rate + + @property + def input_key(self) -> str: + return self._input_key + + @property + def is_return_dict(self) -> bool: + return self._return_dict + + @is_trainable.setter + def is_trainable(self, value: bool): + self._is_trainable = value + + @dropout_rate.setter + def dropout_rate(self, value: Union[float, torch.Tensor]): + self._dropout_rate = value + + @input_key.setter + def input_key(self, value: str): + self._input_key = value + + @is_return_dict.setter + def is_return_dict(self, value: bool): + self._return_dict = value + + @is_trainable.deleter + def is_trainable(self): + del self._is_trainable + + @dropout_rate.deleter + def dropout_rate(self): + del self._dropout_rate + + @input_key.deleter + def input_key(self): + del self._input_key + + @is_return_dict.deleter + def is_return_dict(self): + del self._return_dict + + def random_dropout_input( + self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None + ) -> torch.Tensor: + del key + dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate + return batch_mul( + torch.bernoulli((1.0 - dropout_rate) * torch.ones(in_tensor.shape[0])).type_as(in_tensor), + in_tensor, + ) + + def details(self) -> str: + return "" + + def summary(self) -> str: + input_key = self.input_key if self.input_key is not None else getattr(self, "input_keys", None) + return ( + f"{self.__class__.__name__} \n\tinput key: {input_key}" + f"\n\tParam count: {count_params(self, False)} \n\tTrainable: {self.is_trainable}" + f"\n\tDropout rate: {self.dropout_rate}" + f"\n\t{self.details()}" + ) + + +class TrajectoryAttr(AbstractEmbModel): + def __init__(self, traj_dim: int): + super().__init__() + self.traj_dim = traj_dim + + def forward(self, traj: torch.Tensor) -> Dict[str, torch.Tensor]: + return { + "trajectory": traj, + } + + def details(self) -> str: + return f"Traj dim : {self.traj_dim} \n\tOutput key: [trajectory]" + + +class FrameRepeatAttr(AbstractEmbModel): + def __init__(self): + super().__init__() + + def forward(self, frame_repeat: torch.Tensor) -> Dict[str, torch.Tensor]: + return { + "frame_repeat": frame_repeat / 10.0, + } + + def details(self) -> str: + return "Frame repeat, Output key: [frame_repeat]" + + +@dataclass +class BaseVideoCondition: + crossattn_emb: torch.Tensor + crossattn_mask: torch.Tensor + data_type: DataType = DataType.VIDEO + padding_mask: Optional[torch.Tensor] = None + fps: Optional[torch.Tensor] = None + num_frames: Optional[torch.Tensor] = None + image_size: Optional[torch.Tensor] = None + scalar_feature: Optional[torch.Tensor] = None + trajectory: Optional[torch.Tensor] = None + frame_repeat: Optional[torch.Tensor] = None + + def to_dict(self) -> Dict[str, Optional[torch.Tensor]]: + return {f.name: getattr(self, f.name) for f in fields(self)} + + +@dataclass +class VideoExtendCondition(BaseVideoCondition): + video_cond_bool: Optional[torch.Tensor] = None # whether or not it conditioned on video + gt_latent: Optional[torch.Tensor] = None + condition_video_indicator: Optional[torch.Tensor] = None # 1 for condition region + + # condition_video_input_mask will concat to the input of network, along channel dim; + # Will be concat with the input tensor + condition_video_input_mask: Optional[torch.Tensor] = None + # condition_video_augment_sigma: (B, T) tensor of sigma value for the conditional input augmentation, only valid when apply_corruption_to_condition_region is "noise_with_sigma" or "noise_with_sigma_fixed" + condition_video_augment_sigma: Optional[torch.Tensor] = None + # pose conditional input, will be concat with the input tensor + condition_video_pose: Optional[torch.Tensor] = None + + +@dataclass +class ViewConditionedVideoExtendCondition(VideoExtendCondition): + # view index indicating camera, used to index nn.Embedding + view_indices_B_T: Optional[torch.Tensor] = None + + +@dataclass +class VideoLatentDiffusionDecoderCondition(BaseVideoCondition): + # latent_condition will concat to the input of network, along channel dim; + # cfg will make latent_condition all zero padding. + latent_condition: Optional[torch.Tensor] = None + latent_condition_sigma: Optional[torch.Tensor] = None + + def get_condition_for_cp(self, cp_group): + self.latent_condition = split_inputs_cp(x=self.latent_condition, seq_dim=2, cp_group=cp_group) + self.latent_condition_sigma = split_inputs_cp(x=self.latent_condition_sigma, seq_dim=2, cp_group=cp_group) + + +class VideoConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> BaseVideoCondition: + output = super()._forward(batch, override_dropout_rate) + return BaseVideoCondition(**output) + + +class VideoDiffusionDecoderConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> VideoLatentDiffusionDecoderCondition: + output = super()._forward(batch, override_dropout_rate) + return VideoLatentDiffusionDecoderCondition(**output) + + +class VideoExtendConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> VideoExtendCondition: + output = super()._forward(batch, override_dropout_rate) + return VideoExtendCondition(**output) + + +class ViewConditionedVideoExtendConditioner(GeneralConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> ViewConditionedVideoExtendCondition: + output = super()._forward(batch, override_dropout_rate) + return ViewConditionedVideoExtendCondition(**output) + + +class VideoConditionerWithTraingOnlyEmb(GeneralConditioner): + def get_condition_uncondition( + self, + data_batch: Dict, + ) -> Tuple[Any, Any]: + """ + Processes the provided data batch to generate two sets of outputs: conditioned and unconditioned. This method + manipulates the dropout rates of embedders to simulate two scenarios — one where all conditions are applied + (conditioned), and one where they are removed or reduced to the minimum (unconditioned). + + This method first sets the dropout rates to zero for the conditioned scenario to fully apply the embedders' effects. + For the unconditioned scenario, it sets the dropout rates to 1 (or to 0 if the initial unconditional dropout rate + is insignificant) to minimize the embedders' influences, simulating an unconditioned generation. + + Parameters: + data_batch (Dict): The input data batch that contains all necessary information for embedding processing. The + data is expected to match the required format and keys expected by the embedders. + + Returns: + Tuple[Any, Any]: A tuple containing two condition: + - The first one contains the outputs with all embedders fully applied (conditioned outputs). + - The second one contains the outputs with embedders minimized or not applied (unconditioned outputs). + """ + cond_dropout_rates, dropout_rates = {}, {} + for emb_name, embedder in self.embedders.items(): + if isinstance(embedder, FrameRepeatAttr): + cond_dropout_rates[emb_name] = 1.0 + else: + cond_dropout_rates[emb_name] = 0.0 + dropout_rates[emb_name] = 1.0 if embedder.dropout_rate > 1e-4 else 0.0 + + condition: Any = self(data_batch, override_dropout_rate=cond_dropout_rates) + un_condition: Any = self(data_batch, override_dropout_rate=dropout_rates) + return condition, un_condition + + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> BaseVideoCondition: + output = super()._forward(batch, override_dropout_rate) + return BaseVideoCondition(**output) + + +class VideoExtendConditionerWithTraingOnlyEmb(VideoConditionerWithTraingOnlyEmb): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> VideoExtendCondition: + output = super()._forward(batch, override_dropout_rate) + return VideoExtendCondition(**output) + + +@dataclass +class BaseWithCtrlCondition(VideoExtendCondition): + control_input_canny: Optional[torch.Tensor] = None + control_input_blur: Optional[torch.Tensor] = None + control_input_canny_blur: Optional[torch.Tensor] = None + control_input_depth: Optional[torch.Tensor] = None + control_input_segmentation: Optional[torch.Tensor] = None + control_input_depth_segmentation: Optional[torch.Tensor] = None + control_input_mask: Optional[torch.Tensor] = None + control_input_human_kpts: Optional[torch.Tensor] = None + control_input_upscale: Optional[torch.Tensor] = None + control_input_identity: Optional[torch.Tensor] = None + control_input_multi: Optional[torch.Tensor] = None + base_model: Optional[torch.nn.Module] = None + hint_key: Optional[str] = None + control_weight: Optional[float] = 1.0 + num_layers_to_use: Optional[int] = -1 + + +class VideoConditionerWithCtrl(VideoExtendConditioner): + def forward( + self, + batch: Dict, + override_dropout_rate: Optional[Dict[str, float]] = None, + ) -> BaseWithCtrlCondition: + output = super()._forward(batch, override_dropout_rate) + output["hint_key"] = batch["hint_key"] + if "control_weight" in batch: + output["control_weight"] = batch["control_weight"] + if "num_layers_to_use" in batch: + output["num_layers_to_use"] = batch["num_layers_to_use"] + return BaseWithCtrlCondition(**output) + + +class BooleanFlag(AbstractEmbModel): + def __init__(self, output_key: Optional[str] = None): + super().__init__() + self.output_key = output_key + + def forward(self, *args, **kwargs) -> Dict[str, torch.Tensor]: + del args, kwargs + key = self.output_key if self.output_key else self.input_key + return {key: self.flag} + + def random_dropout_input( + self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None + ) -> torch.Tensor: + del key + dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate + self.flag = torch.bernoulli((1.0 - dropout_rate) * torch.ones(1)).bool().to(device=in_tensor.device) + return in_tensor + + def details(self) -> str: + key = self.output_key if self.output_key else self.input_key + return f"Output key: {key} \n\t This is a boolean flag" diff --git a/diffusion/training/config/base/ema.py b/diffusion/training/config/base/ema.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1800305cc2b3a5f5c0037b59a316d74d03a2e4 --- /dev/null +++ b/diffusion/training/config/base/ema.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from utils.ema import EMAModelTracker, PowerEMATracker +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + +PowerEMAConfig: LazyDict = L(PowerEMATracker.initialize_multi_rank_ema)( + model=PLACEHOLDER, enabled=True, rate=0.10, num=3 +) + +RegEMAConfig: LazyDict = L(EMAModelTracker.initialize_multi_rank_ema)( + model=PLACEHOLDER, enabled=True, rate=0.999, num=1 +) diff --git a/diffusion/training/config/base/lidarverse_vae.py b/diffusion/training/config/base/lidarverse_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..48186e3d3cea89a5309c8ff8ac069b11646c7ca1 --- /dev/null +++ b/diffusion/training/config/base/lidarverse_vae.py @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Released LidarVerse tokenizer wrapper for diffusion training/inference.""" + +import os + +import omegaconf + +from diffusion.training.module.pretrained_vae_base import ConfigBasedVideoVAE +from utils.lazy_config import LazyCall as L + + +def get_lidarverse_tokenizer( + resolution: str = "native", + chunk_duration: int = 21, +) -> omegaconf.dictconfig.DictConfig: + del resolution, chunk_duration + return L(ConfigBasedVideoVAE)( + experiment_name=( + "transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_" + "nuscenes32_gridrope_mask_pts_scratch_200k" + ), + checkpoint_path=os.environ.get( + "LIDARVERSE_TOKENIZER_CHECKPOINT", + "checkpoints/lidarverse-tokenizer/ckpt.pt", + ), + mean_std_fp=os.environ.get( + "LIDARVERSE_TOKENIZER_LATENT_STATS", + "checkpoints/lidarverse-tokenizer/latent_stats.pt", + ), + latent_ch=64, + is_bf16=False, + spatial_compression=8, + apply_validity_mask=True, + # The public checkpoint has EMA weights materialized as network.*. + use_ema=False, + ) diff --git a/diffusion/training/config/base/model.py b/diffusion/training/config/base/model.py new file mode 100644 index 0000000000000000000000000000000000000000..73eb85232e4f6bfb2d12c8788d11975c11dfac8e --- /dev/null +++ b/diffusion/training/config/base/model.py @@ -0,0 +1,457 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List, Optional + +import attrs + +from diffusion.training.config.base.ema import PowerEMAConfig +from diffusion.training.modules.edm_sde import EDMSDE +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +@attrs.define(slots=False) +class FSDPConfig: + policy: str = "block" + checkpoint: bool = False + min_num_params: int = 1024 + sharding_group_size: int = 8 + sharding_strategy: str = "full" + use_orig_params: bool = False + + +@attrs.define(slots=False) +class DefaultModelConfig: + vae: LazyDict = None + conditioner: LazyDict = None + net: LazyDict = None + ema: LazyDict = PowerEMAConfig + sde: LazyDict = L(EDMSDE)( + p_mean=0.0, + p_std=1.0, + sigma_max=80, + sigma_min=0.0002, + ) + sigma_data: float = 0.5 + camera_sample_weight: LazyDict = LazyDict( + dict( + enabled=False, + weight=5.0, + ) + ) + aesthetic_finetuning: LazyDict = LazyDict( + dict( + enabled=False, + ) + ) + loss_mask_enabled: bool = False + loss_masking: LazyDict = None + loss_add_logvar: bool = True + precision: str = "bfloat16" + input_data_key: str = "video" # key to fetch input data from data_batch + input_image_key: str = "images_1024" # key to fetch input image from data_batch + loss_reduce: str = "sum" + loss_scale: float = 1.0 + latent_shape: List[int] = [16, 24, 44, 80] # 24 corresponig to 136 frames + fsdp_enabled: bool = False + use_torch_compile: bool = False + fsdp: FSDPConfig = attrs.field(factory=FSDPConfig) + use_dummy_temporal_dim: bool = False # Whether to use dummy temporal dimension in data + adjust_video_noise: bool = False # whether or not adjust video noise accroding to the video length + peft_control: LazyDict | None = None + num_latents_to_drop: int = 0 # number of P-latents to discard after encoding + + +@attrs.define(slots=False) +class MultiviewModelConfig(DefaultModelConfig): + n_views: int = 6 + + +@attrs.define(slots=False) +class LidarModelConfig(DefaultModelConfig): + # Optional second tokenizer for an aligned per-return LiDAR attribute. + # The primary VAE continues to encode range and HDMap inputs; when present, + # this VAE encodes only the intensity channel. + intensity_vae: LazyDict = None + n_views: int = 4 + rgb_latent_shape: List[int] = [88, 160] + lidar_latent_shape: List[int] = [64, 224] + rgb_shape: List[int] = [704, 1280] + lidar_shape: List[int] = [512, 1792] + # Image-conditioned mininet RF (ImageToLidarMininetRectifiedFlowModel): + # number of RGB conditioning views temporal-concatenated onto the lidar + # latent, their dataset view keys, and the RGB image-VAE latent channel + # count (zero-padded up to the lidar latent ch before the temporal stack). + n_rgb_views: int = 0 + rgb_view_keys: List[int] = attrs.field(factory=list) + image_latent_ch: int = 16 + # Classifier-free guidance on the RGB condition: per-sample probability of + # zeroing ALL RGB condition frames during training (learns the RGB- + # unconditional branch). 0.0 = always conditional (no image CFG). + rgb_dropout_prob: float = 0.0 + # VIDEO image-conditioned mininet RF (VideoImageToLidarMininetRectifiedFlowModel): + # per-frame counts on the joint temporal axis, RGB pixel-time stride (RGB + # temporal compression / lidar temporal compression), RGB input resize + # (HxW) before the Wan encode, and the per-sample probability of dropping a + # random suffix of RGB future frames (lidar extrapolation training). + lidar_latent_t: int = 1 + rgb_latent_t: int = 1 + rgb_temporal_stride: int = 4 + rgb_resize_hw: List[int] = attrs.field(factory=lambda: [256, 448]) + # Encode each RGB frame as an independent T=1 clip (no VAE temporal + # compression) -> Tr == #RGB input frames -> 1:1 with lidar frames. + rgb_per_frame_encode: bool = False + # Prepend a duplicate of RGB latent frame 0 per view (mirrors the lidar VAE + # frame-0 prepend) -> Tr+1 RGB frames matching lidar Tl, exact 1:1 RoPE + # pixel-time alignment (no off-by-one). + rgb_prepend_first_frame: bool = False + # PV-VAE-style RGB future-frame dropping (mirrors the lidar VAE's + # frame_drop_{prob,min_latent,max_latent}): with prob ``future_frame_drop_prob`` + # drop the trailing ``k ~ U[min, max]`` RGB latent frames (same cut across + # views). ``max < 0`` => Tr-1 (keep only the first frame); ``min=0`` => + # sometimes keep all. 0 prob = no future-frame dropping. + future_frame_drop_prob: float = 0.0 + future_frame_drop_min: int = 0 + future_frame_drop_max: int = -1 + # Cross-attn RGB conditioning: spatial avg-pool factor applied to the RGB + # latent HxW before tokenizing into image-context K/V (keeps h/w structure, + # trims token count). 1 = no pooling. + rgb_context_pool: int = 1 + hdmap_channels: int = 0 + additional_concat_ch: int = 0 + skip_hdmap_proj: bool = False + encode_hdmap_with_vae: bool = False + # BEV-native hdmap conditioning: pool the multi-channel BEV hdmap raster + # (one channel per semantic class, solid box footprints) down to the latent + # grid with a learnable conv encoder and channel-concat it. Mutually + # exclusive with encode_hdmap_with_vae / skip_hdmap_proj. + bev_hdmap_pool: bool = False + bev_hdmap_channels: int = 7 + bev_hdmap_size: int = 256 + bev_hdmap_out_size: int = 32 + bev_hdmap_base_channels: int = 64 + # BEV-native hdmap conditioning via a FROZEN pretrained Wan2.2 RGB VAE: + # render the BEV raster to a 3-ch image and encode it (16x spatial, z=48), + # then channel-concat that latent (no learnable projection). Mutually + # exclusive with bev_hdmap_pool / encode_hdmap_with_vae / skip_hdmap_proj. + # ``bev_hdmap_render_mode``: "colored" (per-class palette) or "occupancy". + bev_hdmap_wan_encode: bool = False + bev_hdmap_wan_ckpt: str = "checkpoints/wan_vae_pretrained/Wan2.2_VAE.pth" + bev_hdmap_render_mode: str = "colored" + hdmap_dropout_prob: float = 0.0 + # Mixture of training-time hdmap dropout regimes. When dropout fires for + # a sample (prob = hdmap_dropout_prob), one mode from this list is drawn + # uniformly: + # "full" -- zero the entire hdmap latent (CFG-style) + # "frame_bernoulli" -- independently zero each frame at + # hdmap_frame_dropout_rate + # "keep_first_k" -- zero all frames except the first + # hdmap_keep_first_k frames + # Default = ("full",) preserves the legacy CFG-only behavior, so all + # pre-existing configs train exactly as before. Only video-mode hdmap + # latents (5-D, with a temporal axis) honor frame-wise modes; image-mode + # latents (4-D, T=1) fall back to "full" silently. + hdmap_dropout_modes: List[str] = attrs.field(factory=lambda: ["full"]) + hdmap_frame_dropout_rate: float = 0.5 + hdmap_keep_first_k: int = 1 + # ArtiFixer stage-2 conditioning dropout. One decision is shared across the + # batch: with probability ``hdmap_dropout_prob`` drop every latent frame; + # otherwise retain a uniformly sampled non-empty prefix. This is applied in + # latent space because LiDAR HDMap conditioning has no separate opacity mask. + hdmap_artifixer_dropout: bool = False + shift: float = 1.0 + # LTX training stretch (Fig. 10): map shifted-t percentiles (0.5, 99.9) to [0,1]. + # None = shift only (legacy). Not the same as inference ``enable_shift_stretch``. + shift_clamp_percentiles: Optional[tuple] = None + # LTX stretch (inference only): remap schedule clean end to this t (e.g. 0.1). + enable_shift_stretch: bool = False + shift_stretch_terminal: float = 0.1 + train_time_distribution: str = "uniform" + train_time_weight: str = "uniform" + # RF prediction parameterization. "velocity" (default, legacy): the net + # regresses the flow velocity v = noise - clean. "clean": the net regresses + # the clean latent x0 directly (VGGT-World z-prediction); the sampler + # converts x0_hat -> velocity via v = (x_t - x0_hat)/sigma. Loss is then a + # clean-target MSE ||x0_hat - x0||^2 (uniform-weighted, VGGT eq. 12 style). + rf_prediction_type: str = "velocity" + # Paired single-frame autoregressive baselines. Sensor2Sensor concatenates + # one previous-frame latent; LaGen-SDE concatenates previous, foreground, + # and background latents and FiLM-modulates the previous latent by the + # relative ego pose. + autoregressive_condition_count: int = 0 + autoregressive_pose_film: bool = False + autoregressive_pose_film_hidden_channels: int = 256 + autoregressive_noise_modulation_max: float = 0.0 + autoregressive_ego_action_only: bool = False + autoregressive_geometry_root_path: str = "" + autoregressive_geometry_filter_list: str = "" + autoregressive_min_range: float = 2.5 + autoregressive_max_range: float = 75.0 + autoregressive_min_value: float = -1.0 + autoregressive_inverse_depth: bool = False + # Blockwise Diffusion Forcing (HDMap->LiDAR or forecast RF). A positive + # block size samples one independent RF time per temporal block and pairs it + # with a block-causal DiT mask of the same size. Zero preserves the legacy single + # time per full clip. The current 8-frame Waymo recipe has latent T=9 + # (prepend + 8 real frames), so block_size=3 gives three causal blocks. + diffusion_forcing_block_size: int = 0 + # Match ArtiFixer's stage-2 Diffusion Forcing time sampler and weighting: + # 1000 discrete uniform base-sigma levels, shift-only reparameterization, + # and the reference bell-shaped per-timestep loss weights. + diffusion_forcing_artifixer_matching: bool = False + # Causal teacher-forcing variants optimize only the denoiser, replay clean + # prefix K/V, and optionally rescale the RF objective. + optimizer_net_only: bool = False + teacher_forcing_prefix_frames: int = 0 + teacher_forcing_detach_clean_kv: bool = False + teacher_forcing_loss_scale: float = 1.0 + # Imaginaire causal-training mixture over the number of leading clean + # latent frames. Dedicated Imaginaire models supply their reference + # defaults when these lists are empty; other model classes ignore them. + imaginaire_conditioned_prefix_frames: List[int] = attrs.field( + factory=list + ) + imaginaire_conditioned_prefix_probs: List[float] = attrs.field( + factory=list + ) + # Existing LiDAR video datasets prepend a duplicate of frame 0 before VAE + # encoding. Imaginaire-style training instead consumes unique frames and + # treats the actual frame 0 as its singleton temporal prefix. + input_video_has_prepend: bool = True + # Optional second geometry condition for block-causal HDMap->LiDAR RF. + # The dataloader accumulates only lidar sweeps from blocks preceding each + # target block, renders them at each target pose, and the model encodes the + # resulting range video with the frozen lidar VAE. The latent enters through + # the network's zero-initialized side patch projection; False is a no-op. + blockwise_warped_history_condition: bool = False + # Concatenate the VAE-encoded geometry after the LiDAR and HDMap slots + # instead of using the side patch projection. This is opt-in so faithful + # ArtiFixer and Imaginaire recipes keep their upstream architecture. + blockwise_warped_history_concat: bool = False + # Source of the blockwise warped-history range video. "dataloader" keeps + # the legacy worker-side NumPy all-history union. "torch_spatial_map" + # constructs a causal per-sample TorchSpatialPointMap on the training device. + blockwise_warped_history_backend: str = "dataloader" + blockwise_spatial_map_radius_m: float = 75.0 + blockwise_spatial_map_voxel_m: float = 0.2 + blockwise_spatial_map_voxel_policy: str = "newest" + # "frame" counts distinct frame hits inside each committed block; map + # visibility and candidate expiry remain block-boundary operations. + blockwise_spatial_map_observation_unit: str = "block" + blockwise_spatial_map_static_min_observations: int = 2 + blockwise_spatial_map_candidate_ttl_updates: int = 1 + blockwise_spatial_map_include_latest: bool = True + # Per-global-microstep chance of rebuilding the training map from one + # detached terminal-sigma Euler prediction instead of ground-truth sweeps. + # The decision is synchronized because this path adds an FSDP forward. + blockwise_spatial_map_self_prediction_prob: float = 0.0 + blockwise_spatial_map_free_space_clear: bool = False + blockwise_spatial_map_free_space_margin_m: float = 0.75 + blockwise_spatial_map_free_space_misses_to_remove: int = 2 + blockwise_spatial_map_geometry_root_path: str = "" + blockwise_spatial_map_geometry_filter_list_path: str = "" + blockwise_spatial_map_geometry_resample_width: int = -1 + blockwise_spatial_map_min_range: float = 2.5 + blockwise_spatial_map_max_range: float = 75.0 + blockwise_spatial_map_min_value: float = -1.0 + blockwise_spatial_map_inverse_depth: bool = False + # Replace the Gaussian RF endpoint with a confidence-weighted soft + # geometry proposal. Its confidence-composited range render also enters + # through the DiT side projection. + blockwise_geometry_source: bool = False + blockwise_geometry_source_noise_floor: float = 0.2 + # Composite uncertain projected pixels against empty range before the + # nonlinear VAE encode. Latent confidence/noise blending still applies. + blockwise_geometry_source_preencode_confidence: bool = False + blockwise_geometry_source_dropout_prob: float = 0.0 + blockwise_geometry_source_density_kernel: int = 5 + blockwise_geometry_source_density_saturation_hits: float = 5.0 + # Isolated Stage-2 multi-task conditioning experiment. One mode is sampled + # for the full distributed step so every rank follows the same model path. + stage2_multitask_modes: List[str] = attrs.field(factory=list) + stage2_multitask_probs: List[float] = attrs.field(factory=list) + stage2_multitask_sampling: str = "categorical" + stage2_multitask_known_mask_concat: bool = False + stage2_multitask_forecast_observed_frames: int = 6 + stage2_multitask_resim_known_min_per_block: int = 1 + stage2_multitask_resim_known_max_per_block: int = 2 + stage2_multitask_resim_drop_block_prob: float = 0.1 + stage2_multitask_world_hdmap_dropout_prob: float = 0.1 + stage2_multitask_hdmap_bbox_channel_start: int = 4 + # Factorized Stage-2 conditioning. Prefix length, HDMap form, and geometry + # provenance are sampled without task labels or task embeddings. + stage2_known_mask_concat: bool = False + stage2_factorized_prefix_frames: List[int] = attrs.field(factory=list) + stage2_factorized_prefix_probs: List[float] = attrs.field(factory=list) + stage2_factorized_hdmap_modes: List[str] = attrs.field(factory=list) + stage2_factorized_hdmap_probs: List[float] = attrs.field(factory=list) + stage2_factorized_geometry_modes_k0: List[str] = attrs.field(factory=list) + stage2_factorized_geometry_probs_k0: List[float] = attrs.field( + factory=list + ) + stage2_factorized_geometry_modes_known: List[str] = attrs.field( + factory=list + ) + stage2_factorized_geometry_probs_known: List[float] = attrs.field( + factory=list + ) + factorized_geometry_block_size: int = 4 + factorized_geometry_prefix_frames: int = 1 + # Deskew source sweeps before factorized geometry accumulation and + # re-skew each rendered condition into the target sweep convention. + factorized_geometry_rolling_shutter: bool = False + # ``frame`` preserves the legacy one-box-pose-per-sweep behavior. + # The other modes interpolate adjacent actor boxes by approximate ray time. + factorized_geometry_actor_box_time_mode: str = "frame" + # When enabled, frozen geometry samples its own observed-prefix length G + # instead of reusing the clean-latent prefix length K. + factorized_decouple_geometry_observations: bool = False + factorized_geometry_observation_frames: List[int] = attrs.field( + factory=list + ) + factorized_geometry_observation_probs: List[float] = attrs.field( + factory=list + ) + factorized_force_geometry_observations: int = -1 + factorized_bidirectional_stage1: bool = False + stage2_factorized_hdmap_bbox_channel_start: int = 4 + stage2_factorized_force_prefix_k: int = -1 + stage2_factorized_force_hdmap_mode: str = "" + stage2_factorized_force_geometry_mode: str = "" + # Teacher-forcing discrete consistency distillation. The frozen teacher is + # the causal Stage-2 network; earlier blocks are replayed as clean context + # while one selected block follows an adjacent shifted RF ladder interval. + tfdcm_total_steps: int = 48 + tfdcm_skipping_interval_steps: int = 1 + tfdcm_timestep_shift: float = 5.0 + tfdcm_teacher_guidance: float = 1.0 + tfdcm_teacher_checkpoint: str = "" + tfdcm_loss_scale: float = 100.0 + # Self-Forcing DMD (HDMap->LiDAR DF only). Defaults keep every existing + # experiment unchanged; the dedicated SF-DMD model validates/populates all + # fields before use. + sfdmd_num_real_frames: int = 41 + sfdmd_window_frames: int = 8 + sfdmd_fake_updates_per_cycle: int = 5 + sfdmd_kv_cache_frames: int = 6 + # Optional permanent prefix retained when the bounded DiT K/V cache rolls. + # ArtiFixer's three-frame adaptation uses sink3 + recent3 as persistent + # history, then appends the current three-frame query for nine total frames. + sfdmd_kv_sink_frames: int = 0 + # Number of generated three-frame blocks linked by autograd during student + # replay before cached K/V is detached (truncated BPTT). + sfdmd_tbptt_blocks: int = 1 + # Keep canonical ArtiFixer on full-rollout BPTT unless an isolated, + # memory-bounded handoff explicitly opts into truncation. + sfdmd_allow_truncated_bptt: bool = False + sfdmd_kv_equivalence_atol: float = 2.0e-2 + sfdmd_run_kv_equivalence_gate: bool = True + # Skip bias-free text cross-attention only after a runtime assertion that + # the supplied text embedding is exactly zero. + sfdmd_skip_zero_crossattn: bool = False + sfdmd_stream_condition_vae_encode: bool = False + sfdmd_condition_vae_cache_frames: int = 6 + sfdmd_accumulated_geometry_warp: bool = False + sfdmd_geometry_source: bool = False + sfdmd_geometry_source_noise_floor: float = 0.1 + sfdmd_geometry_source_preencode_confidence: bool = False + sfdmd_geometry_source_density_kernel: int = 5 + sfdmd_geometry_source_density_saturation_hits: float = 5.0 + sfdmd_spatial_map_radius_m: float = 75.0 + sfdmd_spatial_map_voxel_m: float = 0.2 + sfdmd_spatial_map_voxel_policy: str = "newest" + # Kept separate so Stage 4 must explicitly match its input checkpoint. + sfdmd_spatial_map_observation_unit: str = "block" + sfdmd_spatial_map_static_min_observations: int = 2 + sfdmd_spatial_map_candidate_ttl_updates: int = 1 + sfdmd_spatial_map_include_latest: bool = True + sfdmd_spatial_map_free_space_clear: bool = False + sfdmd_spatial_map_free_space_margin_m: float = 0.75 + sfdmd_spatial_map_free_space_misses_to_remove: int = 2 + sfdmd_num_steps: int = 4 + sfdmd_sde_eta: float = 1.0 + # ArtiFixer-compatible DMD mode: randomly select one denoising exit step, + # use fresh-noise SDE transitions, train one full-rollout critic update per + # iteration, and update the student every ``student_update_freq`` iterations. + sfdmd_artifixer_matching: bool = False + sfdmd_imaginaire_matching: bool = False + sfdmd_clean_x0_kv_commit: bool = False + # Preserve the task-free Stage-2 prefix/HDMap/geometry distribution during + # ArtiFixer-style self-forcing rollouts. + sfdmd_factorized_conditioning: bool = False + # Training-only controls for isolating temporal and spatial self-forcing. + # Existing experiments retain generated history by default. + sfdmd_temporal_history_source: str = "generated" + sfdmd_geometry_history_source: str = "generated" + sfdmd_temporal_prefix_frames: int = 0 + sfdmd_student_update_freq: int = 5 + sfdmd_ema_start_cycle: int = 0 + sfdmd_teacher_guidance: float = 1.0 + sfdmd_critic_min_sigma: float = 0.02 + sfdmd_critic_max_sigma: float = 0.98 + sfdmd_max_grad_norm: float = 1.0 + sfdmd_teacher_checkpoint: str = "" + sfdmd_teacher_net: LazyDict | None = None + sfdmd_geometry_root_path: str = "" + sfdmd_geometry_filter_list_path: str = "" + sfdmd_geometry_resample_width: int = -1 + sfdmd_min_range: float = 2.5 + sfdmd_max_range: float = 75.0 + sfdmd_min_value: float = -1.0 + sfdmd_inverse_depth: bool = False + # ---- lidar point-cloud forecasting (LidarForecastRectifiedFlowModel) ---- + # Number of clean PAST context frames in a forecasting clip (the remaining + # sample_n_frames - n_past frames are the FUTURE frames to predict). Only + # consumed by the forecasting model; harmless default for other configs. + n_past: int = 0 + # Per-sample prob of dropping (zeroing) the ego-pose conditioning during + # training so the model learns a pose-unconditional branch -> pose CFG. + pose_dropout_prob: float = 0.0 + # Per-sample prob of "history dropout": hide the k OLDEST past frames + # (structured prefix drop, k~U{1..n_past-1}) by zeroing their latent content + # + pose (mask stays 1 = "present but empty context"). Teaches the generative + # forecaster to work with less history than a deterministic model needs. + history_dropout_prob: float = 0.0 + # Forecasting only: Vista-style anchor concat. When True, broadcast the clean + # most-recent past (t=0) latent across all T frames and channel-concat it to + # the noised input (requires net.in_channels = 2*latent_ch). Gives future + # frames a direct input-level view of the anchor instead of relying purely on + # temporal attention. Default False -> existing configs unchanged. + anchor_concat: bool = False + # Forecasting only: replace the broadcast anchor with a per-frame latent + # encoded from observed lidar sweeps warped into each target ego pose. + # Shares the same extra latent_ch input slot as anchor_concat. + warped_history_concat: bool = False + # Dataloader rasterization mode for warped_history_concat. + # "latest" uses only the newest observed sweep; "all" z-buffers all past. + warped_history_mode: str = "all" + # Whether to also use the legacy flattened-SE(3) ego_pose_head. Geometry-only + # conditioning sets this False and net.ego_pose_dim=0. + use_pose_condition: bool = True + # Forecasting DF only: route the VAE-encoded observed-history warp through + # the block-causal checkpoint's independently projected side condition. + warped_history_side_condition: bool = False + # Forecasting DF only: append this many always-zero channels in the legacy + # HDMap concat slot, preserving the warm-start x_embedder shape while the + # lidar-only warp enters through the side projection. + forecast_null_concat_channels: int = 0 + # Selects the prefix-aware block-causal forecast model in inference tools. + forecast_diffusion_forcing: bool = False + # Forecasting only: Vista-style anchor CFG. Per-sample prob of dropping + # (zeroing) the anchor concat during training so it becomes a CFG target + # (uncond pass zeros the concat). 0.0 -> anchor is always-on context (no + # anchor CFG). Vista uses 0.15. + anchor_dropout_prob: float = 0.0 diff --git a/diffusion/training/config/base/optim.py b/diffusion/training/config/base/optim.py new file mode 100644 index 0000000000000000000000000000000000000000..088834ad62868413d5ffb997f20a896a7b6841bb --- /dev/null +++ b/diffusion/training/config/base/optim.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from diffusion.training.functional.lr_scheduler import LambdaLinearScheduler +from diffusion.training.utils.optim_instantiate import get_base_optimizer +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + +FusedAdamWConfig: LazyDict = L(get_base_optimizer)( + model=PLACEHOLDER, + lr=1e-4, + weight_decay=0.3, + betas=[0.9, 0.999], + optim_type="fusedadam", + eps=1e-8, + sharding=False, + master_weights=True, + capturable=True, +) + +LambdaLinearSchedulerConfig: LazyDict = L(LambdaLinearScheduler)( + warm_up_steps=[1000], + cycle_lengths=[10000000000000], + f_start=[1.0e-6], + f_max=[1.0], + f_min=[1.0], +) diff --git a/diffusion/training/config/config_lidar.py b/diffusion/training/config/config_lidar.py new file mode 100644 index 0000000000000000000000000000000000000000..b88a20e9ca86c9f2548eb94f2ea66af0a2827748 --- /dev/null +++ b/diffusion/training/config/config_lidar.py @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# SPDX-License-Identifier: Apache-2.0 + +"""Minimal configuration entry point for public LidarVerse experiments.""" + +import importlib +from typing import Any, List + +import attrs + +from diffusion.training.config.base.model import LidarModelConfig +from diffusion.training.config.text2world.registry import ( + register_configs as register_configs_text2world, +) +from diffusion.training.models.model import DiffusionModel +from diffusion.training.trainer import Trainer +from utils import config +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +@attrs.define(slots=False) +class Config(config.Config): + defaults: List[Any] = attrs.field( + factory=lambda: [ + "_self_", + {"data_train": None}, + {"data_val": None}, + {"optimizer": "fusedadamw"}, + {"scheduler": "lambdalinear"}, + {"callbacks": None}, + {"net": "mininet_2b"}, + {"conditioner": "add_fps_image_size_padding_mask"}, + {"fsdp": None}, + {"ema": "power"}, + {"vae": "lidarverse_tokenizer"}, + {"checkpoint": "local"}, + {"ckpt_klass": "fsdp"}, + {"experiment": None}, + ] + ) + model_obj: LazyDict = L(DiffusionModel)(config=PLACEHOLDER) + optimizer_fake: LazyDict | None = None + scheduler_fake: LazyDict | None = None + + +_PUBLIC_EXPERIMENT_MODULE = ( + "diffusion.training.config.text2world_hdmaptolidar." + "experiment_lidarverse" +) +_PUBLIC_EXPERIMENTS = { + "lidarverse_stage1_bidir_21f", + "lidarverse_stage2_causal_9f", + "lidarverse_stage3_sfdmd_9f", + "lidarverse_pai_stage1_finetune", + "lidarverse_pai_stage2_finetune", + "lidarverse_pai_stage3_finetune", +} + + +def _register_lidarverse_experiments() -> None: + from hydra.core.config_store import ConfigStore + + importlib.import_module(_PUBLIC_EXPERIMENT_MODULE).register_experiments( + ConfigStore.instance() + ) + importlib.import_module( + "diffusion.training.config.text2world_hdmaptolidar.experiment_pai_release" + ).register_experiments(ConfigStore.instance()) + + +def make_config(experiment_name: str | None = None): + if experiment_name is not None and experiment_name not in _PUBLIC_EXPERIMENTS: + raise ValueError( + f"unknown public LidarVerse experiment {experiment_name!r}; " + f"choose one of {sorted(_PUBLIC_EXPERIMENTS)}" + ) + + c = Config( + model=LidarModelConfig(), + optimizer=None, + scheduler=None, + dataloader_train=None, + dataloader_val=None, + ) + c.job.project = "lidarverse" + c.job.group = "training" + c.job.name = "delete_${now:%Y-%m-%d}_${now:%H-%M-%S}" + c.trainer.type = Trainer + c.trainer.max_iter = 400_000 + c.trainer.logging_iter = 10 + c.trainer.validation_iter = 100 + c.trainer.run_validation = False + c.trainer.callbacks = None + c.checkpoint = None + + register_configs_text2world() + _register_lidarverse_experiments() + return c diff --git a/diffusion/training/config/text2world/registry.py b/diffusion/training/config/text2world/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..d6490a798d4f6f10df9d5b52805d712767e7cc06 --- /dev/null +++ b/diffusion/training/config/text2world/registry.py @@ -0,0 +1,136 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# SPDX-License-Identifier: Apache-2.0 + +"""Minimal shared Hydra registry for LidarVerse diffusion models.""" + +from copy import deepcopy +from typing import Dict + +from hydra.core.config_store import ConfigStore + +from diffusion.checkpointers.ema_fsdp_checkpointer import ( + CheckpointConfig, + FSDPCheckpointer, +) +from diffusion.config.base.conditioner import ( + FPSConfig, + ImageSizeConfig, + NumFramesConfig, + PaddingMaskConfig, + TextConfig, +) +from diffusion.training.conditioner import VideoConditioner +from diffusion.training.config.base.lidarverse_vae import ( + get_lidarverse_tokenizer, +) +from diffusion.training.config.base.optim import ( + FusedAdamWConfig, + LambdaLinearSchedulerConfig, +) +from diffusion.training.networks.lvg_dit import LVGDiTForLidar +from diffusion.training.networks.minimal_v4_dit import SACConfig +from utils.ema import PowerEMATracker +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +FSDP_CHECKPOINTER: Dict[str, str] = L(FSDPCheckpointer)() + +VideoConditionerFpsSizePaddingConfig: LazyDict = L(VideoConditioner)( + text=TextConfig(), + fps=FPSConfig(), + num_frames=NumFramesConfig(), + image_size=ImageSizeConfig(), + padding_mask=PaddingMaskConfig(), +) + +MININET_2B_Config: LazyDict = L(LVGDiTForLidar)( + max_img_h=240, + max_img_w=240, + max_frames=128, + in_channels=16, + out_channels=16, + patch_spatial=2, + patch_temporal=1, + model_channels=2048, + num_blocks=28, + num_heads=16, + concat_padding_mask=True, + pos_emb_cls="rope3d", + pos_emb_learnable=True, + pos_emb_interpolation="crop", + use_adaln_lora=True, + adaln_lora_dim=256, + atten_backend="minimal_a2a", + extra_per_block_abs_pos_emb=False, + rope_h_extrapolation_ratio=1.0, + rope_w_extrapolation_ratio=1.0, + rope_t_extrapolation_ratio=1.0, + sac_config=L(SACConfig)(), +) + +PowerEMAConfig: LazyDict = L(PowerEMATracker.initialize_multi_rank_ema)( + model=PLACEHOLDER, + enabled=True, + rate=0.10, + num=3, +) + + +def register_configs() -> None: + cs = ConfigStore.instance() + cs.store( + group="optimizer", + package="optimizer", + name="fusedadamw", + node=FusedAdamWConfig, + ) + cs.store( + group="scheduler", + package="scheduler", + name="lambdalinear", + node=LambdaLinearSchedulerConfig, + ) + cs.store( + group="net", + package="model.net", + name="mininet_2b", + node=deepcopy(MININET_2B_Config), + ) + cs.store( + group="conditioner", + package="model.conditioner", + name="add_fps_image_size_padding_mask", + node=VideoConditionerFpsSizePaddingConfig, + ) + cs.store( + group="vae", + package="model.vae", + name="lidarverse_tokenizer", + node=get_lidarverse_tokenizer(), + ) + cs.store( + group="ema", + package="model.ema", + name="power", + node=PowerEMAConfig, + ) + cs.store( + group="checkpoint", + package="checkpoint", + name="local", + node=CheckpointConfig( + save_iter=1000, + load_path="", + load_training_state=False, + strict_resume=True, + ), + ) + cs.store( + group="ckpt_klass", + package="checkpoint.type", + name="fsdp", + node=FSDP_CHECKPOINTER, + ) + diff --git a/diffusion/training/config/text2world_hdmaptolidar/__init__.py b/diffusion/training/config/text2world_hdmaptolidar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/diffusion/training/config/text2world_hdmaptolidar/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/diffusion/training/config/text2world_hdmaptolidar/experiment_lidarverse.py b/diffusion/training/config/text2world_hdmaptolidar/experiment_lidarverse.py new file mode 100644 index 0000000000000000000000000000000000000000..5d7faa4360c5bb63eca4fadba2583b074c6ec6ef --- /dev/null +++ b/diffusion/training/config/text2world_hdmaptolidar/experiment_lidarverse.py @@ -0,0 +1,495 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Public LidarVerse training recipes. + +Stage 1 starts directly from an adapted Cosmos-Predict2 2B checkpoint. Stage 2 +trains the causal four-frame student with teacher forcing, and Stage 3 applies +self-forcing distribution matching on nine-frame self-rollouts. +""" + +from copy import deepcopy +import os + +from hydra.core.config_store import ConfigStore + +from diffusion.training.config.base.optim import ( + FusedAdamWConfig, + LambdaLinearSchedulerConfig, +) +from diffusion.training.config.text2world.registry import MININET_2B_Config +from diffusion.training.datasets.lidar_dataset.hdmaptolidar_dataloader import ( + CrossDatasetHdmapLidarDataset, + HomogeneousMultiHdmapDataLoader, +) +from diffusion.training.models.hdmaptolidar_model_rf import ( + FSDPHdmapToLidarFactorizedBidirectionalRFModel, + FSDPHdmapToLidarFactorizedTeacherForcingRFModel, +) +from diffusion.training.models.hdmaptolidar_model_sf_dmd import ( + FSDPHdmapToLidarSFDMDModel, +) +from diffusion.training.networks.minimal_v4_dit import SACConfig +from diffusion.training.trainer_sf_dmd import SFDMDTrainer +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +STAGE1_NAME = "lidarverse_stage1_bidir_21f" +STAGE2_NAME = "lidarverse_stage2_causal_9f" +STAGE3_NAME = "lidarverse_stage3_sfdmd_9f" + +_LATENT_CHANNELS = 64 +_STAGE1_FRAMES = 21 +_CAUSAL_FRAMES = 9 +_DATASET_NAMES = ("nvidia_pai", "nuscenes") +_PREFIX_FRAMES_21 = [0, 1, 2, 4, 8, 10, 12, 16] +_PREFIX_PROBS_21 = [0.5] + [0.5 / 7.0] * 7 +_GEOMETRY_FRAMES_21 = [1, 2, 4, 8, 10, 12, 16, 20] +_PREFIX_FRAMES_9 = [0, 1, 2, 4, 8] +_PREFIX_PROBS_9 = [0.5] + [0.125] * 4 +_GEOMETRY_FRAMES_9 = [1, 2, 4, 8] + + +def _checkpoint(env_name: str, default: str) -> str: + return os.environ.get(env_name, default) + + +def _build_cross_dataset_dataloader( + *, + validation: bool, + sample_n_frames: int, + num_workers: int = 16, +): + suffix = "val" if validation else "train" + dataset_names = [ + f"lidarverse_nvidia_pai_{suffix}", + f"lidarverse_nuscenes_{suffix}", + ] + shared = { + "sample_n_frames": sample_n_frames, + "frame_sampling_method": "sequential", + "process_input": "mono", + "is_video_tokenizer": False, + "blockwise_warped_history_condition": False, + "hdmap_multichannel": False, + "return_hdmap_semantic": False, + "return_moving_boxes": True, + "resolve_moving_box_track_ids": False, + "return_full_lidar_metadata": True, + "load_intensity": False, + } + per_dataset = { + f"lidarverse_nvidia_pai_{suffix}": { + "min_range": 2.5, + "max_range": 100.0, + "sensor_fps": 10.0, + "frame_sampling_every_n_frames": 1, + "moving_box_root": os.environ.get( + "LIDARVERSE_NVIDIA_PAI_ROOT", "data/nvidia_pai" + ), + }, + f"lidarverse_nuscenes_{suffix}": { + "min_range": 2.5, + "max_range": 100.0, + "hdmap_map_max_dist": 100.0, + "sensor_fps": 2.0, + "frame_sampling_every_n_frames": 10, + "repeat_row": 1, + "lidar_size": [32, 1024], + }, + } + return HomogeneousMultiHdmapDataLoader( + dataset=CrossDatasetHdmapLidarDataset( + dataset_names=dataset_names, + shared_overrides=shared, + per_dataset_overrides=per_dataset, + ), + batch_size=1, + validation=validation, + dataset_sampling_weights=[0.5, 0.5], + drop_last=True, + pin_memory=True, + num_workers=num_workers, + ) + + +def _dataloader(*, validation: bool, sample_n_frames: int): + return L(_build_cross_dataset_dataloader)( + validation=validation, + sample_n_frames=sample_n_frames, + num_workers=int(os.environ.get("LIDARVERSE_DATALOADER_WORKERS", "16")), + ) + + +def _factorized_model_config(num_frames: int) -> dict: + prefix_frames = ( + _PREFIX_FRAMES_21 if num_frames == _STAGE1_FRAMES else _PREFIX_FRAMES_9 + ) + prefix_probs = ( + _PREFIX_PROBS_21 if num_frames == _STAGE1_FRAMES else _PREFIX_PROBS_9 + ) + geometry_frames = ( + _GEOMETRY_FRAMES_21 + if num_frames == _STAGE1_FRAMES + else _GEOMETRY_FRAMES_9 + ) + return { + # Spatial dimensions are a shape hint only. Native-grid batches carry + # their own H/W; T is checked by the bidirectional/SF-DMD contracts. + "latent_shape": [_LATENT_CHANNELS, num_frames, 16, 150], + "hdmap_channels": 1, + "additional_concat_ch": _LATENT_CHANNELS, + "skip_hdmap_proj": False, + "encode_hdmap_with_vae": True, + "hdmap_dropout_prob": 0.0, + "loss_reduce": "mean", + "sigma_data": 1.0, + "shift": 5, + "train_time_distribution": "logitnormal", + "train_time_weight": "uniform", + "input_video_has_prepend": False, + "blockwise_warped_history_condition": True, + "blockwise_warped_history_concat": True, + "blockwise_warped_history_backend": "dataloader", + "blockwise_spatial_map_self_prediction_prob": 0.0, + "stage2_known_mask_concat": True, + "imaginaire_conditioned_prefix_frames": prefix_frames, + "imaginaire_conditioned_prefix_probs": prefix_probs, + "stage2_factorized_prefix_frames": prefix_frames, + "stage2_factorized_prefix_probs": prefix_probs, + "stage2_factorized_hdmap_modes": ["null", "full"], + "stage2_factorized_hdmap_probs": [0.5, 0.5], + "stage2_factorized_geometry_modes_k0": [ + "null", + "rolling_static", + "frozen_object", + ], + "stage2_factorized_geometry_probs_k0": [0.1, 0.45, 0.45], + "stage2_factorized_geometry_modes_known": [ + "null", + "rolling_static", + "frozen_object", + ], + "stage2_factorized_geometry_probs_known": [0.1, 0.45, 0.45], + "stage2_factorized_hdmap_bbox_channel_start": 4, + "stage2_factorized_force_prefix_k": -1, + "stage2_factorized_force_hdmap_mode": "", + "stage2_factorized_force_geometry_mode": "", + "factorized_decouple_geometry_observations": True, + "factorized_geometry_observation_frames": geometry_frames, + "factorized_geometry_observation_probs": [ + 1.0 / len(geometry_frames) + ] * len(geometry_frames), + "factorized_force_geometry_observations": -1, + "factorized_geometry_block_size": 4, + "factorized_geometry_prefix_frames": 1, + "factorized_geometry_rolling_shutter": True, + "factorized_geometry_actor_box_time_mode": "frame", + "ema": {"enabled": True}, + "fsdp_enabled": True, + "fsdp": { + "policy": "block", + "checkpoint": False, + "min_num_params": 1024, + "sharding_group_size": 8, + "sharding_strategy": "hybrid", + }, + "net": { + "in_channels": _LATENT_CHANNELS * 3 + 1, + "out_channels": _LATENT_CHANNELS, + "side_condition_channels": 0, + "num_frame_type_embeddings": 0, + "num_dataset_embeddings": len(_DATASET_NAMES), + "timestep_scale": 0.001, + "rope_h_extrapolation_ratio": 3.0, + "rope_w_extrapolation_ratio": 3.0, + "rope_t_extrapolation_ratio": 1.0, + "rope_enable_fps_modulation": False, + "use_wan_fp32_strategy": True, + }, + } + + +stage1_config = LazyDict( + { + "defaults": [ + {"override /net": "mininet_2b"}, + {"override /ckpt_klass": "fsdp"}, + {"override /checkpoint": "local"}, + {"override /vae": "lidarverse_tokenizer"}, + {"override /conditioner": "add_fps_image_size_padding_mask"}, + "_self_", + ], + "job": { + "project": "posttraining", + "group": "lidarverse", + "name": STAGE1_NAME, + }, + "optimizer": { + "lr": 2 ** (-14.3), + "weight_decay": 0.1, + "betas": [0.9, 0.99], + "eps": 1.0e-10, + }, + "checkpoint": { + "save_iter": 200, + "save_at_iters": [2000, 4000, 6000, 8000, 10000, 15000, 20000], + "keep_last_checkpoints": 2, + "broadcast_via_filesystem": False, + "load_path": _checkpoint( + "LIDARVERSE_COSMOS_WARMSTART", + "checkpoints/cosmos-predict2/cosmos2_2b_lidar_warmstart.pt", + ), + "load_training_state": False, + "strict_resume": False, + "keys_not_to_resume": [], + }, + "trainer": { + "max_iter": 20000, + "distributed_parallelism": "fsdp", + "logging_iter": 10, + "grad_accum_iter": 1, + "run_validation": True, + "validation_iter": 1000, + "max_val_iter": 20, + }, + "model_parallel": { + "sequence_parallel": False, + "tensor_model_parallel_size": 1, + "context_parallel_size": 1, + }, + "model": _factorized_model_config(_STAGE1_FRAMES), + "model_obj": L(FSDPHdmapToLidarFactorizedBidirectionalRFModel)( + config=PLACEHOLDER, + fsdp_checkpointer=PLACEHOLDER, + ), + "scheduler": { + "warm_up_steps": [2500], + "cycle_lengths": [20000], + "f_start": [1.0e-6], + "f_max": [1.0], + "f_min": [1.0], + }, + "dataloader_train": _dataloader( + validation=False, sample_n_frames=_STAGE1_FRAMES + ), + "dataloader_val": _dataloader( + validation=True, sample_n_frames=_STAGE1_FRAMES + ), + }, + # Derived stages store the trainer class directly in trainer.type. + flags={"allow_objects": True}, +) +stage1_config["model"].update( + diffusion_forcing_block_size=_STAGE1_FRAMES, + teacher_forcing_prefix_frames=0, + factorized_bidirectional_stage1=True, +) +stage1_config["model"]["net"].update( + atten_backend="minimal_a2a", + temporal_block_size=0, + temporal_prefix_frames=0, +) + + +stage2_config = deepcopy(stage1_config) +stage2_config["job"]["name"] = STAGE2_NAME +stage2_config["checkpoint"].update( + save_iter=200, + save_at_iters=[2000, 4000, 6000, 8000, 10000], + load_path=_checkpoint( + "LIDARVERSE_STAGE1_CHECKPOINT", + "checkpoints/lidarverse-stage1/iter_000020000_ema_model.pt", + ), + load_ema_to_reg=False, + load_training_state=False, + strict_resume=False, +) +stage2_config["trainer"].update( + max_iter=10000, + validation_iter=1000, +) +stage2_config["scheduler"].update( + warm_up_steps=[1000], + cycle_lengths=[10000], +) +stage2_config["model"] = _factorized_model_config(_CAUSAL_FRAMES) +stage2_config["model"].update( + diffusion_forcing_block_size=4, + teacher_forcing_prefix_frames=1, + factorized_bidirectional_stage1=False, +) +stage2_config["model"]["net"].update( + atten_backend="torch-flex", + temporal_block_size=4, + temporal_prefix_frames=1, + # FlexAttention supports full-block recomputation, not selective caching. + sac_config=L(SACConfig)(mode="block_wise"), +) +stage2_config["model_obj"] = L( + FSDPHdmapToLidarFactorizedTeacherForcingRFModel +)( + config=PLACEHOLDER, + fsdp_checkpointer=PLACEHOLDER, +) +stage2_config["dataloader_train"] = _dataloader( + validation=False, sample_n_frames=_CAUSAL_FRAMES +) +stage2_config["dataloader_val"] = _dataloader( + validation=True, sample_n_frames=_CAUSAL_FRAMES +) + + +def _score_net_config(): + net = deepcopy(MININET_2B_Config) + net.in_channels = _LATENT_CHANNELS * 3 + 1 + net.out_channels = _LATENT_CHANNELS + net.patch_spatial = stage2_config["model"]["net"].get( + "patch_spatial", MININET_2B_Config.patch_spatial + ) + net.side_condition_channels = 0 + net.num_frame_type_embeddings = 0 + net.num_dataset_embeddings = len(_DATASET_NAMES) + net.timestep_scale = 0.001 + net.rope_h_extrapolation_ratio = 3.0 + net.rope_w_extrapolation_ratio = 3.0 + net.rope_t_extrapolation_ratio = 1.0 + net.rope_enable_fps_modulation = False + net.use_wan_fp32_strategy = True + net.atten_backend = "minimal_a2a" + net.temporal_block_size = 0 + net.temporal_prefix_frames = 0 + net.sac_config = L(SACConfig)(mode="none") + return net + + +stage3_config = deepcopy(stage2_config) +stage3_config["job"]["name"] = STAGE3_NAME +stage3_config["checkpoint"].update( + save_iter=250, + save_at_iters=[500, 1000, 1500, 2000], + load_path=_checkpoint( + "LIDARVERSE_STAGE2_CHECKPOINT", + "checkpoints/lidarverse-stage2/iter_000010000.pt", + ), + load_ema_to_reg=True, + load_training_state=False, + strict_resume=True, +) +stage3_config["trainer"].update( + type=SFDMDTrainer, + max_iter=2000, + logging_iter=1, + run_validation=False, + grad_accum_iter=1, +) +stage3_config["optimizer"].update( + lr=2.0e-6, + weight_decay=0.01, + betas=[0.9, 0.999], + eps=1.0e-8, +) +fake_optimizer = deepcopy(FusedAdamWConfig) +fake_optimizer.lr = 4.0e-7 +fake_optimizer.weight_decay = 0.01 +fake_optimizer.betas = [0.9, 0.999] +fake_optimizer.eps = 1.0e-8 +stage3_config["optimizer_fake"] = fake_optimizer +fake_scheduler = deepcopy(LambdaLinearSchedulerConfig) +fake_scheduler.warm_up_steps = [0] +fake_scheduler.cycle_lengths = [10000000000000] +fake_scheduler.f_start = [1.0] +fake_scheduler.f_max = [1.0] +fake_scheduler.f_min = [1.0] +stage3_config["scheduler_fake"] = fake_scheduler +stage3_config["scheduler"].update( + warm_up_steps=[0], + cycle_lengths=[10000000000000], + f_start=[1.0], + f_max=[1.0], + f_min=[1.0], +) +stage3_config["model"].update( + sfdmd_num_real_frames=_CAUSAL_FRAMES, + sfdmd_window_frames=_CAUSAL_FRAMES, + sfdmd_fake_updates_per_cycle=1, + sfdmd_student_update_freq=5, + sfdmd_num_steps=4, + sfdmd_sde_eta=1.0, + sfdmd_kv_cache_frames=9, + sfdmd_kv_sink_frames=1, + sfdmd_tbptt_blocks=2, + sfdmd_allow_truncated_bptt=True, + sfdmd_run_kv_equivalence_gate=False, + sfdmd_skip_zero_crossattn=True, + sfdmd_stream_condition_vae_encode=True, + sfdmd_condition_vae_cache_frames=9, + sfdmd_accumulated_geometry_warp=False, + sfdmd_geometry_source=False, + sfdmd_spatial_map_radius_m=100.0, + sfdmd_spatial_map_voxel_m=0.15, + sfdmd_spatial_map_voxel_policy="persistent_static", + sfdmd_spatial_map_observation_unit="block", + sfdmd_spatial_map_static_min_observations=3, + sfdmd_spatial_map_candidate_ttl_updates=1, + sfdmd_spatial_map_include_latest=False, + sfdmd_spatial_map_free_space_clear=True, + sfdmd_spatial_map_free_space_margin_m=0.75, + sfdmd_spatial_map_free_space_misses_to_remove=2, + sfdmd_artifixer_matching=True, + sfdmd_imaginaire_matching=False, + sfdmd_clean_x0_kv_commit=True, + sfdmd_factorized_conditioning=True, + sfdmd_temporal_history_source="generated", + sfdmd_geometry_history_source="generated", + sfdmd_temporal_prefix_frames=1, + sfdmd_ema_start_cycle=200, + sfdmd_teacher_guidance=3.0, + sfdmd_critic_min_sigma=0.02, + sfdmd_critic_max_sigma=0.98, + sfdmd_max_grad_norm=10.0, + sfdmd_teacher_checkpoint=_checkpoint( + "LIDARVERSE_STAGE2_EMA_CHECKPOINT", + "checkpoints/lidarverse-stage2/iter_000010000_ema_model.pt", + ), + sfdmd_teacher_net=_score_net_config(), + sfdmd_min_range=1.0, + sfdmd_max_range=100.0, + sfdmd_min_value=-1.0, + sfdmd_inverse_depth=False, + train_time_distribution="uniform", + shift_clamp_percentiles=None, +) +stage3_config["model"]["net"].update( + temporal_block_size=4, + temporal_prefix_frames=1, + side_condition_channels=0, + sac_config=L(SACConfig)(mode="none"), +) +stage3_config["model"]["fsdp"]["use_orig_params"] = True +stage3_config["model"]["ema"].update(beta=0.99, num=1) +stage3_config["model"]["vae"] = { + "use_ema": False, + "encoder_is_bf16": True, + "decoder_is_bf16": False, +} +stage3_config["model_obj"] = L(FSDPHdmapToLidarSFDMDModel)( + config=PLACEHOLDER, + fsdp_checkpointer=PLACEHOLDER, +) + + +def register_experiments(cs: ConfigStore) -> None: + for name, node in ( + (STAGE1_NAME, stage1_config), + (STAGE2_NAME, stage2_config), + (STAGE3_NAME, stage3_config), + ): + cs.store( + group="experiment", + package="_global_", + name=name, + node=node, + ) diff --git a/diffusion/training/config/text2world_hdmaptolidar/experiment_pai_release.py b/diffusion/training/config/text2world_hdmaptolidar/experiment_pai_release.py new file mode 100644 index 0000000000000000000000000000000000000000..13b0386f89c507c0ad7b8efefa3e321c6ccff8fe --- /dev/null +++ b/diffusion/training/config/text2world_hdmaptolidar/experiment_pai_release.py @@ -0,0 +1,56 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""PAI post-training from processed release weights; no internal dataset roots.""" + +from copy import deepcopy +import os + +from diffusion.training.config.text2world_hdmaptolidar.experiment_lidarverse import ( + stage1_config, stage2_config, stage3_config, _factorized_model_config, +) +from utils.processed_pai import loader_config + + +def register_experiments(cs): + for stage, base, package in ((1, stage1_config, "bidir"), (2, stage2_config, "causal"), (3, stage3_config, "sfdmd")): + node = deepcopy(base) + name = f"lidarverse_pai_stage{stage}_finetune" + node.job.name = name + node.checkpoint.update(load_path=os.environ.get(f"LIDARVERSE_STAGE{stage}_CHECKPOINT", + f"checkpoints/lidarverse-{package}-pai/ema_model.pt"), load_training_state=False, + load_ema_to_reg=False, strict_resume=True, save_iter=200, save_at_iters=[]) + node.trainer.update(max_iter=2000, run_validation=False) + node.scheduler.update(warm_up_steps=[0], cycle_lengths=[2000], f_start=[1.], f_max=[1.], f_min=[1.]) + node.dataloader_train = loader_config() + node.dataloader_val = loader_config(validation=True) + model = node.model + factors = _factorized_model_config(21) + for key, value in factors.items(): + if key.startswith(("stage2_factorized", "imaginaire_conditioned", "factorized_geometry_observation")): + model[key] = value + model.update(latent_shape=[64, 13 if stage == 3 else 21, 16, 128], + precision="bfloat16", enable_shift_stretch=False, shift_clamp_percentiles=None, + blockwise_warped_history_backend="torch_spatial_map", + blockwise_spatial_map_geometry_root_path="", blockwise_spatial_map_geometry_filter_list_path="", + blockwise_spatial_map_min_range=2.5, blockwise_spatial_map_max_range=100., + blockwise_spatial_map_voxel_m=.10 if stage == 3 else .15, blockwise_spatial_map_radius_m=100., + blockwise_spatial_map_voxel_policy="persistent_static", + blockwise_spatial_map_observation_unit="frame", blockwise_spatial_map_static_min_observations=2, + blockwise_spatial_map_include_latest=False, blockwise_spatial_map_candidate_ttl_updates=1, + blockwise_spatial_map_free_space_clear=True, blockwise_spatial_map_free_space_margin_m=.75, + blockwise_spatial_map_free_space_misses_to_remove=2) + model.net.update(patch_spatial=[1, 2], num_dataset_embeddings=3, rope_scale_positions_by_patch=True) + model.vae = dict(experiment_name="transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema40k", + checkpoint_path=os.environ.get("LIDARVERSE_TOKENIZER_CHECKPOINT", "checkpoints/lidarverse-tokenizer-pai/ckpt.pt"), + mean_std_fp=os.environ.get("LIDARVERSE_TOKENIZER_LATENT_STATS", "checkpoints/lidarverse-tokenizer-pai/latent_stats.pt"), + use_ema=False, strict_checkpoint=True, is_bf16=False, + encoder_is_bf16=False, decoder_is_bf16=False) + if stage == 3: + model.update(sfdmd_num_real_frames=21, sfdmd_window_frames=13, sfdmd_min_range=2.5, + sfdmd_spatial_map_voxel_m=.10, + sfdmd_teacher_checkpoint=os.environ.get("LIDARVERSE_SCORE_CHECKPOINT", + "checkpoints/lidarverse-causal-pai/ema_model.pt")) + model.sfdmd_teacher_net.update(patch_spatial=[1, 2], num_dataset_embeddings=3, + rope_scale_positions_by_patch=True) + cs.store(group="experiment", package="_global_", name=name, node=node) diff --git a/diffusion/training/context_parallel.py b/diffusion/training/context_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..4758db33f1d63546d01be917fa19a821ed4bc1f7 --- /dev/null +++ b/diffusion/training/context_parallel.py @@ -0,0 +1,122 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import Tensor +from torch.distributed import ProcessGroup, all_gather, get_process_group_ranks, get_world_size + + +def split_inputs_cp(x: Tensor, seq_dim: int, cp_group: ProcessGroup) -> Tensor: + """ + Split input tensor along the sequence dimension for checkpoint parallelism. + + This function divides the input tensor into equal parts along the specified + sequence dimension, based on the number of ranks in the checkpoint parallelism group. + It then selects the part corresponding to the current rank. + + Args: + x: Input tensor to be split. + seq_dim: The dimension along which to split the input (sequence dimension). + cp_group: The process group for checkpoint parallelism. + + Returns: + A slice of the input tensor corresponding to the current rank. + + Raises: + AssertionError: If the sequence dimension is not divisible by the number of ranks. + """ + cp_ranks = get_process_group_ranks(cp_group) + cp_size = len(cp_ranks) + + assert x.shape[seq_dim] % cp_size == 0, f"{x.shape[seq_dim]} cannot divide cp_size {cp_size}" + x = x.view(*x.shape[:seq_dim], cp_size, x.shape[seq_dim] // cp_size, *x.shape[(seq_dim + 1) :]) + seq_idx = torch.tensor([cp_group.rank()], device=x.device) + x = x.index_select(seq_dim, seq_idx) + # Note that the new sequence length is the original sequence length / cp_size + x = x.view(*x.shape[:seq_dim], -1, *x.shape[(seq_dim + 2) :]) + return x + + +def cat_outputs_cp(x: Tensor, seq_dim: int, cp_group: ProcessGroup) -> Tensor: + """ + Concatenate outputs from different ranks in the checkpoint parallelism group. + + This function gathers tensors from all ranks in the checkpoint parallelism group + and concatenates them along the specified sequence dimension. + + Args: + x: Input tensor to be concatenated. + seq_dim: The dimension along which to concatenate the tensors (sequence dimension). + cp_group: The process group for checkpoint parallelism. + + Returns: + A tensor that is the concatenation of tensors from all ranks in the cp_group. + + Raises: + RuntimeError: If the gather operation fails. + """ + # Get the world size (number of processes in the group) + world_size = get_world_size(cp_group) + + # Create a list to store tensors from all ranks + gathered_tensors = [torch.zeros_like(x) for _ in range(world_size)] + + # Gather tensors from all ranks + try: + all_gather(gathered_tensors, x, group=cp_group) + except RuntimeError as e: + raise RuntimeError(f"Failed to gather tensors: {e}") + + # Concatenate the gathered tensors along the specified dimension + return torch.cat(gathered_tensors, dim=seq_dim) + + +def cat_outputs_cp_with_grad(x: Tensor, seq_dim: int, cp_group: ProcessGroup) -> Tensor: + """ + Concatenate outputs from different ranks in the context parallelism group. + + This function gathers tensors from all ranks in the checkpoint parallelism group + and concatenates them along the specified sequence dimension. + + It retains computational graph locally for each rank by replacing the portion of the tensor with original output. + + Args: + x: Input tensor to be concatenated. + seq_dim: The dimension along which to concatenate the tensors (sequence dimension). + cp_group: The process group for checkpoint parallelism. + + Returns: + A tensor that is the concatenation of tensors from all ranks in the cp_group. + + Raises: + RuntimeError: If the gather operation fails. + """ + # Get the world size (number of processes in the group) + cp_size = cp_group.size() + assert cp_size > 0, "cp_size should be greater than 0" + + # Create a list to store tensors from all ranks + gathered_tensors = [torch.zeros_like(x) for _ in range(cp_size)] + + # Gather tensors from all ranks + try: + all_gather(gathered_tensors, x, group=cp_group) + except RuntimeError as e: + raise RuntimeError(f"Failed to gather tensors: {e}") + + rank = cp_group.rank() + gathered_tensors[rank] = x + # Concatenate the gathered tensors along the specified dimension + return torch.cat(gathered_tensors, dim=seq_dim) diff --git a/diffusion/training/datasets/lidar_dataset/configs.py b/diffusion/training/datasets/lidar_dataset/configs.py new file mode 100644 index 0000000000000000000000000000000000000000..a027aba6b4f9d2940bec3834099d8e466f90de7e --- /dev/null +++ b/diffusion/training/datasets/lidar_dataset/configs.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +"""Public HDMap-to-LiDAR dataset contracts for LidarVerse. + +The released training recipe uses NVIDIA PAI and nuScenes. The Waymo entries +are a generic NCore adapter for users who independently prepare that dataset; +they are not part of the released checkpoint's training lineage. +""" + +import os + + +def _path(name: str, default: str) -> str: + return os.path.expanduser(os.environ.get(name, default)) + + +def _base_hdmap_video( + *, + data_name: str, + root: str, + split: str, + hdmap_root: str, + backend: str, + height: int, + width: int, + lidar_length: int, + sensor_fps: float, + sensor_name: str, +) -> dict: + custom_folders = [root, root] if backend == "radym" else [root] + return { + "data_name": data_name, + "root_path": root, + "filter_list_path": split, + "t5_embedding_path": "", + "custom_folders": custom_folders, + "custom_fields": ["lidar", "hdmap"], + "metadata_folder": "", + "max_range": 100.0, + "min_range": 2.5, + "downsample_factor_row": 1, + "downsample_factor_col": 1, + "repeat_row": 1, + "repeat_col": 1, + "repeat_temporal": 1, + "lidar_crop_size": [-1, -1], + "rgb_crop_size": [-1, -1], + "rgb_resize_size": [-1, -1], + "lidar_size": [height, width], + "lidar_resize_size": [-1, -1], + "downsample_method": "scatter_min", + "min_value": -1.0, + "num_views": 0, + "sample_n_frames": 21, + "lidar_length": lidar_length, + "frame_sampling_method": "sequential", + "frame_sampling_every_n_frames": 1, + "sample_lidar_prob": 1.0, + "is_video_tokenizer": False, + "load_lidar_only": True, + "load_rgb_only": False, + "load_lidar_and_rgb": False, + "load_lidar_or_rgb": False, + "RGB_FPS": 30, + "LIDAR_FPS": int(round(sensor_fps)), + "load_t5_embeddings": False, + "inverse_depth": False, + "process_input": "mono", + "load_intensity": False, + "dataset_backend": backend, + "resample_width": width if backend.endswith("_ncore") else -1, + "center_vehicle_forward": backend == "nuscenes_ncore", + "hdmap_root": hdmap_root, + "hdmap_multichannel": False, + "hdmap_moving_only": False, + "hdmap_include_boxes": True, + "hdmap_map_max_dist": 100.0, + "hdmap_pose_for_lidar_to_world": backend == "nuscenes_ncore", + "sensor_fps": sensor_fps, + "sensor_dataset_name": sensor_name, + "sensor_dataset_id": -1, + } + + +_PAI_ROOT = _path("LIDARVERSE_NVIDIA_PAI_ROOT", "data/nvidia_pai") +_NUSCENES_ROOT = _path("LIDARVERSE_NUSCENES_ROOT", "data/nuscenes_ncore") +_WAYMO_TRAIN_ROOT = _path( + "LIDARVERSE_WAYMO_ROOT", "data/waymo_ncore/training" +) +_WAYMO_VAL_ROOT = _path( + "LIDARVERSE_WAYMO_VAL_ROOT", "data/waymo_ncore/validation" +) + +COMMONDATA_CONFIG = { + "lidarverse_nvidia_pai_train": _base_hdmap_video( + data_name="mads_range_map", + root=_PAI_ROOT, + split=_path( + "LIDARVERSE_NVIDIA_PAI_TRAIN_LIST", + "data/splits/nvidia_pai_train.lst", + ), + hdmap_root=_PAI_ROOT, + backend="radym", + height=128, + width=1200, + lidar_length=200, + sensor_fps=10.0, + sensor_name="nvidia_pai", + ), + "lidarverse_nuscenes_train": _base_hdmap_video( + data_name="nuscenes_lidar_range_map", + root=_NUSCENES_ROOT, + split=_path( + "LIDARVERSE_NUSCENES_TRAIN_LIST", + "data/splits/nuscenes_train.lst", + ), + hdmap_root=_path( + "LIDARVERSE_NUSCENES_HDMAP_ROOT", "data/nuscenes_hdmap" + ), + backend="nuscenes_ncore", + height=32, + width=1024, + lidar_length=380, + sensor_fps=2.0, + sensor_name="nuscenes", + ), + "lidarverse_waymo_train": _base_hdmap_video( + data_name="waymo_lidar_range_map", + root=_WAYMO_TRAIN_ROOT, + split=_path( + "LIDARVERSE_WAYMO_TRAIN_LIST", "data/splits/waymo_train.lst" + ), + hdmap_root=_path( + "LIDARVERSE_WAYMO_HDMAP_ROOT", "data/waymo_hdmap/training" + ), + backend="waymo_ncore", + height=64, + width=1024, + lidar_length=199, + sensor_fps=10.0, + sensor_name="waymo", + ), +} + +for dataset, env_name, default in ( + ( + "nvidia_pai", + "LIDARVERSE_NVIDIA_PAI_VAL_LIST", + "data/splits/nvidia_pai_val.lst", + ), + ( + "nuscenes", + "LIDARVERSE_NUSCENES_VAL_LIST", + "data/splits/nuscenes_val.lst", + ), +): + source = f"lidarverse_{dataset}_train" + target = f"lidarverse_{dataset}_val" + COMMONDATA_CONFIG[target] = dict(COMMONDATA_CONFIG[source]) + COMMONDATA_CONFIG[target]["filter_list_path"] = _path(env_name, default) + +COMMONDATA_CONFIG["lidarverse_waymo_val"] = _base_hdmap_video( + data_name="waymo_lidar_range_map", + root=_WAYMO_VAL_ROOT, + split=_path( + "LIDARVERSE_WAYMO_VAL_LIST", "data/splits/waymo_val.lst" + ), + hdmap_root=_path( + "LIDARVERSE_WAYMO_VAL_HDMAP_ROOT", "data/waymo_hdmap/validation" + ), + backend="waymo_ncore", + height=64, + width=1024, + lidar_length=199, + sensor_fps=10.0, + sensor_name="waymo", +) + +# Native PAI columns are reduced to the trained 1200-column grid. +for split in ("train", "val"): + config = COMMONDATA_CONFIG[f"lidarverse_nvidia_pai_{split}"] + config["metadata_folder"] = _path( + "LIDARVERSE_NVIDIA_PAI_METADATA", "data/nvidia_pai/metadata" + ) + config["downsample_factor_col"] = 3 diff --git a/diffusion/training/datasets/lidar_dataset/forecast_warp.py b/diffusion/training/datasets/lidar_dataset/forecast_warp.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0ce0dfcc468d3ae967ace4ef347cacd30c7df8 --- /dev/null +++ b/diffusion/training/datasets/lidar_dataset/forecast_warp.py @@ -0,0 +1,4785 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Geometry-only target-pose warping for LiDAR forecast conditioning.""" + +from __future__ import annotations + +import math +from typing import Any + +import numpy as np +import torch + +from diffusion.training.utils.diffusion_forcing import temporal_chunk_slices +from tokenizer.training.datasets.lidar_datasets.waymo_hdmap import ( + project_world_points, + scatter_min_range, +) + + +def _unnormalize_valid_depth( + normalized: np.ndarray, + valid: np.ndarray, + min_range: float, + max_range: float, + min_value: float, + inverse_depth: bool, +) -> np.ndarray: + c_min = min_range if not inverse_depth else 1.0 / max_range + c_max = max_range if not inverse_depth else 1.0 / min_range + if min_value == -1: + depth = (normalized + 1.0) * 0.5 * (c_max - c_min) + c_min + else: + depth = normalized * (c_max - c_min) + c_min + if inverse_depth: + depth = 1.0 / depth + return np.where(valid, depth, 0.0).astype(np.float32) + + +def _normalize_metric_depth( + metric: np.ndarray, + min_range: float, + max_range: float, + min_value: float, + inverse_depth: bool, +) -> np.ndarray: + c_min = min_range if not inverse_depth else 1.0 / max_range + c_max = max_range if not inverse_depth else 1.0 / min_range + if inverse_depth: + invalid = metric == 0 + work = metric.copy() + work[invalid] = max_range + work = 1.0 / work + work[invalid] = c_min + else: + work = metric + work = np.clip(work, c_min, c_max) + if min_value == -1: + work = (work - c_min) / (c_max - c_min) * 2.0 - 1.0 + else: + work = (work - c_min) / (c_max - c_min) + return work.astype(np.float32) + + +def _wrap_angle_torch(angle: torch.Tensor) -> torch.Tensor: + return torch.remainder(angle + torch.pi, 2.0 * torch.pi) - torch.pi + + +def _fractional_transform_points_torch( + points: torch.Tensor, + transform: torch.Tensor, + fractions: torch.Tensor, +) -> torch.Tensor: + """Apply identity-to-transform SE(3) interpolation per point.""" + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError(f"points must be (N,3), got {tuple(points.shape)}") + if transform.shape != (4, 4): + raise ValueError( + f"transform must be (4,4), got {tuple(transform.shape)}" + ) + if fractions.shape != (points.shape[0],): + raise ValueError( + "fractions must align with points, got " + f"{tuple(fractions.shape)} for {points.shape[0]} points" + ) + if points.shape[0] == 0: + return points + + transform = transform.to(device=points.device, dtype=points.dtype) + fractions = fractions.to( + device=points.device, dtype=points.dtype + ).clamp_(0.0, 1.0) + rotation = transform[:3, :3] + skew_vector = torch.stack( + [ + rotation[2, 1] - rotation[1, 2], + rotation[0, 2] - rotation[2, 0], + rotation[1, 0] - rotation[0, 1], + ] + ) + cosine = ((torch.trace(rotation) - 1.0) * 0.5).clamp(-1.0, 1.0) + theta = torch.acos(cosine) + sine = torch.sin(theta) + rotvec_scale = torch.where( + theta < 1.0e-4, + 0.5 + theta.square() / 12.0, + theta / (2.0 * sine.clamp_min(1.0e-12)), + ) + rotvec = rotvec_scale * skew_vector + base_theta = torch.linalg.vector_norm(rotvec) + axis = rotvec / base_theta.clamp_min(1.0e-12) + + angles = fractions * base_theta + sin_angles = torch.sin(angles).unsqueeze(1) + cos_angles = torch.cos(angles).unsqueeze(1) + axis_rows = axis.unsqueeze(0).expand_as(points) + rotated = ( + points * cos_angles + + torch.cross(axis_rows, points, dim=1) * sin_angles + + axis_rows + * (points * axis_rows).sum(dim=1, keepdim=True) + * (1.0 - cos_angles) + ) + translation = fractions.unsqueeze(1) * transform[:3, 3].unsqueeze(0) + return rotated + translation + + +_ACTOR_BOX_TIME_MODES = ( + "frame", + "current_to_next", + "previous_to_current", +) + + +def _fractional_rotation_matrices_torch( + rotation: torch.Tensor, + fractions: torch.Tensor, +) -> torch.Tensor: + """Interpolate identity to one rotation for each supplied fraction.""" + if rotation.shape != (3, 3): + raise ValueError( + f"rotation must be (3,3), got {tuple(rotation.shape)}" + ) + if fractions.ndim != 1: + raise ValueError( + f"fractions must be one-dimensional, got {tuple(fractions.shape)}" + ) + rotation = rotation.to(device=fractions.device, dtype=fractions.dtype) + fractions = fractions.clamp(0.0, 1.0) + skew_vector = torch.stack( + [ + rotation[2, 1] - rotation[1, 2], + rotation[0, 2] - rotation[2, 0], + rotation[1, 0] - rotation[0, 1], + ] + ) + cosine = ((torch.trace(rotation) - 1.0) * 0.5).clamp(-1.0, 1.0) + theta = torch.acos(cosine) + sine = torch.sin(theta) + rotvec_scale = torch.where( + theta < 1.0e-4, + 0.5 + theta.square() / 12.0, + theta / (2.0 * sine.clamp_min(1.0e-12)), + ) + rotvec = rotvec_scale * skew_vector + base_theta = torch.linalg.vector_norm(rotvec) + axis = rotvec / base_theta.clamp_min(1.0e-12) + axis_skew = torch.zeros( + (3, 3), device=fractions.device, dtype=fractions.dtype + ) + axis_skew[0, 1] = -axis[2] + axis_skew[0, 2] = axis[1] + axis_skew[1, 0] = axis[2] + axis_skew[1, 2] = -axis[0] + axis_skew[2, 0] = -axis[1] + axis_skew[2, 1] = axis[0] + angles = fractions * base_theta + identity = torch.eye( + 3, device=fractions.device, dtype=fractions.dtype + ).unsqueeze(0) + return ( + identity + + torch.sin(angles)[:, None, None] * axis_skew.unsqueeze(0) + + (1.0 - torch.cos(angles))[:, None, None] + * (axis_skew @ axis_skew).unsqueeze(0) + ) + + +def _interpolate_pose_components_torch( + start_pose: torch.Tensor, + end_pose: torch.Tensor, + fractions: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Return per-fraction object-to-world rotations and translations.""" + if start_pose.shape != (4, 4) or end_pose.shape != (4, 4): + raise ValueError( + "pose interpolation requires two (4,4) transforms, got " + f"{tuple(start_pose.shape)} and {tuple(end_pose.shape)}" + ) + start = start_pose.to(device=fractions.device, dtype=fractions.dtype) + end = end_pose.to(device=fractions.device, dtype=fractions.dtype) + relative_rotation = start[:3, :3].T @ end[:3, :3] + delta_rotation = _fractional_rotation_matrices_torch( + relative_rotation, fractions + ) + rotations = start[:3, :3].unsqueeze(0) @ delta_rotation + translations = ( + (1.0 - fractions[:, None]) * start[:3, 3].unsqueeze(0) + + fractions[:, None] * end[:3, 3].unsqueeze(0) + ) + return rotations, translations + + +def _extrapolate_actor_pose_before_torch( + current_pose: torch.Tensor, + following_pose: torch.Tensor, +) -> torch.Tensor: + """Back-extrapolate one 10 Hz actor pose for a window's first sweep.""" + start = current_pose.clone() + start[:3, 3] = 2.0 * current_pose[:3, 3] - following_pose[:3, 3] + relative_rotation = current_pose[:3, :3].T @ following_pose[:3, :3] + start[:3, :3] = current_pose[:3, :3] @ relative_rotation.T + return start + + +def _extrapolate_actor_pose_after_torch( + previous_pose: torch.Tensor, + current_pose: torch.Tensor, +) -> torch.Tensor: + """Forward-extrapolate one actor pose from the preceding pair.""" + end = current_pose.clone() + end[:3, 3] = 2.0 * current_pose[:3, 3] - previous_pose[:3, 3] + relative_rotation = previous_pose[:3, :3].T @ current_pose[:3, :3] + end[:3, :3] = current_pose[:3, :3] @ relative_rotation + return end + + +def _track_box_index_torch( + valid_boxes: torch.Tensor, + track_ids: torch.Tensor, + frame_idx: int, + track_id: int, +) -> int | None: + matches = ( + valid_boxes[frame_idx] + & (track_ids[frame_idx] == int(track_id)) + ).nonzero(as_tuple=False).flatten() + if matches.numel() == 0: + return None + if matches.numel() != 1: + raise ValueError( + f"track {track_id} has {matches.numel()} boxes at frame {frame_idx}" + ) + return int(matches.item()) + + +def _actor_pose_interval_torch( + object_to_world: torch.Tensor, + valid_boxes: torch.Tensor, + track_ids: torch.Tensor, + frame_idx: int, + box_idx: int, + actor_box_time_mode: str, +) -> tuple[torch.Tensor, torch.Tensor, bool]: + """Resolve the actor pose interval spanning one LiDAR sweep.""" + if actor_box_time_mode not in _ACTOR_BOX_TIME_MODES: + raise ValueError( + f"unsupported actor box time mode {actor_box_time_mode!r}; " + f"expected {_ACTOR_BOX_TIME_MODES}" + ) + current = object_to_world[frame_idx, box_idx] + if actor_box_time_mode == "frame": + return current, current, False + + track_id = int(track_ids[frame_idx, box_idx].item()) + if track_id < 0: + return current, current, False + if actor_box_time_mode == "current_to_next": + if frame_idx + 1 < object_to_world.shape[0]: + following_idx = _track_box_index_torch( + valid_boxes, track_ids, frame_idx + 1, track_id + ) + if following_idx is not None: + return ( + current, + object_to_world[frame_idx + 1, following_idx], + True, + ) + if frame_idx > 0: + previous_idx = _track_box_index_torch( + valid_boxes, track_ids, frame_idx - 1, track_id + ) + if previous_idx is not None: + end = _extrapolate_actor_pose_after_torch( + object_to_world[frame_idx - 1, previous_idx], current + ) + return current, end, True + return current, current, False + if frame_idx > 0: + previous_idx = _track_box_index_torch( + valid_boxes, track_ids, frame_idx - 1, track_id + ) + if previous_idx is not None: + return object_to_world[frame_idx - 1, previous_idx], current, True + if frame_idx + 1 < object_to_world.shape[0]: + following_idx = _track_box_index_torch( + valid_boxes, track_ids, frame_idx + 1, track_id + ) + if following_idx is not None: + start = _extrapolate_actor_pose_before_torch( + current, object_to_world[frame_idx + 1, following_idx] + ) + return start, current, True + return current, current, False + + +def _world_points_to_actor_local_torch( + points_world: torch.Tensor, + start_pose: torch.Tensor, + end_pose: torch.Tensor, + fractions: torch.Tensor, +) -> torch.Tensor: + rotations, translations = _interpolate_pose_components_torch( + start_pose, end_pose, fractions + ) + return torch.einsum( + "ni,nij->nj", points_world - translations, rotations + ) + + +def infer_pose_sensor_start_end_from_lidar_poses( + lidar_to_world: torch.Tensor, +) -> torch.Tensor: + """Approximate within-sweep motion from adjacent sweep-start poses.""" + poses = torch.as_tensor(lidar_to_world) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"lidar_to_world must be (T,4,4), got {tuple(poses.shape)}" + ) + relative = torch.eye( + 4, device=poses.device, dtype=poses.dtype + ).repeat(poses.shape[0], 1, 1) + if poses.shape[0] > 1: + relative[:-1] = torch.linalg.inv(poses[1:]) @ poses[:-1] + relative[-1] = relative[-2] + return relative + + +def apply_planar_novel_view_offset( + lidar_to_world: np.ndarray, + pose_sensor_start_end: np.ndarray | None, + *, + start_frame: int, + forward_m: float, + left_m: float, + sensor_to_ego_rotation: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray | None]: + """Translate a target trajectory in the ego plane without changing yaw.""" + poses = np.asarray(lidar_to_world) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"lidar_to_world must be (T,4,4), got {poses.shape}" + ) + if not 0 <= int(start_frame) < poses.shape[0]: + raise ValueError( + f"start_frame must be in [0,{poses.shape[0]}), got {start_frame}" + ) + if not np.isfinite(forward_m) or not np.isfinite(left_m): + raise ValueError("forward_m and left_m must be finite") + + sensor_to_ego = ( + np.eye(3, dtype=poses.dtype) + if sensor_to_ego_rotation is None + else np.asarray(sensor_to_ego_rotation, dtype=poses.dtype) + ) + if sensor_to_ego.shape != (3, 3): + raise ValueError( + "sensor_to_ego_rotation must be (3,3), got " + f"{sensor_to_ego.shape}" + ) + if not np.isfinite(sensor_to_ego).all(): + raise ValueError("sensor_to_ego_rotation must be finite") + + offset = np.eye(4, dtype=poses.dtype) + ego_offset = np.array( + [float(forward_m), float(left_m), 0.0], + dtype=poses.dtype, + ) + try: + offset[:3, 3] = np.linalg.solve(sensor_to_ego, ego_offset) + except np.linalg.LinAlgError as exc: + raise ValueError( + "sensor_to_ego_rotation must be invertible" + ) from exc + shifted_poses = poses.copy() + shifted_poses[start_frame:] = shifted_poses[start_frame:] @ offset + + if pose_sensor_start_end is None: + return shifted_poses, None + motion = np.asarray(pose_sensor_start_end) + if motion.shape != poses.shape: + raise ValueError( + "pose_sensor_start_end must match lidar_to_world, got " + f"{motion.shape} and {poses.shape}" + ) + shifted_motion = motion.copy() + inverse_offset = np.linalg.inv(offset) + shifted_motion[start_frame:] = ( + inverse_offset @ shifted_motion[start_frame:] @ offset + ) + return shifted_poses, shifted_motion + + +def apply_lateral_novel_view_offset( + lidar_to_world: np.ndarray, + pose_sensor_start_end: np.ndarray | None, + *, + start_frame: int, + left_m: float, + sensor_to_ego_rotation: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray | None]: + """Shift a target trajectory along the ego-frame left axis.""" + return apply_planar_novel_view_offset( + lidar_to_world, + pose_sensor_start_end, + start_frame=start_frame, + forward_m=0.0, + left_m=left_m, + sensor_to_ego_rotation=sensor_to_ego_rotation, + ) + + +def _normalize_metric_depth_torch( + metric: torch.Tensor, + min_range: float, + max_range: float, + min_value: float, + inverse_depth: bool, +) -> torch.Tensor: + c_min = min_range if not inverse_depth else 1.0 / max_range + c_max = max_range if not inverse_depth else 1.0 / min_range + if inverse_depth: + invalid = metric == 0 + work = torch.where(invalid, metric.new_full((), max_range), metric) + work = work.reciprocal() + work = torch.where(invalid, work.new_full((), c_min), work) + else: + work = metric + work = work.clamp(c_min, c_max) + if min_value == -1: + return (work - c_min) / (c_max - c_min) * 2.0 - 1.0 + return (work - c_min) / (c_max - c_min) + + +def compose_normalized_range_channels( + channels: torch.Tensor, + *, + channel_dim: int, + min_value: float, + inverse_depth: bool, +) -> torch.Tensor: + """Compose semantic range channels with the nearest valid return.""" + if channels.ndim < 3: + raise ValueError( + "range channels must include channel and spatial dimensions, got " + f"{tuple(channels.shape)}" + ) + valid = torch.isfinite(channels) & ( + channels > float(min_value) + 1.0e-5 + ) + if inverse_depth: + work = channels.masked_fill(~valid, -torch.inf) + composed = work.amax(dim=channel_dim, keepdim=True) + else: + work = channels.masked_fill(~valid, torch.inf) + composed = work.amin(dim=channel_dim, keepdim=True) + return torch.where( + torch.isfinite(composed), + composed, + composed.new_full((), float(min_value)), + ) + + +def compose_normalized_range_feature_layers( + ranges: torch.Tensor, + features: torch.Tensor, + *, + min_value: float, + inverse_depth: bool, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Compose attributed returns while retaining the nearest return's feature.""" + if ranges.ndim != 3 or features.ndim != 4: + raise ValueError("ranges/features must be (N,H,W)/(N,F,H,W)") + if ranges.shape[0] != features.shape[0] or ranges.shape[1:] != features.shape[2:]: + raise ValueError( + f"range/feature layers do not align: {ranges.shape}/{features.shape}" + ) + valid = torch.isfinite(ranges) & ( + ranges > float(min_value) + 1.0e-5 + ) + if inverse_depth: + work = ranges.masked_fill(~valid, -torch.inf) + winner = work.argmax(dim=0) + composed_range = work.amax(dim=0) + else: + work = ranges.masked_fill(~valid, torch.inf) + winner = work.argmin(dim=0) + composed_range = work.amin(dim=0) + hit = valid.any(dim=0) + height, width = ranges.shape[1:] + flat_winner = winner.reshape(-1) + flat_pixel = torch.arange( + height * width, device=ranges.device, dtype=torch.long + ) + feature_count = features.shape[1] + flattened = features.permute(0, 2, 3, 1).reshape( + ranges.shape[0], height * width, feature_count + ) + composed_features = flattened[flat_winner, flat_pixel].reshape( + height, width, feature_count + ).permute(2, 0, 1) + composed_range = torch.where( + hit, + composed_range, + composed_range.new_full((), float(min_value)), + ) + composed_features = torch.where( + hit.unsqueeze(0), + composed_features, + composed_features.new_full((), float(min_value)), + ) + return composed_range.unsqueeze(0), composed_features, hit + + +@torch.no_grad() +def remove_points_inside_moving_boxes( + video: torch.Tensor, + lidar_to_world: torch.Tensor, + box_object_to_world: torch.Tensor, + box_lwh: torch.Tensor, + box_valid: torch.Tensor, + box_track_id: torch.Tensor | None = None, + *, + ray_dirs: torch.Tensor, + min_range: float, + max_range: float, + min_value: float, + inverse_depth: bool, + pose_sensor_start_end: torch.Tensor | None = None, + actor_box_time_mode: str = "frame", + point_chunk_size: int = 8192, +) -> tuple[torch.Tensor, torch.Tensor]: + """Remove LiDAR returns lying inside supplied moving 3-D boxes.""" + if video.ndim != 4 or video.shape[0] < 1: + raise ValueError( + "dynamic filtering requires (C,T,H,W) with range in channel 0, got " + f"{tuple(video.shape)}" + ) + num_frames, height, width = map(int, video.shape[1:]) + poses = torch.as_tensor( + lidar_to_world, device=video.device, dtype=torch.float32 + ) + if poses.shape != (num_frames, 4, 4): + raise ValueError( + "lidar_to_world must align one pose per frame, got " + f"{tuple(poses.shape)} for T={num_frames}" + ) + motion = None + if pose_sensor_start_end is not None: + motion = torch.as_tensor( + pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + if motion.shape != (num_frames, 4, 4): + raise ValueError( + "pose_sensor_start_end must align one transform per frame, " + f"got {tuple(motion.shape)} for T={num_frames}" + ) + if ( + box_object_to_world.ndim != 4 + or box_object_to_world.shape[:2] != box_lwh.shape[:2] + or box_object_to_world.shape[:2] != box_valid.shape + or box_object_to_world.shape[0] != num_frames + or box_object_to_world.shape[2:] != (4, 4) + or box_lwh.shape[2:] != (3,) + ): + raise ValueError( + "moving boxes must be aligned as (T,M,4,4)/(T,M,3)/(T,M), " + f"got {tuple(box_object_to_world.shape)}, " + f"{tuple(box_lwh.shape)}, {tuple(box_valid.shape)}" + ) + if actor_box_time_mode not in _ACTOR_BOX_TIME_MODES: + raise ValueError( + f"unsupported actor box time mode {actor_box_time_mode!r}; " + f"expected {_ACTOR_BOX_TIME_MODES}" + ) + track_ids = None + if box_track_id is not None: + track_ids = torch.as_tensor( + box_track_id, device=video.device, dtype=torch.long + ) + if track_ids.shape != box_valid.shape: + raise ValueError( + "box_track_id must align with box_valid, got " + f"{tuple(track_ids.shape)} and {tuple(box_valid.shape)}" + ) + if actor_box_time_mode != "frame" and track_ids is None: + raise ValueError( + "ray-time actor box interpolation requires box_track_id" + ) + object_to_world_all = torch.as_tensor( + box_object_to_world, device=video.device, dtype=torch.float32 + ) + lwh_all = torch.as_tensor( + box_lwh, device=video.device, dtype=torch.float32 + ) + valid_boxes_all = torch.as_tensor( + box_valid, device=video.device, dtype=torch.bool + ) + rays = torch.as_tensor( + ray_dirs, device=video.device, dtype=torch.float32 + ) + if rays.shape != (height, width, 3): + raise ValueError( + "ray grid must match the video spatial shape, got " + f"{tuple(rays.shape)} vs {(height, width, 3)}" + ) + if point_chunk_size <= 0: + raise ValueError("point_chunk_size must be positive") + + filtered = video.clone() + removed_count = 0 + valid_count = 0 + c_min = min_range if not inverse_depth else 1.0 / max_range + c_max = max_range if not inverse_depth else 1.0 / min_range + for frame_idx in range(num_frames): + sweep = video[0, frame_idx].float() + valid = torch.isfinite(sweep) & ( + sweep > float(min_value) + 1.0e-5 + ) + flat_indices = valid.reshape(-1).nonzero(as_tuple=False).flatten() + valid_count += int(flat_indices.numel()) + frame_boxes = box_valid[frame_idx].to( + device=video.device, dtype=torch.bool + ) + if flat_indices.numel() == 0 or not bool(frame_boxes.any()): + continue + + if min_value == -1: + depth = (sweep + 1.0) * 0.5 * (c_max - c_min) + c_min + else: + depth = sweep * (c_max - c_min) + c_min + if inverse_depth: + depth = depth.reciprocal() + points_sensor = ( + depth[..., None] * rays + ).reshape(-1, 3).index_select(0, flat_indices) + columns = torch.remainder(flat_indices, width).to( + dtype=points_sensor.dtype + ) + fractions = columns / float(max(width - 1, 1)) + if motion is not None: + points_sensor = _fractional_transform_points_torch( + points_sensor, + torch.linalg.inv(motion[frame_idx]), + fractions, + ) + + pose = poses[frame_idx] + points_world = ( + points_sensor @ pose[:3, :3].T + pose[:3, 3] + ) + remove = torch.zeros( + points_world.shape[0], + device=video.device, + dtype=torch.bool, + ) + if actor_box_time_mode == "frame": + object_to_world = object_to_world_all[frame_idx, frame_boxes] + half_lwh = 0.5 * lwh_all[frame_idx, frame_boxes] + centers = object_to_world[:, :3, 3] + rotations = object_to_world[:, :3, :3] + for start in range(0, points_world.shape[0], point_chunk_size): + end = min(start + point_chunk_size, points_world.shape[0]) + delta = points_world[start:end, None, :] - centers[None] + points_object = torch.einsum( + "nmi,mij->nmj", delta, rotations + ) + remove[start:end] = ( + points_object.abs() <= half_lwh[None] + 1.0e-3 + ).all(dim=-1).any(dim=-1) + else: + assert track_ids is not None + for box_idx in valid_boxes_all[frame_idx].nonzero( + as_tuple=False + ).flatten().tolist(): + start_pose, end_pose, _ = _actor_pose_interval_torch( + object_to_world_all, + valid_boxes_all, + track_ids, + frame_idx, + box_idx, + actor_box_time_mode, + ) + for start in range(0, points_world.shape[0], point_chunk_size): + end = min(start + point_chunk_size, points_world.shape[0]) + points_object = _world_points_to_actor_local_torch( + points_world[start:end], + start_pose, + end_pose, + fractions[start:end], + ) + remove[start:end] |= ( + points_object.abs() + <= 0.5 * lwh_all[frame_idx, box_idx] + 1.0e-3 + ).all(dim=1) + + remove_indices = flat_indices[remove] + removed_count += int(remove_indices.numel()) + filtered[:, frame_idx].reshape(video.shape[0], -1)[ + :, remove_indices + ] = float(min_value) + + fraction = filtered.new_tensor( + float(removed_count) / float(max(valid_count, 1)), + dtype=torch.float32, + ) + return filtered, fraction + + +def local_hit_density_confidence( + hit: torch.Tensor, + *, + kernel_size: int = 5, + saturation_hits: float = 5.0, +) -> torch.Tensor: + """Return circular-azimuth local hit density in ``[0, 1]``.""" + if hit.ndim < 2: + raise ValueError(f"hit must end in (H,W), got {tuple(hit.shape)}") + if kernel_size <= 0 or kernel_size % 2 == 0: + raise ValueError( + f"kernel_size must be a positive odd integer, got {kernel_size}" + ) + if saturation_hits <= 0.0: + raise ValueError( + f"saturation_hits must be positive, got {saturation_hits}" + ) + density_input = hit.float().reshape( + -1, 1, hit.shape[-2], hit.shape[-1] + ) + pad = kernel_size // 2 + if pad: + density_input = torch.cat( + [ + density_input[..., -pad:], + density_input, + density_input[..., :pad], + ], + dim=-1, + ) + density_counts = torch.nn.functional.conv2d( + density_input, + torch.ones( + (1, 1, kernel_size, kernel_size), + device=density_input.device, + dtype=density_input.dtype, + ), + padding=(pad, 0), + ).reshape_as(hit) + return ( + density_counts / float(saturation_hits) + ).clamp_(0.0, 1.0) * hit.float() + + +def spatial_warp_window( + global_warp: torch.Tensor, + window_start: int, + window_frames: int, + *, + input_has_prepend: bool = True, +) -> torch.Tensor: + """Build a model-aligned window from a global warp stream.""" + if global_warp.ndim != 5: + raise ValueError( + f"global_warp must be (B,C,T,H,W), got {global_warp.shape}" + ) + if window_start < 0 or window_frames <= 0: + raise ValueError( + f"invalid warp window start={window_start}, frames={window_frames}" + ) + if not input_has_prepend: + result = global_warp[ + :, :, window_start : window_start + window_frames + ] + if result.shape[2] != window_frames: + raise ValueError( + "global warp does not contain the requested unique-frame " + f"window: start={window_start}, frames={window_frames}, " + f"available_T={global_warp.shape[2]}" + ) + return result.contiguous() + if window_start == 0: + result = global_warp[:, :, : window_frames + 1] + else: + first_real_token = window_start + 1 + real = global_warp[ + :, :, first_real_token : first_real_token + window_frames + ] + if real.shape[2] != window_frames: + raise ValueError( + "global warp does not contain the requested real-frame window: " + f"start={window_start}, frames={window_frames}, " + f"available_T={global_warp.shape[2]}" + ) + result = torch.cat([real[:, :, :1], real], dim=2) + if result.shape[2] != window_frames + 1: + raise ValueError( + f"warp window has T={result.shape[2]}, expected {window_frames + 1}" + ) + return result.contiguous() + + +def lidar_poses_for_global_tokens( + lidar_to_world: torch.Tensor, + global_start: int, + block_size: int, + *, + input_has_prepend: bool = True, +) -> torch.Tensor: + """Map global token indices to their real LiDAR target poses.""" + if lidar_to_world.ndim != 3 or lidar_to_world.shape[1:] != (4, 4): + raise ValueError( + "lidar_to_world must be (S,4,4), got " + f"{tuple(lidar_to_world.shape)}" + ) + token_indices = torch.arange( + global_start, + global_start + block_size, + device=lidar_to_world.device, + dtype=torch.long, + ) + pose_indices = (token_indices - int(input_has_prepend)).clamp( + min=0, max=lidar_to_world.shape[0] - 1 + ) + return lidar_to_world.index_select(0, pose_indices) + + +@torch.autocast("cuda", enabled=False) +def sensor_tables_from_ray_directions( + ray_dirs: Any, + *, + allow_approximate: bool = False, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Recover coarse elevation/azimuth tables from calibrated rays. + + Native spinning-LiDAR grids encode azimuth as one shared column table plus + a constant per-row offset. Some calibrated grids are not exactly separable; + callers that retain the exact ray grid can allow an approximate table for + coarse lookup and refine against the original rays during rasterization. + """ + rays = torch.as_tensor(ray_dirs, dtype=torch.float32) + if rays.ndim != 3 or rays.shape[-1] != 3: + raise ValueError( + f"ray_dirs must be (H,W,3), got {tuple(rays.shape)}" + ) + norm = torch.linalg.vector_norm(rays, dim=-1, keepdim=True) + if not torch.isfinite(norm).all() or bool((norm <= 0).any()): + raise ValueError("ray_dirs must contain finite nonzero vectors") + rays = rays / norm + + elevation_grid = torch.atan2( + rays[..., 2], + torch.linalg.vector_norm(rays[..., :2], dim=-1), + ) + elevations = elevation_grid.mean(dim=1) + azimuth_grid = torch.atan2(rays[..., 1], rays[..., 0]) + azimuths = azimuth_grid[0].contiguous() + relative = _wrap_angle_torch(azimuth_grid - azimuths[None]) + row_offsets = torch.atan2( + torch.sin(relative).mean(dim=1), + torch.cos(relative).mean(dim=1), + ) + + reconstructed = torch.stack( + ( + torch.cos(elevations)[:, None] + * torch.cos(azimuths[None] + row_offsets[:, None]), + torch.cos(elevations)[:, None] + * torch.sin(azimuths[None] + row_offsets[:, None]), + torch.sin(elevations)[:, None].expand(-1, rays.shape[1]), + ), + dim=-1, + ) + max_error = torch.linalg.vector_norm( + reconstructed - rays, dim=-1 + ).max() + if not torch.isfinite(max_error): + raise ValueError("reconstructed sensor rays must be finite") + if float(max_error) > 1e-3 and not allow_approximate: + raise ValueError( + "sensor rays are not representable by a spinning-LiDAR row/column " + f"grid (max direction error={float(max_error):.6g})" + ) + return elevations, azimuths, row_offsets + + +class TorchSpatialPointMap: + """Persistent pose-registered voxel map and local LiDAR rasterizer. + + Points remain on the caller's device and are compacted to one newest point + per globally anchored voxel when new sweeps are appended. The optional + ``persistent_static`` policy promotes a voxel only after it is occupied in + enough selected observation units. ``block`` counts at most once per + committed block, while ``frame`` counts at most once per distinct frame + within that block. The newest sweep can remain as an ephemeral layer so + current dynamic objects stay visible without leaving long trails. Optional + free-space clearing removes a confirmed voxel only + after repeated in-range current rays pass through it to farther returns; + nearer returns, missing rays, and out-of-range voxels are treated as + unobservable. Rendering queries a GPU-resident coarse XY cell index, + applies an exact target-local radius mask to that temporary subset, and + leaves the global map unchanged. + """ + + @torch.autocast("cuda", enabled=False) + def __init__( + self, + *, + ray_dirs: Any, + row_elevations_rad: Any, + column_azimuths_rad: Any, + row_azimuth_offsets_rad: Any, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + radius_m: float = 75.0, + voxel_size_m: float = 0.2, + voxel_policy: str = "newest", + observation_unit: str = "block", + static_min_observations: int = 2, + candidate_ttl_updates: int = 1, + include_latest: bool = True, + free_space_clear: bool = False, + free_space_margin_m: float = 0.75, + free_space_misses_to_remove: int = 2, + feature_channels: int = 0, + device: torch.device | str | None = None, + ): + if radius_m <= 0.0: + raise ValueError(f"radius_m must be positive, got {radius_m}") + if voxel_size_m <= 0.0: + raise ValueError( + f"voxel_size_m must be positive, got {voxel_size_m}" + ) + if voxel_policy not in ("newest", "persistent_static"): + raise ValueError( + f"unsupported voxel policy {voxel_policy!r}; expected " + "'newest' or 'persistent_static'" + ) + if observation_unit not in ("block", "frame"): + raise ValueError( + f"unsupported observation unit {observation_unit!r}; expected " + "'block' or 'frame'" + ) + if static_min_observations < 1: + raise ValueError( + "static_min_observations must be positive, got " + f"{static_min_observations}" + ) + if candidate_ttl_updates < 1: + raise ValueError( + "candidate_ttl_updates must be positive, got " + f"{candidate_ttl_updates}" + ) + if free_space_clear and voxel_policy != "persistent_static": + raise ValueError( + "free_space_clear requires voxel_policy='persistent_static'" + ) + if free_space_margin_m <= 0.0: + raise ValueError( + "free_space_margin_m must be positive, got " + f"{free_space_margin_m}" + ) + if free_space_misses_to_remove < 1: + raise ValueError( + "free_space_misses_to_remove must be positive, got " + f"{free_space_misses_to_remove}" + ) + self.ray_dirs = torch.as_tensor( + ray_dirs, device=device, dtype=torch.float32 + ).contiguous() + if self.ray_dirs.ndim != 3 or self.ray_dirs.shape[-1] != 3: + raise ValueError( + f"ray_dirs must be (H,W,3), got {self.ray_dirs.shape}" + ) + ray_norm = torch.linalg.vector_norm( + self.ray_dirs, dim=-1, keepdim=True + ) + if not torch.isfinite(ray_norm).all() or bool((ray_norm <= 0).any()): + raise ValueError("ray_dirs must contain finite nonzero vectors") + self.ray_dirs = (self.ray_dirs / ray_norm).contiguous() + self.height, self.width = map(int, self.ray_dirs.shape[:2]) + self.elev = torch.as_tensor( + row_elevations_rad, device=self.ray_dirs.device, dtype=torch.float32 + ).contiguous() + self.azim = torch.as_tensor( + column_azimuths_rad, + device=self.ray_dirs.device, + dtype=torch.float32, + ).contiguous() + self.row_off = torch.as_tensor( + row_azimuth_offsets_rad, + device=self.ray_dirs.device, + dtype=torch.float32, + ).contiguous() + if self.elev.shape != (self.height,): + raise ValueError( + f"row elevations must be {(self.height,)}, got {self.elev.shape}" + ) + if self.row_off.shape != (self.height,): + raise ValueError( + f"row offsets must be {(self.height,)}, got {self.row_off.shape}" + ) + if self.azim.shape != (self.width,): + raise ValueError( + f"column azimuths must be {(self.width,)}, got {self.azim.shape}" + ) + + self.elev_order = torch.argsort(self.elev, stable=True) + self.elev_sorted = self.elev[self.elev_order].contiguous() + azim_wrapped = _wrap_angle_torch(self.azim) + self.azim_order = torch.argsort(azim_wrapped, stable=True) + self.azim_sorted = azim_wrapped[self.azim_order].contiguous() + reconstructed_dirs = torch.stack( + ( + torch.cos(self.elev)[:, None] + * torch.cos(self.azim[None] + self.row_off[:, None]), + torch.cos(self.elev)[:, None] + * torch.sin(self.azim[None] + self.row_off[:, None]), + torch.sin(self.elev)[:, None].expand(-1, self.width), + ), + dim=-1, + ) + table_error = torch.linalg.vector_norm( + reconstructed_dirs - self.ray_dirs, dim=-1 + ).max() + if not torch.isfinite(table_error): + raise ValueError("sensor lookup tables must reconstruct finite rays") + self.refine_exact_beam_lookup = bool(float(table_error) > 1e-3) + self.min_range = float(min_range) + self.max_range = float(max_range) + self.min_value = float(min_value) + self.inverse_depth = bool(inverse_depth) + self.radius_m = float(radius_m) + self.voxel_size_m = float(voxel_size_m) + self.voxel_policy = voxel_policy + self.observation_unit = observation_unit + self.static_min_observations = int(static_min_observations) + self.candidate_ttl_updates = int(candidate_ttl_updates) + self.include_latest = bool(include_latest) + self.free_space_clear = bool(free_space_clear) + self.free_space_margin_m = float(free_space_margin_m) + self.free_space_misses_to_remove = int(free_space_misses_to_remove) + self.feature_channels = int(feature_channels) + if self.feature_channels < 0: + raise ValueError("feature_channels must be non-negative") + # A current beam must pass through the stored voxel, up to 10 cm of + # calibration/pose slack, before a farther return counts as free space. + self.free_space_lateral_tolerance_m = ( + 0.5 * math.sqrt(3.0) * self.voxel_size_m + 0.1 + ) + # Four cells per radius keeps the coarse square query close to the + # exact target disk while requiring only a fixed 9x9 lookup stencil. + self.spatial_cell_size_m = max( + self.voxel_size_m, self.radius_m / 4.0 + ) + cell_radius = int( + math.ceil(self.radius_m / self.spatial_cell_size_m) + ) + cell_axis = torch.arange( + -cell_radius, + cell_radius + 1, + device=self.ray_dirs.device, + dtype=torch.int64, + ) + cell_x, cell_y = torch.meshgrid( + cell_axis, cell_axis, indexing="ij" + ) + self.query_cell_offsets = torch.stack( + [cell_x.reshape(-1), cell_y.reshape(-1)], dim=1 + ).contiguous() + self.points_world = torch.empty( + (0, 3), device=self.ray_dirs.device, dtype=torch.float32 + ) + self.point_features = torch.empty( + (0, self.feature_channels), + device=self.ray_dirs.device, + dtype=torch.float32, + ) + self.timestamps = torch.empty( + (0,), device=self.ray_dirs.device, dtype=torch.long + ) + self.observation_counts = torch.empty( + (0,), device=self.ray_dirs.device, dtype=torch.long + ) + self.last_seen_updates = torch.empty( + (0,), device=self.ray_dirs.device, dtype=torch.long + ) + self.free_miss_counts = torch.empty( + (0,), device=self.ray_dirs.device, dtype=torch.long + ) + self.latest_points_world = torch.empty( + (0, 3), device=self.ray_dirs.device, dtype=torch.float32 + ) + self.latest_point_features = torch.empty( + (0, self.feature_channels), + device=self.ray_dirs.device, + dtype=torch.float32, + ) + self.latest_timestamp = -1 + self._update_index = -1 + self.last_free_space_cleared = 0 + self.total_free_space_cleared = 0 + # One packed coarse-XY key per point, sorted for searchsorted lookup. + self.cell_keys = torch.empty( + (0,), device=self.ray_dirs.device, dtype=torch.int64 + ) + + @property + def num_points(self) -> int: + return int(self.points_world.shape[0]) + + @property + def confirmed_mask(self) -> torch.Tensor: + if self.voxel_policy != "persistent_static": + return torch.ones( + self.points_world.shape[0], + device=self.points_world.device, + dtype=torch.bool, + ) + if self.observation_counts.shape[0] != self.points_world.shape[0]: + raise RuntimeError("persistent-static observation state is stale") + return self.observation_counts >= self.static_min_observations + + @property + def confirmed_points_world(self) -> torch.Tensor: + return self.points_world[self.confirmed_mask] + + @property + def confirmed_point_features(self) -> torch.Tensor: + return self.point_features[self.confirmed_mask] + + @property + def num_confirmed_points(self) -> int: + return int(self.confirmed_mask.sum().item()) + + @property + def num_candidate_points(self) -> int: + return self.num_points - self.num_confirmed_points + + @property + def num_latest_points(self) -> int: + return int(self.latest_points_world.shape[0]) + + def _normalized_sweep_to_metric( + self, normalized_range: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + sweep = normalized_range.to( + device=self.ray_dirs.device, dtype=torch.float32 + ) + if sweep.ndim == 3 and sweep.shape[0] == 1: + sweep = sweep[0] + if sweep.shape != (self.height, self.width): + raise ValueError( + "normalized sweep must match the ray grid: " + f"got {tuple(sweep.shape)}, expected " + f"{(self.height, self.width)}" + ) + valid = torch.isfinite(sweep) & ( + sweep > self.min_value + 1.0e-5 + ) + c_min = ( + self.min_range + if not self.inverse_depth + else 1.0 / self.max_range + ) + c_max = ( + self.max_range + if not self.inverse_depth + else 1.0 / self.min_range + ) + if self.min_value == -1: + depth = (sweep + 1.0) * 0.5 * (c_max - c_min) + c_min + else: + depth = sweep * (c_max - c_min) + c_min + if self.inverse_depth: + depth = depth.reciprocal() + return depth, valid + + def _sweep_to_world( + self, + normalized_range: torch.Tensor, + lidar_to_world: torch.Tensor, + pose_sensor_start_end: torch.Tensor | None = None, + ) -> torch.Tensor: + pose = lidar_to_world.to( + device=self.ray_dirs.device, dtype=torch.float32 + ) + if pose.shape != (4, 4): + raise ValueError(f"lidar_to_world must be (4,4), got {pose.shape}") + + depth, valid = self._normalized_sweep_to_metric(normalized_range) + points_local = (depth[..., None] * self.ray_dirs)[valid] + if points_local.numel() == 0: + return self.points_world.new_empty((0, 3)) + if pose_sensor_start_end is not None: + relative = torch.as_tensor( + pose_sensor_start_end, + device=points_local.device, + dtype=points_local.dtype, + ) + if relative.shape != (4, 4): + raise ValueError( + "pose_sensor_start_end must be (4,4), got " + f"{tuple(relative.shape)}" + ) + columns = torch.arange( + self.width, + device=points_local.device, + dtype=points_local.dtype, + ).view(1, self.width).expand(self.height, self.width)[valid] + fractions = columns / float(max(self.width - 1, 1)) + points_local = _fractional_transform_points_torch( + points_local, + torch.linalg.inv(relative), + fractions, + ) + return ( + points_local @ pose[:3, :3].T + pose[:3, 3].unsqueeze(0) + ) + + def _sweep_to_world_with_features( + self, + normalized_range: torch.Tensor, + point_features: torch.Tensor | None, + lidar_to_world: torch.Tensor, + pose_sensor_start_end: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Lift one sweep and preserve attributes on the same valid returns.""" + points_world = self._sweep_to_world( + normalized_range, + lidar_to_world, + pose_sensor_start_end, + ) + if self.feature_channels == 0: + if ( + point_features is not None + and torch.as_tensor(point_features).numel() > 0 + ): + raise ValueError("this spatial map was created without features") + return points_world, self.point_features.new_empty( + (points_world.shape[0], 0) + ) + if point_features is None: + raise ValueError( + f"spatial map requires {self.feature_channels} point features" + ) + features = torch.as_tensor( + point_features, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if features.ndim == 2 and self.feature_channels == 1: + features = features.unsqueeze(0) + if features.shape != ( + self.feature_channels, + self.height, + self.width, + ): + raise ValueError( + "point features must be (F,H,W), got " + f"{tuple(features.shape)}" + ) + _, valid = self._normalized_sweep_to_metric(normalized_range) + selected = features[:, valid].T.contiguous() + if selected.shape[0] != points_world.shape[0]: + raise RuntimeError("range points and point features lost alignment") + return points_world, selected + + @torch.autocast("cuda", enabled=False) + def _nearest_beam_indices( + self, points_sensor: torch.Tensor, ranges: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + point_elev = torch.asin( + (points_sensor[:, 2] / ranges).clamp(-1.0, 1.0) + ) + elev_idx = torch.searchsorted(self.elev_sorted, point_elev) + elev_idx0 = (elev_idx - 1).clamp(0, self.height - 1) + elev_idx1 = elev_idx.clamp(0, self.height - 1) + elev_dist0 = (point_elev - self.elev_sorted[elev_idx0]).abs() + elev_dist1 = (point_elev - self.elev_sorted[elev_idx1]).abs() + choose0 = (elev_dist0 < elev_dist1) | ( + (elev_dist0 == elev_dist1) + & ( + self.elev_order[elev_idx0] + <= self.elev_order[elev_idx1] + ) + ) + nearest_sorted = torch.where(choose0, elev_idx0, elev_idx1) + rows = self.elev_order[nearest_sorted] + + point_azim = _wrap_angle_torch( + torch.atan2(points_sensor[:, 1], points_sensor[:, 0]) + - self.row_off[rows] + ) + azim_idx = torch.searchsorted(self.azim_sorted, point_azim) + azim_idx0 = torch.remainder(azim_idx - 1, self.width) + azim_idx1 = torch.remainder(azim_idx, self.width) + azim_dist0 = _wrap_angle_torch( + point_azim - self.azim_sorted[azim_idx0] + ).abs() + azim_dist1 = _wrap_angle_torch( + point_azim - self.azim_sorted[azim_idx1] + ).abs() + nearest_azim = torch.where( + azim_dist0 <= azim_dist1, azim_idx0, azim_idx1 + ) + columns = self.azim_order[nearest_azim] + if not self.refine_exact_beam_lookup or points_sensor.shape[0] == 0: + return rows, columns + + unit_directions = points_sensor / ranges[:, None] + refined_rows = torch.empty_like(rows) + refined_columns = torch.empty_like(columns) + row_deltas = torch.arange( + -3, 4, device=rows.device, dtype=torch.long + ) + column_deltas = torch.arange( + -4, 4, device=rows.device, dtype=torch.long + ) + # Bound temporary candidate tensors for long persistent-map queries. + for start in range(0, points_sensor.shape[0], 32768): + stop = min(start + 32768, points_sensor.shape[0]) + directions = unit_directions[start:stop] + row_sorted = nearest_sorted[start:stop, None] + row_deltas[None] + row_sorted = row_sorted.clamp(0, self.height - 1) + candidate_rows = self.elev_order[row_sorted] + + point_azimuth = torch.atan2(directions[:, 1], directions[:, 0]) + adjusted_azimuth = _wrap_angle_torch( + point_azimuth[:, None] - self.row_off[candidate_rows] + ).contiguous() + column_sorted = torch.searchsorted( + self.azim_sorted, adjusted_azimuth + ) + column_sorted = torch.remainder( + column_sorted[..., None] + column_deltas, + self.width, + ) + candidate_columns = self.azim_order[column_sorted] + candidate_rays = self.ray_dirs[ + candidate_rows[..., None], candidate_columns + ] + similarity = ( + candidate_rays * directions[:, None, None] + ).sum(dim=-1) + best = similarity.flatten(1).argmax(dim=1) + best_row = torch.div( + best, column_deltas.numel(), rounding_mode="floor" + ) + best_column = torch.remainder(best, column_deltas.numel()) + batch = torch.arange( + stop - start, device=rows.device, dtype=torch.long + ) + refined_rows[start:stop] = candidate_rows[batch, best_row] + refined_columns[start:stop] = candidate_columns[ + batch, best_row, best_column + ] + return refined_rows, refined_columns + + def _apply_free_space_clearing( + self, + normalized_range: torch.Tensor, + lidar_to_world: torch.Tensor, + *, + pose_sensor_start_end: torch.Tensor | None = None, + ) -> int: + """Remove confirmed voxels contradicted by repeated visible free space.""" + if ( + not self.free_space_clear + or self.points_world.shape[0] == 0 + ): + return 0 + if self.free_miss_counts.shape[0] != self.points_world.shape[0]: + raise RuntimeError("persistent-static free-space state is stale") + + pose = lidar_to_world.to( + device=self.points_world.device, dtype=torch.float32 + ) + depth, valid = self._normalized_sweep_to_metric(normalized_range) + map_indices = self._local_point_indices_for_targets( + pose.unsqueeze(0), confirmed_only=True + ) + if map_indices.numel() == 0: + return 0 + points_world = self.points_world[map_indices] + if pose_sensor_start_end is None: + points_sensor = ( + points_world - pose[:3, 3].unsqueeze(0) + ) @ pose[:3, :3] + ranges = torch.linalg.vector_norm(points_sensor, dim=1) + rows, cols = self._nearest_beam_indices( + points_sensor, ranges.clamp_min(1.0e-8) + ) + else: + points_sensor, ranges, rows, cols = ( + self._points_world_to_rolling_sensor( + pose, + points_world, + pose_sensor_start_end, + ) + ) + in_observable_range = ( + (ranges >= self.min_range) + & (ranges <= self.max_range) + ) + if not bool(in_observable_range.any()): + return 0 + + map_indices = map_indices[in_observable_range] + points_sensor = points_sensor[in_observable_range] + ranges = ranges[in_observable_range] + rows = rows[in_observable_range] + cols = cols[in_observable_range] + nearest_dirs = self.ray_dirs[rows, cols] + along_ray = (points_sensor * nearest_dirs).sum(dim=1) + lateral_sq = ( + ranges.square() - along_ray.square() + ).clamp_min(0.0) + near_real_beam = ( + (along_ray > 0.0) + & ( + lateral_sq + <= self.free_space_lateral_tolerance_m**2 + ) + ) + if not bool(near_real_beam.any()): + return 0 + + map_indices = map_indices[near_real_beam] + ranges = ranges[near_real_beam] + rows = rows[near_real_beam] + cols = cols[near_real_beam] + offsets = torch.arange( + -1, 2, device=rows.device, dtype=torch.long + ) + row_grid, col_grid = torch.meshgrid( + offsets, offsets, indexing="ij" + ) + neighbor_rows = ( + rows[:, None] + row_grid.reshape(1, -1) + ).clamp(0, self.height - 1) + neighbor_cols = torch.remainder( + cols[:, None] + col_grid.reshape(1, -1), + self.width, + ) + neighbor_depth = depth[neighbor_rows, neighbor_cols] + neighbor_valid = valid[neighbor_rows, neighbor_cols] + range_delta = neighbor_depth - ranges[:, None] + reobserved = ( + neighbor_valid + & (range_delta.abs() <= self.free_space_margin_m) + ).any(dim=1) + has_valid_return = neighbor_valid.any(dim=1) + all_valid_returns_farther = ( + (~neighbor_valid) + | (range_delta > self.free_space_margin_m) + ).all(dim=1) + contradicted = ( + ~reobserved & has_valid_return & all_valid_returns_farther + ) + + miss_counts = self.free_miss_counts[map_indices] + miss_counts = torch.where( + reobserved, torch.zeros_like(miss_counts), miss_counts + ) + miss_counts = torch.where( + contradicted, miss_counts + 1, miss_counts + ) + self.free_miss_counts[map_indices] = miss_counts + remove_indices = map_indices[ + miss_counts >= self.free_space_misses_to_remove + ] + if remove_indices.numel() == 0: + return 0 + + keep = torch.ones( + self.points_world.shape[0], + device=self.points_world.device, + dtype=torch.bool, + ) + keep[remove_indices] = False + self.points_world = self.points_world[keep] + self.point_features = self.point_features[keep] + self.timestamps = self.timestamps[keep] + self.observation_counts = self.observation_counts[keep] + self.last_seen_updates = self.last_seen_updates[keep] + self.free_miss_counts = self.free_miss_counts[keep] + cleared = int(remove_indices.numel()) + self.total_free_space_cleared += cleared + self._rebuild_cell_index() + return cleared + + def append_block( + self, + normalized_block: torch.Tensor, + lidar_to_world: torch.Tensor, + global_start: int, + *, + point_feature_block: torch.Tensor | None = None, + input_has_prepend: bool = True, + pose_sensor_start_end: torch.Tensor | None = None, + ) -> None: + """Append committed real sweeps using the configured token layout.""" + token_poses = lidar_poses_for_global_tokens( + lidar_to_world.to(device=self.ray_dirs.device), + global_start, + normalized_block.shape[-3], + input_has_prepend=input_has_prepend, + ) + token_motion = ( + lidar_poses_for_global_tokens( + pose_sensor_start_end.to(device=self.ray_dirs.device), + global_start, + normalized_block.shape[-3], + input_has_prepend=input_has_prepend, + ) + if pose_sensor_start_end is not None + else None + ) + self.append_token_block( + normalized_block=normalized_block, + point_feature_block=point_feature_block, + token_lidar_to_world=token_poses, + token_pose_sensor_start_end=token_motion, + global_start=global_start, + input_has_prepend=input_has_prepend, + ) + + def append_token_block( + self, + normalized_block: torch.Tensor, + token_lidar_to_world: torch.Tensor, + global_start: int, + *, + point_feature_block: torch.Tensor | None = None, + input_has_prepend: bool = True, + token_pose_sensor_start_end: torch.Tensor | None = None, + ) -> None: + """Append committed sweeps with one explicit pose per global token.""" + block = normalized_block + if block.ndim == 4: + if block.shape[0] != 1: + raise ValueError( + "normalized block with channels must have C=1, got " + f"{tuple(block.shape)}" + ) + block = block[0] + if block.ndim != 3: + raise ValueError( + f"normalized_block must be (T,H,W), got {tuple(block.shape)}" + ) + feature_block = None + if self.feature_channels > 0: + if point_feature_block is None: + raise ValueError( + f"spatial map requires {self.feature_channels} features" + ) + feature_block = torch.as_tensor( + point_feature_block, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if feature_block.shape != ( + self.feature_channels, + *block.shape, + ): + raise ValueError( + "point_feature_block must be (F,T,H,W), got " + f"{tuple(feature_block.shape)}" + ) + elif ( + point_feature_block is not None + and torch.as_tensor(point_feature_block).numel() > 0 + ): + raise ValueError("this spatial map was created without features") + poses = token_lidar_to_world.to(device=self.ray_dirs.device) + if poses.shape != (block.shape[0], 4, 4): + raise ValueError( + "token_lidar_to_world must be (T,4,4) aligned with the block, " + f"got {tuple(poses.shape)} for T={block.shape[0]}" + ) + motion = None + if token_pose_sensor_start_end is not None: + motion = token_pose_sensor_start_end.to( + device=self.ray_dirs.device, dtype=torch.float32 + ) + if motion.shape != (block.shape[0], 4, 4): + raise ValueError( + "token_pose_sensor_start_end must be (T,4,4) aligned " + f"with the block, got {tuple(motion.shape)} for " + f"T={block.shape[0]}" + ) + new_points = [] + new_features = [] + new_times = [] + latest_points = self.points_world.new_empty((0, 3)) + latest_features = self.point_features.new_empty( + (0, self.feature_channels) + ) + latest_timestamp = -1 + latest_sweep = None + latest_pose = None + latest_motion = None + self.last_free_space_cleared = 0 + self._update_index += 1 + update_index = self._update_index + for local_idx in range(block.shape[0]): + global_idx = global_start + local_idx + if input_has_prepend and global_idx == 0: + continue + pose = poses[local_idx] + motion_i = motion[local_idx] if motion is not None else None + points, features = self._sweep_to_world_with_features( + block[local_idx], + ( + None + if feature_block is None + else feature_block[:, local_idx] + ), + pose, + motion_i, + ) + if global_idx >= latest_timestamp: + latest_points = points + latest_features = features + latest_timestamp = global_idx + latest_sweep = block[local_idx] + latest_pose = pose + latest_motion = motion_i + if points.shape[0] > 0: + new_points.append(points) + new_features.append(features) + new_times.append( + torch.full( + (points.shape[0],), + global_idx, + device=points.device, + dtype=torch.long, + ) + ) + self.latest_points_world = latest_points + self.latest_point_features = latest_features + self.latest_timestamp = latest_timestamp + if latest_sweep is not None and latest_pose is not None: + self.last_free_space_cleared = self._apply_free_space_clearing( + latest_sweep, + latest_pose, + pose_sensor_start_end=latest_motion, + ) + if not new_points: + if self.voxel_policy == "persistent_static": + self._compact_global(current_update=update_index) + return + self.points_world = torch.cat( + [self.points_world, *new_points], dim=0 + ) + self.point_features = torch.cat( + [self.point_features, *new_features], dim=0 + ) + self.timestamps = torch.cat( + [self.timestamps, *new_times], dim=0 + ) + if self.voxel_policy == "persistent_static": + if self.observation_counts.shape[0] != ( + self.points_world.shape[0] - sum(x.shape[0] for x in new_points) + ): + raise RuntimeError("persistent-static observation state is stale") + num_new = sum(x.shape[0] for x in new_points) + self.observation_counts = torch.cat( + [ + self.observation_counts, + torch.ones( + num_new, + device=self.points_world.device, + dtype=torch.long, + ), + ] + ) + self.last_seen_updates = torch.cat( + [ + self.last_seen_updates, + torch.full( + (num_new,), + update_index, + device=self.points_world.device, + dtype=torch.long, + ), + ] + ) + self.free_miss_counts = torch.cat( + [ + self.free_miss_counts, + torch.zeros( + num_new, + device=self.points_world.device, + dtype=torch.long, + ), + ] + ) + self._compact_global(current_update=update_index) + else: + self._compact_global() + + def prune_outside_radius( + self, + target_lidar_to_world: torch.Tensor, + radius_m: float, + ) -> None: + """Discard map state outside a bounded radius of the target poses.""" + if radius_m <= 0.0: + raise ValueError(f"radius_m must be positive, got {radius_m}") + poses = target_lidar_to_world.to( + device=self.points_world.device, dtype=torch.float32 + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target poses must be (T,4,4), got {tuple(poses.shape)}" + ) + if self.points_world.shape[0] == 0: + return + keep = torch.zeros( + self.points_world.shape[0], + device=self.points_world.device, + dtype=torch.bool, + ) + radius_sq = float(radius_m) ** 2 + for center in poses[:, :2, 3]: + delta = self.points_world[:, :2] - center.unsqueeze(0) + keep |= delta.square().sum(dim=1) <= radius_sq + self.points_world = self.points_world[keep] + self.point_features = self.point_features[keep] + self.timestamps = self.timestamps[keep] + if self.observation_counts.shape[0] == keep.shape[0]: + self.observation_counts = self.observation_counts[keep] + self.last_seen_updates = self.last_seen_updates[keep] + self.free_miss_counts = self.free_miss_counts[keep] + self._rebuild_cell_index() + + @staticmethod + def _pack_xy_cells(cells: torch.Tensor) -> torch.Tensor: + """Pack signed int32 XY cells losslessly into one signed int64 key.""" + cells64 = cells.to(torch.int64) + x_bits = cells64[..., 0] & 0xFFFFFFFF + y_bits = cells64[..., 1] & 0xFFFFFFFF + return (x_bits << 32) | y_bits + + def _rebuild_cell_index(self) -> None: + if self.points_world.shape[0] == 0: + self.cell_keys = self.cell_keys.new_empty((0,)) + return + xy_cells = torch.floor( + self.points_world[:, :2] / self.spatial_cell_size_m + ).to(torch.int64) + cell_keys = self._pack_xy_cells(xy_cells) + order = torch.argsort(cell_keys, stable=True) + self.points_world = self.points_world[order] + self.point_features = self.point_features[order] + self.timestamps = self.timestamps[order] + if self.voxel_policy == "persistent_static": + self.observation_counts = self.observation_counts[order] + self.last_seen_updates = self.last_seen_updates[order] + self.free_miss_counts = self.free_miss_counts[order] + self.cell_keys = cell_keys[order].contiguous() + + def _compact_global(self, current_update: int | None = None) -> None: + """Keep the newest point per global voxel and rebuild the cell index.""" + if self.points_world.shape[0] == 0: + self.cell_keys = self.cell_keys.new_empty((0,)) + self.point_features = self.point_features.new_empty( + (0, self.feature_channels) + ) + self.observation_counts = self.observation_counts.new_empty((0,)) + self.last_seen_updates = self.last_seen_updates.new_empty((0,)) + self.free_miss_counts = self.free_miss_counts.new_empty((0,)) + return + + voxels = torch.floor( + self.points_world / self.voxel_size_m + ).to(torch.int64) + unique_voxels, inverse = torch.unique( + voxels, dim=0, sorted=True, return_inverse=True + ) + num_voxels = unique_voxels.shape[0] + latest_time = torch.full( + (num_voxels,), + torch.iinfo(torch.int64).min, + device=inverse.device, + dtype=torch.int64, + ) + latest_time.scatter_reduce_( + 0, inverse, self.timestamps, reduce="amax", include_self=True + ) + point_indices = torch.arange( + self.points_world.shape[0], + device=inverse.device, + dtype=torch.int64, + ) + candidates = torch.where( + self.timestamps == latest_time[inverse], + point_indices, + point_indices.new_full((), -1), + ) + selected = torch.full( + (num_voxels,), -1, device=inverse.device, dtype=torch.int64 + ) + selected.scatter_reduce_( + 0, inverse, candidates, reduce="amax", include_self=True + ) + if self.voxel_policy == "persistent_static": + if ( + self.observation_counts.shape[0] != self.points_world.shape[0] + or self.last_seen_updates.shape[0] != self.points_world.shape[0] + or self.free_miss_counts.shape[0] + != self.points_world.shape[0] + ): + raise RuntimeError( + "persistent-static point metadata must align before compaction" + ) + selected_free_misses = self.free_miss_counts[selected] + if current_update is None: + merged_counts = torch.zeros( + num_voxels, + device=inverse.device, + dtype=torch.long, + ) + merged_counts.scatter_reduce_( + 0, + inverse, + self.observation_counts, + reduce="amax", + include_self=True, + ) + else: + is_current = self.last_seen_updates == current_update + old_present = torch.zeros( + num_voxels, + device=inverse.device, + dtype=torch.long, + ) + old_present.scatter_reduce_( + 0, + inverse, + (~is_current).to(torch.long), + reduce="amax", + include_self=True, + ) + current_observations = torch.zeros_like(old_present) + if self.observation_unit == "frame": + current_pairs = torch.stack( + [inverse[is_current], self.timestamps[is_current]], + dim=1, + ) + if current_pairs.shape[0] > 0: + unique_current_pairs = torch.unique( + current_pairs, dim=0 + ) + current_observations.scatter_add_( + 0, + unique_current_pairs[:, 0], + torch.ones( + unique_current_pairs.shape[0], + device=inverse.device, + dtype=torch.long, + ), + ) + else: + current_observations.scatter_reduce_( + 0, + inverse, + is_current.to(torch.long), + reduce="amax", + include_self=True, + ) + old_counts = torch.zeros_like(old_present) + old_counts.scatter_reduce_( + 0, + inverse, + torch.where( + is_current, + self.observation_counts.new_zeros(()), + self.observation_counts, + ), + reduce="amax", + include_self=True, + ) + merged_counts = torch.where( + old_present.bool(), + old_counts + current_observations, + current_observations, + ) + merged_last_seen = torch.full( + (num_voxels,), + torch.iinfo(torch.int64).min, + device=inverse.device, + dtype=torch.long, + ) + merged_last_seen.scatter_reduce_( + 0, + inverse, + self.last_seen_updates, + reduce="amax", + include_self=True, + ) + keep = merged_counts >= self.static_min_observations + if current_update is not None: + oldest_candidate_update = ( + current_update - self.candidate_ttl_updates + 1 + ) + keep |= merged_last_seen >= oldest_candidate_update + selected = selected[keep] + self.observation_counts = merged_counts[keep] + self.last_seen_updates = merged_last_seen[keep] + self.free_miss_counts = selected_free_misses[keep] + self.points_world = self.points_world[selected] + self.point_features = self.point_features[selected] + self.timestamps = self.timestamps[selected] + self._rebuild_cell_index() + + def _points_within_target_radius( + self, points: torch.Tensor, poses: torch.Tensor + ) -> torch.Tensor: + if points.shape[0] == 0: + return points + keep = torch.zeros( + points.shape[0], device=points.device, dtype=torch.bool + ) + radius_sq = self.radius_m * self.radius_m + for center in poses[:, :2, 3]: + delta_xy = points[:, :2] - center.unsqueeze(0) + keep |= delta_xy.square().sum(dim=1) <= radius_sq + return points[keep] + + def _local_point_indices_for_targets( + self, + target_poses: torch.Tensor, + *, + confirmed_only: bool, + ) -> torch.Tensor: + """Query indexed cells and return exact-radius point indices.""" + if self.points_world.shape[0] == 0: + return torch.empty( + (0,), device=self.points_world.device, dtype=torch.long + ) + if self.cell_keys.shape[0] != self.points_world.shape[0]: + raise RuntimeError( + "spatial cell index is stale; points must be appended through " + "append_block" + ) + poses = target_poses.to( + device=self.points_world.device, dtype=torch.float32 + ) + center_cells = torch.floor( + poses[:, :2, 3] / self.spatial_cell_size_m + ).to(torch.int64) + query_cells = ( + center_cells[:, None, :] + self.query_cell_offsets[None, :, :] + ).reshape(-1, 2) + query_keys = torch.unique( + self._pack_xy_cells(query_cells), sorted=True + ) + left = torch.searchsorted(self.cell_keys, query_keys, right=False) + right = torch.searchsorted(self.cell_keys, query_keys, right=True) + counts = right - left + max_count = int(counts.max().item()) + if max_count == 0: + return torch.empty( + (0,), device=self.points_world.device, dtype=torch.long + ) + offsets = torch.arange( + max_count, device=self.points_world.device, dtype=torch.int64 + ) + candidate_indices = left[:, None] + offsets[None, :] + valid_indices = offsets[None, :] < counts[:, None] + candidate_indices = candidate_indices[valid_indices] + if confirmed_only and self.voxel_policy == "persistent_static": + candidate_indices = candidate_indices[ + self.observation_counts[candidate_indices] + >= self.static_min_observations + ] + candidates = self.points_world[candidate_indices] + keep = torch.zeros( + candidates.shape[0], device=candidates.device, dtype=torch.bool + ) + radius_sq = self.radius_m * self.radius_m + for center in poses[:, :2, 3]: + delta_xy = candidates[:, :2] - center.unsqueeze(0) + keep |= delta_xy.square().sum(dim=1) <= radius_sq + return candidate_indices[keep] + + def _local_points_for_targets( + self, target_poses: torch.Tensor + ) -> torch.Tensor: + """Query nearby indexed cells, then apply the exact XY-radius mask.""" + candidate_indices = self._local_point_indices_for_targets( + target_poses, confirmed_only=True + ) + return self.points_world[candidate_indices] + + @staticmethod + def _temporal_confidence_from_counts( + observation_counts: torch.Tensor, + ) -> torch.Tensor: + """Map distinct selected-unit observations to geometry confidence.""" + counts = observation_counts.to(torch.float32) + return torch.where( + counts >= 4, + torch.ones_like(counts), + torch.where( + counts >= 3, + counts.new_full((), 0.8), + torch.where( + counts >= 2, + counts.new_full((), 0.6), + counts.new_full((), 0.2), + ), + ), + ) + + def _project_one( + self, + target_pose: torch.Tensor, + points_world: torch.Tensor, + point_confidence: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + metric = self.points_world.new_full( + (self.height * self.width,), torch.inf + ) + confidence = self.points_world.new_zeros( + (self.height * self.width,) + ) + if points_world.shape[0] == 0: + hit = torch.zeros_like(metric, dtype=torch.bool) + return ( + metric.new_zeros((self.height, self.width)), + hit.view(self.height, self.width), + confidence.view(self.height, self.width), + ) + if ( + point_confidence is not None + and point_confidence.shape != (points_world.shape[0],) + ): + raise ValueError( + "point confidence must align with points: " + f"got {tuple(point_confidence.shape)} for " + f"{points_world.shape[0]} points" + ) + + pose = target_pose.to( + device=self.points_world.device, dtype=torch.float32 + ) + ps = (points_world - pose[:3, 3].unsqueeze(0)) @ pose[ + :3, :3 + ] + ranges = torch.linalg.vector_norm(ps, dim=1) + keep = (ranges >= self.min_range) & (ranges <= self.max_range) + ps = ps[keep] + ranges = ranges[keep] + if point_confidence is not None: + point_confidence = point_confidence[keep] + if ps.shape[0] == 0: + hit = torch.zeros_like(metric, dtype=torch.bool) + return ( + metric.new_zeros((self.height, self.width)), + hit.view(self.height, self.width), + confidence.view(self.height, self.width), + ) + + rows, cols = self._nearest_beam_indices(ps, ranges) + flat_indices = rows * self.width + cols + metric.scatter_reduce_( + 0, flat_indices, ranges, reduce="amin", include_self=True + ) + if point_confidence is not None: + nearest = ranges == metric[flat_indices] + confidence.scatter_reduce_( + 0, + flat_indices[nearest], + point_confidence[nearest], + reduce="amax", + include_self=True, + ) + hit = torch.isfinite(metric) + metric = torch.where(hit, metric, metric.new_zeros(())) + return ( + metric.view(self.height, self.width), + hit.view(self.height, self.width), + confidence.view(self.height, self.width), + ) + + def _gather_nearest_features( + self, + flat_indices: torch.Tensor, + ranges: torch.Tensor, + point_features: torch.Tensor, + metric: torch.Tensor, + ) -> torch.Tensor: + """Gather attributes from the same point that wins the range z-buffer.""" + features = torch.as_tensor( + point_features, + device=self.points_world.device, + dtype=torch.float32, + ) + if features.shape != (ranges.shape[0], self.feature_channels): + raise ValueError( + "point features must align with projected ranges, got " + f"{tuple(features.shape)} for {ranges.shape[0]} ranges" + ) + output = features.new_full( + (self.height * self.width, self.feature_channels), + float(self.min_value), + ) + if ranges.shape[0] == 0 or self.feature_channels == 0: + return output.T.reshape( + self.feature_channels, self.height, self.width + ) + metric_flat = metric.reshape(-1) + nearest = ranges == metric_flat[flat_indices] + source_indices = torch.arange( + ranges.shape[0], device=ranges.device, dtype=torch.long + ) + sentinel = ranges.shape[0] + winners = torch.full( + (self.height * self.width,), + sentinel, + device=ranges.device, + dtype=torch.long, + ) + winners.scatter_reduce_( + 0, + flat_indices[nearest], + source_indices[nearest], + reduce="amin", + include_self=True, + ) + hit = winners < sentinel + output[hit] = features[winners[hit]] + return output.T.reshape( + self.feature_channels, self.height, self.width + ) + + def _project_one_with_features( + self, + target_pose: torch.Tensor, + points_world: torch.Tensor, + point_features: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + metric, hit, _ = self._project_one(target_pose, points_world) + pose = target_pose.to( + device=self.points_world.device, dtype=torch.float32 + ) + points = torch.as_tensor( + points_world, device=self.points_world.device, dtype=torch.float32 + ) + features = torch.as_tensor( + point_features, + device=self.points_world.device, + dtype=torch.float32, + ) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError( + f"points_world must be (N,3), got {tuple(points.shape)}" + ) + if features.shape != (points.shape[0], self.feature_channels): + raise ValueError( + "point features must align with points_world, got " + f"{tuple(features.shape)} and {tuple(points.shape)}" + ) + ps = (points - pose[:3, 3].unsqueeze(0)) @ pose[:3, :3] + ranges = torch.linalg.vector_norm(ps, dim=1) + keep = (ranges >= self.min_range) & (ranges <= self.max_range) + ps = ps[keep] + ranges = ranges[keep] + features = features[keep] + if ranges.shape[0] == 0: + feature_image = features.new_full( + (self.feature_channels, self.height, self.width), + float(self.min_value), + ) + else: + rows, cols = self._nearest_beam_indices(ps, ranges) + feature_image = self._gather_nearest_features( + rows * self.width + cols, + ranges, + features, + metric, + ) + return metric, hit, feature_image + + def _points_world_to_rolling_sensor( + self, + target_pose: torch.Tensor, + points_world: torch.Tensor, + pose_sensor_start_end: torch.Tensor, + *, + projection_iterations: int = 3, + ) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + ]: + """Project world points into their time-dependent target sensor frame.""" + if projection_iterations <= 0: + raise ValueError("projection_iterations must be positive") + pose = target_pose.to( + device=self.points_world.device, dtype=torch.float32 + ) + relative = torch.as_tensor( + pose_sensor_start_end, + device=self.points_world.device, + dtype=torch.float32, + ) + if relative.shape != (4, 4): + raise ValueError( + "pose_sensor_start_end must be (4,4), got " + f"{tuple(relative.shape)}" + ) + points_start = ( + points_world - pose[:3, 3].unsqueeze(0) + ) @ pose[:3, :3] + if points_start.shape[0] == 0: + empty_long = torch.empty( + (0,), device=points_start.device, dtype=torch.long + ) + return ( + points_start, + points_start.new_empty((0,)), + empty_long, + empty_long, + ) + + start_ranges = torch.linalg.vector_norm(points_start, dim=1) + _, columns = self._nearest_beam_indices( + points_start, start_ranges.clamp_min(1.0e-8) + ) + for _ in range(projection_iterations): + fractions = columns.to(points_start.dtype) / float( + max(self.width - 1, 1) + ) + points_sensor = _fractional_transform_points_torch( + points_start, relative, fractions + ) + ranges = torch.linalg.vector_norm(points_sensor, dim=1) + _, columns = self._nearest_beam_indices( + points_sensor, ranges.clamp_min(1.0e-8) + ) + + fractions = columns.to(points_start.dtype) / float( + max(self.width - 1, 1) + ) + points_sensor = _fractional_transform_points_torch( + points_start, relative, fractions + ) + ranges = torch.linalg.vector_norm(points_sensor, dim=1) + rows, columns = self._nearest_beam_indices( + points_sensor, ranges.clamp_min(1.0e-8) + ) + return points_sensor, ranges, rows, columns + + def _project_one_rolling( + self, + target_pose: torch.Tensor, + points_world: torch.Tensor, + pose_sensor_start_end: torch.Tensor, + point_confidence: torch.Tensor | None = None, + *, + projection_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Rasterize world points using the target sweep's per-column pose.""" + metric = self.points_world.new_full( + (self.height * self.width,), torch.inf + ) + confidence = self.points_world.new_zeros( + (self.height * self.width,) + ) + if points_world.shape[0] == 0: + hit = torch.zeros_like(metric, dtype=torch.bool) + return ( + metric.new_zeros((self.height, self.width)), + hit.view(self.height, self.width), + confidence.view(self.height, self.width), + ) + if ( + point_confidence is not None + and point_confidence.shape != (points_world.shape[0],) + ): + raise ValueError( + "point confidence must align with points: " + f"got {tuple(point_confidence.shape)} for " + f"{points_world.shape[0]} points" + ) + + _, ranges, rows, cols = self._points_world_to_rolling_sensor( + target_pose, + points_world, + pose_sensor_start_end, + projection_iterations=projection_iterations, + ) + keep = (ranges >= self.min_range) & (ranges <= self.max_range) + ranges = ranges[keep] + rows = rows[keep] + cols = cols[keep] + if point_confidence is not None: + point_confidence = point_confidence[keep] + if ranges.shape[0] == 0: + hit = torch.zeros_like(metric, dtype=torch.bool) + return ( + metric.new_zeros((self.height, self.width)), + hit.view(self.height, self.width), + confidence.view(self.height, self.width), + ) + + flat_indices = rows * self.width + cols + metric.scatter_reduce_( + 0, flat_indices, ranges, reduce="amin", include_self=True + ) + if point_confidence is not None: + nearest = ranges == metric[flat_indices] + confidence.scatter_reduce_( + 0, + flat_indices[nearest], + point_confidence[nearest], + reduce="amax", + include_self=True, + ) + hit = torch.isfinite(metric) + metric = torch.where(hit, metric, metric.new_zeros(())) + return ( + metric.view(self.height, self.width), + hit.view(self.height, self.width), + confidence.view(self.height, self.width), + ) + + def _project_one_rolling_with_features( + self, + target_pose: torch.Tensor, + points_world: torch.Tensor, + point_features: torch.Tensor, + pose_sensor_start_end: torch.Tensor, + *, + projection_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + metric, hit, _ = self._project_one_rolling( + target_pose, + points_world, + pose_sensor_start_end, + projection_iterations=projection_iterations, + ) + _, ranges, rows, cols = self._points_world_to_rolling_sensor( + target_pose, + points_world, + pose_sensor_start_end, + projection_iterations=projection_iterations, + ) + features = torch.as_tensor( + point_features, + device=self.points_world.device, + dtype=torch.float32, + ) + if features.shape != (ranges.shape[0], self.feature_channels): + raise ValueError( + "point features must align with rolling-shutter points, got " + f"{tuple(features.shape)} for {ranges.shape[0]} points" + ) + keep = (ranges >= self.min_range) & (ranges <= self.max_range) + ranges = ranges[keep] + rows = rows[keep] + cols = cols[keep] + features = features[keep] + feature_image = self._gather_nearest_features( + rows * self.width + cols, + ranges, + features, + metric, + ) + return metric, hit, feature_image + + def _project_moving_object_one( + self, + target_pose: torch.Tensor, + local_points: torch.Tensor, + actor_start_pose: torch.Tensor, + actor_end_pose: torch.Tensor, + pose_sensor_start_end: torch.Tensor | None, + *, + projection_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Rasterize one canonical actor with ray-time actor and ego poses.""" + if projection_iterations <= 0: + raise ValueError("projection_iterations must be positive") + metric = self.points_world.new_full( + (self.height * self.width,), torch.inf + ) + points = torch.as_tensor( + local_points, device=self.points_world.device, dtype=torch.float32 + ) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError( + f"local actor points must be (N,3), got {tuple(points.shape)}" + ) + if points.shape[0] == 0: + return ( + metric.new_zeros((self.height, self.width)), + torch.zeros( + (self.height, self.width), + device=metric.device, + dtype=torch.bool, + ), + ) + + pose = target_pose.to(device=metric.device, dtype=torch.float32) + start_actor = actor_start_pose.to( + device=metric.device, dtype=torch.float32 + ) + end_actor = actor_end_pose.to( + device=metric.device, dtype=torch.float32 + ) + relative = ( + None + if pose_sensor_start_end is None + else torch.as_tensor( + pose_sensor_start_end, + device=metric.device, + dtype=torch.float32, + ) + ) + if relative is not None and relative.shape != (4, 4): + raise ValueError( + "pose_sensor_start_end must be (4,4), got " + f"{tuple(relative.shape)}" + ) + + world_end = ( + points @ end_actor[:3, :3].T + end_actor[:3, 3].unsqueeze(0) + ) + points_start = ( + world_end - pose[:3, 3].unsqueeze(0) + ) @ pose[:3, :3] + ranges = torch.linalg.vector_norm(points_start, dim=1) + _, columns = self._nearest_beam_indices( + points_start, ranges.clamp_min(1.0e-8) + ) + + for _ in range(projection_iterations): + fractions = columns.to(points.dtype) / float( + max(self.width - 1, 1) + ) + actor_rotations, actor_translations = ( + _interpolate_pose_components_torch( + start_actor, end_actor, fractions + ) + ) + points_world = ( + torch.einsum( + "ni,nji->nj", points, actor_rotations + ) + + actor_translations + ) + points_start = ( + points_world - pose[:3, 3].unsqueeze(0) + ) @ pose[:3, :3] + points_sensor = ( + points_start + if relative is None + else _fractional_transform_points_torch( + points_start, relative, fractions + ) + ) + ranges = torch.linalg.vector_norm(points_sensor, dim=1) + _, columns = self._nearest_beam_indices( + points_sensor, ranges.clamp_min(1.0e-8) + ) + + fractions = columns.to(points.dtype) / float( + max(self.width - 1, 1) + ) + actor_rotations, actor_translations = ( + _interpolate_pose_components_torch( + start_actor, end_actor, fractions + ) + ) + points_world = ( + torch.einsum("ni,nji->nj", points, actor_rotations) + + actor_translations + ) + points_start = ( + points_world - pose[:3, 3].unsqueeze(0) + ) @ pose[:3, :3] + points_sensor = ( + points_start + if relative is None + else _fractional_transform_points_torch( + points_start, relative, fractions + ) + ) + ranges = torch.linalg.vector_norm(points_sensor, dim=1) + rows, columns = self._nearest_beam_indices( + points_sensor, ranges.clamp_min(1.0e-8) + ) + keep = (ranges >= self.min_range) & (ranges <= self.max_range) + ranges = ranges[keep] + rows = rows[keep] + columns = columns[keep] + if ranges.shape[0] == 0: + return ( + metric.new_zeros((self.height, self.width)), + torch.zeros( + (self.height, self.width), + device=metric.device, + dtype=torch.bool, + ), + ) + flat_indices = rows * self.width + columns + metric.scatter_reduce_( + 0, flat_indices, ranges, reduce="amin", include_self=True + ) + hit = torch.isfinite(metric) + metric = torch.where(hit, metric, metric.new_zeros(())) + return ( + metric.view(self.height, self.width), + hit.view(self.height, self.width), + ) + + def render( + self, + target_lidar_to_world: torch.Tensor, + *, + include_latest: bool | None = None, + target_pose_sensor_start_end: torch.Tensor | None = None, + rolling_shutter_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Render a temporary local query of the persistent global map.""" + poses = target_lidar_to_world.to( + device=self.ray_dirs.device, dtype=torch.float32 + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target poses must be (T,4,4), got {tuple(poses.shape)}" + ) + target_motion = None + if target_pose_sensor_start_end is not None: + target_motion = torch.as_tensor( + target_pose_sensor_start_end, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if target_motion.shape != (poses.shape[0], 4, 4): + raise ValueError( + "target_pose_sensor_start_end must be (T,4,4), got " + f"{tuple(target_motion.shape)} for T={poses.shape[0]}" + ) + local_points = self._local_points_for_targets(poses) + render_latest = ( + self.include_latest + if include_latest is None + else bool(include_latest) + ) + if ( + self.voxel_policy == "persistent_static" + and render_latest + and self.latest_points_world.shape[0] > 0 + ): + latest_points = self._points_within_target_radius( + self.latest_points_world, poses + ) + local_points = torch.cat([local_points, latest_points], dim=0) + metric_frames = [] + hit_frames = [] + for frame_idx, pose in enumerate(poses): + if target_motion is None: + metric, hit, _ = self._project_one(pose, local_points) + else: + metric, hit, _ = self._project_one_rolling( + pose, + local_points, + target_motion[frame_idx], + projection_iterations=rolling_shutter_iterations, + ) + metric_frames.append(metric) + hit_frames.append(hit) + metric_video = torch.stack(metric_frames, dim=0) + hit_video = torch.stack(hit_frames, dim=0) + normalized = _normalize_metric_depth_torch( + metric_video, + self.min_range, + self.max_range, + self.min_value, + self.inverse_depth, + ) + return normalized.unsqueeze(0), hit_video + + def render_with_features( + self, + target_lidar_to_world: torch.Tensor, + *, + include_latest: bool | None = None, + target_pose_sensor_start_end: torch.Tensor | None = None, + rolling_shutter_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Render range and aligned attributes from one shared z-buffer.""" + if self.feature_channels == 0: + normalized, hit = self.render( + target_lidar_to_world, + include_latest=include_latest, + target_pose_sensor_start_end=target_pose_sensor_start_end, + rolling_shutter_iterations=rolling_shutter_iterations, + ) + empty = normalized.new_empty( + (0, normalized.shape[1], self.height, self.width) + ) + return normalized, empty, hit + poses = torch.as_tensor( + target_lidar_to_world, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target poses must be (T,4,4), got {tuple(poses.shape)}" + ) + target_motion = None + if target_pose_sensor_start_end is not None: + target_motion = torch.as_tensor( + target_pose_sensor_start_end, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if target_motion.shape != (poses.shape[0], 4, 4): + raise ValueError( + "target_pose_sensor_start_end must align with target poses" + ) + candidate_indices = self._local_point_indices_for_targets( + poses, confirmed_only=True + ) + points = self.points_world[candidate_indices] + features = self.point_features[candidate_indices] + render_latest = ( + self.include_latest + if include_latest is None + else bool(include_latest) + ) + if ( + self.voxel_policy == "persistent_static" + and render_latest + and self.latest_points_world.shape[0] > 0 + ): + latest_keep = torch.zeros( + self.latest_points_world.shape[0], + device=self.points_world.device, + dtype=torch.bool, + ) + radius_sq = self.radius_m * self.radius_m + for center in poses[:, :2, 3]: + delta = self.latest_points_world[:, :2] - center.unsqueeze(0) + latest_keep |= delta.square().sum(dim=1) <= radius_sq + points = torch.cat( + [points, self.latest_points_world[latest_keep]], dim=0 + ) + features = torch.cat( + [features, self.latest_point_features[latest_keep]], dim=0 + ) + metric_frames = [] + feature_frames = [] + hit_frames = [] + for frame_idx, pose in enumerate(poses): + if target_motion is None: + metric, hit, feature_image = self._project_one_with_features( + pose, points, features + ) + else: + metric, hit, feature_image = ( + self._project_one_rolling_with_features( + pose, + points, + features, + target_motion[frame_idx], + projection_iterations=rolling_shutter_iterations, + ) + ) + metric_frames.append(metric) + feature_frames.append(feature_image) + hit_frames.append(hit) + normalized = _normalize_metric_depth_torch( + torch.stack(metric_frames, dim=0), + self.min_range, + self.max_range, + self.min_value, + self.inverse_depth, + ).unsqueeze(0) + feature_video = torch.stack(feature_frames, dim=1) + return normalized, feature_video, torch.stack(hit_frames, dim=0) + + def render_points_world( + self, + points_world: torch.Tensor, + target_lidar_to_world: torch.Tensor, + *, + target_pose_sensor_start_end: torch.Tensor | None = None, + rolling_shutter_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Render an explicit world-space cloud without mutating the map.""" + points = torch.as_tensor( + points_world, device=self.ray_dirs.device, dtype=torch.float32 + ) + poses = torch.as_tensor( + target_lidar_to_world, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError( + f"points_world must be (N,3), got {tuple(points.shape)}" + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target poses must be (T,4,4), got {tuple(poses.shape)}" + ) + target_motion = None + if target_pose_sensor_start_end is not None: + target_motion = torch.as_tensor( + target_pose_sensor_start_end, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if target_motion.shape != (poses.shape[0], 4, 4): + raise ValueError( + "target_pose_sensor_start_end must be (T,4,4), got " + f"{tuple(target_motion.shape)} for T={poses.shape[0]}" + ) + metric_frames = [] + hit_frames = [] + for frame_idx, pose in enumerate(poses): + if target_motion is None: + metric, hit, _ = self._project_one(pose, points) + else: + metric, hit, _ = self._project_one_rolling( + pose, + points, + target_motion[frame_idx], + projection_iterations=rolling_shutter_iterations, + ) + metric_frames.append(metric) + hit_frames.append(hit) + metric_video = torch.stack(metric_frames, dim=0) + hit_video = torch.stack(hit_frames, dim=0) + normalized = _normalize_metric_depth_torch( + metric_video, + self.min_range, + self.max_range, + self.min_value, + self.inverse_depth, + ) + return normalized.unsqueeze(0), hit_video + + def render_points_world_with_features( + self, + points_world: torch.Tensor, + point_features: torch.Tensor, + target_lidar_to_world: torch.Tensor, + *, + target_pose_sensor_start_end: torch.Tensor | None = None, + rolling_shutter_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Render an explicit attributed world cloud without mutating the map.""" + points = torch.as_tensor( + points_world, device=self.ray_dirs.device, dtype=torch.float32 + ) + features = torch.as_tensor( + point_features, device=self.ray_dirs.device, dtype=torch.float32 + ) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError( + f"points_world must be (N,3), got {tuple(points.shape)}" + ) + if features.shape != (points.shape[0], self.feature_channels): + raise ValueError( + "point_features must align with points_world, got " + f"{tuple(features.shape)} and {tuple(points.shape)}" + ) + poses = torch.as_tensor( + target_lidar_to_world, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target poses must be (T,4,4), got {tuple(poses.shape)}" + ) + target_motion = None + if target_pose_sensor_start_end is not None: + target_motion = torch.as_tensor( + target_pose_sensor_start_end, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if target_motion.shape != (poses.shape[0], 4, 4): + raise ValueError( + "target_pose_sensor_start_end must be (T,4,4), got " + f"{tuple(target_motion.shape)} for T={poses.shape[0]}" + ) + metric_frames = [] + feature_frames = [] + hit_frames = [] + for frame_idx, pose in enumerate(poses): + if target_motion is None: + metric, hit, feature_image = self._project_one_with_features( + pose, points, features + ) + else: + metric, hit, feature_image = ( + self._project_one_rolling_with_features( + pose, + points, + features, + target_motion[frame_idx], + projection_iterations=rolling_shutter_iterations, + ) + ) + metric_frames.append(metric) + feature_frames.append(feature_image) + hit_frames.append(hit) + normalized = _normalize_metric_depth_torch( + torch.stack(metric_frames, dim=0), + self.min_range, + self.max_range, + self.min_value, + self.inverse_depth, + ).unsqueeze(0) + return ( + normalized, + torch.stack(feature_frames, dim=1), + torch.stack(hit_frames, dim=0), + ) + + def render_soft_proposal( + self, + target_lidar_to_world: torch.Tensor, + *, + confirmed_only: bool = False, + target_pose_sensor_start_end: torch.Tensor | None = None, + rolling_shutter_iterations: int = 3, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Render confidence-scored candidate or confirmed map voxels.""" + poses = target_lidar_to_world.to( + device=self.ray_dirs.device, dtype=torch.float32 + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target poses must be (T,4,4), got {tuple(poses.shape)}" + ) + target_motion = None + if target_pose_sensor_start_end is not None: + target_motion = torch.as_tensor( + target_pose_sensor_start_end, + device=self.ray_dirs.device, + dtype=torch.float32, + ) + if target_motion.shape != (poses.shape[0], 4, 4): + raise ValueError( + "target_pose_sensor_start_end must be (T,4,4), got " + f"{tuple(target_motion.shape)} for T={poses.shape[0]}" + ) + point_indices = self._local_point_indices_for_targets( + poses, confirmed_only=confirmed_only + ) + local_points = self.points_world[point_indices] + if self.voxel_policy == "persistent_static": + temporal_confidence = self._temporal_confidence_from_counts( + self.observation_counts[point_indices] + ) + else: + temporal_confidence = local_points.new_ones( + (local_points.shape[0],) + ) + + metric_frames = [] + hit_frames = [] + confidence_frames = [] + for frame_idx, pose in enumerate(poses): + if target_motion is None: + metric, hit, confidence = self._project_one( + pose, local_points, temporal_confidence + ) + else: + metric, hit, confidence = self._project_one_rolling( + pose, + local_points, + target_motion[frame_idx], + temporal_confidence, + projection_iterations=rolling_shutter_iterations, + ) + metric_frames.append(metric) + hit_frames.append(hit) + confidence_frames.append(confidence) + metric_video = torch.stack(metric_frames, dim=0) + hit_video = torch.stack(hit_frames, dim=0) + confidence_video = torch.stack(confidence_frames, dim=0) + normalized = _normalize_metric_depth_torch( + metric_video, + self.min_range, + self.max_range, + self.min_value, + self.inverse_depth, + ) + return normalized.unsqueeze(0), hit_video, confidence_video + + +@torch.no_grad() +def build_lagen_sde_conditions( + previous_video: torch.Tensor, + lidar_to_world: torch.Tensor, + box_object_to_world: torch.Tensor, + box_lwh: torch.Tensor, + box_valid: torch.Tensor, + box_type: torch.Tensor, + *, + ray_dirs: Any, + row_elevations_rad: Any, + column_azimuths_rad: Any, + row_azimuth_offsets_rad: Any, + min_range: float, + max_range: float, + min_value: float, + inverse_depth: bool, +) -> tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + """Build LaGen foreground/background SDE conditions for one frame pair. + + Previous returns inside an annotated box are transformed through the + nearest same-class box at the target frame. Remaining returns stay fixed + in world coordinates and are re-rendered from the target ego pose. + """ + if previous_video.ndim != 4 or previous_video.shape[:2] != (1, 1): + raise ValueError( + "LaGen SDE expects previous_video=(1,1,H,W), got " + f"{tuple(previous_video.shape)}" + ) + poses = torch.as_tensor( + lidar_to_world, device=previous_video.device, dtype=torch.float32 + ) + object_to_world = torch.as_tensor( + box_object_to_world, + device=previous_video.device, + dtype=torch.float32, + ) + lwh = torch.as_tensor( + box_lwh, device=previous_video.device, dtype=torch.float32 + ) + valid_boxes = torch.as_tensor( + box_valid, device=previous_video.device, dtype=torch.bool + ) + types = torch.as_tensor( + box_type, device=previous_video.device, dtype=torch.long + ) + if poses.shape != (2, 4, 4): + raise ValueError( + f"LaGen SDE requires two lidar poses, got {tuple(poses.shape)}" + ) + if ( + object_to_world.ndim != 4 + or object_to_world.shape[0] != 2 + or object_to_world.shape[2:] != (4, 4) + or lwh.shape != (*object_to_world.shape[:2], 3) + or valid_boxes.shape != object_to_world.shape[:2] + or types.shape != object_to_world.shape[:2] + ): + raise ValueError("LaGen SDE box tensors must align over two frames") + + projector = TorchSpatialPointMap( + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=max_range + 1.0, + voxel_size_m=0.15, + voxel_policy="newest", + observation_unit="frame", + static_min_observations=2, + candidate_ttl_updates=1, + include_latest=False, + free_space_clear=False, + device=previous_video.device, + ) + depth, valid_returns = projector._normalized_sweep_to_metric( + previous_video[0, 0] + ) + flat_indices = valid_returns.reshape(-1).nonzero( + as_tuple=False + ).flatten() + if flat_indices.numel() == 0: + empty = previous_video.new_full( + previous_video.shape, float(min_value) + ) + zero = previous_video.new_zeros((), dtype=torch.float32) + return empty, empty.clone(), { + "foreground_fraction": zero, + "matched_objects": zero, + } + points_sensor = ( + depth[..., None] * projector.ray_dirs + ).reshape(-1, 3).index_select(0, flat_indices) + points_world = ( + points_sensor @ poses[0, :3, :3].T + poses[0, :3, 3] + ) + + claimed = torch.zeros( + points_world.shape[0], + device=points_world.device, + dtype=torch.bool, + ) + foreground_world = [] + matched_objects = 0 + for source_idx in valid_boxes[0].nonzero( + as_tuple=False + ).flatten().tolist(): + source_pose = object_to_world[0, source_idx] + local = ( + points_world - source_pose[:3, 3] + ) @ source_pose[:3, :3] + inside = ( + local.abs() <= 0.5 * lwh[0, source_idx] + 1.0e-3 + ).all(dim=1) + inside &= ~claimed + if not bool(inside.any()): + continue + # Object points that have no same-class target match should disappear + # rather than leaking into the static background as a ghost. + claimed |= inside + candidates = valid_boxes[1] & ( + types[1] == types[0, source_idx] + ) + candidate_indices = candidates.nonzero( + as_tuple=False + ).flatten() + if candidate_indices.numel() == 0: + continue + target_centers = object_to_world[ + 1, candidate_indices, :3, 3 + ] + nearest = torch.linalg.vector_norm( + target_centers - source_pose[:3, 3], dim=1 + ).argmin() + target_idx = int(candidate_indices[nearest].item()) + target_pose = object_to_world[1, target_idx] + foreground_world.append( + local[inside] @ target_pose[:3, :3].T + + target_pose[:3, 3] + ) + matched_objects += 1 + + background_points = points_world[~claimed] + foreground_points = ( + torch.cat(foreground_world, dim=0) + if foreground_world + else points_world.new_empty((0, 3)) + ) + background, _ = projector.render_points_world( + background_points, poses[1:2] + ) + foreground, _ = projector.render_points_world( + foreground_points, poses[1:2] + ) + return foreground.to(previous_video.dtype), background.to( + previous_video.dtype + ), { + "foreground_fraction": previous_video.new_tensor( + float(claimed.sum().item()) + / float(max(points_world.shape[0], 1)) + ), + "matched_objects": previous_video.new_tensor( + float(matched_objects) + ), + } + + +@torch.no_grad() +def warp_frozen_observed_history_with_spatial_map( + video: torch.Tensor, + lidar_to_world: torch.Tensor, + observed_mask: torch.Tensor, + *, + ray_dirs: Any, + row_elevations_rad: Any, + column_azimuths_rad: Any, + row_azimuth_offsets_rad: Any, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + radius_m: float = 75.0, + voxel_size_m: float = 0.2, + pose_sensor_start_end: torch.Tensor | None = None, + target_lidar_to_world: torch.Tensor | None = None, + target_pose_sensor_start_end: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Accumulate selected GT frames once, then render from target poses.""" + if video.ndim != 4 or video.shape[0] < 1: + raise ValueError( + "frozen observed history requires (C,T,H,W), got " + f"{tuple(video.shape)}" + ) + num_frames, height, width = map(int, video.shape[1:]) + poses = torch.as_tensor( + lidar_to_world, device=video.device, dtype=torch.float32 + ) + if poses.shape != (num_frames, 4, 4): + raise ValueError( + "frozen observed history requires one pose per unique frame, got " + f"{tuple(poses.shape)} for T={num_frames}" + ) + target_poses = ( + poses + if target_lidar_to_world is None + else torch.as_tensor( + target_lidar_to_world, + device=video.device, + dtype=torch.float32, + ) + ) + if target_poses.shape != (num_frames, 4, 4): + raise ValueError( + "frozen observed history target poses must align one pose per " + f"frame, got {tuple(target_poses.shape)} for T={num_frames}" + ) + motion = None + if pose_sensor_start_end is not None: + motion = torch.as_tensor( + pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + if motion.shape != (num_frames, 4, 4): + raise ValueError( + "frozen observed history requires one start/end transform " + f"per frame, got {tuple(motion.shape)} for T={num_frames}" + ) + target_motion = ( + motion + if target_pose_sensor_start_end is None + else torch.as_tensor( + target_pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + ) + if ( + target_motion is not None + and target_motion.shape != (num_frames, 4, 4) + ): + raise ValueError( + "frozen observed history target motion must align one transform " + f"per frame, got {tuple(target_motion.shape)} for T={num_frames}" + ) + selected = torch.as_tensor( + observed_mask, device=video.device, dtype=torch.bool + ) + if selected.shape != (num_frames,): + raise ValueError( + f"observed_mask must be ({num_frames},), got {tuple(selected.shape)}" + ) + + spatial_map = TorchSpatialPointMap( + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + voxel_policy="newest", + observation_unit="frame", + static_min_observations=2, + candidate_ttl_updates=1, + include_latest=False, + free_space_clear=False, + feature_channels=video.shape[0] - 1, + device=video.device, + ) + if (spatial_map.height, spatial_map.width) != (height, width): + raise ValueError( + "video and frozen spatial-map ray grid must match: " + f"video={(height, width)}, " + f"rays={(spatial_map.height, spatial_map.width)}" + ) + for frame_idx in selected.nonzero(as_tuple=False).flatten().tolist(): + spatial_map.append_token_block( + normalized_block=video[:1, frame_idx : frame_idx + 1], + point_feature_block=video[1:, frame_idx : frame_idx + 1], + token_lidar_to_world=poses[frame_idx : frame_idx + 1], + token_pose_sensor_start_end=( + motion[frame_idx : frame_idx + 1] + if motion is not None + else None + ), + global_start=int(frame_idx), + input_has_prepend=False, + ) + if video.shape[0] == 1: + return spatial_map.render( + target_poses, + include_latest=False, + target_pose_sensor_start_end=target_motion, + ) + rendered_range, rendered_features, hit = spatial_map.render_with_features( + target_poses, + include_latest=False, + target_pose_sensor_start_end=target_motion, + ) + return torch.cat([rendered_range, rendered_features], dim=0), hit + + +@torch.no_grad() +def warp_frozen_object_history_with_spatial_map( + video: torch.Tensor, + lidar_to_world: torch.Tensor, + observed_mask: torch.Tensor, + box_object_to_world: torch.Tensor, + box_lwh: torch.Tensor, + box_valid: torch.Tensor, + box_track_id: torch.Tensor, + *, + ray_dirs: Any, + row_elevations_rad: Any, + column_azimuths_rad: Any, + row_azimuth_offsets_rad: Any, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + radius_m: float = 75.0, + voxel_size_m: float = 0.2, + pose_sensor_start_end: torch.Tensor | None = None, + target_lidar_to_world: torch.Tensor | None = None, + target_pose_sensor_start_end: torch.Tensor | None = None, + actor_box_time_mode: str = "frame", + return_components: bool = False, +) -> ( + tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]] + | tuple[ + torch.Tensor, + torch.Tensor, + dict[str, torch.Tensor], + dict[str, torch.Tensor], + ] +): + """Render frozen static GT plus canonical per-track dynamic clouds.""" + if video.ndim != 4 or video.shape[0] < 1: + raise ValueError( + "frozen object history requires (C,T,H,W), got " + f"{tuple(video.shape)}" + ) + num_frames, height, width = map(int, video.shape[1:]) + poses = torch.as_tensor( + lidar_to_world, device=video.device, dtype=torch.float32 + ) + selected = torch.as_tensor( + observed_mask, device=video.device, dtype=torch.bool + ) + object_to_world = torch.as_tensor( + box_object_to_world, device=video.device, dtype=torch.float32 + ) + lwh = torch.as_tensor( + box_lwh, device=video.device, dtype=torch.float32 + ) + valid_boxes = torch.as_tensor( + box_valid, device=video.device, dtype=torch.bool + ) + track_ids = torch.as_tensor( + box_track_id, device=video.device, dtype=torch.long + ) + if poses.shape != (num_frames, 4, 4): + raise ValueError( + f"lidar_to_world must be ({num_frames},4,4), got {tuple(poses.shape)}" + ) + target_poses = ( + poses + if target_lidar_to_world is None + else torch.as_tensor( + target_lidar_to_world, + device=video.device, + dtype=torch.float32, + ) + ) + if target_poses.shape != (num_frames, 4, 4): + raise ValueError( + "frozen-object target poses must align one pose per frame, got " + f"{tuple(target_poses.shape)} for T={num_frames}" + ) + motion = None + if pose_sensor_start_end is not None: + motion = torch.as_tensor( + pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + if motion.shape != (num_frames, 4, 4): + raise ValueError( + "pose_sensor_start_end must align one transform per frame, " + f"got {tuple(motion.shape)} for T={num_frames}" + ) + target_motion = ( + motion + if target_pose_sensor_start_end is None + else torch.as_tensor( + target_pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + ) + if ( + target_motion is not None + and target_motion.shape != (num_frames, 4, 4) + ): + raise ValueError( + "frozen-object target motion must align one transform per frame, " + f"got {tuple(target_motion.shape)} for T={num_frames}" + ) + if selected.shape != (num_frames,): + raise ValueError( + f"observed_mask must be ({num_frames},), got {tuple(selected.shape)}" + ) + if ( + object_to_world.ndim != 4 + or object_to_world.shape[0] != num_frames + or object_to_world.shape[2:] != (4, 4) + or lwh.shape != (*object_to_world.shape[:2], 3) + or valid_boxes.shape != object_to_world.shape[:2] + or track_ids.shape != object_to_world.shape[:2] + ): + raise ValueError( + "dynamic boxes must be aligned (T,M,4,4)/(T,M,3)/(T,M): " + f"o2w={tuple(object_to_world.shape)}, lwh={tuple(lwh.shape)}, " + f"valid={tuple(valid_boxes.shape)}, ids={tuple(track_ids.shape)}" + ) + if bool(valid_boxes.any()) and not bool( + ((track_ids >= 0) & valid_boxes).any() + ): + raise ValueError( + "frozen-object geometry received moving boxes but no track IDs" + ) + if actor_box_time_mode not in _ACTOR_BOX_TIME_MODES: + raise ValueError( + f"unsupported actor box time mode {actor_box_time_mode!r}; " + f"expected {_ACTOR_BOX_TIME_MODES}" + ) + + projector = TorchSpatialPointMap( + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + voxel_policy="newest", + observation_unit="frame", + static_min_observations=2, + candidate_ttl_updates=1, + include_latest=False, + free_space_clear=False, + feature_channels=video.shape[0] - 1, + device=video.device, + ) + if (projector.height, projector.width) != (height, width): + raise ValueError( + "video and ray grid must match: " + f"video={(height, width)}, rays=" + f"{(projector.height, projector.width)}" + ) + + static_video = video.clone() + object_local_parts: dict[int, list[torch.Tensor]] = {} + object_feature_parts: dict[int, list[torch.Tensor]] = {} + observed_points = 0 + removed_points = 0 + untracked_points = 0 + interpolated_boxes = 0 + fallback_boxes = 0 + for frame_idx in selected.nonzero(as_tuple=False).flatten().tolist(): + _, valid = projector._normalized_sweep_to_metric( + video[0, frame_idx] + ) + flat_indices = valid.reshape(-1).nonzero( + as_tuple=False + ).flatten() + observed_points += int(flat_indices.numel()) + if flat_indices.numel() == 0: + continue + pose = poses[frame_idx] + points_world = projector._sweep_to_world( + video[0, frame_idx], + pose, + motion[frame_idx] if motion is not None else None, + ) + feature_channels = int(video.shape[0] - 1) + if feature_channels == 0: + point_features = video.new_empty((flat_indices.numel(), 0)) + else: + point_features = video[1:, frame_idx].reshape( + feature_channels, -1 + )[:, flat_indices].T.contiguous() + columns = torch.remainder(flat_indices, width).to( + device=video.device, dtype=points_world.dtype + ) + fractions = columns / float(max(width - 1, 1)) + claimed = torch.zeros( + points_world.shape[0], + device=video.device, + dtype=torch.bool, + ) + for box_idx in valid_boxes[frame_idx].nonzero( + as_tuple=False + ).flatten().tolist(): + if actor_box_time_mode == "frame": + box_pose = object_to_world[frame_idx, box_idx] + local = ( + points_world - box_pose[:3, 3] + ) @ box_pose[:3, :3] + else: + start_pose, end_pose, interpolated = ( + _actor_pose_interval_torch( + object_to_world, + valid_boxes, + track_ids, + frame_idx, + box_idx, + actor_box_time_mode, + ) + ) + if interpolated: + interpolated_boxes += 1 + else: + fallback_boxes += 1 + local = _world_points_to_actor_local_torch( + points_world, + start_pose, + end_pose, + fractions, + ) + inside = ( + local.abs() <= 0.5 * lwh[frame_idx, box_idx] + 1.0e-3 + ).all(dim=1) + inside &= ~claimed + if not bool(inside.any()): + continue + claimed |= inside + count = int(inside.sum().item()) + track_id = int(track_ids[frame_idx, box_idx].item()) + if track_id >= 0: + object_local_parts.setdefault(track_id, []).append( + local[inside] + ) + object_feature_parts.setdefault(track_id, []).append( + point_features[inside] + ) + else: + untracked_points += count + removed_points += int(claimed.sum().item()) + static_video[:, frame_idx].reshape(video.shape[0], -1)[ + :, flat_indices[claimed] + ] = float(min_value) + + static_condition, static_hit = ( + warp_frozen_observed_history_with_spatial_map( + static_video, + poses, + selected, + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + pose_sensor_start_end=motion, + target_lidar_to_world=target_poses, + target_pose_sensor_start_end=target_motion, + ) + ) + object_local = { + track_id: torch.cat(parts, dim=0) + for track_id, parts in object_local_parts.items() + } + object_features = { + track_id: torch.cat(parts, dim=0) + for track_id, parts in object_feature_parts.items() + } + dynamic_frames = [] + dynamic_hits = [] + for frame_idx in range(num_frames): + if actor_box_time_mode != "frame": + if video.shape[0] > 1: + raise NotImplementedError( + "attributed frozen-object geometry currently requires " + "actor_box_time_mode='frame'" + ) + actor_frames = [] + actor_hits = [] + emitted: set[int] = set() + for box_idx in valid_boxes[frame_idx].nonzero( + as_tuple=False + ).flatten().tolist(): + track_id = int(track_ids[frame_idx, box_idx].item()) + if track_id < 0 or track_id in emitted: + continue + local = object_local.get(track_id) + if local is None or local.numel() == 0: + continue + start_pose, end_pose, _ = _actor_pose_interval_torch( + object_to_world, + valid_boxes, + track_ids, + frame_idx, + box_idx, + actor_box_time_mode, + ) + metric, hit = projector._project_moving_object_one( + target_poses[frame_idx], + local, + start_pose, + end_pose, + ( + target_motion[frame_idx] + if target_motion is not None + else None + ), + ) + actor_frames.append( + _normalize_metric_depth_torch( + metric, + min_range, + max_range, + min_value, + inverse_depth, + ) + ) + actor_hits.append(hit) + emitted.add(track_id) + if actor_frames: + dynamic_frames.append( + compose_normalized_range_channels( + torch.stack(actor_frames, dim=0), + channel_dim=0, + min_value=min_value, + inverse_depth=inverse_depth, + ) + ) + dynamic_hits.append(torch.stack(actor_hits, dim=0).any(dim=0)) + else: + dynamic_frames.append( + video.new_full((1, height, width), float(min_value)) + ) + dynamic_hits.append( + torch.zeros( + (height, width), + device=video.device, + dtype=torch.bool, + ) + ) + continue + + world_parts = [] + feature_parts = [] + emitted: set[int] = set() + for box_idx in valid_boxes[frame_idx].nonzero( + as_tuple=False + ).flatten().tolist(): + track_id = int(track_ids[frame_idx, box_idx].item()) + if track_id < 0 or track_id in emitted: + continue + local = object_local.get(track_id) + if local is None or local.numel() == 0: + continue + box_pose = object_to_world[frame_idx, box_idx] + world_parts.append( + local @ box_pose[:3, :3].T + box_pose[:3, 3] + ) + feature_parts.append(object_features[track_id]) + emitted.add(track_id) + points_world = ( + torch.cat(world_parts, dim=0) + if world_parts + else video.new_empty((0, 3), dtype=torch.float32) + ) + target_motion_i = ( + target_motion[frame_idx : frame_idx + 1] + if target_motion is not None + else None + ) + if video.shape[0] == 1: + rendered, hit = projector.render_points_world( + points_world, + target_poses[frame_idx : frame_idx + 1], + target_pose_sensor_start_end=target_motion_i, + ) + dynamic_frames.append(rendered[:, 0]) + else: + point_features = ( + torch.cat(feature_parts, dim=0) + if feature_parts + else video.new_empty((0, video.shape[0] - 1)) + ) + rendered, rendered_features, hit = ( + projector.render_points_world_with_features( + points_world, + point_features, + target_poses[frame_idx : frame_idx + 1], + target_pose_sensor_start_end=target_motion_i, + ) + ) + dynamic_frames.append( + torch.cat( + [rendered[:, 0], rendered_features[:, 0]], dim=0 + ) + ) + dynamic_hits.append(hit[0]) + dynamic_condition = torch.stack(dynamic_frames, dim=1).to(video.dtype) + dynamic_hit = torch.stack(dynamic_hits, dim=0) + if video.shape[0] == 1: + condition = compose_normalized_range_channels( + torch.cat([static_condition, dynamic_condition], dim=0), + channel_dim=0, + min_value=min_value, + inverse_depth=inverse_depth, + ) + else: + composed_frames = [] + for frame_idx in range(num_frames): + composed_range, composed_features, _ = ( + compose_normalized_range_feature_layers( + torch.stack( + [ + static_condition[0, frame_idx], + dynamic_condition[0, frame_idx], + ], + dim=0, + ), + torch.stack( + [ + static_condition[1:, frame_idx], + dynamic_condition[1:, frame_idx], + ], + dim=0, + ), + min_value=min_value, + inverse_depth=inverse_depth, + ) + ) + composed_frames.append( + torch.cat([composed_range, composed_features], dim=0) + ) + condition = torch.stack(composed_frames, dim=1).to(video.dtype) + diagnostics = { + "dynamic_removed_fraction": video.new_tensor( + float(removed_points) / float(max(observed_points, 1)) + ), + "dynamic_untracked_fraction": video.new_tensor( + float(untracked_points) / float(max(removed_points, 1)) + ), + "dynamic_tracks": video.new_tensor(float(len(object_local))), + "dynamic_object_points": video.new_tensor( + float(sum(points.shape[0] for points in object_local.values())) + ), + "dynamic_actor_interpolated_boxes": video.new_tensor( + float(interpolated_boxes) + ), + "dynamic_actor_fallback_boxes": video.new_tensor( + float(fallback_boxes) + ), + } + if return_components: + static_range = static_condition[0] + dynamic_range = dynamic_condition[0] + if inverse_depth: + dynamic_visible = dynamic_hit & ( + ~static_hit | (dynamic_range > static_range) + ) + else: + dynamic_visible = dynamic_hit & ( + ~static_hit | (dynamic_range < static_range) + ) + components = { + "static_condition": static_condition, + "static_hit": static_hit, + "dynamic_condition": dynamic_condition, + "dynamic_hit": dynamic_hit, + "dynamic_visible": dynamic_visible, + } + return condition, static_hit | dynamic_hit, diagnostics, components + return condition, static_hit | dynamic_hit, diagnostics + + +@torch.no_grad() +def build_stage2_factorized_geometry( + video: torch.Tensor, + lidar_to_world: torch.Tensor, + geometry_source_mask: torch.Tensor, + geometry_mode: str, + *, + pose_sensor_start_end: torch.Tensor | None = None, + geometry_source_lidar_to_world: torch.Tensor | None = None, + geometry_source_pose_sensor_start_end: torch.Tensor | None = None, + actor_box_time_mode: str = "frame", + static_only_geometry: bool = False, + box_object_to_world: torch.Tensor | None, + box_lwh: torch.Tensor | None, + box_valid: torch.Tensor | None, + box_track_id: torch.Tensor | None, + block_size: int, + prefix_frames: int, + input_has_prepend: bool, + ray_dirs: Any, + row_elevations_rad: Any, + column_azimuths_rad: Any, + row_azimuth_offsets_rad: Any, + min_range: float, + max_range: float, + min_value: float, + inverse_depth: bool, + radius_m: float, + voxel_size_m: float, + voxel_policy: str, + observation_unit: str, + static_min_observations: int, + candidate_ttl_updates: int, + include_latest: bool, + free_space_clear: bool, + free_space_margin_m: float, + free_space_misses_to_remove: int, +) -> tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + """Build the exact Stage-2 geometry tensor for one factorized mode.""" + modes = ("null", "rolling_static", "frozen_raw", "frozen_object") + if geometry_mode not in modes: + raise ValueError( + f"unsupported geometry mode {geometry_mode!r}; expected {modes}" + ) + if video.ndim != 4 or video.shape[0] < 1: + raise ValueError( + "factorized geometry requires (C,T,H,W), got " + f"{tuple(video.shape)}" + ) + num_frames, height, width = map(int, video.shape[1:]) + selected = torch.as_tensor( + geometry_source_mask, device=video.device, dtype=torch.bool + ) + if selected.shape != (num_frames,): + raise ValueError( + "geometry_source_mask must be " + f"({num_frames},), got {tuple(selected.shape)}" + ) + zero = video.new_zeros((), dtype=torch.float32) + diagnostics = { + "dynamic_removed_fraction": zero, + "dynamic_untracked_fraction": zero, + "dynamic_tracks": zero, + "dynamic_object_points": zero, + "dynamic_actor_interpolated_boxes": zero, + "dynamic_actor_fallback_boxes": zero, + } + if geometry_mode == "null": + return ( + video.new_full(video.shape, float(min_value)), + torch.zeros( + (num_frames, height, width), + device=video.device, + dtype=torch.bool, + ), + diagnostics, + ) + if geometry_mode in ("frozen_raw", "frozen_object") and not bool( + selected.any() + ): + raise ValueError( + f"{geometry_mode} requires at least one observed geometry frame" + ) + poses = torch.as_tensor( + lidar_to_world, device=video.device, dtype=torch.float32 + ) + source_poses = ( + poses + if geometry_source_lidar_to_world is None + else torch.as_tensor( + geometry_source_lidar_to_world, + device=video.device, + dtype=torch.float32, + ) + ) + source_motion = ( + pose_sensor_start_end + if geometry_source_pose_sensor_start_end is None + else torch.as_tensor( + geometry_source_pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + ) + if geometry_mode == "frozen_raw": + condition, hit = warp_frozen_observed_history_with_spatial_map( + video, + source_poses, + selected, + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + pose_sensor_start_end=source_motion, + target_lidar_to_world=poses, + target_pose_sensor_start_end=pose_sensor_start_end, + ) + return condition, hit, diagnostics + + required_boxes = { + "box_object_to_world": box_object_to_world, + "box_lwh": box_lwh, + "box_valid": box_valid, + } + missing = [name for name, value in required_boxes.items() if value is None] + if missing: + raise KeyError( + f"{geometry_mode} geometry is missing box tensors {missing}" + ) + assert box_object_to_world is not None + assert box_lwh is not None + assert box_valid is not None + if geometry_mode == "frozen_object": + if static_only_geometry: + static_video, removed_fraction = remove_points_inside_moving_boxes( + video, + source_poses, + box_object_to_world, + box_lwh, + box_valid, + box_track_id, + ray_dirs=torch.as_tensor( + ray_dirs, device=video.device, dtype=torch.float32 + ), + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + pose_sensor_start_end=source_motion, + actor_box_time_mode=actor_box_time_mode, + ) + condition, hit = warp_frozen_observed_history_with_spatial_map( + static_video, + source_poses, + selected, + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + pose_sensor_start_end=source_motion, + target_lidar_to_world=poses, + target_pose_sensor_start_end=pose_sensor_start_end, + ) + diagnostics["dynamic_removed_fraction"] = removed_fraction + return condition, hit, diagnostics + if box_track_id is None: + raise KeyError( + "frozen_object geometry requires box_track_id" + ) + return warp_frozen_object_history_with_spatial_map( + video, + source_poses, + selected, + box_object_to_world, + box_lwh, + box_valid, + box_track_id, + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + pose_sensor_start_end=source_motion, + target_lidar_to_world=poses, + target_pose_sensor_start_end=pose_sensor_start_end, + actor_box_time_mode=actor_box_time_mode, + ) + + static_video, removed_fraction = remove_points_inside_moving_boxes( + video, + poses, + box_object_to_world, + box_lwh, + box_valid, + box_track_id, + ray_dirs=torch.as_tensor( + ray_dirs, device=video.device, dtype=torch.float32 + ), + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + pose_sensor_start_end=pose_sensor_start_end, + actor_box_time_mode=actor_box_time_mode, + ) + condition, hit = warp_blockwise_history_with_spatial_map( + video=static_video, + lidar_to_world=poses, + block_size=block_size, + prefix_frames=prefix_frames, + input_has_prepend=input_has_prepend, + pose_sensor_start_end=pose_sensor_start_end, + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + voxel_policy=voxel_policy, + observation_unit=observation_unit, + static_min_observations=static_min_observations, + candidate_ttl_updates=candidate_ttl_updates, + include_latest=include_latest, + free_space_clear=free_space_clear, + free_space_margin_m=free_space_margin_m, + free_space_misses_to_remove=free_space_misses_to_remove, + ) + diagnostics["dynamic_removed_fraction"] = removed_fraction + return condition, hit, diagnostics + + +@torch.no_grad() +def warp_blockwise_history_with_spatial_map( + video: torch.Tensor, + lidar_to_world: Any, + block_size: int, + *, + prefix_frames: int = 0, + input_has_prepend: bool = True, + pose_sensor_start_end: Any | None = None, + ray_dirs: Any, + row_elevations_rad: Any, + column_azimuths_rad: Any, + row_azimuth_offsets_rad: Any, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + radius_m: float = 75.0, + voxel_size_m: float = 0.2, + voxel_policy: str = "newest", + observation_unit: str = "block", + static_min_observations: int = 2, + candidate_ttl_updates: int = 1, + include_latest: bool = True, + free_space_clear: bool = False, + free_space_margin_m: float = 0.75, + free_space_misses_to_remove: int = 2, + return_soft_source: bool = False, + soft_density_kernel: int = 5, + soft_density_saturation_hits: float = 5.0, +) -> ( + tuple[torch.Tensor, torch.Tensor] + | tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + ] +): + """Build a causal blockwise condition with a transient spatial map. + + With ``input_has_prepend=True``, the input is aligned as + ``[dup(f0), f0, f1, ...]`` while poses contain only real sweeps. Otherwise + every token maps directly to the pose at the same index. Each active block + is rendered before its own GT returns are appended, so no target-block + LiDAR can leak into its condition. Frame-level evidence changes promotion + counts only; newly promoted voxels remain invisible until the next block. + """ + if not isinstance(video, torch.Tensor): + raise TypeError( + "Torch spatial-map history requires video to be a torch.Tensor" + ) + if video.ndim != 4: + raise ValueError(f"video must be (C,T,H,W), got {tuple(video.shape)}") + if video.shape[0] < 1: + raise ValueError("video must contain at least one depth channel") + if return_soft_source and video.shape[0] != 1: + raise ValueError( + "soft geometry proposals currently support range-only video" + ) + if block_size <= 0: + raise ValueError(f"block_size must be positive, got {block_size}") + + poses = torch.as_tensor( + lidar_to_world, device=video.device, dtype=torch.float32 + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + "lidar_to_world must be (S,4,4), got " + f"{tuple(poses.shape)}" + ) + num_frames, height, width = map(int, video.shape[1:]) + required_poses = max(0, num_frames - int(input_has_prepend)) + if poses.shape[0] < required_poses: + raise ValueError( + f"{num_frames} tokens with input_has_prepend=" + f"{input_has_prepend} require at least {required_poses} poses, " + f"got {poses.shape[0]}" + ) + motion = None + if pose_sensor_start_end is not None: + motion = torch.as_tensor( + pose_sensor_start_end, + device=video.device, + dtype=torch.float32, + ) + if motion.shape != poses.shape: + raise ValueError( + "pose_sensor_start_end must align with lidar_to_world, got " + f"{tuple(motion.shape)} and {tuple(poses.shape)}" + ) + + spatial_map = TorchSpatialPointMap( + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + radius_m=radius_m, + voxel_size_m=voxel_size_m, + voxel_policy=voxel_policy, + observation_unit=observation_unit, + static_min_observations=static_min_observations, + candidate_ttl_updates=candidate_ttl_updates, + include_latest=include_latest, + free_space_clear=free_space_clear, + free_space_margin_m=free_space_margin_m, + free_space_misses_to_remove=free_space_misses_to_remove, + feature_channels=video.shape[0] - 1, + device=video.device, + ) + if (spatial_map.height, spatial_map.width) != (height, width): + raise ValueError( + "video and spatial-map ray grid must match: " + f"video={(height, width)}, " + f"rays={(spatial_map.height, spatial_map.width)}" + ) + + warped = video.new_full(video.shape, float(min_value)) + hit = torch.zeros( + (num_frames, height, width), + device=video.device, + dtype=torch.bool, + ) + soft_source = None + soft_hit = None + soft_confidence = None + if return_soft_source: + soft_source = torch.full_like(warped, float(min_value)) + soft_hit = torch.zeros_like(hit) + soft_confidence = torch.zeros( + (num_frames, height, width), + device=video.device, + dtype=torch.float32, + ) + if prefix_frames: + chunks = temporal_chunk_slices( + num_frames, + block_size, + prefix_frames, + ) + else: + # Preserve the legacy diagnostic behavior, which permits a short + # final block. Imaginaire matching uses the strict prefixed layout. + chunks = [ + (start, min(start + block_size, num_frames)) + for start in range(0, num_frames, block_size) + ] + for block_start, block_end in chunks: + if block_start > 0: + target_poses = lidar_poses_for_global_tokens( + poses, + block_start, + block_end - block_start, + input_has_prepend=input_has_prepend, + ) + target_motion = ( + lidar_poses_for_global_tokens( + motion, + block_start, + block_end - block_start, + input_has_prepend=input_has_prepend, + ) + if motion is not None + else None + ) + if video.shape[0] == 1: + rendered, rendered_hit = spatial_map.render( + target_poses, + target_pose_sensor_start_end=target_motion, + ) + else: + rendered_range, rendered_features, rendered_hit = ( + spatial_map.render_with_features( + target_poses, + target_pose_sensor_start_end=target_motion, + ) + ) + rendered = torch.cat( + [rendered_range, rendered_features], dim=0 + ) + warped[:, block_start:block_end] = rendered.to(video.dtype) + hit[block_start:block_end] = rendered_hit + if return_soft_source: + assert soft_source is not None + assert soft_hit is not None + assert soft_confidence is not None + ( + rendered_soft, + rendered_soft_hit, + temporal_confidence, + ) = spatial_map.render_soft_proposal( + target_poses, + target_pose_sensor_start_end=target_motion, + ) + density_confidence = local_hit_density_confidence( + rendered_soft_hit, + kernel_size=soft_density_kernel, + saturation_hits=soft_density_saturation_hits, + ) + soft_source[:, block_start:block_end] = ( + rendered_soft.to(video.dtype) + ) + soft_hit[block_start:block_end] = rendered_soft_hit + soft_confidence[block_start:block_end] = ( + temporal_confidence * density_confidence + ) + spatial_map.append_block( + normalized_block=video[:1, block_start:block_end], + point_feature_block=video[1:, block_start:block_end], + lidar_to_world=poses, + global_start=block_start, + input_has_prepend=input_has_prepend, + pose_sensor_start_end=motion, + ) + if return_soft_source: + assert soft_source is not None + assert soft_hit is not None + assert soft_confidence is not None + return warped, hit, soft_source, soft_hit, soft_confidence + return warped, hit + + +def range_sweep_to_world_points( + normalized_range: Any, + lidar_to_world: Any, + ray_dirs: np.ndarray, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + pose_sensor_start_end: Any | None = None, +) -> np.ndarray: + """Convert one normalized range sweep into world-space points. + + When ``pose_sensor_start_end`` is provided, each azimuth column is first + ego-deskewed into the sweep-start sensor frame using its normalized scan + time. The final world transform remains ``lidar_to_world`` at sweep start. + """ + if hasattr(normalized_range, "detach"): + sweep = normalized_range.detach().float().cpu().numpy() + else: + sweep = np.asarray(normalized_range) + if hasattr(lidar_to_world, "detach"): + pose = lidar_to_world.detach().double().cpu().numpy() + else: + pose = np.asarray(lidar_to_world, dtype=np.float64) + if sweep.ndim == 3 and sweep.shape[0] == 1: + sweep = sweep[0] + if sweep.ndim != 2: + raise ValueError( + f"normalized_range must be (H,W) or (1,H,W), got {sweep.shape}" + ) + if pose.shape != (4, 4): + raise ValueError(f"lidar_to_world must be (4,4), got {pose.shape}") + dirs = np.asarray(ray_dirs, dtype=np.float32) + if dirs.shape != (*sweep.shape, 3): + raise ValueError( + f"ray_dirs must be {(*sweep.shape, 3)}, got {dirs.shape}" + ) + + sweep = sweep.astype(np.float32, copy=False) + valid = np.isfinite(sweep) & (sweep > float(min_value) + 1.0e-5) + depth = _unnormalize_valid_depth( + sweep, + valid, + min_range, + max_range, + min_value, + inverse_depth, + ) + points_local = (depth[..., None] * dirs)[valid] + if points_local.size == 0: + return np.empty((0, 3), dtype=np.float64) + if pose_sensor_start_end is not None: + relative_pose = ( + pose_sensor_start_end.detach().double().cpu().numpy() + if hasattr(pose_sensor_start_end, "detach") + else np.asarray(pose_sensor_start_end, dtype=np.float64) + ) + if relative_pose.shape != (4, 4): + raise ValueError( + "pose_sensor_start_end must be (4,4), got " + f"{relative_pose.shape}" + ) + from utils.lidar_rangemap import apply_motion_compensation_impl + + columns = np.broadcast_to( + np.arange(sweep.shape[1], dtype=np.float64), sweep.shape + )[valid] + scan_fraction = columns / float(max(sweep.shape[1] - 1, 1)) + points_local = apply_motion_compensation_impl( + points_local.astype(np.float64), + relative_pose, + [0.0, 1.0], + scan_fraction, + ) + return ( + points_local.astype(np.float64) @ pose[:3, :3].T + + pose[:3, 3][None] + ) + + +def generated_block_to_world_points( + normalized_block: Any, + lidar_to_world: Any, + global_start: int, + ray_dirs: np.ndarray, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, +) -> list[np.ndarray]: + """Convert newly generated tokens to world points, skipping token-0 prepend.""" + if hasattr(normalized_block, "detach"): + block = normalized_block.detach().float().cpu().numpy() + else: + block = np.asarray(normalized_block) + if hasattr(lidar_to_world, "detach"): + poses = lidar_to_world.detach().double().cpu().numpy() + else: + poses = np.asarray(lidar_to_world, dtype=np.float64) + if block.ndim == 4: + block = block[0] + if block.ndim != 3: + raise ValueError( + f"normalized_block must be (C,T,H,W) or (T,H,W), got {block.shape}" + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError(f"lidar_to_world must be (S,4,4), got {poses.shape}") + + parts = [] + for local_idx in range(block.shape[0]): + global_idx = global_start + local_idx + if global_idx == 0: + continue + pose_idx = global_idx - 1 + if pose_idx >= poses.shape[0]: + raise ValueError( + f"generated token {global_idx} has no real pose in {poses.shape}" + ) + points = range_sweep_to_world_points( + normalized_range=block[local_idx], + lidar_to_world=poses[pose_idx], + ray_dirs=ray_dirs, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + ) + if points.shape[0] > 0: + parts.append(points) + return parts + + +def render_world_points_to_range_video( + points_world: Any, + target_lidar_to_world: Any, + ray_dirs: np.ndarray, + row_elevations_rad: np.ndarray, + column_azimuths_rad: np.ndarray, + row_azimuth_offsets_rad: np.ndarray, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, +) -> tuple[np.ndarray, np.ndarray]: + """Rasterize a persistent world-space cloud into target LiDAR poses.""" + if hasattr(points_world, "detach"): + points = points_world.detach().double().cpu().numpy() + else: + points = np.asarray(points_world, dtype=np.float64) + if hasattr(target_lidar_to_world, "detach"): + poses = target_lidar_to_world.detach().double().cpu().numpy() + else: + poses = np.asarray(target_lidar_to_world, dtype=np.float64) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError(f"points_world must be (N,3), got {points.shape}") + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target_lidar_to_world must be (T,4,4), got {poses.shape}" + ) + + dirs = np.asarray(ray_dirs) + if dirs.ndim != 3 or dirs.shape[2] != 3: + raise ValueError(f"ray_dirs must be (H,W,3), got {dirs.shape}") + height, width = dirs.shape[:2] + warped = np.full( + (1, poses.shape[0], height, width), + float(min_value), + dtype=np.float32, + ) + hit = np.zeros((poses.shape[0], height, width), dtype=bool) + if points.shape[0] == 0: + return warped, hit + + elev = np.asarray(row_elevations_rad, dtype=np.float64) + azim = np.asarray(column_azimuths_rad, dtype=np.float64) + row_off = np.asarray(row_azimuth_offsets_rad, dtype=np.float64) + for target_idx, target_pose in enumerate(poses): + rows, cols, ranges = project_world_points( + points, + target_pose, + elev, + azim, + row_off, + width, + width, + min_range, + max_range, + ) + metric = scatter_min_range(height, width, rows, cols, ranges) + hit[target_idx] = metric > 0.0 + warped[0, target_idx] = _normalize_metric_depth( + metric, + min_range, + max_range, + min_value, + inverse_depth, + ) + return warped, hit + + +def _nearest_beam_indices_numpy( + points_sensor: np.ndarray, + ranges: np.ndarray, + row_elevations_rad: np.ndarray, + column_azimuths_rad: np.ndarray, + row_azimuth_offsets_rad: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Match sensor-space points to the nearest native LiDAR beams.""" + points = np.asarray(points_sensor, dtype=np.float64) + radii = np.asarray(ranges, dtype=np.float64) + elev = np.asarray(row_elevations_rad, dtype=np.float64) + azim = np.asarray(column_azimuths_rad, dtype=np.float64) + row_off = np.asarray(row_azimuth_offsets_rad, dtype=np.float64) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError( + f"points_sensor must be (N,3), got {points.shape}" + ) + if radii.shape != (points.shape[0],): + raise ValueError( + f"ranges must be ({points.shape[0]},), got {radii.shape}" + ) + if points.shape[0] == 0: + empty = np.empty((0,), dtype=np.int64) + return empty, empty + + point_elev = np.arcsin( + np.clip(points[:, 2] / np.maximum(radii, 1.0e-12), -1.0, 1.0) + ) + elev_order = np.argsort(elev, kind="stable") + elev_sorted = elev[elev_order] + elev_idx = np.searchsorted(elev_sorted, point_elev) + elev_idx0 = np.clip(elev_idx - 1, 0, elev.shape[0] - 1) + elev_idx1 = np.clip(elev_idx, 0, elev.shape[0] - 1) + elev_dist0 = np.abs(point_elev - elev_sorted[elev_idx0]) + elev_dist1 = np.abs(point_elev - elev_sorted[elev_idx1]) + nearest_sorted = np.where( + elev_dist0 < elev_dist1, + elev_idx0, + np.where( + elev_dist1 < elev_dist0, + elev_idx1, + np.where( + elev_order[elev_idx0] <= elev_order[elev_idx1], + elev_idx0, + elev_idx1, + ), + ), + ) + rows = elev_order[nearest_sorted] + + def _wrap(angle: np.ndarray) -> np.ndarray: + return (angle + np.pi) % (2.0 * np.pi) - np.pi + + point_azim = _wrap( + np.arctan2(points[:, 1], points[:, 0]) - row_off[rows] + ) + azim_wrapped = _wrap(azim) + azim_order = np.argsort(azim_wrapped, kind="stable") + azim_sorted = azim_wrapped[azim_order] + azim_idx = np.searchsorted(azim_sorted, point_azim) + azim_idx0 = (azim_idx - 1) % azim.shape[0] + azim_idx1 = azim_idx % azim.shape[0] + azim_dist0 = np.abs(_wrap(point_azim - azim_sorted[azim_idx0])) + azim_dist1 = np.abs(_wrap(point_azim - azim_sorted[azim_idx1])) + columns = azim_order[ + np.where(azim_dist0 <= azim_dist1, azim_idx0, azim_idx1) + ] + return rows.astype(np.int64), columns.astype(np.int64) + + +def render_world_points_to_rolling_range_video( + points_world: Any, + target_lidar_to_world: Any, + target_pose_sensor_start_end: Any, + ray_dirs: np.ndarray, + row_elevations_rad: np.ndarray, + column_azimuths_rad: np.ndarray, + row_azimuth_offsets_rad: np.ndarray, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + projection_iterations: int = 3, +) -> tuple[np.ndarray, np.ndarray]: + """Rasterize a world cloud using each target sweep's per-column pose.""" + if projection_iterations <= 0: + raise ValueError("projection_iterations must be positive") + points = ( + points_world.detach().double().cpu().numpy() + if hasattr(points_world, "detach") + else np.asarray(points_world, dtype=np.float64) + ) + poses = ( + target_lidar_to_world.detach().double().cpu().numpy() + if hasattr(target_lidar_to_world, "detach") + else np.asarray(target_lidar_to_world, dtype=np.float64) + ) + target_motion = ( + target_pose_sensor_start_end.detach().double().cpu().numpy() + if hasattr(target_pose_sensor_start_end, "detach") + else np.asarray(target_pose_sensor_start_end, dtype=np.float64) + ) + if points.ndim != 2 or points.shape[1:] != (3,): + raise ValueError(f"points_world must be (N,3), got {points.shape}") + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + f"target_lidar_to_world must be (T,4,4), got {poses.shape}" + ) + if target_motion.shape != (poses.shape[0], 4, 4): + raise ValueError( + "target_pose_sensor_start_end must be (T,4,4), got " + f"{target_motion.shape} for T={poses.shape[0]}" + ) + + dirs = np.asarray(ray_dirs) + if dirs.ndim != 3 or dirs.shape[2] != 3: + raise ValueError(f"ray_dirs must be (H,W,3), got {dirs.shape}") + height, width = dirs.shape[:2] + warped = np.full( + (1, poses.shape[0], height, width), + float(min_value), + dtype=np.float32, + ) + hit = np.zeros((poses.shape[0], height, width), dtype=bool) + if points.shape[0] == 0: + return warped, hit + + from utils.lidar_rangemap import apply_motion_compensation_impl + + for target_idx, target_pose in enumerate(poses): + rotation = target_pose[:3, :3].astype(np.float64) + translation = target_pose[:3, 3].astype(np.float64) + points_start = (points - translation[None]) @ rotation + start_ranges = np.linalg.norm(points_start, axis=1) + _, columns = _nearest_beam_indices_numpy( + points_start, + start_ranges, + row_elevations_rad, + column_azimuths_rad, + row_azimuth_offsets_rad, + ) + inverse_relative = np.linalg.inv(target_motion[target_idx]) + for _ in range(projection_iterations): + fractions = columns.astype(np.float64) / float( + max(width - 1, 1) + ) + points_sensor = apply_motion_compensation_impl( + points_start, + inverse_relative, + [0.0, 1.0], + fractions, + ) + ranges = np.linalg.norm(points_sensor, axis=1) + _, columns = _nearest_beam_indices_numpy( + points_sensor, + ranges, + row_elevations_rad, + column_azimuths_rad, + row_azimuth_offsets_rad, + ) + + fractions = columns.astype(np.float64) / float(max(width - 1, 1)) + points_sensor = apply_motion_compensation_impl( + points_start, + inverse_relative, + [0.0, 1.0], + fractions, + ) + ranges = np.linalg.norm(points_sensor, axis=1) + rows, columns = _nearest_beam_indices_numpy( + points_sensor, + ranges, + row_elevations_rad, + column_azimuths_rad, + row_azimuth_offsets_rad, + ) + keep = (ranges >= min_range) & (ranges <= max_range) + metric = scatter_min_range( + height, + width, + rows[keep], + columns[keep], + ranges[keep].astype(np.float32), + ) + hit[target_idx] = metric > 0.0 + warped[0, target_idx] = _normalize_metric_depth( + metric, + min_range, + max_range, + min_value, + inverse_depth, + ) + return warped, hit + + +def warp_latest_past_sweep_to_video( + video: Any, + lidar_to_world: Any, + n_past: int, + ray_dirs: np.ndarray, + row_elevations_rad: np.ndarray, + column_azimuths_rad: np.ndarray, + row_azimuth_offsets_rad: np.ndarray, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + history_mode: str = "latest", +) -> tuple[np.ndarray, np.ndarray]: + """Warp observed sweep(s) into every prepend-aligned frame pose. + + Args: + video: Normalized range video ``(C, S+1, H, W)`` with frame-0 prepend. + lidar_to_world: Sampled sweep-start poses ``(S, 4, 4)`` without prepend. + n_past: Number of observed sampled sweeps. + history_mode: ``"latest"`` uses video index ``n_past`` and pose index + ``n_past - 1``. ``"all"`` uses every unique past video index + ``1..n_past`` and merges their target-pose projections with one + nearest-return z-buffer. + + Returns: + ``(warped_video, hit_mask)`` with shapes ``(1, S+1, H, W)`` and + ``(S+1, H, W)``. Future lidar never enters the construction. Empty + target pixels retain the dataset's normalized invalid sentinel. + """ + if hasattr(video, "detach"): + video_np = video.detach().cpu().numpy() + else: + video_np = np.asarray(video) + if hasattr(lidar_to_world, "detach"): + l2w = lidar_to_world.detach().cpu().numpy() + else: + l2w = np.asarray(lidar_to_world) + + if video_np.ndim != 4 or video_np.shape[0] < 1: + raise ValueError(f"video must be (C,T,H,W), got {video_np.shape}") + if l2w.ndim != 3 or l2w.shape[1:] != (4, 4): + raise ValueError(f"lidar_to_world must be (S,4,4), got {l2w.shape}") + if video_np.shape[1] != l2w.shape[0] + 1: + raise ValueError( + f"prepend mismatch: video T={video_np.shape[1]} but poses S={l2w.shape[0]}" + ) + if not 0 < n_past <= l2w.shape[0]: + raise ValueError(f"n_past={n_past} is invalid for S={l2w.shape[0]}") + if history_mode not in ("latest", "all"): + raise ValueError( + f"history_mode must be 'latest' or 'all', got {history_mode!r}" + ) + + _, T, H, W = video_np.shape + dirs = np.asarray(ray_dirs, dtype=np.float32) + if dirs.shape != (H, W, 3): + raise ValueError(f"ray_dirs must be {(H, W, 3)}, got {dirs.shape}") + elev = np.asarray(row_elevations_rad, dtype=np.float64) + azim = np.asarray(column_azimuths_rad, dtype=np.float64) + row_off = np.asarray(row_azimuth_offsets_rad, dtype=np.float64) + if elev.shape != (H,) or row_off.shape != (H,) or azim.shape != (W,): + raise ValueError( + "beam-table shapes must match video grid: " + f"elev={elev.shape}, azim={azim.shape}, row_off={row_off.shape}, " + f"grid={(H, W)}" + ) + + source_indices = [n_past] if history_mode == "latest" else list( + range(1, n_past + 1) + ) + world_parts = [] + for video_idx in source_indices: + source_norm = video_np[0, video_idx].astype(np.float32, copy=True) + valid = np.isfinite(source_norm) & ( + source_norm > float(min_value) + 1.0e-5 + ) + source_depth = _unnormalize_valid_depth( + source_norm, + valid, + min_range, + max_range, + min_value, + inverse_depth, + ) + points_source = (source_depth[..., None] * dirs)[valid] + source_pose = l2w[video_idx - 1].astype(np.float64) + world_parts.append( + points_source.astype(np.float64) @ source_pose[:3, :3].T + + source_pose[:3, 3][None] + ) + points_world = np.concatenate(world_parts, axis=0) + poses_prepend = np.concatenate([l2w[:1], l2w], axis=0).astype(np.float64) + + warped = np.full((1, T, H, W), float(min_value), dtype=np.float32) + hit = np.zeros((T, H, W), dtype=bool) + for t in range(T): + rows, cols, ranges = project_world_points( + points_world, + poses_prepend[t], + elev, + azim, + row_off, + W, + W, + min_range, + max_range, + ) + metric = scatter_min_range(H, W, rows, cols, ranges) + hit[t] = metric > 0.0 + warped[0, t] = _normalize_metric_depth( + metric, + min_range, + max_range, + min_value, + inverse_depth, + ) + return warped, hit + + +def warp_blockwise_history_to_video( + video: Any, + lidar_to_world: Any, + block_size: int, + ray_dirs: np.ndarray, + row_elevations_rad: np.ndarray, + column_azimuths_rad: np.ndarray, + row_azimuth_offsets_rad: np.ndarray, + min_range: float, + max_range: float, + min_value: float = -1.0, + inverse_depth: bool = False, + history_mode: str = "all", +) -> tuple[np.ndarray, np.ndarray]: + """Build a leakage-free history warp for each causal temporal block. + + The input video is prepend-aligned: ``[dup(f0), f0, f1, ...]``. Block zero + has no earlier observations and remains invalid. For each later block + beginning at video index ``s``, only unique lidar frames at indices + ``1..s-1`` are accumulated and rendered into that block's target poses. + Frames inside the target block never enter their own conditioning signal. + """ + if hasattr(video, "detach"): + video_np = video.detach().cpu().numpy() + else: + video_np = np.asarray(video) + if video_np.ndim != 4: + raise ValueError(f"video must be (C,T,H,W), got {video_np.shape}") + if block_size <= 0: + raise ValueError(f"block_size must be positive, got {block_size}") + + _, num_frames, height, width = video_np.shape + warped = np.full( + (1, num_frames, height, width), + float(min_value), + dtype=np.float32, + ) + hit = np.zeros((num_frames, height, width), dtype=bool) + + for block_start in range(block_size, num_frames, block_size): + # video index 0 duplicates f0, so the number of unique observed sweeps + # before this block is exactly block_start - 1. + n_past = block_start - 1 + block_warped, block_hit = warp_latest_past_sweep_to_video( + video=video_np, + lidar_to_world=lidar_to_world, + n_past=n_past, + ray_dirs=ray_dirs, + row_elevations_rad=row_elevations_rad, + column_azimuths_rad=column_azimuths_rad, + row_azimuth_offsets_rad=row_azimuth_offsets_rad, + min_range=min_range, + max_range=max_range, + min_value=min_value, + inverse_depth=inverse_depth, + history_mode=history_mode, + ) + block_end = min(block_start + block_size, num_frames) + warped[:, block_start:block_end] = block_warped[ + :, block_start:block_end + ] + hit[block_start:block_end] = block_hit[block_start:block_end] + + return warped, hit diff --git a/diffusion/training/datasets/lidar_dataset/hdmaptolidar_dataloader.py b/diffusion/training/datasets/lidar_dataset/hdmaptolidar_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..2955800ad6b5e035cf1a9e65dcc12329abb846ee --- /dev/null +++ b/diffusion/training/datasets/lidar_dataset/hdmaptolidar_dataloader.py @@ -0,0 +1,960 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Dataloader for hdmap-to-lidar diffusion training. + +Loads lidar range-map + HD-map conditioning, reusing the diffusion +``LidarRangeMapSampler`` infrastructure and adding the metadata fields +expected by the Cosmos diffusion training loop (t5 embeddings, fps, etc.). +""" + +import gc +import json +import os + +import numpy as np +import torch +from omegaconf import OmegaConf +from torch.utils.data import DataLoader, Dataset, Sampler + +from diffusion.training.datasets.lidar_dataset.configs import COMMONDATA_CONFIG +from diffusion.training.datasets.lidar_dataset.imagetolidar_dataloader import ( + LidarRangeMapSampler, + dict_collation_fn, + frames_as_batch_collation_fn, +) +from diffusion.training.datasets.lidar_dataset.forecast_warp import ( + compose_normalized_range_channels, + warp_blockwise_history_to_video, +) +from diffusion.training.datasets.lidar_dataset.waymo_track_ids import ( + resolve_waymo_box_track_ids_from_ncore, +) +from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField +from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_lidar_geometry, +) +from utils import log +from utils.lazy_config import LazyCall as L + +try: + from megatron.core import parallel_state +except ImportError: + pass + + +class HdmapLidarSampler(LidarRangeMapSampler): + """Dataset that returns lidar range-map + HD-map with diffusion metadata. + + Inherits all lidar/hdmap loading logic from the existing + ``LidarRangeMapSampler`` and adds the metadata fields required by the + Cosmos diffusion training loop. + """ + + def __init__( + self, + blockwise_warped_history_condition: bool = False, + blockwise_warped_history_block_size: int = 3, + blockwise_warped_history_mode: str = "all", + autoregressive_pair: bool = False, + autoregressive_previous_root: str = "", + autoregressive_generated_previous_prob: float = 0.0, + autoregressive_include_static_boxes: bool = False, + synthesize_null_hdmap: bool = False, + return_hdmap_semantic: bool = False, + return_moving_boxes: bool = False, + resolve_moving_box_track_ids: bool = False, + return_full_lidar_metadata: bool = False, + moving_box_limit: int = 256, + moving_box_root: str = "", + sensor_fps: float = 24.0, + emit_sensor_metadata: bool = False, + sensor_dataset_id: int = -1, + sensor_dataset_name: str = "", + **kwargs, + ): + self.sensor_fps = float(sensor_fps) + if self.sensor_fps <= 0.0: + raise ValueError( + f"sensor_fps must be positive, got {self.sensor_fps}" + ) + self.emit_sensor_metadata = bool(emit_sensor_metadata) + self.sensor_dataset_id = int(sensor_dataset_id) + self.sensor_dataset_name = str( + sensor_dataset_name or kwargs.get("data_name", "") + ) + self._sensor_root_path = kwargs.get("root_path") + self._sensor_filter_list_path = kwargs.get("filter_list_path") + self._sensor_center_vehicle_forward = bool( + kwargs.get("center_vehicle_forward", True) + ) + self._sensor_ray_directions = None + self.autoregressive_pair = bool(autoregressive_pair) + self.autoregressive_target_frames = int( + kwargs.get("sample_n_frames", 1) + ) + if self.autoregressive_pair: + if self.autoregressive_target_frames != 1: + raise ValueError( + "autoregressive_pair currently requires " + "sample_n_frames=1" + ) + if bool(kwargs.get("is_video_tokenizer", False)): + raise ValueError( + "autoregressive_pair requires a per-frame tokenizer" + ) + kwargs["sample_n_frames"] = 2 + if kwargs.get("dataset_backend", "radym") == "radym": + custom_folders = kwargs.get("custom_folders") + custom_fields = kwargs.get("custom_fields") + if ( + custom_folders is not None + and custom_fields is not None + and len(custom_folders) != len(custom_fields) + ): + raise ValueError( + "Radym custom_folders and custom_fields must have the " + "same length, got " + f"{len(custom_folders)} and {len(custom_fields)}" + ) + super().__init__(**kwargs) + self.autoregressive_previous_root = str( + autoregressive_previous_root + ) + self.autoregressive_generated_previous_prob = float( + autoregressive_generated_previous_prob + ) + self.autoregressive_include_static_boxes = bool( + autoregressive_include_static_boxes + ) + if not 0.0 <= self.autoregressive_generated_previous_prob <= 1.0: + raise ValueError( + "autoregressive_generated_previous_prob must be in [0,1]" + ) + if ( + self.autoregressive_generated_previous_prob > 0.0 + and not self.autoregressive_previous_root + ): + raise ValueError( + "generated previous-frame sampling requires " + "autoregressive_previous_root" + ) + self.synthesize_null_hdmap = bool(synthesize_null_hdmap) + self.return_hdmap_semantic = bool(return_hdmap_semantic) + self.return_moving_boxes = bool(return_moving_boxes) + self.resolve_moving_box_track_ids = bool( + resolve_moving_box_track_ids + ) + self.return_full_lidar_metadata = bool( + return_full_lidar_metadata + ) + self.moving_box_limit = int(moving_box_limit) + self.moving_box_root = str(moving_box_root) + if ( + self.return_hdmap_semantic + and self.dataset_backend != "waymo_ncore" + ): + raise ValueError( + "semantic HDMap output requires " + "dataset_backend='waymo_ncore'" + ) + if self.return_hdmap_semantic and not bool( + self._hdmap_kwargs["hdmap_multichannel"] + ): + raise ValueError( + "return_hdmap_semantic requires hdmap_multichannel=True" + ) + if self.return_moving_boxes and self.moving_box_limit <= 0: + raise ValueError("moving_box_limit must be positive") + if ( + self.return_moving_boxes + and self.dataset_backend == "radym" + and not self.moving_box_root + ): + raise ValueError( + "radym moving-box output requires moving_box_root" + ) + if ( + self.resolve_moving_box_track_ids + and self.dataset_backend != "waymo_ncore" + ): + raise ValueError( + "NCore track-ID resolution is only defined for Waymo" + ) + if self.synthesize_null_hdmap: + # Preserve the LiDAR + HDMap conditioner view count even though the + # underlying NCore reader was asked to load only LiDAR. + self.plus = 2 + self.blockwise_warped_history_condition = bool( + blockwise_warped_history_condition + ) + self.blockwise_warped_history_block_size = int( + blockwise_warped_history_block_size + ) + self.blockwise_warped_history_mode = str( + blockwise_warped_history_mode + ) + self._blockwise_warp_geometry = None + self._blockwise_warp_geometry_args = None + if self.blockwise_warped_history_condition: + if self.dataset_backend != "waymo_ncore": + raise ValueError( + "blockwise warped-history conditioning requires " + f"dataset_backend='waymo_ncore', got {self.dataset_backend!r}" + ) + if self.process_input != "mono": + raise ValueError( + "blockwise warped-history conditioning requires " + f"process_input='mono', got {self.process_input!r}" + ) + if not self.is_video_tokenizer: + raise ValueError( + "blockwise warped-history conditioning requires a video " + "tokenizer with frame-0 prepend" + ) + if self.blockwise_warped_history_block_size <= 0: + raise ValueError( + "blockwise_warped_history_block_size must be positive" + ) + if self.blockwise_warped_history_mode not in ("latest", "all"): + raise ValueError( + "blockwise_warped_history_mode must be 'latest' or 'all', " + f"got {self.blockwise_warped_history_mode!r}" + ) + self._blockwise_warp_geometry_args = dict( + root_path=kwargs["root_path"], + filter_list_path=kwargs.get("filter_list_path"), + resample_width=int(kwargs.get("resample_width", -1)), + ) + + def get_sensor_metadata(self, height: int, width: int) -> dict: + """Return the calibrated native ray grid for cross-dataset training.""" + if not self.emit_sensor_metadata: + return {} + if self._sensor_ray_directions is None: + if self.dataset_backend == "waymo_ncore": + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_ray_directions, + ) + + rays = load_waymo_ray_directions( + root_path=self._sensor_root_path, + filter_list_path=self._sensor_filter_list_path, + lidar_id="lidar_top", + resample_width=self.resample_width, + ) + elif self.dataset_backend == "nuscenes_ncore": + from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import ( + load_nuscenes_ray_directions, + ) + + rays = load_nuscenes_ray_directions( + root_path=self._sensor_root_path, + filter_list_path=self._sensor_filter_list_path, + lidar_id="lidar_top", + resample_width=self.resample_width, + center_vehicle_forward=self._sensor_center_vehicle_forward, + ) + else: + from utils.lidar_rangemap import ( + load_pandar128_elevations, + range_map_to_ray_directions, + ) + + elevations = torch.tensor( + load_pandar128_elevations(), dtype=torch.float32 + ) + rays = range_map_to_ray_directions( + width // self.repeat_col, elevations + ) + rays = torch.as_tensor(rays, dtype=torch.float32) + rays = rays.repeat_interleave(self.repeat_row, dim=0) + rays = rays.repeat_interleave(self.repeat_col, dim=1) + if tuple(rays.shape) != (height, width, 3): + raise ValueError( + "sensor rays must match the repeated native grid: " + f"rays={tuple(rays.shape)}, sample={(height, width, 3)}" + ) + self._sensor_ray_directions = rays.contiguous() + return { + "sensor_ray_directions": self._sensor_ray_directions, + "sensor_depth_bounds": torch.tensor( + [self.min_distance, self.max_distance], dtype=torch.float32 + ), + "sensor_dataset_id": self.sensor_dataset_id, + "sensor_dataset_name": self.sensor_dataset_name, + } + + def _radym_moving_box_arrays(self, example): + key = str(example["__key__"]) + frame_names = [] + for value in example["rgb_frame_indices"]: + frame_name = str(value) + if frame_name.isdigit(): + frame_name = f"{int(frame_name):06d}" + frame_names.append(frame_name) + tar_handle = self.dataset._get_tar_handle( + self.moving_box_root, "all_object_info", key + ) + frame_payloads = [] + actor_names = set() + for frame_name in frame_names: + member_name = ( + f"{key}.{frame_name}.all_object_info.json" + ) + member = tar_handle.extractfile(member_name) + if member is None: + raise FileNotFoundError( + f"missing moving-box metadata {member_name}" + ) + payload = json.load(member) + frame_payloads.append(payload) + actor_names.update(payload) + ordered_names = sorted( + actor_names, + key=lambda value: ( + 0, int(value) + ) if str(value).isdigit() else (1, str(value)), + ) + track_ids = { + actor_name: index + for index, actor_name in enumerate(ordered_names) + } + type_ids = {"Car": 0, "Pedestrian": 1, "Cyclist": 2} + box_frame = [] + box_o2w = [] + box_lwh = [] + box_type = [] + box_moving = [] + box_track_id = [] + for local_frame, payload in enumerate(frame_payloads): + for actor_name, actor in payload.items(): + box_frame.append(local_frame) + box_o2w.append(actor["object_to_world"]) + box_lwh.append(actor["object_lwh"]) + box_type.append(type_ids.get(actor["object_type"], -1)) + box_moving.append(bool(actor["object_is_moving"])) + box_track_id.append(track_ids[actor_name]) + if box_frame: + return ( + np.asarray(box_frame, dtype=np.int64), + np.asarray(box_o2w, dtype=np.float32), + np.asarray(box_lwh, dtype=np.float32), + np.asarray(box_type, dtype=np.int64), + np.asarray(box_moving, dtype=bool), + np.asarray(box_track_id, dtype=np.int64), + np.arange(len(frame_names), dtype=np.int64), + ) + return ( + np.zeros((0,), dtype=np.int64), + np.zeros((0, 4, 4), dtype=np.float32), + np.zeros((0, 3), dtype=np.float32), + np.zeros((0,), dtype=np.int64), + np.zeros((0,), dtype=bool), + np.zeros((0,), dtype=np.int64), + np.arange(len(frame_names), dtype=np.int64), + ) + + def _moving_boxes_for_sample(self, example): + if self.dataset_backend == "radym": + ( + box_frame, + box_o2w, + box_lwh, + box_type, + box_moving, + track_ids, + frame_indices, + ) = self._radym_moving_box_arrays(example) + else: + composer = self.dataset.composers.get(example["__key__"]) + if composer is None: + raise RuntimeError( + "moving-box output requires a cached HDMap composer" + ) + track_ids = getattr( + composer, "_resolved_box_track_ids", None + ) + if track_ids is None and self.resolve_moving_box_track_ids: + loader = self.dataset._get_loader(example["__key__"]) + lidar_sensor = loader.get_lidar_sensor( + self.dataset.lidar_id + ) + track_ids, metadata = ( + resolve_waymo_box_track_ids_from_ncore( + hdmap_composer=composer, + sequence_loader=loader, + lidar_sensor=lidar_sensor, + ) + ) + composer._resolved_box_track_ids = track_ids + composer._resolved_box_track_id_metadata = metadata + if track_ids is None: + track_ids = composer.box_track_id + box_frame = np.asarray(composer.box_frame, dtype=np.int64) + box_o2w = np.asarray(composer.box_o2w, dtype=np.float32) + box_lwh = np.asarray(composer.box_lwh, dtype=np.float32) + box_type = np.asarray(composer.box_type, dtype=np.int64) + box_moving = np.asarray(composer.box_moving, dtype=bool) + track_ids = np.asarray(track_ids, dtype=np.int64) + frame_indices = np.asarray( + example["rgb_frame_indices"], dtype=np.int64 + ) + if bool((box_moving & (track_ids < 0)).any()): + raise ValueError( + "moving actors have no persistent track IDs; refresh the " + "dataset's HDMap/box metadata" + ) + moving_rows = box_moving + dynamic_track_ids = np.unique(track_ids[moving_rows]) + dynamic_rows = np.isin(track_ids, dynamic_track_ids) + selected_rows = ( + np.ones_like(dynamic_rows) + if self.autoregressive_include_static_boxes + else dynamic_rows + ) + num_frames = int(frame_indices.shape[0]) + object_to_world = np.zeros( + (num_frames, self.moving_box_limit, 4, 4), + dtype=np.float32, + ) + lwh = np.zeros( + (num_frames, self.moving_box_limit, 3), dtype=np.float32 + ) + valid = np.zeros( + (num_frames, self.moving_box_limit), dtype=bool + ) + sampled_track_ids = np.full( + (num_frames, self.moving_box_limit), -1, dtype=np.int64 + ) + sampled_box_types = np.full( + (num_frames, self.moving_box_limit), -1, dtype=np.int64 + ) + truncated = 0 + for local_idx, frame_idx in enumerate(frame_indices): + indices = np.nonzero( + (box_frame == int(frame_idx)) + & selected_rows + )[0] + truncated += max(0, int(indices.shape[0]) - self.moving_box_limit) + indices = indices[: self.moving_box_limit] + count = int(indices.shape[0]) + if count == 0: + continue + object_to_world[local_idx, :count] = box_o2w[indices] + lwh[local_idx, :count] = box_lwh[indices] + sampled_track_ids[local_idx, :count] = track_ids[indices] + sampled_box_types[local_idx, :count] = box_type[indices] + valid[local_idx, :count] = True + return ( + torch.from_numpy(object_to_world), + torch.from_numpy(lwh), + torch.from_numpy(valid), + torch.from_numpy(sampled_track_ids), + torch.from_numpy(sampled_box_types), + truncated, + ) + + def _generated_previous_frame( + self, clip_key: str, native_frame_idx: int + ) -> torch.Tensor: + path = os.path.join( + self.autoregressive_previous_root, f"{clip_key}.npz" + ) + if not os.path.isfile(path): + raise FileNotFoundError( + f"missing DAgger rollout for {clip_key!r}: {path}" + ) + with np.load(path, allow_pickle=False) as payload: + frames = np.asarray(payload["range"], dtype=np.float32) + frame_indices = np.asarray( + payload["frame_indices"], dtype=np.int64 + ) + matches = np.nonzero(frame_indices == int(native_frame_idx))[0] + if matches.shape[0] != 1: + raise RuntimeError( + f"{path} must contain native frame {native_frame_idx} " + f"exactly once, found {matches.shape[0]}" + ) + frame = frames[int(matches[0])] + if frame.shape != tuple(self.lidar_size): + raise ValueError( + f"DAgger frame shape {frame.shape} does not match " + f"lidar_size={tuple(self.lidar_size)}" + ) + return torch.from_numpy(frame)[None, None] + + def _sample_generated_previous_frame( + self, clip_key: str + ) -> tuple[int, torch.Tensor]: + path = os.path.join( + self.autoregressive_previous_root, f"{clip_key}.npz" + ) + if not os.path.isfile(path): + raise FileNotFoundError( + f"missing DAgger rollout for {clip_key!r}: {path}" + ) + with np.load(path, allow_pickle=False) as payload: + frames = np.asarray(payload["range"], dtype=np.float32) + frame_indices = np.asarray( + payload["frame_indices"], dtype=np.int64 + ) + if frames.shape[0] != frame_indices.shape[0] or frames.shape[0] == 0: + raise ValueError( + f"invalid DAgger bank shapes in {path}: " + f"range={frames.shape}, frame_indices={frame_indices.shape}" + ) + selected = int(np.random.randint(0, frames.shape[0])) + frame = frames[selected] + if frame.shape != tuple(self.lidar_size): + raise ValueError( + f"DAgger frame shape {frame.shape} does not match " + f"lidar_size={tuple(self.lidar_size)}" + ) + return int(frame_indices[selected]), torch.from_numpy(frame)[None, None] + + def __getitem__(self, idx): + # Deterministic parity mode: caller-provided (clip_idx, native rows) via + # ``self._explicit_windows`` (set e.g. by scripts/dump_hdmap_gen_ncore.py + # to align with an r2flow manifest). Mirrors the base + # ``LidarRangeMapSampler.__getitem__`` -- this override otherwise drops + # the explicit-windows branch and silently falls back to the random / + # frame-index path, ignoring the requested (clip, frame). + if self._explicit_windows is not None: + lidar_data_idx, lidar_frame_indices = self._explicit_windows[idx] + lidar_frame_indices = np.asarray(lidar_frame_indices, dtype=np.int64) + else: + lidar_data_idx = (idx % self.n_data_per_node) + self.data_start_idx + lidar_frame_indices = self.sample_frame_indices(load_lidar=True) + use_generated_previous = ( + self.autoregressive_pair + and self.autoregressive_generated_previous_prob > 0.0 + and np.random.random() + < self.autoregressive_generated_previous_prob + ) + generated_previous = None + if use_generated_previous: + if self._explicit_windows is None: + clip_key = self.dataset.filter_set[lidar_data_idx] + ( + generated_frame_idx, + generated_previous, + ) = self._sample_generated_previous_frame(clip_key) + lidar_frame_indices = np.asarray( + [generated_frame_idx, generated_frame_idx + 1], + dtype=np.int64, + ) + else: + generated_previous = self._generated_previous_frame( + self.dataset.filter_set[lidar_data_idx], + int(lidar_frame_indices[0]), + ) + + # When cameras are requested, additionally pull RGB + intrinsics + + # Camera-to-LiDAR transforms supplied by the configured dataset root. + data_fields = ["custom"] + if self.load_lidar_and_rgb: + data_fields = [ + "custom", + DataField.CAMERA_C2LIDAR_TRANSFORM, + DataField.CAMERA_INTRINSICS, + DataField.IMAGE_RGB, + ] + + try: + example = self.dataset._read_rgb_and_lidar( + lidar_data_idx, lidar_frame_indices, data_fields + ) + except Exception as e: + log.info(f"Error loading data for index {idx}: {e}", rank0_only=False) + return self.__getitem__(np.random.randint(0, self.__len__())) + + lidar_rangemap = self.get_lidar(example) + if lidar_rangemap is None: + log.info(f"Lidar rangemap missing for index {idx}, retrying", rank0_only=False) + return self.__getitem__(np.random.randint(0, self.__len__())) + + lidar_hdmap = self.get_lidar_hdmap(example) + if lidar_hdmap is None: + if self.synthesize_null_hdmap: + lidar_hdmap = torch.full_like( + lidar_rangemap[:1], self.min_value + ) + else: + log.info( + f"HDmap missing for index {idx}, retrying", + rank0_only=False, + ) + return self.__getitem__(np.random.randint(0, self.__len__())) + autoregressive_previous = None + autoregressive_lidar_to_world = None + autoregressive_frame_indices = None + if self.autoregressive_pair: + if lidar_rangemap.shape[1] != 2 or lidar_hdmap.shape[1] != 2: + raise RuntimeError( + "autoregressive pair must load exactly two frames, got " + f"lidar={tuple(lidar_rangemap.shape)}, " + f"hdmap={tuple(lidar_hdmap.shape)}" + ) + autoregressive_previous = lidar_rangemap[:, :1].clone() + autoregressive_lidar_to_world = np.asarray( + example["lidar_to_world"], dtype=np.float32 + ) + autoregressive_frame_indices = np.asarray( + example["rgb_frame_indices"], dtype=np.int64 + ) + if generated_previous is not None: + autoregressive_previous = generated_previous + lidar_rangemap = lidar_rangemap[:, 1:2] + lidar_hdmap = lidar_hdmap[:, 1:2] + lidar_hdmap_semantic = None + if lidar_hdmap.shape[0] > 1: + lidar_hdmap_semantic = lidar_hdmap + lidar_hdmap = compose_normalized_range_channels( + lidar_hdmap_semantic, + channel_dim=0, + min_value=self.min_value, + inverse_depth=self.inverse_depth, + ) + if self.return_hdmap_semantic and lidar_hdmap_semantic is None: + raise RuntimeError( + "semantic HDMap output requested but the reader returned a " + "single composited channel" + ) + + try: + t5_embed = self.prepare_t5_embeddings(example, lidar_frame_indices) + except (FileNotFoundError, RuntimeError) as e: + log.warning( + f"T5 embedding load failed for index {idx} " + f"(key={example['__key__']}): {e}; retrying with new index", + rank0_only=False, + ) + return self.__getitem__(np.random.randint(0, self.__len__())) + + bev_hdmap = self.get_lidar_hdmap_bev(example) + + metadata_slice = ( + slice(None) + if self.return_full_lidar_metadata + else slice(-1, None) + ) + sample = { + "video": lidar_rangemap, + "lidar_hdmap": lidar_hdmap, + "__key__": example["__key__"], + "clip_name": "%s-%s-%d" % (self.data_name, example["__key__"], idx), + "data_type": "lidar", + "num_frames": ( + self.autoregressive_target_frames + if self.autoregressive_pair + else self.sample_n_frames + ), + "is_preprocessed": True, + "image_size": torch.tensor(self.lidar_size), + "padding_mask": torch.zeros(1, self.lidar_size[0], self.lidar_size[1]), + "fps": self.sensor_fps, + "sensor_dataset_id": int(self.sensor_dataset_id), + "sensor_dataset_name": str(self.sensor_dataset_name), + "t5_text_embeddings": t5_embed["t5_text_embeddings"], + "t5_text_mask": t5_embed["t5_text_mask"], + # Sweep-start (and start/end) ego poses for the *actually sampled* + # frames (sequential sampling uses a random start_idx) -- forwarded + # so --save_poses dumps poses aligned to the dumped range maps + # instead of re-deriving from metadata assuming start frame 0. + "lidar_to_world": np.asarray( + example["lidar_to_world"][metadata_slice], + dtype=np.float32, + ), + "pose_sensor_start_end": np.asarray( + example["pose_sensor_start_end"][metadata_slice], + dtype=np.float32, + ), + # Actual sampled lidar frame indices (post frame-sampling). Mirrors + # the base image sampler; consumed by verification viz that re-reads + # the raw cloud/camera for the SAME frames (viz_waymo_cam5_overlay). + "rgb_frame_indices": np.asarray( + example["rgb_frame_indices"][metadata_slice], + dtype=np.int64, + ), + } + sample.update( + self.get_sensor_metadata(*lidar_rangemap.shape[-2:]) + ) + if self.autoregressive_pair: + sample["autoregressive_previous_video"] = ( + autoregressive_previous + ) + sample["autoregressive_lidar_to_world"] = ( + autoregressive_lidar_to_world + ) + sample["autoregressive_frame_indices"] = ( + autoregressive_frame_indices + ) + if bev_hdmap is not None: + sample["bev_hdmap"] = bev_hdmap + if self.return_hdmap_semantic: + sample["lidar_hdmap_semantic"] = lidar_hdmap_semantic + if self.return_moving_boxes: + ( + moving_box_object_to_world, + moving_box_lwh, + moving_box_valid, + moving_box_track_id, + moving_box_type, + moving_box_truncated, + ) = self._moving_boxes_for_sample(example) + sample["moving_box_object_to_world"] = ( + moving_box_object_to_world + ) + sample["moving_box_lwh"] = moving_box_lwh + sample["moving_box_valid"] = moving_box_valid + sample["moving_box_track_id"] = moving_box_track_id + sample["moving_box_type"] = moving_box_type + sample["moving_box_truncated"] = moving_box_truncated + + if self.blockwise_warped_history_condition: + if self._blockwise_warp_geometry is None: + self._blockwise_warp_geometry = load_waymo_lidar_geometry( + **self._blockwise_warp_geometry_args + ) + ray_dirs, elev, azim, row_off = self._blockwise_warp_geometry + warped, _ = warp_blockwise_history_to_video( + video=sample["video"], + lidar_to_world=sample["lidar_to_world"], + block_size=self.blockwise_warped_history_block_size, + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=self.min_distance, + max_range=self.max_distance, + min_value=self.min_value, + inverse_depth=self.inverse_depth, + history_mode=self.blockwise_warped_history_mode, + ) + sample["lidar_blockwise_warped_history"] = torch.from_numpy(warped) + + if self.load_lidar_and_rgb: + # image_rgb_ / camera_intrinsics_ / camera_c2lidar_transform_ + for getter in ( + self.get_rgb, + self.get_camera_intrinsics, + self.get_camera_c2lidar_transform, + ): + cam_dict = getter(example) + if cam_dict is not None: + sample.update(cam_dict) + + del example + gc.collect() + return sample + + +class HdmapLidarDataset: + """Lazy-constructable dataset config that builds ``HdmapLidarSampler``.""" + + def __init__(self, dataset_name: str, **kwargs): + self.dataset_name = dataset_name + self.dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + self.extra_config = OmegaConf.create(kwargs) + + def build_dataset(self): + if self.extra_config: + merged_config = OmegaConf.merge(self.dataset_config, self.extra_config) + else: + merged_config = self.dataset_config + config_dict = OmegaConf.to_container(merged_config, resolve=True) + return HdmapLidarSampler(**config_dict) + + +class HdmapLidarDataLoader(DataLoader): + def __init__(self, dataset, batch_size: int = 1, *args, **kw): + dataset_obj = dataset.build_dataset() + if "dataloaders" in kw: + kw.pop("dataloaders") + super().__init__(dataset_obj, batch_size, collate_fn=dict_collation_fn, *args, **kw) + + +class CrossDatasetHdmapLidarDataset: + """Lazy native-grid HDMap/LiDAR mixture with homogeneous batches.""" + + def __init__( + self, + dataset_names, + shared_overrides=None, + per_dataset_overrides=None, + ): + self.dataset_names = list(dataset_names) + self.shared_overrides = dict(shared_overrides or {}) + self.per_dataset_overrides = dict(per_dataset_overrides or {}) + + def build_dataset(self): + children = [] + for dataset_id, dataset_name in enumerate(self.dataset_names): + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + overrides = OmegaConf.create( + { + **self.shared_overrides, + **self.per_dataset_overrides.get(dataset_name, {}), + "emit_sensor_metadata": True, + "sensor_dataset_id": dataset_id, + "sensor_dataset_name": dataset_name, + } + ) + config_dict = OmegaConf.to_container( + OmegaConf.merge(dataset_config, overrides), resolve=True + ) + children.append(HdmapLidarSampler(**config_dict)) + return HomogeneousMultiHdmapDataset(children) + + +class HomogeneousMultiHdmapDataset(Dataset): + def __init__(self, children): + self.children = list(children) + if not self.children: + raise ValueError("At least one child dataset is required") + + def __len__(self): + return sum(len(child) for child in self.children) + + def __getitem__(self, index): + dataset_id, local_index = index + return self.children[dataset_id][local_index] + + +class HomogeneousHdmapBatchSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + validation=False, + mix_datasets_across_ranks=False, + dataset_sampling_weights=None, + seed=0, + ): + self.dataset = dataset + self.batch_size = int(batch_size) + self.validation = bool(validation) + self.mix_datasets_across_ranks = bool(mix_datasets_across_ranks) + self.seed = int(seed) + if "parallel_state" in globals() and parallel_state.is_initialized(): + self.rank = parallel_state.get_data_parallel_rank() + self.world_size = parallel_state.get_data_parallel_world_size() + elif torch.distributed.is_initialized(): + self.rank = torch.distributed.get_rank() + self.world_size = torch.distributed.get_world_size() + else: + self.rank = 0 + self.world_size = 1 + self.dataset_sampling_weights = None + if dataset_sampling_weights is not None: + weights = torch.as_tensor( + dataset_sampling_weights, dtype=torch.float64 + ) + if weights.numel() != len(dataset.children): + raise ValueError( + "dataset_sampling_weights must have one value per dataset; " + f"got {weights.numel()} values for {len(dataset.children)}" + ) + if ( + not torch.isfinite(weights).all() + or (weights < 0).any() + or weights.sum() <= 0 + ): + raise ValueError( + "dataset_sampling_weights must be finite, non-negative, " + "and sum positive" + ) + if self.mix_datasets_across_ranks and not torch.allclose( + weights, weights.new_full(weights.shape, weights.mean()) + ): + raise ValueError( + "Non-uniform dataset sampling is incompatible with " + "mix_datasets_across_ranks=True" + ) + self.dataset_sampling_weights = weights / weights.sum() + self.num_batches = max( + 1, + sum(len(child) for child in dataset.children) + // (self.batch_size * self.world_size), + ) + + def __len__(self): + return self.num_batches + + def __iter__(self): + generator = torch.Generator().manual_seed(self.seed) + cursors = [0] * len(self.dataset.children) + for step in range(self.num_batches): + if self.validation: + dataset_id = step % len(self.dataset.children) + elif self.mix_datasets_across_ranks: + dataset_id = (self.rank + step) % len(self.dataset.children) + elif self.dataset_sampling_weights is None: + dataset_id = int( + torch.randint( + len(self.dataset.children), (1,), generator=generator + ).item() + ) + else: + dataset_id = int( + torch.multinomial( + self.dataset_sampling_weights, + 1, + generator=generator, + ).item() + ) + child_len = len(self.dataset.children[dataset_id]) + start = cursors[dataset_id] + self.rank * self.batch_size + batch = [ + (dataset_id, (start + offset) % child_len) + for offset in range(self.batch_size) + ] + cursors[dataset_id] = ( + cursors[dataset_id] + self.world_size * self.batch_size + ) % child_len + yield batch + + +class HomogeneousMultiHdmapDataLoader(DataLoader): + def __init__( + self, + dataset, + batch_size=1, + validation=False, + mix_datasets_across_ranks=False, + dataset_sampling_weights=None, + seed=0, + *args, + **kwargs, + ): + dataset_obj = dataset.build_dataset() + batch_sampler = HomogeneousHdmapBatchSampler( + dataset_obj, + batch_size=batch_size, + validation=validation, + mix_datasets_across_ranks=mix_datasets_across_ranks, + dataset_sampling_weights=dataset_sampling_weights, + seed=seed, + ) + if "dataloaders" in kwargs: + kwargs.pop("dataloaders") + if "drop_last" in kwargs: + kwargs.pop("drop_last") + super().__init__( + dataset_obj, + batch_sampler=batch_sampler, + collate_fn=dict_collation_fn, + *args, + **kwargs, + ) + + +def get_hdmap_lidar_dataset(dataset_name: str, **kwargs): + """Build the raw dataset (no DataLoader wrapping).""" + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + if kwargs: + dataset_config = OmegaConf.merge(dataset_config, OmegaConf.create(kwargs)) + config_dict = OmegaConf.to_container(dataset_config, resolve=True) + return HdmapLidarSampler(**config_dict) diff --git a/diffusion/training/datasets/lidar_dataset/imagetolidar_dataloader.py b/diffusion/training/datasets/lidar_dataset/imagetolidar_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..2c68aa594e452ba2f7980d37fe6715e2274aeb8a --- /dev/null +++ b/diffusion/training/datasets/lidar_dataset/imagetolidar_dataloader.py @@ -0,0 +1,969 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc + +import numpy as np +import torch + +import os +import pickle + +import einops +import omegaconf +import torchvision.transforms as transforms + +from utils.lazy_config import LazyCall as L +from utils import log + +try: + from megatron.core import parallel_state + USE_MEGATRON = True +except ImportError: + USE_MEGATRON = False + +from omegaconf import OmegaConf +from torch.utils.data import DataLoader, Dataset + +from tokenizer.training.datasets.lidar_datasets.datasets import RadymLidar +from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField +from utils.lidar_rangemap import RangeMapDownsampler, normalize_range_map + +from diffusion.training.datasets.lidar_dataset.configs import COMMONDATA_CONFIG + +def dict_collation_fn(samples, combine_tensors=True, combine_scalars=True, ignore_keys=None): + """Take a list of samples (as dictionary) and create a batch, preserving the keys. + If `tensors` is True, `ndarray` objects are combined into + tensor batches. + :param dict samples: list of samples + :param bool tensors: whether to turn lists of ndarrays into a single ndarray + :returns: single sample consisting of a batch + :rtype: dict + """ + + batched = {key: [] for key in samples[0]} + # assert isinstance(samples[0][first_key], (list, tuple)), type(samples[first_key]) + + for s in samples: + [batched[key].append(s[key]) for key in batched if not (ignore_keys is not None and key in ignore_keys)] + + result = {} + for key in batched: + if ignore_keys and key in ignore_keys: + continue + try: + if isinstance(batched[key][0], bool): + assert key == "is_preprocessed" + result[key] = batched[key][0] # this is a hack to align with cosmos data + elif isinstance(batched[key][0], (int, float)): + if combine_scalars: + result[key] = torch.from_numpy(np.array(list(batched[key]))) + elif isinstance(batched[key][0], torch.Tensor): + if combine_tensors: + result[key] = torch.stack(list(batched[key])) + elif isinstance(batched[key][0], np.ndarray): + if combine_tensors: + result[key] = np.array(list(batched[key])) + elif isinstance(batched[key][0], list) and isinstance(batched[key][0][0], int): + result[key] = [torch.Tensor(elems).long() for elems in zip(*batched[key])] + else: + result[key] = list(batched[key]) + except Exception as e: + print(key) + raise e + # result.append(b) + del batched + return result + + +def frames_as_batch_collation_fn( + samples, combine_tensors=True, combine_scalars=True, ignore_keys=None, + video_key="video", hdmap_key="lidar_hdmap", +): + """Flatten the per-sample temporal dim (N>1) into the batch dim. + + This is intended for image-style training (``is_video_tokenizer=False``) + where each ``__getitem__`` call returns a tensor of shape ``[C, N, H, W]`` + representing N independent frames from the same clip. After the normal + collation produces ``[B, C, N, H, W]`` for video/hdmap, we reshape to + ``[B*N, C, 1, H, W]`` so every frame becomes its own training example, and + repeat per-sample metadata N times so alignment is preserved. + + If N == 1 this is a no-op and the output is identical to ``dict_collation_fn``. + """ + batch = dict_collation_fn(samples, combine_tensors, combine_scalars, ignore_keys) + + vid = batch.get(video_key) + if not (isinstance(vid, torch.Tensor) and vid.ndim == 5): + return batch + + B, C, N, H, W = vid.shape + if N <= 1: + return batch + + def _flatten_frames(t: torch.Tensor) -> torch.Tensor: + Bt, Ct, Nt, Ht, Wt = t.shape + return t.permute(0, 2, 1, 3, 4).reshape(Bt * Nt, Ct, 1, Ht, Wt).contiguous() + + batch[video_key] = _flatten_frames(vid) + _flatten_keys = {video_key, hdmap_key, "bev_hdmap"} + for fk in (hdmap_key, "bev_hdmap"): + if isinstance(batch.get(fk), torch.Tensor) and batch[fk].ndim == 5: + batch[fk] = _flatten_frames(batch[fk]) + + for key, v in list(batch.items()): + if key in _flatten_keys: + continue + if isinstance(v, bool): + continue + if isinstance(v, torch.Tensor) and v.ndim >= 1 and v.shape[0] == B: + batch[key] = v.repeat_interleave(N, dim=0) + elif isinstance(v, np.ndarray) and v.ndim >= 1 and v.shape[0] == B: + batch[key] = np.repeat(v, N, axis=0) + elif isinstance(v, list) and len(v) == B: + expanded = [] + for item in v: + expanded.extend([item] * N) + batch[key] = expanded + + return batch + + +class MyDataLoader(DataLoader): + def __init__(self, dataset, batch_size: int = 1, *args, **kw): + dataset_obj = dataset.build_dataset() + print("dl", kw.get("dataloaders")) + if "dataloaders" in kw: + kw.pop("dataloaders") # HACK? + print("dl2", kw.get("dataloaders")) + super().__init__(dataset_obj, batch_size, collate_fn=dict_collation_fn, *args, **kw) + + +class LidarRangeMapDataset: + def __init__(self, dataset_name, filter_list_path=None, **kwargs): + self.dataset_name = dataset_name + self.dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + self.extra_config = OmegaConf.create(kwargs) + + if filter_list_path is not None: + self.dataset_config["filter_list_path"] = filter_list_path + + def build_dataset(self): + config_dict = OmegaConf.to_container(self.dataset_config, resolve=True) + return LidarRangeMapSampler(**config_dict) + + +def get_lidar_dataset(dataset_name, filter_list_path=None): + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + + if filter_list_path is not None: + dataset_config["filter_list_path"] = filter_list_path + + config_dict = OmegaConf.to_container(dataset_config, resolve=True) + return LidarRangeMapSampler(**config_dict) + + +class LidarRangeMapSampler(Dataset): + def __init__( + self, + data_name, + root_path, + filter_list_path, + t5_embedding_path, + custom_folders, + custom_fields, + metadata_folder, + max_range, + min_range, + downsample_factor_row, + downsample_factor_col, + repeat_row, + repeat_col, + repeat_temporal, + lidar_crop_size, + rgb_crop_size, + rgb_resize_size, + lidar_size, + downsample_method, # for range map + min_value, + num_views, # the number of RGB cameras + sample_n_frames, + lidar_length, + frame_sampling_method, + frame_sampling_every_n_frames, + sample_lidar_prob, + is_video_tokenizer, + sequential_start_idx=0, + load_lidar_only=True, + load_rgb_only=False, + load_lidar_and_rgb=False, # load both lidar and rgb + load_lidar_or_rgb=False, + RGB_FPS=30, + LIDAR_FPS=10, + load_t5_embeddings=False, + inverse_depth=False, + to_three_channels="repeat", # legacy: "repeat" or "concat" (3 channels) + process_input=None, # if set, overrides to_three_channels. One of "repeat", "concat", "mono". + load_intensity=False, # if True, append per-frame intensity as an extra channel (dual tokenizer) + intensity_transform="legacy", + intensity_raw_max=1.0, + inv_depth_threshold=20, + # Optional fixed-size resize of the final range map to [H, W] (use -1 to + # keep a dim), done with nearest-exact interpolation (NOT bilinear) so + # depth values are resampled, never blended across depth discontinuities. + # Mirrors the tokenizer dataset's resize -- use it to feed a VAE at its + # exact training resolution when downsample_factor_col can't hit it. + lidar_resize_size=(-1, -1), + view_indices=None, + # Which frame of the sampled clip drives the T5 "chunk_id" lookup + # in prepare_t5_embeddings. The current on-disk layout is one + # `<__key__>.pkl` per clip (chunk-agnostic), so all three options + # resolve to the same pickle today, but this kwarg lets us pin + # the semantic intent ("the caption that describes the first + # frame of the window") so we get correct behavior if per-chunk + # pickles ever ship under `<__key__>_.pkl`. + # "middle" (default) -- frame_indices[len(...)//2] (legacy) + # "first" -- frame_indices[0] + # "last" -- frame_indices[-1] + t5_chunk_anchor="middle", + # --- backend dispatch (mirrors the tokenizer LidarRangeMapSampler) --- # + # "radym" (LidarGEN tar) or "waymo_ncore" (NCore .itar). The waymo backend + # reads the native 64x2650 grid + rasterizes hdmap on the fly. + dataset_backend="radym", + resample_width=-1, # waymo_ncore only: rebin azimuth to this width; <=0 native + center_vehicle_forward=False, + # waymo_ncore hdmap (on-the-fly rasterized from dump_waymo_hdmap NPZs) + hdmap_root=None, + hdmap_multichannel=False, + hdmap_moving_only=False, + hdmap_include_boxes=True, + hdmap_box_edge_spacing=0.15, + hdmap_map_max_dist=None, + # BEV multi-channel hdmap raster (for BEV-latent conditioning). + hdmap_bev=False, + hdmap_bev_size=(256, 256), + hdmap_bev_pc_range=(-75.0, 75.0, -75.0, 75.0, -3.0, 5.0), + hdmap_sensor_template="native", + hdmap_template_root_path=None, + hdmap_template_filter_list_path=None, + hdmap_virtual_sensor_height_m=None, + hdmap_virtual_sensor_yaw_deg=0.0, + canonical_lidar_mode="native", + hdmap_pose_for_lidar_to_world=False, + ): + super().__init__() + self.data_name = data_name + self.load_intensity = load_intensity + self.intensity_transform = str(intensity_transform) + if self.intensity_transform not in ("legacy", "log1p"): + raise ValueError( + f"Unknown intensity_transform: {self.intensity_transform!r}" + ) + self.intensity_raw_max = float(intensity_raw_max) + if self.intensity_raw_max <= 0.0: + raise ValueError("intensity_raw_max must be positive") + self.dataset_backend = dataset_backend + self.resample_width = resample_width + # waymo_ncore hdmap rasterization knobs (consumed in _build_dataset). + self._hdmap_kwargs = dict( + hdmap_root=hdmap_root, + min_range=min_range, + max_range=max_range, + hdmap_multichannel=hdmap_multichannel, + hdmap_moving_only=hdmap_moving_only, + hdmap_include_boxes=hdmap_include_boxes, + hdmap_box_edge_spacing=hdmap_box_edge_spacing, + hdmap_map_max_dist=hdmap_map_max_dist, + hdmap_bev=hdmap_bev, + hdmap_bev_size=hdmap_bev_size, + hdmap_bev_pc_range=hdmap_bev_pc_range, + ) + self._nuscenes_canonical_kwargs = dict( + hdmap_sensor_template=hdmap_sensor_template, + hdmap_template_root_path=hdmap_template_root_path, + hdmap_template_filter_list_path=hdmap_template_filter_list_path, + hdmap_virtual_sensor_height_m=hdmap_virtual_sensor_height_m, + hdmap_virtual_sensor_yaw_deg=hdmap_virtual_sensor_yaw_deg, + canonical_lidar_mode=canonical_lidar_mode, + center_vehicle_forward=bool(center_vehicle_forward), + hdmap_pose_for_lidar_to_world=bool(hdmap_pose_for_lidar_to_world), + ) + # waymo_ncore only: open the per-view camera zarrs when RGB is requested + # (the radym backend ignores this; it reads RGB from separate tars). + self._load_cameras = bool( + load_lidar_and_rgb or load_rgb_only or load_lidar_or_rgb + ) + # build the dataset + self.dataset = self._build_dataset( + root_path=root_path, + filter_list_path=filter_list_path, + num_views=num_views, + metadata_folder=metadata_folder, + custom_folders=custom_folders, + custom_fields=custom_fields, + view_indices=view_indices, + load_intensity=load_intensity, + ) + self.plus = 1 if "hdmap" not in self.dataset.custom_fields else 2 + self.num_views = num_views + + self.LIDAR_FPS = LIDAR_FPS + self.RGB_FPS = RGB_FPS + + self.sample_n_frames = sample_n_frames # the "actual" target sequence length + self.lidar_length = lidar_length + self.rgb_length = lidar_length * (RGB_FPS // LIDAR_FPS) + self.frame_sampling_method = frame_sampling_method + assert self.frame_sampling_method in ["random", "sequential", "sequential_from_zero"] + self.frame_sampling_every_n_frames = frame_sampling_every_n_frames + # Chunk offset for sequential_from_zero: render frames [start, start+n). + # Default 0 preserves existing behavior bit-for-bit. Mirrors the tokenizer + # LidarRangeMapSampler; used by infer_diffusion.py --chunk_start tiling. + self.sequential_start_idx = int(sequential_start_idx) + # Optional deterministic-window override: list of (clip_idx, frame_rows). + # When set, __getitem__/__len__ use it instead of the random clip+start + # logic, so an external driver can request the EXACT (clip, native rows) + # window it needs (used by the parity eval that mirrors waymo_ncore). + self._explicit_windows = None + + self.inverse_depth = inverse_depth + self.min_distance = min_range + self.max_distance = max_range + self.max_range = max_range if not inverse_depth else 1 / min_range + self.min_range = min_range if not inverse_depth else 1 / max_range + + self.min_value = min_value # min value after normalisation, if 0 then [0, 1],if -1, then [-1, 1] + + self.repeat_row = repeat_row + self.repeat_col = repeat_col + self.repeat_temporal = repeat_temporal + self.lidar_resize_size = lidar_resize_size + self.to_three_channels = to_three_channels + assert self.to_three_channels in ["repeat", "concat"] + # process_input takes precedence over the legacy to_three_channels arg. + # "mono" produces a single-channel range map; required for the dual + # (range + intensity) tokenizer. + self.process_input = process_input if process_input is not None else to_three_channels + assert self.process_input in ["repeat", "concat", "mono"], ( + f"Unsupported process_input={self.process_input!r}; " + "expected one of 'repeat', 'concat', 'mono'." + ) + if self.load_intensity and self.process_input != "mono": + log.warning( + f"[lidar dataset] load_intensity=True with process_input=" + f"{self.process_input!r}; intensity will be appended as an extra " + f"channel, but this combination is unusual. " + f"Use process_input='mono' for the dual tokenizer.", + rank0_only=True, + ) + + self.lidar_size = lidar_size + self.lidar_crop_size = lidar_crop_size + self.rgb_crop_size = rgb_crop_size + self.rgb_resize_size = rgb_resize_size + + self.sample_lidar_prob = sample_lidar_prob if not load_rgb_only else -1 + self.load_lidar_only = load_lidar_only + self.load_rgb_only = load_rgb_only + self.load_lidar_and_rgb = load_lidar_and_rgb + self.load_lidar_or_rgb = load_lidar_or_rgb + + assert sum([self.load_lidar_only, self.load_rgb_only, self.load_lidar_and_rgb, self.load_lidar_or_rgb]) == 1 + + # t5 text embedding + self.load_t5_embeddings = load_t5_embeddings + self.t5_embedding_path = t5_embedding_path + if t5_chunk_anchor not in ("first", "middle", "last"): + raise ValueError( + f"t5_chunk_anchor must be one of 'first'/'middle'/'last', " + f"got {t5_chunk_anchor!r}." + ) + self.t5_chunk_anchor = t5_chunk_anchor + # One-shot probe flag so prepare_t5_embeddings logs the first real + # embedding it loads (per dataloader-worker process). Each fork gets + # its own copy, so we'll see one probe line per worker. + self._t5_probe_logged = False + + self.length = self.dataset.size_of_filter_set() + log.critical(f"load_lidar_only: {self.load_lidar_only}") + log.critical(f"dataset size: {self.length}") + log.critical(f"load_t5_embeddings: {self.load_t5_embeddings}") + if self.load_t5_embeddings: + log.critical(f"t5_embedding_path: {self.t5_embedding_path}") + if not os.path.isdir(self.t5_embedding_path): + log.warning( + f"[t5] embedding directory does NOT exist: " + f"{self.t5_embedding_path} -- prepare_t5_embeddings " + f"will fall back to zero embeddings", + rank0_only=False, + ) + + self.is_video_tokenizer = is_video_tokenizer # if true, then the frame sampling method is sequential, also we need to upsample the lidar to the rgb fps + if self.is_video_tokenizer: + assert self.frame_sampling_method == "sequential" or self.frame_sampling_method == "sequential_from_zero" + + self.range_map_downsampler = RangeMapDownsampler(row_factor = downsample_factor_row, col_factor = downsample_factor_col, method = downsample_method) + + # image transform + self.img_transform = transforms.Compose( + [ + transforms.Resize( + self.rgb_resize_size, interpolation=transforms.InterpolationMode.BILINEAR, antialias=True + ), + transforms.CenterCrop(self.rgb_crop_size), + ] + ) + self.norm_image = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) + + # Prepare infinite dataset logic + self.n_data = self.length + if parallel_state.is_initialized(): + dp_group_id = parallel_state.get_data_parallel_rank() + dp_world_size = parallel_state.get_data_parallel_world_size() + log.critical( + f"Using parallelism size CP :{parallel_state.get_context_parallel_world_size()}, " + + f"TP :{parallel_state.get_tensor_model_parallel_world_size()} for video dataset, " + + f"DP: {dp_group_id}, DP World size: {dp_world_size}" + ) + else: + dp_world_size = 1 + dp_group_id = 0 + + # Data partitioning + self.n_data_per_node = self.n_data // dp_world_size + self.data_start_idx = dp_group_id * self.n_data_per_node + self.dp_group_id = dp_group_id + + # Infinite loop multiplier. Guard against n_data_per_node == 0, which + # happens when a (tiny, e.g. overfit) filter set has fewer clips than + # dp_world_size (n_data // dp_world_size == 0). Such datasets are only + # ever eagerly constructed at registry import and never iterated by the + # current experiment, so a 0 multiplier (=> len 0) is harmless; without + # the guard the bare division kills every job that imports the registry + # at higher GPU counts. + maximum_iter = 2000000 # hack to create infinite loop + self.multiplier = maximum_iter // max(1, self.n_data_per_node) + # self.multiplier = 1 + + def __len__(self): + """ + Return the artificially multiplied length + """ + if self._explicit_windows is not None: + return len(self._explicit_windows) + return self.multiplier * self.n_data_per_node + + def sample_random_frames(self, n_frames, total_frames): + # sample self.sample_n_frames frames from the video + # return the frame indices + frame_indices = np.random.randint(0, total_frames, size=n_frames) + return frame_indices + + def sample_sequential_frames(self, n_frames, total_frames): + # sample every self.frame_sampling_every_n_frames frames + if self.frame_sampling_method == "sequential_from_zero": + start_idx = self.sequential_start_idx + else: + start_idx = np.random.randint(0, total_frames - n_frames * self.frame_sampling_every_n_frames) + frame_indices = np.arange(start_idx, start_idx + n_frames * self.frame_sampling_every_n_frames, self.frame_sampling_every_n_frames) + return frame_indices + + + def sample_frame_indices(self, load_lidar): + if load_lidar: + if self.frame_sampling_method == "random": + frame_indices = self.sample_random_frames(self.sample_n_frames, self.lidar_length) + else: + frame_indices = self.sample_sequential_frames( + self.sample_n_frames // self.repeat_temporal, self.lidar_length + ) + + else: # load rgb + if self.frame_sampling_method == "random": + frame_indices = self.sample_random_frames(self.sample_n_frames, self.rgb_length) + else: + frame_indices = self.sample_sequential_frames( + self.sample_n_frames + 1, self.rgb_length + ) # + 1 because the video tokenizer will need one more additional frame + return frame_indices + + def normalise_and_convert_range_map_to_three_channels(self, range_maps): + """Normalize the range map and lift to ``[N, C, H, W]``. + + ``C`` is 3 for ``repeat``/``concat`` (legacy 3-channel paths) and 1 for + ``mono`` (used by the dual range+intensity tokenizer). + """ + if self.process_input == "repeat": + range_maps = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth + ) # shape: [N, H, W] + range_maps = range_maps[:, None, :, :].repeat(3, axis=1) # shape: [N, 3, H, W] + elif self.process_input == "mono": + range_maps = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth + ) # shape: [N, H, W] + range_maps = range_maps[:, None, :, :] # shape: [N, 1, H, W] + elif self.process_input == "concat": + inverse_depth = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, True + ) # shape: [N, H, W] + depth = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, False + ) # shape: [N, H, W] + range_maps = np.concatenate( + [inverse_depth[:, None, :, :], depth[:, None, :, :], depth[:, None, :, :]], axis=1 + ) # shape: [N, 3, H, W] + + return range_maps + + def _normalize_intensity(self, intensity_maps): + """Apply the intensity tokenizer's input transform.""" + intensity_maps = intensity_maps.copy() + if self.intensity_transform == "log1p": + intensity_maps = np.clip( + intensity_maps / self.intensity_raw_max, 0.0, 1.0 + ) + intensity_maps = np.log1p(intensity_maps) / np.log(2.0) + intensity_maps = intensity_maps * 2.0 - 1.0 + return intensity_maps[:, None, :, :] + if self.min_value == -1: + intensity_maps = intensity_maps * 2 - 1 + return intensity_maps[:, None, :, :] # [N, 1, H, W] + + def _build_dataset(self, **kwargs): + """Construct the low-level reader. Defaults to the LidarGEN tar-backed + ``RadymLidar``; ``dataset_backend='waymo_ncore'`` swaps in the NCore + reader (native 64x2650 grid + on-the-fly hdmap rasterization). Mirrors + the tokenizer ``LidarRangeMapSampler._build_dataset``.""" + if self.dataset_backend == "waymo_ncore": + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + WaymoNCoreLidar, + ) + + return WaymoNCoreLidar( + resample_width=self.resample_width, + load_cameras=self._load_cameras, + **self._hdmap_kwargs, + **kwargs, + ) + if self.dataset_backend == "nuscenes_ncore": + from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import ( + NuScenesNCoreLidar, + ) + + return NuScenesNCoreLidar( + resample_width=self.resample_width, + load_cameras=self._load_cameras, + **self._hdmap_kwargs, + **self._nuscenes_canonical_kwargs, + **kwargs, + ) + return RadymLidar(**kwargs) + + def process_lidar(self, range_maps, intensity_maps=None): + """Downsample, normalize, optionally append intensity, then repeat/crop/temporal-pad. + + When ``intensity_maps`` is provided it is downsampled jointly with the range + map (so the same valid pixels are kept), normalized, and concatenated as an + extra channel after ``normalise_and_convert_range_map_to_three_channels``. + """ + if intensity_maps is not None: + range_maps, [intensity_maps] = self.range_map_downsampler.downsample( + range_maps, [intensity_maps] + ) # range_maps: [N, H, W]; intensity: [N, H, W] + else: + range_maps = self.range_map_downsampler.downsample(range_maps) # [N, H, W] + + range_maps = self.normalise_and_convert_range_map_to_three_channels( + range_maps + ) # [N, C, H, W] with C=3 (repeat/concat) or C=1 (mono) + + if intensity_maps is not None: + intensity_np = self._normalize_intensity(intensity_maps) # [N, 1, H, W] + range_maps = np.concatenate([range_maps, intensity_np], axis=1) # [N, C+1, H, W] + + range_maps = range_maps.repeat(self.repeat_row, axis=2) + range_maps = range_maps.repeat(self.repeat_col, axis=3) + + # only crop along the column dimension + if self.lidar_crop_size[1] != -1: + if self.lidar_crop_size[1] > 1600: # we do center crop + start_col_idx = (range_maps.shape[-1] - self.lidar_crop_size[1]) // 2 + range_maps = range_maps[:, :, :, start_col_idx : start_col_idx + self.lidar_crop_size[1]] + else: + start_col_idx = np.random.randint(0, range_maps.shape[-1] - self.lidar_crop_size[1]) + range_maps = range_maps[:, :, :, start_col_idx : start_col_idx + self.lidar_crop_size[1]] + + # if it comes from sequential sampling, then we need to repeat the range maps for sequence + if self.frame_sampling_method in ("sequential", "sequential_from_zero") and self.is_video_tokenizer: + first_range_map = range_maps[ + 0 + ] # let's just repeat the first frame to make task easier. This is the same practice as when I evaluate the tokenizer + range_maps = range_maps.repeat(self.repeat_temporal, axis=0) + range_maps = np.concatenate( + [first_range_map[None], range_maps], axis=0 + ) # this one will be repeated later on in the encoder + + # to torch tensor + range_maps = torch.from_numpy(range_maps).float() # [N, C(+1), H, W] + + # Optional fixed-size resize (nearest-exact). Applied to [N, C, H, W] so + # depth values are resampled, never blended. Matches the tokenizer's + # ``lidar_resize_size`` so a VAE can be fed at its training resolution. + if self.lidar_resize_size is not None and ( + self.lidar_resize_size[0] != -1 or self.lidar_resize_size[1] != -1 + ): + _, _, H, W = range_maps.shape + target_h = self.lidar_resize_size[0] if self.lidar_resize_size[0] != -1 else H + target_w = self.lidar_resize_size[1] if self.lidar_resize_size[1] != -1 else W + if (target_h, target_w) != (H, W): + range_maps = torch.nn.functional.interpolate( + range_maps, size=(target_h, target_w), mode="nearest-exact" + ) + + return range_maps + + def process_lidar_multichannel(self, range_maps): + """Process ``(N,K,H,W)`` semantic range maps without mixing K.""" + if range_maps.ndim != 4: + raise ValueError( + "multi-channel HDMap must be (N,K,H,W), got " + f"{tuple(range_maps.shape)}" + ) + if self.process_input != "mono": + raise ValueError( + "multi-channel HDMap processing requires process_input='mono'" + ) + num_frames, num_channels = range_maps.shape[:2] + flat = range_maps.reshape( + num_frames * num_channels, *range_maps.shape[2:] + ) + flat = self.range_map_downsampler.downsample(flat) + flat = self.normalise_and_convert_range_map_to_three_channels(flat) + if flat.shape[1] != 1: + raise RuntimeError( + "semantic HDMap normalization must preserve one depth channel" + ) + range_maps = flat.reshape( + num_frames, num_channels, *flat.shape[2:] + ) + range_maps = range_maps.repeat(self.repeat_row, axis=2) + range_maps = range_maps.repeat(self.repeat_col, axis=3) + + if self.lidar_crop_size[1] != -1: + crop_width = self.lidar_crop_size[1] + if crop_width > 1600: + start_col_idx = (range_maps.shape[-1] - crop_width) // 2 + else: + start_col_idx = np.random.randint( + 0, range_maps.shape[-1] - crop_width + ) + range_maps = range_maps[ + :, :, :, start_col_idx : start_col_idx + crop_width + ] + + if ( + self.frame_sampling_method + in ("sequential", "sequential_from_zero") + and self.is_video_tokenizer + ): + first_range_map = range_maps[0] + range_maps = range_maps.repeat(self.repeat_temporal, axis=0) + range_maps = np.concatenate( + [first_range_map[None], range_maps], axis=0 + ) + + range_maps = torch.from_numpy(range_maps).float() + if self.lidar_resize_size is not None and ( + self.lidar_resize_size[0] != -1 + or self.lidar_resize_size[1] != -1 + ): + n, k, height, width = range_maps.shape + target_h = ( + self.lidar_resize_size[0] + if self.lidar_resize_size[0] != -1 + else height + ) + target_w = ( + self.lidar_resize_size[1] + if self.lidar_resize_size[1] != -1 + else width + ) + if (target_h, target_w) != (height, width): + range_maps = torch.nn.functional.interpolate( + range_maps.reshape(n * k, 1, height, width), + size=(target_h, target_w), + mode="nearest-exact", + ).reshape(n, k, target_h, target_w) + return range_maps + + def process_rgb(self, rgb_images): + rgb_images = self.img_transform(rgb_images) + rgb_images = self.norm_image(rgb_images) # N C H W + return rgb_images + + def prepare_dummy_data(self): + data = {} + dummy_text_embedding = torch.zeros(512, 1024) + dummy_text_mask = torch.zeros(512) + dummy_text_mask[0] = 1 + data["t5_text_embeddings"] = dummy_text_embedding + data["t5_text_mask"] = dummy_text_mask + + return data + + def prepare_t5_embeddings(self, example, frame_indices): + # determine which chunk to use based on the frame indices + if self.t5_chunk_anchor == "first": + anchor_indice = frame_indices[0] + elif self.t5_chunk_anchor == "last": + anchor_indice = frame_indices[-1] + else: # "middle" (legacy default) + anchor_indice = frame_indices[len(frame_indices) // 2] + chunk_id = anchor_indice // int(self.lidar_length / 5) + + if self.load_t5_embeddings: + # t5_embed_path = os.path.join(self.t5_embedding_path, example["__key__"] + f"_{chunk_id}.pkl") + t5_embed_path = os.path.join(self.t5_embedding_path, example["__key__"] + ".pkl") + if not os.path.exists(t5_embed_path): + # Mirror the lidar/hdmap behavior: signal __getitem__ to draw a + # different sample instead of silently feeding zero embeddings. + raise FileNotFoundError( + f"t5 embedding missing for {example['__key__']}: {t5_embed_path}" + ) + # Truncated/corrupt .pkl files exist in the wild. Re-raise so the + # caller can retry with a different index (same pattern as + # hdmap/lidar load failures). + try: + with open(t5_embed_path, "rb") as fh: + t5_embed_pickle = pickle.load(fh) + text_embedding = t5_embed_pickle["pickle"]["ground_truth"]["embeddings"]["t5_xxl"] + except (EOFError, pickle.UnpicklingError, OSError, KeyError) as e: + raise RuntimeError( + f"[t5] failed to load {t5_embed_path} " + f"({type(e).__name__}: {e})" + ) from e + + t5_embed = {} + dummy_text_embedding = torch.zeros(512, 1024) + dummy_text_mask = torch.zeros(512) + n_text = text_embedding.shape[0] # 512 + dummy_text_embedding[:n_text] = torch.from_numpy(text_embedding) + dummy_text_mask[:n_text] = 1 + t5_embed["t5_text_embeddings"] = dummy_text_embedding + t5_embed["t5_text_mask"] = dummy_text_mask + # One-shot probe: confirm to the training log that real + # (non-zero) T5 embeddings are flowing through this worker. + if not self._t5_probe_logged: + nz_rows = int( + (dummy_text_embedding.abs().sum(dim=-1) > 0).sum() + ) + log.critical( + f"[t5 probe] pid={os.getpid()} loaded {t5_embed_path} " + f"shape={tuple(text_embedding.shape)} " + f"nonzero_rows={nz_rows}/{dummy_text_embedding.shape[0]}", + rank0_only=False, + ) + self._t5_probe_logged = True + del t5_embed_pickle + else: + t5_embed = self.prepare_dummy_data() + + if self.num_views > 1: + t5_embed["t5_text_embeddings"] = torch.cat([t5_embed["t5_text_embeddings"]] * (self.num_views+self.plus), dim=0) + t5_embed["t5_text_mask"] = torch.cat([t5_embed["t5_text_mask"]] * (self.num_views+self.plus), dim=0) + + return t5_embed + + def get_lidar(self, example, lidar_key = "lidar"): + if lidar_key in example["custom"]: + range_maps = example["custom"][lidar_key] # shape: [N, 128, 3600] + intensity_maps = ( + example["custom"].get("lidar_intensity") if self.load_intensity else None + ) + range_maps = self.process_lidar(range_maps, intensity_maps=intensity_maps) + range_maps = range_maps.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + else: + range_maps = None + + return range_maps + + def get_lidar_hdmap(self, example, hdmap_key = "hdmap"): + if hdmap_key in example["custom"]: + hdmap = example["custom"][hdmap_key] # shape: [N, 128, 3600] + if hdmap.ndim == 4: + hdmap = self.process_lidar_multichannel(hdmap) + else: + hdmap = self.process_lidar(hdmap) + hdmap = hdmap.permute(1, 0, 2, 3).contiguous() + else: + hdmap = None + return hdmap + + def get_lidar_hdmap_bev(self, example, key="hdmap_bev"): + """Multi-channel BEV hdmap raster -> (C_cls, N, Y, X) tensor. + + Already a {0,1} top-down occupancy grid (one channel per semantic + class); NOT a range map, so it skips ``process_lidar`` (no depth + normalize / azimuth resize / repeat-crop) -- just tensor + permute to + the (C, N, H, W) convention the collation flattens.""" + if key not in example["custom"]: + return None + bev = example["custom"][key] # (N, C_cls, Y, X) float32 in {0, 1} + if not isinstance(bev, torch.Tensor): + bev = torch.from_numpy(bev) + return bev.float().permute(1, 0, 2, 3).contiguous() # (C_cls, N, Y, X) + + def get_rgb(self, example): + key = DataField.IMAGE_RGB + if key in example.keys(): + rgb_images_dict = dict() + view_keys = example[key].keys() + for view_key in view_keys: + rgb_images = example[key][view_key] + rgb_images = self.process_rgb(rgb_images) + rgb_images = rgb_images.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + rgb_images_dict[key.value + "_" + str(view_key)] = rgb_images + else: + rgb_images_dict = None + return rgb_images_dict + + def get_rgb_hdmap(self, example): + key = DataField.IMAGE_HDMAP + if key in example.keys(): + rgb_hdmap_dict = dict() + view_keys = example[key].keys() + for view_key in view_keys: + rgb_hdmap = example[key][view_key] + rgb_hdmap = self.process_rgb(rgb_hdmap) + rgb_hdmap = rgb_hdmap.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + rgb_hdmap_dict[key.value + "_" + str(view_key)] = rgb_hdmap + else: + rgb_hdmap_dict = None + return rgb_hdmap_dict + + def get_camera_c2lidar_transform(self, example): + key = DataField.CAMERA_C2LIDAR_TRANSFORM + if key in example.keys(): + camera_c2lidar_transform_dict = dict() + view_keys = example[key].keys() + for view_key in view_keys: + camera_c2lidar_transform = example[key][view_key] + camera_c2lidar_transform_dict[key.value + "_" + str(view_key)] = camera_c2lidar_transform + else: + camera_c2lidar_transform_dict = None + return camera_c2lidar_transform_dict + + def get_camera_intrinsics(self, example): + key = DataField.CAMERA_INTRINSICS + if key in example.keys(): + view_keys = example[key].keys() + camera_intrinsics_dict = dict() + for view_key in view_keys: + camera_intrinsics = example[key][view_key] + camera_intrinsics_dict[key.value + "_" + str(view_key)] = camera_intrinsics + else: + camera_intrinsics_dict = None + return camera_intrinsics_dict + + + + def __getitem__(self, idx): + if self.load_rgb_only: + raise NotImplementedError + if self.load_lidar_or_rgb: + raise NotImplementedError + + # sample the video index + if self._explicit_windows is not None: + # Deterministic parity mode: caller-provided (clip_idx, native rows). + lidar_data_idx, lidar_frame_indices = self._explicit_windows[idx] + lidar_frame_indices = np.asarray(lidar_frame_indices, dtype=np.int64) + else: + lidar_data_idx = (idx % self.n_data_per_node) + self.data_start_idx # frame idx + lidar_frame_indices = self.sample_frame_indices(load_lidar=True) + + # load the data + try: + if self.load_lidar_and_rgb: # we also load the camera intrinsics and camera-to-lidar transformation matrix as well as the timestamp for motion compensation + # example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom", DataField.CAMERA_C2LIDAR_TRANSFORM, DataField.CAMERA_INTRINSICS, DataField.IMAGE_HDMAP, DataField.IMAGE_RGB]) + example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom", DataField.CAMERA_C2LIDAR_TRANSFORM, DataField.CAMERA_INTRINSICS, DataField.IMAGE_RGB]) + else: + example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom"]) + except Exception as e: + log.info(f"Error loading data for index {idx}: {e}", rank0_only=False) + return self.__getitem__(np.random.randint(0, self.__len__())) + + lidar_rangemap = self.get_lidar(example) + lidar_hdmap = self.get_lidar_hdmap(example) + bev_hdmap = self.get_lidar_hdmap_bev(example) + rgb_images = self.get_rgb(example) + rgb_hdmap = self.get_rgb_hdmap(example) + try: + t5_embed = self.prepare_t5_embeddings(example, lidar_frame_indices) + except (FileNotFoundError, RuntimeError) as e: + log.warning( + f"T5 embedding load failed for index {idx} " + f"(key={example['__key__']}): {e}; retrying with new index", + rank0_only=False, + ) + return self.__getitem__(np.random.randint(0, self.__len__())) + + + cam_intrinsics = self.get_camera_intrinsics(example) + cam_c2lidar_transform = self.get_camera_c2lidar_transform(example) + + key = "video" + + sample = {} + sample[key] = lidar_rangemap + sample["__key__"] = example["__key__"] + sample["clip_name"] = "%s-%s-%d" % (self.data_name, example["__key__"], idx) + sample["data_type"] = "lidar" + sample["num_frames"] = self.sample_n_frames + 1 if self.is_video_tokenizer else self.sample_n_frames + sample["is_preprocessed"] = True + sample["image_size"] = torch.tensor(self.lidar_size) + sample["padding_mask"] = torch.zeros(1, self.lidar_size[0], self.lidar_size[1]) + sample["fps"] = 24 # unsure why this value + sample['num_views'] = self.num_views + sample["view_indices"] = torch.arange(self.num_views + self.plus) # +1 for the lidar view + sample["timestamp_list"] = example["timestamp_list"] + sample["pose_sensor_start_end"] = example["pose_sensor_start_end"] + # Sweep-start ego poses for the *actually sampled* frames (sequential + # sampling uses a random start_idx) -- forwarded so --save_poses dumps + # poses aligned to the dumped range maps rather than re-deriving from + # metadata assuming start frame 0. + sample["lidar_to_world"] = np.asarray( + example["lidar_to_world"], dtype=np.float32) + sample["rgb_frame_indices"]=example["rgb_frame_indices"] + sample.update(t5_embed) + + if lidar_hdmap is not None: + sample["lidar_hdmap"] = lidar_hdmap + if bev_hdmap is not None: + sample["bev_hdmap"] = bev_hdmap + if rgb_images is not None: + sample.update(rgb_images) + if rgb_hdmap is not None: + sample.update(rgb_hdmap) + if self.load_lidar_and_rgb: + + sample.update(cam_intrinsics) + sample.update(cam_c2lidar_transform) + + + del example + gc.collect() + return sample diff --git a/diffusion/training/datasets/lidar_dataset/waymo_track_ids.py b/diffusion/training/datasets/lidar_dataset/waymo_track_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0d24a54e20aab634e9dfbd3b6b412dfc6ded2b --- /dev/null +++ b/diffusion/training/datasets/lidar_dataset/waymo_track_ids.py @@ -0,0 +1,191 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Exact track-ID join for legacy Waymo HDMap box dumps.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np + + +_NCORE_CLASS_TO_BOX_TYPE = { + "vehicle": 0, + "pedestrian": 1, + "cyclist": 2, +} + + +def resolve_waymo_box_track_ids_from_ncore( + *, + hdmap_composer, + sequence_loader, + lidar_sensor, +) -> tuple[np.ndarray, dict[str, Any]]: + """Attach exact NCore cuboid track IDs to legacy HDMap box rows.""" + box_frame = np.asarray(hdmap_composer.box_frame, dtype=np.int64) + existing = np.asarray(hdmap_composer.box_track_id, dtype=np.int64) + if existing.shape != box_frame.shape: + raise ValueError( + "box_track_id must align with box_frame, got " + f"{existing.shape} and {box_frame.shape}" + ) + if existing.size == 0 or np.all(existing >= 0): + return existing.copy(), { + "track_id_source": "hdmap_npz", + "matched_box_rows": int(existing.shape[0]), + "max_box_center_error_m": 0.0, + "max_box_size_error_m": 0.0, + } + + from ncore.impl.data.v4.components import CuboidsComponent + + component_reader = getattr(sequence_loader, "_reader", None) + if component_reader is None: + raise ValueError( + "the NCore sequence loader does not expose its component reader" + ) + cuboid_readers = component_reader.open_component_readers( + CuboidsComponent.Reader + ) + if "default" not in cuboid_readers: + raise ValueError( + "the NCore sequence has no default cuboid component; exact dynamic " + "actor composition is unavailable" + ) + observations = list(cuboid_readers["default"].get_observations()) + + frame_timestamps = np.asarray( + lidar_sensor.get_frames_timestamps_us(), dtype=np.int64 + ) + timestamp_to_frame = { + int(timestamp): frame_index + for frame_index, timestamp in enumerate(frame_timestamps) + } + frame_indices = np.arange(frame_timestamps.shape[0], dtype=np.int64) + lidar_to_world = np.asarray( + lidar_sensor.get_frames_T_sensor_target("world", frame_indices), + dtype=np.float64, + ) + sensor_id = str(lidar_sensor.sensor_id) + + candidates: dict[ + tuple[int, int], list[tuple[str, np.ndarray, np.ndarray]] + ] = {} + for observation in observations: + class_name = str(observation.class_id).split(".")[-1].lower() + box_type = _NCORE_CLASS_TO_BOX_TYPE.get(class_name) + if box_type is None: + continue + if str(observation.reference_frame_id) != sensor_id: + raise ValueError( + "expected NCore cuboids in the LiDAR frame, got " + f"{observation.reference_frame_id!r}" + ) + frame_index = timestamp_to_frame.get( + int(observation.reference_frame_timestamp_us) + ) + if frame_index is None: + continue + pose = lidar_to_world[frame_index] + center_sensor = np.asarray( + observation.bbox3.centroid, dtype=np.float64 + ) + center_world = center_sensor @ pose[:3, :3].T + pose[:3, 3] + candidates.setdefault((frame_index, box_type), []).append( + ( + str(observation.track_id), + center_world, + np.asarray(observation.bbox3.dim, dtype=np.float64), + ) + ) + + box_o2w = np.asarray(hdmap_composer.box_o2w, dtype=np.float64) + box_lwh = np.asarray(hdmap_composer.box_lwh, dtype=np.float64) + box_type = np.asarray(hdmap_composer.box_type, dtype=np.int64) + matched_track_names: list[str | None] = [None] * box_frame.shape[0] + center_errors: list[float] = [] + size_errors: list[float] = [] + + for key in sorted(set(zip(box_frame.tolist(), box_type.tolist()))): + rows = np.nonzero( + (box_frame == key[0]) & (box_type == key[1]) + )[0] + frame_candidates = candidates.get(key, []) + if len(frame_candidates) != int(rows.shape[0]): + raise ValueError( + "NCore cuboids do not align with HDMap boxes for " + f"frame/type={key}: boxes={rows.shape[0]}, " + f"cuboids={len(frame_candidates)}" + ) + + candidate_centers = np.stack( + [candidate[1] for candidate in frame_candidates] + ) + candidate_sizes = np.stack( + [candidate[2] for candidate in frame_candidates] + ) + row_centers = box_o2w[rows, :3, 3] + row_sizes = box_lwh[rows] + center_distance = np.linalg.norm( + row_centers[:, None] - candidate_centers[None], axis=-1 + ) + size_distance = np.linalg.norm( + row_sizes[:, None] - candidate_sizes[None], axis=-1 + ) + cost = center_distance + size_distance + + row_assignment = np.full(rows.shape[0], -1, dtype=np.int64) + used_candidates = np.zeros(len(frame_candidates), dtype=bool) + for flat_index in np.argsort(cost, axis=None): + local_row, candidate_index = np.unravel_index( + int(flat_index), cost.shape + ) + if ( + row_assignment[local_row] >= 0 + or used_candidates[candidate_index] + ): + continue + row_assignment[local_row] = candidate_index + used_candidates[candidate_index] = True + if (row_assignment < 0).any(): + raise RuntimeError( + f"failed to join all HDMap boxes for frame/type={key}" + ) + + for local_row, candidate_index in enumerate(row_assignment): + center_error = float( + center_distance[local_row, candidate_index] + ) + size_error = float(size_distance[local_row, candidate_index]) + if center_error > 0.05 or size_error > 0.01: + raise ValueError( + "NCore cuboid does not exactly match its HDMap box: " + f"frame/type={key}, center_error={center_error:.6f}m, " + f"size_error={size_error:.6f}m" + ) + matched_track_names[int(rows[local_row])] = frame_candidates[ + int(candidate_index) + ][0] + center_errors.append(center_error) + size_errors.append(size_error) + + if any(track_name is None for track_name in matched_track_names): + raise RuntimeError("not every HDMap box received an NCore track ID") + unique_names = sorted(set(matched_track_names)) + name_to_id = { + track_name: track_id + for track_id, track_name in enumerate(unique_names) + } + resolved = np.asarray( + [name_to_id[track_name] for track_name in matched_track_names], + dtype=np.int64, + ) + return resolved, { + "track_id_source": "ncore_cuboids_exact_geometry_join", + "matched_box_rows": int(resolved.shape[0]), + "cuboid_tracks": int(len(unique_names)), + "max_box_center_error_m": max(center_errors, default=0.0), + "max_box_size_error_m": max(size_errors, default=0.0), + } diff --git a/diffusion/training/functional/loss.py b/diffusion/training/functional/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..cc2990ad5e4f118b7393e5a185ac2fc1ee04e225 --- /dev/null +++ b/diffusion/training/functional/loss.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Tuple, Union + +import torch + +from diffusion.functional.batch_ops import batch_mul + + +def create_per_sample_loss_mask( + loss_masking_cfg: dict, + data_batch: dict, + x_shape: Tuple[int], + dtype: torch.dtype, + device: Union[str, torch.device] = "cuda", +): + """ + Creates a per-sample loss mask based on the given configuration and input data batch. + + This function generates a dictionary of loss masks for each specified key in the loss masking configuration. + For keys present in both the configuration and the data batch, the corresponding data batch value is used. + For keys present only in the configuration, a tensor of zeros with the specified shape is created. + Additionally, it computes loss mask weights for each key based on the configuration values and adjusts them + based on the presence of certain keys in the data batch, such as "skip_face" and "object_loss_map". + + Note: + - The original `loss_masking_cfg` and `data_batch` are not modified by this function. + - For image data, it is assumed that the channel is always the first dimension. + - `skip_face` is for face regions that should be skipped during training, the key is provided so that we can generate + diverse human and avoid collapse to a single face given certain prompts. The issue happens for getty projects, + where face distribution in the dataset is high unbalanced that single man face can be shown in more than 100+ images. + + Parameters: + loss_masking_cfg (dict): Configuration for loss masking, specifying which keys to include and their weights. + data_batch (dict): The batch of data containing actual data points and potential mask indicators like "skip_face". + x_shape (tuple): The shape of the input data, used to initialize zero masks for keys not in the data batch. + dtype (torch.dtype): The data type for the tensors in the loss masks. + device (str, optional): The device on which to create the tensors. Defaults to 'cuda'. + + Returns: + dict: A dictionary containing combined loss masks adjusted according to the `loss_masking_cfg` and `data_batch`. + + Raises: + AssertionError: If "skip_face" is not present in `data_batch`. + + Note: `create_combined_loss_mask` is assumed to be a separate function that combines individual loss masks into a + single mask or set of masks based on the given parameters. Its behavior should be documented separately. + """ + loss_mask_data: dict = {} + for key in loss_masking_cfg: + if key not in data_batch: + loss_mask_data[key] = torch.zeros((x_shape[0], 1, x_shape[2], x_shape[3]), device=device) + else: + loss_mask_data[key] = data_batch[key] + + if "skip_face" not in data_batch: + # When skip_face is not there in data_dict, use 0 as default. This will not skip any sample. + data_batch["skip_face"] = torch.zeros((x_shape[0],), dtype=dtype, device=device) + + loss_mask_weight: dict = {} + for k, v in loss_masking_cfg.items(): + loss_mask_weight[k] = torch.tensor(v, device=device).expand(data_batch["skip_face"].size()) + + if "human_face_mask" in loss_mask_weight: + loss_mask_weight["human_face_mask"] = (1 - data_batch["skip_face"]) * loss_mask_weight["human_face_mask"] + + if "object_loss_map" in data_batch: + loss_mask_weight["object_loss_map"] = torch.ones(data_batch["object_loss_map"].shape[0], device=device) + + return create_combined_loss_mask(loss_mask_data, x_shape, dtype, device, loss_mask_weight) + + +def create_combined_loss_mask(data, x_shape, dtype, device="cuda", loss_masking=None): + """ + Creates a combined loss mask from multiple input masks. + + This function combines several loss masks into a single mask. In regions where masks overlap, + the highest value is assigned. Non-overlapping regions are assigned a default value of 1. + Regions with a mask value of zero are explicitly zeroed out, which is essential for padded loss calculations. + + Example: + Given the following masks and weights: + mask1: [0, 1, 1, 1, 0, 0], weight: 2 + mask2: [1, 0, 1, 0, 0, 0], weight: 4 + mask3: [0, 1, 0, 0, 0, 0], weight: 0 + The resulting combined loss mask would be: + [4, 0, 4, 2, 1, 1] + + Parameters: + data (dict): Contains the loss masks and their weights. + x_shape (tuple): The shape of the output mask. + dtype: The data type for the output mask. + device: The device on which the output mask will be allocated. + loss_masking: The loss masking weight configuration. + + Returns: + torch.Tensor: The combined loss mask. + """ + + loss_mask = torch.ones(x_shape, dtype=dtype, device=device) + zero_mask = torch.ones(x_shape, dtype=dtype, device=device) + + if loss_masking: + for key in loss_masking: + # Repeat mask along channel's dimension. ndim=4 for images. + repeat_dims = (1, x_shape[1]) + tuple([1] * (data[key].ndim - 2)) + mask_key = torch.tile(data[key], dims=repeat_dims) + weight_key = loss_masking[key] + + # handle zero weight case + is_zero_weight = (weight_key == 0).float()[:, None, None, None] + zero_mask = zero_mask * ( + (1 - is_zero_weight) * torch.ones(x_shape, dtype=dtype, device=device) + + is_zero_weight * (1 - mask_key.bool().float()) + ) + + # calculate weights + no_mask_region = (mask_key.bool() == 0).float() + loss_mask = batch_mul(mask_key, weight_key) + batch_mul(no_mask_region, loss_mask) + + loss_mask_final = loss_mask * zero_mask + return loss_mask_final diff --git a/diffusion/training/functional/lr_scheduler.py b/diffusion/training/functional/lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..9eaef8cd6071d7b35313a09fd716fe2a3a2a17ef --- /dev/null +++ b/diffusion/training/functional/lr_scheduler.py @@ -0,0 +1,178 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional + +import numpy as np + +from utils import distributed, log + + +class TeroPolyScheduler: + def __init__( + self, + total_Mimg: int, + batch_size: int, + ref_Mimg: Optional[int] = None, + ref_batches: float = 70e3 / 1024, + max_lr_ratio: Optional[float] = 1.0, + min_lr_ratio: Optional[float] = None, + rampup_Mimg: float = 0, + rampdown_Mimg: int = 0, + verbosity_interval: int = 0, + formula: str = "poly", + poly_exp: float = 0.5, + ): + self.total_Mimg = total_Mimg + self.batch_size = batch_size * distributed.get_world_size() + self.ref_Mimg = ref_Mimg or ref_batches * batch_size / 1e6 + self.ref_batches = ref_batches + self.max_lr_ratio = max_lr_ratio + self.min_lr_ratio = min_lr_ratio + self.rampup_Mimg = rampup_Mimg + self.rampdown_Mimg = rampdown_Mimg + self.verbosity_interval = verbosity_interval + self.formula = formula + self.poly_exp = poly_exp + + self._model = None + + @property + def model(self): + return self._model + + @model.setter + def model(self, model): + self._model = model + + def schedule(self, n, **kwargs): + cur_Mimg = getattr(self.model, "sample_counter", 0) / 1e6 + + if self.formula == "constant": + lr = 1.0 + elif self.formula == "poly": + lr = max(cur_Mimg / self.ref_Mimg, 1e-8) ** -self.poly_exp + else: + raise ValueError(f'Invalid learning rate formula "{self.formula}"') + + if self.max_lr_ratio is not None: + lr = min(lr, self.max_lr_ratio) + if self.min_lr_ratio is not None: + lr = max(lr, self.min_lr_ratio) + + if self.rampup_Mimg > 0 and cur_Mimg < self.rampup_Mimg: + lr *= cur_Mimg / self.rampup_Mimg + if self.rampdown_Mimg > 0 and cur_Mimg > self.total_Mimg - self.rampdown_Mimg: + lr *= (self.total_Mimg - cur_Mimg) / self.rampdown_Mimg + + return lr + + def __call__(self, n, **kwargs): + return self.schedule(n, **kwargs) + + +class LambdaWarmUpCosineScheduler: + """ + A learning rate scheduler that combines warm-up with a cosine decay schedule for multiple cycles. + It supports different configurations for each cycle, including the number of warm-up steps, minimum + and maximum scaling factors for the learning rate. + + The scheduler is intended to be used with a base learning rate of 1.0, where the actual learning + rate at any step is the base learning rate multiplied by the scaling factor computed by the scheduler. + + Parameters: + warm_up_steps (list[int]): List of integers where each element represents the number of warm-up + steps for the corresponding cycle. + f_min (list[float]): List of the minimum scaling factors for each cycle after warm-up. + f_max (list[float]): List of the maximum scaling factors at the start and end of each cosine cycle. + f_start (list[float]): List of starting scaling factors for each warm-up phase. + cycle_lengths (list[int]): List of the total lengths of each cycle, including warm-up steps. + verbosity_interval (int, optional): Interval of training steps at which to print current step and + scaling factor information. Set to 0 by default to disable verbosity. + + Examples: + >>> scheduler = LambdaWarmUpCosineScheduler2( + warm_up_steps=[10, 10], + f_min=[0.1, 0.1], + f_max=[1.0, 1.0], + f_start=[0.01, 0.01], + cycle_lengths=[50, 50], + verbosity_interval=10) + >>> for step in range(100): + >>> lr_multiplier = scheduler(step) + >>> print(f"Step {step}: LR Multiplier = {lr_multiplier}") + """ + + def __init__(self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0): + assert len(warm_up_steps) == len(f_min) == len(f_max) == len(f_start) == len(cycle_lengths) + self.lr_warm_up_steps = warm_up_steps + self.f_start = f_start + self.f_min = f_min + self.f_max = f_max + self.cycle_lengths = cycle_lengths + self.cum_cycles = np.cumsum([0] + list(self.cycle_lengths)) + self.last_f = 0.0 + self.verbosity_interval = verbosity_interval + + def find_in_interval(self, n): + interval = 0 + for cl in self.cum_cycles[1:]: + if n <= cl: + return interval + interval += 1 + + def schedule(self, n, **kwargs): + cycle = self.find_in_interval(n) + n = n - self.cum_cycles[cycle] + if self.verbosity_interval > 0: + if n % self.verbosity_interval == 0: + log.info(f"current step: {n}, recent lr-multiplier: {self.last_f}, " f"current cycle {cycle}") + if n < self.lr_warm_up_steps[cycle]: + f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle] + self.last_f = f + return f + else: + t = (n - self.lr_warm_up_steps[cycle]) / (self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle]) + t = min(t, 1.0) + f = self.f_min[cycle] + 0.5 * (self.f_max[cycle] - self.f_min[cycle]) * (1 + np.cos(t * np.pi)) + self.last_f = f + return f + + def __call__(self, n, **kwargs): + return self.schedule(n, **kwargs) + + +class LambdaLinearScheduler(LambdaWarmUpCosineScheduler): + """ + Linear instead of cosine decay for the main part of the cycle. + """ + + def schedule(self, n, **kwargs): + cycle = self.find_in_interval(n) + n = n - self.cum_cycles[cycle] + if self.verbosity_interval > 0: + if n % self.verbosity_interval == 0: + log.info(f"current step: {n}, recent lr-multiplier: {self.last_f}, " f"current cycle {cycle}") + + if n < self.lr_warm_up_steps[cycle]: + f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle] + self.last_f = f + return f + else: + f = self.f_min[cycle] + (self.f_max[cycle] - self.f_min[cycle]) * (self.cycle_lengths[cycle] - n) / ( + self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle] + ) + self.last_f = f + return f diff --git a/diffusion/training/models/fm_solvers_dpm.py b/diffusion/training/models/fm_solvers_dpm.py new file mode 100644 index 0000000000000000000000000000000000000000..be60f254d84b09a6d8e43589b4cbd506c01b4309 --- /dev/null +++ b/diffusion/training/models/fm_solvers_dpm.py @@ -0,0 +1,420 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2025 TSAIL Team and The HuggingFace Team. All rights reserved. +# NVIDIA modifications: LiDAR rectified-flow sampling integration. + +# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py +# Specialized for FLOW MATCHING (rectified flow): prediction_type="flow_prediction", +# flow sigmas (alpha_t = 1 - sigma, sigma_t = sigma), and the SAME shift / LTX-stretch +# sigma ladder as ``FlowUniPCMultistepScheduler`` so it is a drop-in sibling of the +# UniPC scheduler already used by the RF models. +# +# Supports the "dpmsolver++" (deterministic, high-order ODE) and "sde-dpmsolver++" +# (stochastic) algorithm types -- i.e. "Flow-DPM-Solver++". Orders 1-3, midpoint / +# heun second-order variants. + +import math +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.schedulers.scheduling_utils import ( + KarrasDiffusionSchedulers, + SchedulerMixin, + SchedulerOutput, +) + +from diffusion.training.schedulers.shift_schedule import stretch_shifts_to_terminal + + +class FlowDPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin): + """Flow-matching DPM-Solver++ (and SDE-DPM-Solver++) multistep scheduler. + + Mirrors :class:`FlowUniPCMultistepScheduler` (same flow sigma ladder, + ``set_timesteps`` shift/stretch interface, ``step`` signature) but the + update rule is DPM-Solver++ (data-prediction exponential integrator). + + Args: + solver_order: 1, 2, or 3. Effective ODE order. 2 is a good default for + guided sampling; 3 for unconditional. + algorithm_type: ``"dpmsolver++"`` (deterministic) or + ``"sde-dpmsolver++"`` (stochastic). The SDE variant injects fresh + noise each step (the marginal-preserving Langevin term) and tends to + beat the ODE for imperfect models at enough steps. + solver_type: ``"midpoint"`` or ``"heun"`` (2nd-order coefficient variant). + lower_order_final / euler_at_final: drop to lower order on the last + step(s) for stability at small step counts (recommended). + """ + + _compatibles = [e.name for e in KarrasDiffusionSchedulers] + order = 1 + + @register_to_config + def __init__( + self, + num_train_timesteps: int = 1000, + solver_order: int = 2, + prediction_type: str = "flow_prediction", + shift: Optional[float] = 1.0, + use_dynamic_shifting: bool = False, + thresholding: bool = False, + dynamic_thresholding_ratio: float = 0.995, + sample_max_value: float = 1.0, + algorithm_type: str = "dpmsolver++", + solver_type: str = "midpoint", + lower_order_final: bool = True, + euler_at_final: bool = False, + final_sigmas_type: str = "zero", # "zero" | "sigma_min" + ): + if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"]: + raise NotImplementedError( + f"{algorithm_type} is not implemented for {self.__class__}. " + "Use 'dpmsolver++' or 'sde-dpmsolver++'." + ) + if solver_type not in ["midpoint", "heun"]: + if solver_type in ["logrho", "bh1", "bh2"]: + self.register_to_config(solver_type="midpoint") + else: + raise NotImplementedError( + f"{solver_type} is not implemented for {self.__class__}" + ) + + # Flow sigma ladder (sigma in [0,1]); mirrors FlowUniPCMultistepScheduler. + self.num_inference_steps = None + alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps)[::-1].copy() + sigmas = 1.0 - alphas + sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32) + if not use_dynamic_shifting: + sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) + + self.sigmas = sigmas + self.timesteps = sigmas * num_train_timesteps + + self.model_outputs = [None] * solver_order + self.lower_order_nums = 0 + self._step_index = None + self._begin_index = None + + self.sigmas = self.sigmas.to("cpu") + self.sigma_min = self.sigmas[-1].item() + self.sigma_max = self.sigmas[0].item() + + @property + def step_index(self): + return self._step_index + + @property + def begin_index(self): + return self._begin_index + + def set_begin_index(self, begin_index: int = 0): + self._begin_index = begin_index + + def _sigma_to_alpha_sigma_t(self, sigma): + # Flow matching: x_t = (1 - sigma) * x0 + sigma * eps. + return 1 - sigma, sigma + + def time_shift(self, mu: float, sigma: float, t: torch.Tensor): + return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma) + + def set_timesteps( + self, + num_inference_steps: Union[int, None] = None, + device: Union[str, torch.device] = None, + sigmas: Optional[List[float]] = None, + mu: Optional[float] = None, + shift: Optional[float] = None, + stretch_terminal: Optional[float] = None, + ): + """Build the flow sigma ladder (shift + optional LTX stretch), append the + terminal sigma, and reset the multistep buffers. Signature matches + ``FlowUniPCMultistepScheduler.set_timesteps`` so it's a drop-in swap.""" + if self.config.use_dynamic_shifting and mu is None: + raise ValueError("pass `mu` when `use_dynamic_shifting=True`") + + if sigmas is None: + sigmas = np.linspace(self.sigma_max, self.sigma_min, num_inference_steps + 1).copy()[:-1] + + if self.config.use_dynamic_shifting: + sigmas = self.time_shift(mu, 1.0, sigmas) + else: + if shift is None: + shift = self.config.shift + sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) + if stretch_terminal is not None: + sigmas = stretch_shifts_to_terminal( + np.asarray(sigmas, dtype=np.float64), float(stretch_terminal) + ) + + if self.config.final_sigmas_type == "sigma_min": + sigma_last = self.sigma_min + elif self.config.final_sigmas_type == "zero": + sigma_last = 0 + else: + raise ValueError( + f"`final_sigmas_type` must be 'zero' or 'sigma_min', got " + f"{self.config.final_sigmas_type}" + ) + + timesteps = sigmas * self.config.num_train_timesteps + sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32) + + self.sigmas = torch.from_numpy(sigmas) + self.timesteps = torch.from_numpy(timesteps).to(device=device, dtype=torch.int64) + + self.num_inference_steps = len(timesteps) + self.model_outputs = [None] * self.config.solver_order + self.lower_order_nums = 0 + self._step_index = None + self._begin_index = None + self.sigmas = self.sigmas.to("cpu") + + def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor: + dtype = sample.dtype + batch_size, channels, *remaining_dims = sample.shape + if dtype not in (torch.float32, torch.float64): + sample = sample.float() + sample = sample.reshape(batch_size, channels * int(np.prod(remaining_dims))) + abs_sample = sample.abs() + s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1) + s = torch.clamp(s, min=1, max=self.config.sample_max_value) + s = s.unsqueeze(1) + sample = torch.clamp(sample, -s, s) / s + sample = sample.reshape(batch_size, channels, *remaining_dims) + return sample.to(dtype) + + def convert_model_output( + self, model_output: torch.Tensor, *args, sample: torch.Tensor = None, **kwargs + ) -> torch.Tensor: + """Flow velocity -> predicted clean latent x0 (DPM-Solver++ is a data- + prediction integrator). x_t = (1-sigma)x0 + sigma*eps, v = eps - x0 + => x0 = x_t - sigma * v.""" + if sample is None: + raise ValueError("missing `sample` as a required keyword argument") + if self.config.prediction_type != "flow_prediction": + raise ValueError( + f"prediction_type {self.config.prediction_type} must be " + "'flow_prediction' for FlowDPMSolverMultistepScheduler." + ) + sigma_t = self.sigmas[self.step_index] + x0_pred = sample - sigma_t * model_output + if self.config.thresholding: + x0_pred = self._threshold_sample(x0_pred) + return x0_pred + + def dpm_solver_first_order_update( + self, model_output: torch.Tensor, *args, + sample: torch.Tensor = None, noise: Optional[torch.Tensor] = None, **kwargs, + ) -> torch.Tensor: + if sample is None: + raise ValueError("missing `sample` as a required keyword argument") + sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s) + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s = torch.log(alpha_s) - torch.log(sigma_s) + h = lambda_t - lambda_s + if self.config.algorithm_type == "dpmsolver++": + x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output + elif self.config.algorithm_type == "sde-dpmsolver++": + assert noise is not None + x_t = ( + (sigma_t / sigma_s * torch.exp(-h)) * sample + + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output + + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise + ) + return x_t + + def multistep_dpm_solver_second_order_update( + self, model_output_list: List[torch.Tensor], *args, + sample: torch.Tensor = None, noise: Optional[torch.Tensor] = None, **kwargs, + ) -> torch.Tensor: + if sample is None: + raise ValueError("missing `sample` as a required keyword argument") + sigma_t, sigma_s0, sigma_s1 = ( + self.sigmas[self.step_index + 1], + self.sigmas[self.step_index], + self.sigmas[self.step_index - 1], + ) + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1) + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1) + + m0, m1 = model_output_list[-1], model_output_list[-2] + h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1 + r0 = h_0 / h + D0, D1 = m0, (1.0 / r0) * (m0 - m1) + if self.config.algorithm_type == "dpmsolver++": + if self.config.solver_type == "midpoint": + x_t = ( + (sigma_t / sigma_s0) * sample + - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1 + ) + else: # heun + x_t = ( + (sigma_t / sigma_s0) * sample + - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 + ) + elif self.config.algorithm_type == "sde-dpmsolver++": + assert noise is not None + if self.config.solver_type == "midpoint": + x_t = ( + (sigma_t / sigma_s0 * torch.exp(-h)) * sample + + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0 + + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1 + + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise + ) + else: # heun + x_t = ( + (sigma_t / sigma_s0 * torch.exp(-h)) * sample + + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0 + + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1 + + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise + ) + return x_t + + def multistep_dpm_solver_third_order_update( + self, model_output_list: List[torch.Tensor], *args, + sample: torch.Tensor = None, noise: Optional[torch.Tensor] = None, **kwargs, + ) -> torch.Tensor: + if sample is None: + raise ValueError("missing `sample` as a required keyword argument") + sigma_t, sigma_s0, sigma_s1, sigma_s2 = ( + self.sigmas[self.step_index + 1], + self.sigmas[self.step_index], + self.sigmas[self.step_index - 1], + self.sigmas[self.step_index - 2], + ) + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1) + alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2) + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1) + lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2) + + m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3] + h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2 + r0, r1 = h_0 / h, h_1 / h + D0 = m0 + D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2) + D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1) + D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1) + if self.config.algorithm_type == "dpmsolver++": + x_t = ( + (sigma_t / sigma_s0) * sample + - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 + - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2 + ) + elif self.config.algorithm_type == "sde-dpmsolver++": + assert noise is not None + x_t = ( + (sigma_t / sigma_s0 * torch.exp(-h)) * sample + + (alpha_t * (1.0 - torch.exp(-2.0 * h))) * D0 + + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1 + + (alpha_t * ((1.0 - torch.exp(-2.0 * h) - 2.0 * h) / (2.0 * h) ** 2 - 0.5)) * D2 + + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise + ) + return x_t + + def index_for_timestep(self, timestep, schedule_timesteps=None): + if schedule_timesteps is None: + schedule_timesteps = self.timesteps + indices = (schedule_timesteps == timestep).nonzero() + pos = 1 if len(indices) > 1 else 0 + return indices[pos].item() + + def _init_step_index(self, timestep): + if self.begin_index is None: + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + self._step_index = self.index_for_timestep(timestep) + else: + self._step_index = self._begin_index + + def step( + self, + model_output: torch.Tensor, + timestep: Union[int, torch.Tensor], + sample: torch.Tensor, + generator=None, + variance_noise: Optional[torch.Tensor] = None, + return_dict: bool = True, + ) -> Union[SchedulerOutput, Tuple]: + """One multistep DPM-Solver++ update. Signature matches + ``FlowUniPCMultistepScheduler.step`` (extra ``variance_noise`` kwarg for + the SDE variant is optional).""" + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', run 'set_timesteps' first." + ) + if self.step_index is None: + self._init_step_index(timestep) + + # Lower the order on the final step(s) for stability (and to land exactly + # on x0 when the terminal sigma is 0). + is_last = self.step_index == len(self.timesteps) - 1 + lower_order_final = is_last and ( + self.config.euler_at_final + or (self.config.lower_order_final and len(self.timesteps) < 15) + or self.config.final_sigmas_type == "zero" + ) + lower_order_second = ( + (self.step_index == len(self.timesteps) - 2) + and self.config.lower_order_final + and len(self.timesteps) < 15 + ) + + model_output = self.convert_model_output(model_output, sample=sample) + for i in range(self.config.solver_order - 1): + self.model_outputs[i] = self.model_outputs[i + 1] + self.model_outputs[-1] = model_output + + sample = sample.to(torch.float32) + if self.config.algorithm_type == "sde-dpmsolver++": + if variance_noise is None: + noise = torch.randn( + model_output.shape, generator=generator, + device=model_output.device, dtype=torch.float32, + ) + else: + noise = variance_noise.to(device=model_output.device, dtype=torch.float32) + else: + noise = None + + if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final: + prev_sample = self.dpm_solver_first_order_update( + model_output, sample=sample, noise=noise + ) + elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second: + prev_sample = self.multistep_dpm_solver_second_order_update( + self.model_outputs, sample=sample, noise=noise + ) + else: + prev_sample = self.multistep_dpm_solver_third_order_update( + self.model_outputs, sample=sample, noise=noise + ) + + if self.lower_order_nums < self.config.solver_order: + self.lower_order_nums += 1 + + prev_sample = prev_sample.to(model_output.dtype) + self._step_index += 1 + + if not return_dict: + return (prev_sample, model_output) + return SchedulerOutput(prev_sample=prev_sample) + + def scale_model_input(self, sample: torch.Tensor, *args, **kwargs) -> torch.Tensor: + return sample + + def __len__(self): + return self.config.num_train_timesteps diff --git a/diffusion/training/models/fm_solvers_unipc.py b/diffusion/training/models/fm_solvers_unipc.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5c7ff27a26e9b62fbfc62d38359bc8ffdd7799 --- /dev/null +++ b/diffusion/training/models/fm_solvers_unipc.py @@ -0,0 +1,790 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2024 TSAIL Team and The HuggingFace Team. All rights reserved. +# NVIDIA modifications: LiDAR rectified-flow sampling integration. + +# Copied from https://github.com/huggingface/diffusers/blob/v0.31.0/src/diffusers/schedulers/scheduling_unipc_multistep.py +# Convert unipc for flow matching +# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. + +import math +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput +from diffusers.utils import deprecate + +from diffusion.training.schedulers.shift_schedule import stretch_shifts_to_terminal + + +class FlowUniPCMultistepScheduler(SchedulerMixin, ConfigMixin): + """ + `UniPCMultistepScheduler` is a training-free framework designed for the fast sampling of diffusion models. + + This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic + methods the library implements for all schedulers such as loading and saving. + + Args: + num_train_timesteps (`int`, defaults to 1000): + The number of diffusion steps to train the model. + solver_order (`int`, default `2`): + The UniPC order which can be any positive integer. The effective order of accuracy is `solver_order + 1` + due to the UniC. It is recommended to use `solver_order=2` for guided sampling, and `solver_order=3` for + unconditional sampling. + prediction_type (`str`, defaults to "flow_prediction"): + Prediction type of the scheduler function; must be `flow_prediction` for this scheduler, which predicts + the flow of the diffusion process. + thresholding (`bool`, defaults to `False`): + Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such + as Stable Diffusion. + dynamic_thresholding_ratio (`float`, defaults to 0.995): + The ratio for the dynamic thresholding method. Valid only when `thresholding=True`. + sample_max_value (`float`, defaults to 1.0): + The threshold value for dynamic thresholding. Valid only when `thresholding=True` and `predict_x0=True`. + predict_x0 (`bool`, defaults to `True`): + Whether to use the updating algorithm on the predicted x0. + solver_type (`str`, default `bh2`): + Solver type for UniPC. It is recommended to use `bh1` for unconditional sampling when steps < 10, and `bh2` + otherwise. + lower_order_final (`bool`, default `True`): + Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can + stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10. + disable_corrector (`list`, default `[]`): + Decides which step to disable the corrector to mitigate the misalignment between `epsilon_theta(x_t, c)` + and `epsilon_theta(x_t^c, c)` which can influence convergence for a large guidance scale. Corrector is + usually disabled during the first few steps. + solver_p (`SchedulerMixin`, default `None`): + Any other scheduler that if specified, the algorithm becomes `solver_p + UniC`. + use_karras_sigmas (`bool`, *optional*, defaults to `False`): + Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`, + the sigmas are determined according to a sequence of noise levels {σi}. + use_exponential_sigmas (`bool`, *optional*, defaults to `False`): + Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process. + timestep_spacing (`str`, defaults to `"linspace"`): + The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and + Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information. + steps_offset (`int`, defaults to 0): + An offset added to the inference steps, as required by some model families. + final_sigmas_type (`str`, defaults to `"zero"`): + The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final + sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0. + """ + + _compatibles = [e.name for e in KarrasDiffusionSchedulers] + order = 1 + + @register_to_config + def __init__( + self, + num_train_timesteps: int = 1000, + solver_order: int = 2, + prediction_type: str = "flow_prediction", + shift: Optional[float] = 1.0, + use_dynamic_shifting=False, + thresholding: bool = False, + dynamic_thresholding_ratio: float = 0.995, + sample_max_value: float = 1.0, + predict_x0: bool = True, + solver_type: str = "bh2", + lower_order_final: bool = True, + disable_corrector: List[int] = [], + solver_p: SchedulerMixin = None, + timestep_spacing: str = "linspace", + steps_offset: int = 0, + final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min" + ): + if solver_type not in ["bh1", "bh2"]: + if solver_type in ["midpoint", "heun", "logrho"]: + self.register_to_config(solver_type="bh2") + else: + raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}") + + self.predict_x0 = predict_x0 + # setable values + self.num_inference_steps = None + alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps)[::-1].copy() + sigmas = 1.0 - alphas + sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32) + + if not use_dynamic_shifting: + # when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution + sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) # pyright: ignore + + self.sigmas = sigmas + self.timesteps = sigmas * num_train_timesteps + + self.model_outputs = [None] * solver_order + self.timestep_list = [None] * solver_order + self.lower_order_nums = 0 + self.disable_corrector = disable_corrector + self.solver_p = solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication + self.sigma_min = self.sigmas[-1].item() + self.sigma_max = self.sigmas[0].item() + + @property + def step_index(self): + """ + The index counter for current timestep. It will increase 1 after each scheduler step. + """ + return self._step_index + + @property + def begin_index(self): + """ + The index for the first timestep. It should be set from pipeline with `set_begin_index` method. + """ + return self._begin_index + + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index + def set_begin_index(self, begin_index: int = 0): + """ + Sets the begin index for the scheduler. This function should be run from pipeline before the inference. + + Args: + begin_index (`int`): + The begin index for the scheduler. + """ + self._begin_index = begin_index + + # Modified from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.set_timesteps + def set_timesteps( + self, + num_inference_steps: Union[int, None] = None, + device: Union[str, torch.device] = None, + sigmas: Optional[List[float]] = None, + mu: Optional[Union[float, None]] = None, + shift: Optional[Union[float, None]] = None, + stretch_terminal: Optional[float] = None, + use_kerras_sigma: bool = False, + ): + """ + Sets the discrete timesteps used for the diffusion chain (to be run before inference). + Args: + num_inference_steps (`int`): + Total number of the spacing of the time steps. + device (`str` or `torch.device`, *optional*): + The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. + """ + if self.config.use_dynamic_shifting and mu is None: + raise ValueError(" you have to pass a value for `mu` when `use_dynamic_shifting` is set to be `True`") + + if use_kerras_sigma: + # force to use the exact sigma used in edm sampler + sigma_max = 200 + sigma_min = 0.01 + rho = 7 + sigmas = np.arange(num_inference_steps + 1) / num_inference_steps + min_inv_rho = sigma_min ** (1 / rho) + max_inv_rho = sigma_max ** (1 / rho) + sigmas = (max_inv_rho + sigmas * (min_inv_rho - max_inv_rho)) ** rho + sigmas = sigmas / (1 + sigmas) + else: + if sigmas is None: + # RF sampling is defined on the continuous [1, 0] interval. + # Do not inherit the training table's discretized 0.999 + # endpoint or few-step schedules drift from the distilled + # query ladder. + sigmas = np.linspace( + 1.0, + 0.0, + num_inference_steps + 1, + dtype=np.float64, + )[:-1] + + if self.config.use_dynamic_shifting: + sigmas = self.time_shift(mu, 1.0, sigmas) # pyright: ignore + else: + if shift is None: + shift = self.config.shift + sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) # pyright: ignore + if stretch_terminal is not None: + sigmas = stretch_shifts_to_terminal( + np.asarray(sigmas, dtype=np.float64), + float(stretch_terminal), + ) + + if self.config.final_sigmas_type == "sigma_min": + sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5 + elif self.config.final_sigmas_type == "zero": + sigma_last = 0 + else: + raise ValueError( + f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}" + ) + + timesteps = sigmas * self.config.num_train_timesteps + sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32) # pyright: ignore + + self.sigmas = torch.from_numpy(sigmas) + self.timesteps = torch.from_numpy(timesteps).to( + device=device, dtype=torch.float32 + ) + + self.num_inference_steps = len(timesteps) + + self.model_outputs = [ + None, + ] * self.config.solver_order + self.lower_order_nums = 0 + self.last_sample = None + if self.solver_p: + self.solver_p.set_timesteps(self.num_inference_steps, device=device) + + # add an index counter for schedulers that allow duplicated timesteps + self._step_index = None + self._begin_index = None + self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication + + # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample + def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor: + """ + "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the + prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by + s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing + pixels from saturation at each step. We find that dynamic thresholding results in significantly better + photorealism as well as better image-text alignment, especially when using very large guidance weights." + + https://arxiv.org/abs/2205.11487 + """ + dtype = sample.dtype + batch_size, channels, *remaining_dims = sample.shape + + if dtype not in (torch.float32, torch.float64): + sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half + + # Flatten sample for doing quantile calculation along each image + sample = sample.reshape(batch_size, channels * np.prod(remaining_dims)) + + abs_sample = sample.abs() # "a certain percentile absolute pixel value" + + s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1) + s = torch.clamp( + s, min=1, max=self.config.sample_max_value + ) # When clamped to min=1, equivalent to standard clipping to [-1, 1] + s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0 + sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s" + + sample = sample.reshape(batch_size, channels, *remaining_dims) + sample = sample.to(dtype) + + return sample + + # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._sigma_to_t + def _sigma_to_t(self, sigma): + return sigma * self.config.num_train_timesteps + + def _sigma_to_alpha_sigma_t(self, sigma): + return 1 - sigma, sigma + + # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.set_timesteps + def time_shift(self, mu: float, sigma: float, t: torch.Tensor): + return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma) + + def convert_model_output( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + r""" + Convert the model output to the corresponding type the UniPC algorithm needs. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + + Returns: + `torch.Tensor`: + The converted model output. + """ + timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyward argument") + if timestep is not None: + deprecate( + "timesteps", + "1.0.0", + "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + sigma = self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + + # print("sigma_t ==>", self.step_index, sigma, sigma_t, alpha_t, sample.shape, model_output.shape) + if self.predict_x0: + if self.config.prediction_type == "flow_prediction": + sigma_t = self.sigmas[self.step_index] + x0_pred = sample - sigma_t * model_output + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`," + " `v_prediction` or `flow_prediction` for the UniPCMultistepScheduler." + ) + + if self.config.thresholding: + x0_pred = self._threshold_sample(x0_pred) + # print("self.config.thresholding", self.config.thresholding) + return x0_pred + else: + if self.config.prediction_type == "flow_prediction": + sigma_t = self.sigmas[self.step_index] + epsilon = sample - (1 - sigma_t) * model_output + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`," + " `v_prediction` or `flow_prediction` for the UniPCMultistepScheduler." + ) + + if self.config.thresholding: + sigma_t = self.sigmas[self.step_index] + x0_pred = sample - sigma_t * model_output + x0_pred = self._threshold_sample(x0_pred) + epsilon = model_output + x0_pred + + return epsilon + + def multistep_uni_p_bh_update( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + order: int = None, # pyright: ignore + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model at the current timestep. + prev_timestep (`int`): + The previous discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + order (`int`): + The order of UniP at this timestep (corresponds to the *p* in UniPC-p). + + Returns: + `torch.Tensor`: + The sample tensor at the previous timestep. + """ + prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError(" missing `sample` as a required keyward argument") + if order is None: + if len(args) > 2: + order = args[2] + else: + raise ValueError(" missing `order` as a required keyward argument") + if prev_timestep is not None: + deprecate( + "prev_timestep", + "1.0.0", + "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + model_output_list = self.model_outputs + + s0 = self.timestep_list[-1] + m0 = model_output_list[-1] + x = sample + + if self.solver_p: + x_t = self.solver_p.step(model_output, s0, x).prev_sample + return x_t + + sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] # pyright: ignore + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - i # pyright: ignore + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) # pyright: ignore + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) # (B, K) + # for order 2, we use a simplified version + if order == 2: + rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype) + else: + D1s = None + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) # pyright: ignore + else: + pred_res = 0 + x_t = x_t_ - alpha_t * B_h * pred_res + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) # pyright: ignore + else: + pred_res = 0 + x_t = x_t_ - sigma_t * B_h * pred_res + + x_t = x_t.to(x.dtype) + return x_t + + def multistep_uni_c_bh_update( + self, + this_model_output: torch.Tensor, + *args, + last_sample: torch.Tensor = None, + this_sample: torch.Tensor = None, + order: int = None, # pyright: ignore + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniC (B(h) version). + + Args: + this_model_output (`torch.Tensor`): + The model outputs at `x_t`. + this_timestep (`int`): + The current timestep `t`. + last_sample (`torch.Tensor`): + The generated sample before the last predictor `x_{t-1}`. + this_sample (`torch.Tensor`): + The generated sample after the last predictor `x_{t}`. + order (`int`): + The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`. + + Returns: + `torch.Tensor`: + The corrected sample tensor at the current timestep. + """ + this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None) + if last_sample is None: + if len(args) > 1: + last_sample = args[1] + else: + raise ValueError(" missing`last_sample` as a required keyward argument") + if this_sample is None: + if len(args) > 2: + this_sample = args[2] + else: + raise ValueError(" missing`this_sample` as a required keyward argument") + if order is None: + if len(args) > 3: + order = args[3] + else: + raise ValueError(" missing`order` as a required keyward argument") + if this_timestep is not None: + deprecate( + "this_timestep", + "1.0.0", + "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + model_output_list = self.model_outputs + + m0 = model_output_list[-1] + x = last_sample + x_t = this_sample + model_t = this_model_output + + sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1] # pyright: ignore + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = this_sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - (i + 1) # pyright: ignore + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) # pyright: ignore + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) + else: + D1s = None + + # for order 1, we use a simplified version + if order == 1: + rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype) + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t) + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t) + x_t = x_t.to(x.dtype) + return x_t + + def index_for_timestep(self, timestep, schedule_timesteps=None): + if schedule_timesteps is None: + schedule_timesteps = self.timesteps + + indices = (schedule_timesteps == timestep).nonzero() + + # The sigma index that is taken for the **very** first `step` + # is always the second index (or the last index if there is only 1) + # This way we can ensure we don't accidentally skip a sigma in + # case we start in the middle of the denoising schedule (e.g. for image-to-image) + pos = 1 if len(indices) > 1 else 0 + + return indices[pos].item() + + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index + def _init_step_index(self, timestep): + """ + Initialize the step_index counter for the scheduler. + """ + + if self.begin_index is None: + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + self._step_index = self.index_for_timestep(timestep) + else: + self._step_index = self._begin_index + + def step( + self, + model_output: torch.Tensor, + timestep: Union[int, torch.Tensor], + sample: torch.Tensor, + return_dict: bool = True, + generator=None, + ) -> Union[SchedulerOutput, Tuple]: + """ + Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with + the multistep UniPC. + + Args: + model_output (`torch.Tensor`): + The direct output from learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + return_dict (`bool`): + Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`. + + Returns: + [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`: + If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a + tuple is returned where the first element is the sample tensor. + + """ + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if self.step_index is None: + self._init_step_index(timestep) + + # print("self.step_index ==> ", self.step_index) + + use_corrector = ( + self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None # pyright: ignore + ) + + model_output_convert = self.convert_model_output(model_output, sample=sample) + + if use_corrector: + sample = self.multistep_uni_c_bh_update( + this_model_output=model_output_convert, + last_sample=self.last_sample, + this_sample=sample, + order=self.this_order, + ) + + for i in range(self.config.solver_order - 1): + self.model_outputs[i] = self.model_outputs[i + 1] + self.timestep_list[i] = self.timestep_list[i + 1] + + self.model_outputs[-1] = model_output_convert + self.timestep_list[-1] = timestep # pyright: ignore + + if self.config.lower_order_final: + this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index) # pyright: ignore + else: + this_order = self.config.solver_order + + self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep + assert self.this_order > 0 + + self.last_sample = sample + prev_sample = self.multistep_uni_p_bh_update( + model_output=model_output, # pass the original non-converted model output, in case solver-p is used + sample=sample, + order=self.this_order, + ) + + if self.lower_order_nums < self.config.solver_order: + self.lower_order_nums += 1 + + # upon completion increase step index by one + self._step_index += 1 # pyright: ignore + + if not return_dict: + return (prev_sample, model_output_convert) + + return SchedulerOutput(prev_sample=prev_sample) + + def scale_model_input(self, sample: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Ensures interchangeability with schedulers that need to scale the denoising model input depending on the + current timestep. + + Args: + sample (`torch.Tensor`): + The input sample. + + Returns: + `torch.Tensor`: + A scaled input sample. + """ + return sample + + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.add_noise + def add_noise( + self, + original_samples: torch.Tensor, + noise: torch.Tensor, + timesteps: torch.IntTensor, + ) -> torch.Tensor: + # Make sure sigmas and timesteps have the same device and dtype as original_samples + sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype) + if original_samples.device.type == "mps" and torch.is_floating_point(timesteps): + # mps does not support float64 + schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32) + timesteps = timesteps.to(original_samples.device, dtype=torch.float32) + else: + schedule_timesteps = self.timesteps.to(original_samples.device) + timesteps = timesteps.to(original_samples.device) + + # begin_index is None when the scheduler is used for training or pipeline does not implement set_begin_index + if self.begin_index is None: + step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps] + elif self.step_index is not None: + # add_noise is called after first denoising step (for inpainting) + step_indices = [self.step_index] * timesteps.shape[0] + else: + # add noise is called before first denoising step to create initial latent(img2img) + step_indices = [self.begin_index] * timesteps.shape[0] + + sigma = sigmas[step_indices].flatten() + while len(sigma.shape) < len(original_samples.shape): + sigma = sigma.unsqueeze(-1) + + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + noisy_samples = alpha_t * original_samples + sigma_t * noise + return noisy_samples + + def __len__(self): + return self.config.num_train_timesteps diff --git a/diffusion/training/models/hdmaptolidar_model.py b/diffusion/training/models/hdmaptolidar_model.py new file mode 100644 index 0000000000000000000000000000000000000000..bad80b327eb449230eeb1098bf17cdb0d9741b85 --- /dev/null +++ b/diffusion/training/models/hdmaptolidar_model.py @@ -0,0 +1,821 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Hdmap-to-Lidar diffusion model. + +Conditions on an HD-map via channel concatenation: the hdmap is resized to +the latent spatial resolution and concatenated with the noisy latent along +the channel dimension before the network. + +Three hdmap-conditioning modes (mutually exclusive, evaluated in order): + +* ``encode_hdmap_with_vae=True`` — run the hdmap through the same frozen VAE + encoder as the lidar. The encoded latent has the same shape as the noisy + lidar latent, so no resize / 1x1 conv is required; set + ``additional_concat_ch`` to the VAE's ``latent_ch`` and + ``net.in_channels = latent_ch * 2``. +* ``skip_hdmap_proj=True`` — bypass the projection and directly concat the + raw (spatially resized) hdmap; avoids randomly-initialised weights + corrupting the conditioning signal early in training. +* Default — a learnable 1x1 conv projects ``hdmap_channels`` → + ``additional_concat_ch`` before concat. + +Uses the standard ``GeneralDIT`` network (no multiview extensions). +""" + +from typing import Tuple, Union + +import torch +import torch.nn.functional as F +from einops import rearrange +from torch import Tensor, nn + +from diffusion.functional.batch_ops import batch_mul +from diffusion.training.conditioner import BaseVideoCondition +from diffusion.training.models.model import DiffusionModel, _broadcast, broadcast_condition +from diffusion.training.models.model_image import ( + CosmosCondition, + DenoisePrediction, + diffusion_fsdp_class_decorator, +) +from diffusion.conditioner import DataType +from utils import log, misc + + +# Fixed class -> RGB palette for the "colored" BEV hdmap render fed to the +# frozen Wan2.2 VAE (must match scripts/hdmap_bev_wan2p2_roundtrip.py so the +# training render == the render validated by the roundtrip test). +# Order = waymo_hdmap.CLASS_NAMES: lane, road_line, road_edge, crosswalk, +# vehicle, pedestrian, cyclist. +_BEV_CLASS_COLORS = ( + (0.20, 0.20, 0.20), # lane - dark gray + (1.00, 1.00, 0.00), # road_line - yellow + (1.00, 1.00, 1.00), # road_edge - white + (0.00, 1.00, 1.00), # crosswalk - cyan + (1.00, 0.00, 0.00), # vehicle - red + (0.00, 1.00, 0.00), # pedestrian - green + (0.00, 0.00, 1.00), # cyclist - blue +) + + +class HdmapToLidarModel(DiffusionModel): + """Rectified-flow diffusion conditioned on HD-map via channel concat.""" + + def __init__(self, config): + super().__init__(config) + + self.diffusion_dtype = torch.bfloat16 + + hdmap_ch = getattr(config, "hdmap_channels", 3) + additional_concat_ch = getattr(config, "additional_concat_ch", 3) + self.skip_hdmap_proj = getattr(config, "skip_hdmap_proj", False) + self.encode_hdmap_with_vae = bool( + getattr(config, "encode_hdmap_with_vae", False) + ) + self.bev_hdmap_pool = None + self.bev_hdmap_wan = None + if getattr(config, "bev_hdmap_wan_encode", False) or getattr( + config, "bev_hdmap_pool", False + ): + raise ValueError( + "The public LidarVerse release supports range-rendered HDMap " + "conditioning only" + ) + + if self.encode_hdmap_with_vae: + # Hdmap is routed through the same frozen VAE as the lidar. + # The encoded latent already lives in (B, latent_ch, T_z, H_z, W_z) + # — no spatial/temporal resize and no learnable projection are + # required. ``additional_concat_ch`` is bookkeeping here and + # should equal the VAE's ``latent_ch`` so that the downstream + # ``net.in_channels = lidar_latent_ch + additional_concat_ch`` + # matches reality. Mutually exclusive with ``skip_hdmap_proj``. + assert not self.skip_hdmap_proj, ( + "encode_hdmap_with_vae and skip_hdmap_proj are mutually " + "exclusive." + ) + self.hdmap_proj = None + self._hdmap_concat_ch = additional_concat_ch + log.info( + f"HdmapToLidarModel: encode_hdmap_with_vae=True, " + f"concat {additional_concat_ch} VAE-encoded hdmap channels" + ) + elif self.skip_hdmap_proj: + self.hdmap_proj = None + self._hdmap_concat_ch = hdmap_ch + log.info( + f"HdmapToLidarModel: raw hdmap concat (no proj), {hdmap_ch} ch" + ) + elif additional_concat_ch > 0: + self.hdmap_proj = nn.Conv2d(hdmap_ch, additional_concat_ch, kernel_size=1) + self._hdmap_concat_ch = additional_concat_ch + log.info( + f"HdmapToLidarModel: hdmap_proj {hdmap_ch} -> {additional_concat_ch}" + ) + else: + self.hdmap_proj = None + self._hdmap_concat_ch = 0 + + # Per-sample dropout of the hdmap condition during training, enabling + # classifier-free guidance at inference. Defaults to 0.0 (no dropout) + # so existing configs remain unchanged. + self.hdmap_dropout_prob = float(getattr(config, "hdmap_dropout_prob", 0.0)) + # Mixture of dropout regimes; see LidarModelConfig.hdmap_dropout_modes. + # When dropout fires for a sample we draw one of these uniformly. + # Legacy default is ("full",) which reproduces the original CFG-only + # behavior bit-for-bit. + raw_modes = list(getattr(config, "hdmap_dropout_modes", ["full"])) + _ALLOWED_MODES = ("full", "frame_bernoulli", "keep_first_k") + for m in raw_modes: + if m not in _ALLOWED_MODES: + raise ValueError( + f"hdmap_dropout_modes contains unknown mode {m!r}; " + f"allowed: {_ALLOWED_MODES}" + ) + if len(raw_modes) == 0: + raise ValueError("hdmap_dropout_modes must not be empty") + self.hdmap_dropout_modes = raw_modes + self.hdmap_frame_dropout_rate = float( + getattr(config, "hdmap_frame_dropout_rate", 0.5) + ) + self.hdmap_keep_first_k = int(getattr(config, "hdmap_keep_first_k", 1)) + self.hdmap_artifixer_dropout = bool( + getattr(config, "hdmap_artifixer_dropout", False) + ) + if self.hdmap_dropout_prob > 0.0: + log.info( + f"HdmapToLidarModel: hdmap_dropout_prob={self.hdmap_dropout_prob}, " + f"hdmap_dropout_modes={self.hdmap_dropout_modes} " + f"(frame_rate={self.hdmap_frame_dropout_rate}, " + f"keep_first_k={self.hdmap_keep_first_k}, " + f"artifixer={self.hdmap_artifixer_dropout})" + ) + + self._current_hdmap = None + self._num_dataset_embeddings = int( + getattr(config.net, "num_dataset_embeddings", 0) + ) + self._current_sensor_dataset_ids: Tensor | None = None + # Transient flag used by `generate_samples_from_batch` to zero the + # hdmap for the unconditional CFG pass. Kept off outside inference. + self._hdmap_force_null = False + # Inference-only: when set to int K, zero all hdmap latent frames except + # the first K in get_data_and_condition (see usage there). None = off. + self._hdmap_keep_first_k_infer = None + # Inference-only: when set to a list of ints, keep exactly those hdmap + # latent-frame indices (negatives index from the end). Takes precedence + # over _hdmap_keep_first_k_infer. None = off. + self._hdmap_keep_frames_infer = None + + # ------------------------------------------------------------------ + # HD-map helpers + # ------------------------------------------------------------------ + + def _prepare_hdmap( + self, hdmap: torch.Tensor, latent: torch.Tensor + ) -> torch.Tensor: + """Resize hdmap to latent spatial dims and optionally project channels. + + When ``skip_hdmap_proj`` is True the raw resized hdmap is returned + without any learnable transformation. + + Works for both 4-D ``(B, C, H, W)`` and 5-D ``(B, C, T, H, W)`` inputs. + """ + is_5d = hdmap.ndim == 5 + if is_5d: + B, C, T, H, W = hdmap.shape + lat_T, lat_H, lat_W = latent.shape[2], latent.shape[3], latent.shape[4] + hdmap = F.interpolate( + hdmap.reshape(B * T, C, H, W), + size=(lat_H, lat_W), + mode="nearest-exact", + ) + if self.hdmap_proj is not None: + hdmap = self.hdmap_proj(hdmap) + _, C_out, _, _ = hdmap.shape + hdmap = hdmap.reshape(B, C_out, T, lat_H, lat_W) + if T != lat_T: + hdmap = F.interpolate( + hdmap, + size=(lat_T, lat_H, lat_W), + mode="nearest-exact", + ) + else: + lat_H, lat_W = latent.shape[2], latent.shape[3] + hdmap = F.interpolate( + hdmap, size=(lat_H, lat_W), mode="nearest-exact" + ) + if self.hdmap_proj is not None: + hdmap = self.hdmap_proj(hdmap) + return hdmap + + # ------------------------------------------------------------------ + # HD-map training-time dropout (3-mode mixture) + # ------------------------------------------------------------------ + + def _apply_hdmap_dropout(self, hdmap_z: torch.Tensor) -> torch.Tensor: + """Per-sample dropout with a uniform mixture over enabled modes. + + With probability ``self.hdmap_dropout_prob`` each sample is "fired" + for dropout. Conditional on firing, a mode is drawn uniformly from + ``self.hdmap_dropout_modes``: + + * ``"full"`` -- zero the entire hdmap latent + * ``"frame_bernoulli"`` -- zero each frame independently with rate + ``self.hdmap_frame_dropout_rate`` + * ``"keep_first_k"`` -- zero all frames except the first + ``self.hdmap_keep_first_k`` frames + + Frame-wise modes require a temporal axis at ``hdmap_z.shape[2]``; + image-mode inputs (4-D) silently collapse to the legacy "full" path + regardless of the configured mixture. + """ + B = hdmap_z.shape[0] + device = hdmap_z.device + if self.hdmap_artifixer_dropout: + # ArtiFixer samples one conditioning decision for the whole batch. + # Its RGB condition is masked before VAE encoding and accompanied by + # a separate opacity mask. LiDAR HDMap conditioning has no opacity + # channel, so the behaviorally equivalent safe representation is a + # zero latent suffix (the existing unconditional HDMap convention). + if bool( + torch.rand((), device=device) < self.hdmap_dropout_prob + ): + return torch.zeros_like(hdmap_z) + if hdmap_z.ndim != 5 or hdmap_z.shape[2] == 1: + return hdmap_z + num_frames = hdmap_z.shape[2] + keep_frames = int( + torch.randint( + 1, num_frames + 1, (1,), device=device + ).item() + ) + frame_keep = torch.zeros( + (1, 1, num_frames, 1, 1), + device=device, + dtype=hdmap_z.dtype, + ) + frame_keep[:, :, :keep_frames] = 1.0 + return hdmap_z * frame_keep + + fire = torch.rand(B, device=device) < self.hdmap_dropout_prob # (B,) + if not fire.any(): + return hdmap_z + + is_video = hdmap_z.ndim == 5 + T_lat = hdmap_z.shape[2] if is_video else 1 + # Frame-wise modes are meaningless for 4-D / T=1 hdmaps; fall back + # to the legacy full-dropout path in that case. + if (not is_video) or T_lat == 1: + keep_sample = (~fire).to(hdmap_z.dtype) + keep_sample = keep_sample.view(B, *([1] * (hdmap_z.ndim - 1))) + return hdmap_z * keep_sample + + n_modes = len(self.hdmap_dropout_modes) + mode_ix = torch.randint(0, n_modes, (B,), device=device) # (B,) + + # frame_keep[b, t] == 1 means "keep frame t of sample b". + frame_keep = torch.ones( + (B, T_lat), device=device, dtype=hdmap_z.dtype + ) + + for ix, mode in enumerate(self.hdmap_dropout_modes): + sel = fire & (mode_ix == ix) # (B,) + if not sel.any(): + continue + if mode == "full": + # Zero every frame for this sample. + drop_mask = torch.zeros( + (1, T_lat), device=device, dtype=hdmap_z.dtype + ) + frame_keep = torch.where(sel.view(B, 1), drop_mask, frame_keep) + elif mode == "frame_bernoulli": + per_frame = ( + torch.rand((B, T_lat), device=device) + >= self.hdmap_frame_dropout_rate + ).to(hdmap_z.dtype) + frame_keep = torch.where(sel.view(B, 1), per_frame, frame_keep) + elif mode == "keep_first_k": + K = max(0, min(int(self.hdmap_keep_first_k), T_lat)) + keep_first = torch.zeros( + (1, T_lat), device=device, dtype=hdmap_z.dtype + ) + if K > 0: + keep_first[:, :K] = 1.0 + frame_keep = torch.where(sel.view(B, 1), keep_first, frame_keep) + else: + # Caught at __init__; defensive. + raise ValueError(f"Unknown hdmap dropout mode: {mode!r}") + + # Broadcast to (B, 1, T, 1, 1) and apply. + frame_keep = frame_keep.view(B, 1, T_lat, 1, 1) + return hdmap_z * frame_keep + + # ------------------------------------------------------------------ + # Override: encode/decode for video support + # ------------------------------------------------------------------ + + def _encode_with_vae( + self, vae, state: torch.Tensor + ) -> torch.Tensor: + if getattr(vae, "is_image", True): + return vae.encode(state.squeeze(2)).unsqueeze(2) * self.sigma_data + return vae.encode(state) * self.sigma_data + + def _decode_with_vae( + self, + vae, + latent: torch.Tensor, + t: float | torch.Tensor | None = None, + ) -> torch.Tensor: + is_ltx = getattr(vae, "is_ltx", False) + if t is not None and not is_ltx: + raise ValueError( + f"Got t={t!r} but {type(vae).__name__} is not LTX-style" + ) + if getattr(vae, "is_image", True): + return vae.decode(latent.squeeze(2) / self.sigma_data).unsqueeze(2) + if is_ltx: + return vae.decode(latent / self.sigma_data, t=t) + return vae.decode(latent / self.sigma_data) + + @torch.no_grad() + def encode(self, state: torch.Tensor) -> torch.Tensor: + # Disable any outer autocast so the VAE wrapper exclusively controls + # encoder precision. Existing configs remain FP32; selected configs + # may opt into a measured BF16 encoder. + state = state.float() + with torch.autocast("cuda", enabled=False): + if self.intensity_vae is None: + return self._encode_with_vae(self.vae, state) + if state.shape[1] == 1: + return self._encode_with_vae(self.vae, state) + if state.shape[1] != 2: + raise ValueError( + "paired range/intensity encoding expects C=1 or C=2, " + f"got {tuple(state.shape)}" + ) + range_z = self._encode_with_vae(self.vae, state[:, :1]) + intensity_z = self._encode_with_vae( + self.intensity_vae, state[:, 1:2] + ) + if range_z.shape[2:] != intensity_z.shape[2:]: + raise ValueError( + "range and intensity tokenizer grids do not align: " + f"{tuple(range_z.shape)} vs {tuple(intensity_z.shape)}" + ) + return torch.cat([range_z, intensity_z], dim=1) + + @torch.no_grad() + def _encode_stream_with_vae( + self, + vae, + state_new: torch.Tensor, + temporal_kv_cache=None, + max_cache_frames: int | None = None, + ): + if getattr(vae, "is_image", True): + raise NotImplementedError( + "streaming encode requires a causal video VAE" + ) + if not hasattr(vae, "encode_stream"): + raise NotImplementedError( + f"{type(vae).__name__} does not implement encode_stream" + ) + latent, new_cache = vae.encode_stream( + state_new, + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + ) + return latent * self.sigma_data, new_cache + + @torch.no_grad() + def encode_stream( + self, + state_new: torch.Tensor, + temporal_kv_cache=None, + max_cache_frames: int | None = None, + ): + """Encode newly appended frames at the VAE's configured precision.""" + state_new = state_new.float() + with torch.autocast("cuda", enabled=False): + if self.intensity_vae is None or state_new.shape[1] == 1: + return self._encode_stream_with_vae( + self.vae, + state_new, + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + ) + if state_new.shape[1] != 2: + raise ValueError( + "paired range/intensity streaming encode expects C=1 " + f"or C=2, got {tuple(state_new.shape)}" + ) + if temporal_kv_cache is None: + range_cache = None + intensity_cache = None + elif isinstance(temporal_kv_cache, dict) and set( + temporal_kv_cache + ) == {"range", "intensity"}: + range_cache = temporal_kv_cache["range"] + intensity_cache = temporal_kv_cache["intensity"] + else: + raise ValueError( + "paired range/intensity streaming cache must contain " + "exactly 'range' and 'intensity'" + ) + range_z, range_cache = self._encode_stream_with_vae( + self.vae, + state_new[:, :1], + temporal_kv_cache=range_cache, + max_cache_frames=max_cache_frames, + ) + intensity_z, intensity_cache = self._encode_stream_with_vae( + self.intensity_vae, + state_new[:, 1:2], + temporal_kv_cache=intensity_cache, + max_cache_frames=max_cache_frames, + ) + if range_z.shape[2:] != intensity_z.shape[2:]: + raise ValueError( + "range and intensity streaming latent grids do not align: " + f"{tuple(range_z.shape)} vs {tuple(intensity_z.shape)}" + ) + return torch.cat([range_z, intensity_z], dim=1), { + "range": range_cache, + "intensity": intensity_cache, + } + + @torch.no_grad() + def decode( + self, + latent: torch.Tensor, + t: float | torch.Tensor | None = None, + ) -> torch.Tensor: + """Decode a diffusion-space latent back to pixels. + + ``t`` (rectified-flow timestep in [0, 1]) is forwarded to the VAE + wrapper only when ``self.vae.is_ltx`` is True (i.e. the wrapped + VAE net supports LTX-style timestep-conditioned decoding via + ``decode(z, t=t)``). For non-LTX wrappers -- which is every + wrapper today other than ``ConfigBasedVideoVAE`` around a + ``TransformerVAELTX`` with ``denoising_t_max > 0`` -- passing + ``t`` raises so we don't silently drop it. Note: T=1 single- + frame inputs go through the video path unchanged; ``is_ltx`` is + about the wrapper's decode signature, not the input tensor's + temporal length. + """ + if self.intensity_vae is not None: + latent = latent.float() + range_channels = int(self.vae.latent_ch) + intensity_channels = int(self.intensity_vae.latent_ch) + with torch.autocast("cuda", enabled=False): + if latent.shape[1] == range_channels: + return self._decode_with_vae(self.vae, latent, t=t) + if latent.shape[1] != range_channels + intensity_channels: + raise ValueError( + "paired range/intensity decoding expects " + f"{range_channels} or " + f"{range_channels + intensity_channels} channels, " + f"got {tuple(latent.shape)}" + ) + if t is not None: + raise ValueError( + "paired range/intensity decoding does not support " + "timestep-conditioned VAE decoding" + ) + range_recon = self._decode_with_vae( + self.vae, latent[:, :range_channels] + ) + intensity_recon = self._decode_with_vae( + self.intensity_vae, latent[:, range_channels:] + ) + if range_recon.shape[2:] != intensity_recon.shape[2:]: + raise ValueError( + "range and intensity decoder grids do not align: " + f"{tuple(range_recon.shape)} vs " + f"{tuple(intensity_recon.shape)}" + ) + return torch.cat([range_recon, intensity_recon], dim=1) + is_ltx = getattr(self.vae, "is_ltx", False) + if t is not None and not is_ltx: + raise ValueError( + f"Got t={t!r} but the wrapped VAE " + f"({type(self.vae).__name__}) is not LTX-style " + f"(is_ltx=False). Either drop --decoder_t1 or swap in a " + f"TransformerVAELTX checkpoint with denoising_t_max > 0." + ) + latent = latent.float() + with torch.autocast("cuda", enabled=False): + if getattr(self.vae, "is_image", True): + # 4D image-tokenizer wrapper path (no T dim). LTX-style + # decoders are never image VAEs in this codebase, so we + # ignore ``t`` here (the gate above already rejected + # non-None t for any non-LTX wrapper). + return super().decode(latent) + if is_ltx: + return self.vae.decode(latent / self.sigma_data, t=t) + return self.vae.decode(latent / self.sigma_data) + + @torch.no_grad() + def decode_stream( + self, + latent_new: torch.Tensor, + temporal_kv_cache=None, + max_cache_frames: int | None = None, + ): + """Decode only newly appended diffusion-space latent frames.""" + if getattr(self.vae, "is_image", True): + raise NotImplementedError( + "streaming decode requires a causal video VAE" + ) + if not hasattr(self.vae, "decode_stream"): + raise NotImplementedError( + f"{type(self.vae).__name__} does not implement decode_stream" + ) + latent_new = latent_new.float() + with torch.autocast("cuda", enabled=False): + decode_kwargs = {"temporal_kv_cache": temporal_kv_cache} + if max_cache_frames is not None: + decode_kwargs["max_cache_frames"] = max_cache_frames + return self.vae.decode_stream( + latent_new / self.sigma_data, + **decode_kwargs, + ) + + # ------------------------------------------------------------------ + # BEV hdmap -> Wan2.2 latent + # ------------------------------------------------------------------ + + @torch.no_grad() + def _bev_hdmap_to_wan_latent(self, bev: torch.Tensor) -> torch.Tensor: + """``(B, C_cls, T, Y, X)`` {0,1} BEV raster -> ``(B, 48, T, Y/16, X/16)``. + + Renders the per-class occupancy grid into a 3-channel image (colored + palette or grayscale occupancy), maps to [-1, 1], and encodes with the + frozen Wan2.2 RGB VAE. Matches the render used in the roundtrip test. + """ + assert bev.ndim == 5, f"bev_hdmap must be 5-D (B,C,T,Y,X), got {bev.shape}" + B, C, T, Y, X = bev.shape + bev = (bev.reshape(B * T, C, Y, X) > 0.5).float() + if self.bev_hdmap_render_mode == "occupancy": + occ = bev.amax(dim=1, keepdim=True) # (BT, 1, Y, X) + img01 = occ.repeat(1, 3, 1, 1) + else: # colored (later classes paint over earlier ones) + pal = self._bev_palette.to(device=bev.device, dtype=bev.dtype) # (C, 3) + img01 = bev.new_zeros(B * T, 3, Y, X) + n = min(C, pal.shape[0]) + for ci in range(n): + m = bev[:, ci : ci + 1] > 0.5 # (BT, 1, Y, X) + img01 = torch.where(m, pal[ci].view(1, 3, 1, 1), img01) + img = (img01 * 2.0 - 1.0).reshape(B, 3, T, Y, X) # Wan wants (B,3,T,H,W) + return self.bev_hdmap_wan.encode(img) + + # ------------------------------------------------------------------ + # Override: data preparation + # ------------------------------------------------------------------ + + def _store_hdmap_latent(self, hdmap_z: Tensor | None) -> None: + """Apply configured HDMap masking and store the current latent.""" + if hdmap_z is None: + self._current_hdmap = None + return + + if self.training and self.hdmap_dropout_prob > 0.0: + hdmap_z = self._apply_hdmap_dropout(hdmap_z) + + frames_inf = getattr(self, "_hdmap_keep_frames_infer", None) + k_inf = getattr(self, "_hdmap_keep_first_k_infer", None) + if (frames_inf is not None or k_inf is not None) and hdmap_z.ndim == 5: + T_lat = hdmap_z.shape[2] + frame_keep = torch.zeros( + (1, 1, T_lat, 1, 1), + device=hdmap_z.device, + dtype=hdmap_z.dtype, + ) + if frames_inf is not None: + kept = sorted({int(i) % T_lat for i in frames_inf}) + for i in kept: + frame_keep[:, :, i] = 1.0 + log.info( + f"[infer] hdmap keep_frames={kept}/{T_lat}: zeroed " + f"{T_lat - len(kept)} other hdmap latent frames" + ) + else: + K = max(0, min(int(k_inf), T_lat)) + if K > 0: + frame_keep[:, :, :K] = 1.0 + log.info( + f"[infer] hdmap keep_first_k={K}/{T_lat}: zeroed " + f"{T_lat - K} trailing hdmap latent frames" + ) + hdmap_z = hdmap_z * frame_keep + if getattr(self, "_hdmap_force_zero_latent", False): + hdmap_z = torch.zeros_like(hdmap_z) + self._current_hdmap = hdmap_z + + def get_data_and_condition( + self, data_batch: dict[str, Tensor] + ) -> Tuple[Tensor, Tensor, BaseVideoCondition]: + self._normalize_video_databatch_inplace(data_batch) + self._augment_image_dim_inplace(data_batch) + input_key = self.input_data_key + is_image_batch = self.is_image_batch(data_batch) + is_video_batch = not is_image_batch + + for key in sorted(data_batch.keys()): + data_batch[key] = _broadcast( + data_batch[key], to_tp=True, to_cp=is_video_batch + ) + + if is_image_batch: + input_key = self.input_image_key + + # Encode lidar + raw_state = data_batch[input_key] + self._current_sensor_dataset_ids = None + if self._num_dataset_embeddings > 0: + dataset_ids = data_batch.get("sensor_dataset_id") + if dataset_ids is None: + raise KeyError( + "dataset-conditioned DiT requires sensor_dataset_id" + ) + dataset_ids = torch.as_tensor( + dataset_ids, device=raw_state.device, dtype=torch.long + ).reshape(-1) + if dataset_ids.shape != (raw_state.shape[0],): + raise ValueError( + "sensor_dataset_id must have one value per sample, got " + f"{tuple(dataset_ids.shape)} for B={raw_state.shape[0]}" + ) + if bool( + ((dataset_ids < 0) | ( + dataset_ids >= self._num_dataset_embeddings + )).any() + ): + raise ValueError( + "sensor_dataset_id contains a value outside [0, " + f"{self._num_dataset_embeddings})" + ) + self._current_sensor_dataset_ids = dataset_ids + latent_state = self.encode(raw_state).contiguous() + latent_state = latent_state.to(self.diffusion_dtype) + + # Prepare HD-map conditioning + hdmap_z = None + if self._hdmap_concat_ch > 0: + if self.bev_hdmap_wan is not None: + # BEV-native path: render the multi-channel BEV hdmap raster + # (B, C_cls, T, Y, X) to a 3-ch image and encode it with the + # frozen Wan2.2 VAE -> (B, 48, T, Y/16, X/16). + bev = data_batch.get("bev_hdmap") + if bev is not None: + hdmap_z = self._bev_hdmap_to_wan_latent(bev.float()).to( + self.diffusion_dtype + ) + elif self.bev_hdmap_pool is not None: + # BEV-native path: pool the multi-channel BEV hdmap raster + # (B, C_cls, T, Y, X) down to the latent grid (B, out, T, Hz, Wz). + bev = data_batch.get("bev_hdmap") + if bev is not None: + hdmap_z = self.bev_hdmap_pool(bev.float()).to(self.diffusion_dtype) + else: + hdmap = data_batch.get("lidar_hdmap") + if hdmap is not None: + if self.encode_hdmap_with_vae: + if getattr(self, "_hdmap_force_zero_latent", False): + hdmap_z = latent_state.new_zeros( + latent_state.shape[0], + self._hdmap_concat_ch, + *latent_state.shape[2:], + ) + else: + # Hdmap shares the lidar's pixel format (C, T, H, W); + # reuse the lidar VAE so the conditioning is already in + # the same latent space as the noisy target. + # ``self.encode`` already applies the ``sigma_data`` + # scaling, matching ``latent_state``. For a mono + # ``mask_as_input`` VAE the wrapper auto-derives + + # appends the (threshold) validity-mask channel from the + # 1-channel depth -- the SAME encode path as the lidar. + hdmap_z = self.encode(hdmap.float()).contiguous() + else: + hdmap_z = self._prepare_hdmap(hdmap.float(), latent_state) + hdmap_z = hdmap_z.to(self.diffusion_dtype) + self._store_hdmap_latent(hdmap_z) + + # Condition + condition = self.conditioner(data_batch) + if is_image_batch: + condition.data_type = DataType.IMAGE + else: + condition.data_type = DataType.VIDEO + + latent_state = _broadcast(latent_state, to_tp=True, to_cp=is_video_batch) + condition = broadcast_condition(condition, to_tp=True, to_cp=is_video_batch) + + return raw_state, latent_state, condition + + # ------------------------------------------------------------------ + # Override: denoise — concat hdmap with network input + # ------------------------------------------------------------------ + + def denoise( + self, xt: torch.Tensor, sigma: torch.Tensor, condition: CosmosCondition + ) -> DenoisePrediction: + if getattr(self.config, "use_dummy_temporal_dim", False): + xt = xt.unsqueeze(2) + + xt = xt.to(**self.tensor_kwargs) + sigma = sigma.to(**self.tensor_kwargs) + + c_skip, c_out, c_in, c_noise = self.scaling(sigma=sigma) + + net_input = batch_mul(c_in, xt) + + # Channel-concat HD-map + if self._current_hdmap is not None: + hdmap = self._current_hdmap.to(net_input.dtype) + # Handle CFG batch doubling + if net_input.shape[0] != hdmap.shape[0]: + repeats = net_input.shape[0] // hdmap.shape[0] + hdmap = hdmap.repeat(repeats, *([1] * (hdmap.ndim - 1))) + # Unconditional CFG pass: replace hdmap with zeros (the "null" + # condition the model saw during training with hdmap dropout). + if self._hdmap_force_null: + hdmap = torch.zeros_like(hdmap) + net_input = torch.cat([net_input, hdmap], dim=1) + + net_output = self.net( + x=net_input, + timesteps=c_noise, + **condition.to_dict(), + ) + + logvar = self.model.logvar(c_noise) + x0_pred = batch_mul(c_skip, xt) + batch_mul(c_out, net_output) + eps_pred = batch_mul(xt - x0_pred, 1.0 / sigma) + + if getattr(self.config, "use_dummy_temporal_dim", False): + x0_pred = x0_pred.squeeze(2) + eps_pred = eps_pred.squeeze(2) + + return DenoisePrediction(x0_pred, eps_pred, logvar) + + # ------------------------------------------------------------------ + # Override: validation — provide defaults for missing keys + # ------------------------------------------------------------------ + + @torch.no_grad() + def validation_step( + self, data: dict[str, Tensor], iteration: int + ) -> tuple[dict[str, Tensor], Tensor]: + raw_data, x0, condition = self.get_data_and_condition(data) + + guidance = data.get("guidance", 1.5) + data = misc.to(data, **self.tensor_kwargs) + + sample = self.generate_samples_from_batch( + data, + guidance=guidance, + state_shape=x0.shape[1:], + n_sample=x0.shape[0], + ) + sample = self.decode(sample) + reconstruction = self.decode(x0) + + hdmap = data.get("lidar_hdmap") + if hdmap is not None: + hdmap = hdmap.float().cpu() + + return { + "gt": raw_data, + "result": sample, + "reconstruction": reconstruction, + "lidar_hdmap": hdmap, + }, torch.tensor([0]).to(**self.tensor_kwargs) + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + def on_train_start( + self, memory_format: torch.memory_format = torch.preserve_format + ) -> None: + super().on_train_start(memory_format) + if self.hdmap_proj is not None: + self.hdmap_proj = self.hdmap_proj.to( + device="cuda", dtype=torch.float32 + ) + # The frozen Wan2.2 hdmap encoder lives on ``self`` (not in + # ``self.model``), so the trainer's ``self.model.to(cuda)`` does not + # move it. Place it on CUDA explicitly, mirroring ``hdmap_proj`` (kept + # fp32 -- it was built with is_bf16=False and encodes in fp32). + if self.bev_hdmap_wan is not None: + self.bev_hdmap_wan = self.bev_hdmap_wan.to(device="cuda") + self._bev_palette = self._bev_palette.to(device="cuda") + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarDiffusionModel(HdmapToLidarModel): + pass diff --git a/diffusion/training/models/hdmaptolidar_model_rf.py b/diffusion/training/models/hdmaptolidar_model_rf.py new file mode 100644 index 0000000000000000000000000000000000000000..498591e7f2e4a534bd8f325976e1821b5f0c9e0c --- /dev/null +++ b/diffusion/training/models/hdmaptolidar_model_rf.py @@ -0,0 +1,5300 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Rectified-flow variant of the Hdmap-to-Lidar model. + +Replaces EDM training (SDE + preconditioning) with flow-matching velocity +prediction and uses FlowUniPCMultistepScheduler for inference. + +Inherits all hdmap conditioning, VAE, FSDP, and data-loading logic from +``HdmapToLidarModel``. To disable the EDM ``sigma_data`` latent scaling +set ``sigma_data: 1.0`` in the experiment config. +""" + +from dataclasses import fields +from typing import Dict, Optional, Tuple + +import torch +from einops import rearrange +from torch import Tensor, nn + +from diffusion.conditioner import DataType +from diffusion.functional.batch_ops import batch_mul +from diffusion.training.models.hdmaptolidar_model import ( + HdmapToLidarModel, + diffusion_fsdp_class_decorator, +) +from diffusion.training.datasets.lidar_dataset.forecast_warp import ( + build_lagen_sde_conditions, + build_stage2_factorized_geometry, + compose_normalized_range_channels, + remove_points_inside_moving_boxes, + warp_blockwise_history_with_spatial_map, + warp_frozen_observed_history_with_spatial_map, +) +from diffusion.training.models.fm_solvers_unipc import FlowUniPCMultistepScheduler +from diffusion.training.models.fm_solvers_dpm import FlowDPMSolverMultistepScheduler +from diffusion.training.schedulers.rectified_flow import RectifiedFlow +from diffusion.training.utils.diffusion_forcing import ( + artifixer_flow_schedule, + build_clean_context_timesteps, + expand_chunkwise, + temporal_chunk_slices, + validate_prefix_mask, +) +from diffusion.training.utils.sf_dmd import ( + confidence_composite_geometry, + confidence_weighted_geometry_source, +) +from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_lidar_geometry, +) +from utils import log, misc + + +@torch.autocast("cuda", enabled=False) +def _sensor_tables_from_ray_directions( + ray_dirs: Tensor, + *, + allow_approximate: bool = False, +) -> tuple[Tensor, Tensor, Tensor]: + """Recover coarse elevation and azimuth tables from calibrated rays.""" + rays = torch.as_tensor(ray_dirs, dtype=torch.float32) + if rays.ndim != 3 or rays.shape[-1] != 3: + raise ValueError( + f"ray_dirs must be (H,W,3), got {tuple(rays.shape)}" + ) + norm = torch.linalg.vector_norm(rays, dim=-1, keepdim=True) + if not torch.isfinite(norm).all() or bool((norm <= 0).any()): + raise ValueError("ray_dirs must contain finite nonzero vectors") + rays = rays / norm + + elevation_grid = torch.atan2( + rays[..., 2], + torch.linalg.vector_norm(rays[..., :2], dim=-1), + ) + elevations = elevation_grid.mean(dim=1) + azimuth_grid = torch.atan2(rays[..., 1], rays[..., 0]) + azimuths = azimuth_grid[0].contiguous() + relative = torch.remainder( + azimuth_grid - azimuths[None] + torch.pi, + 2.0 * torch.pi, + ) - torch.pi + row_offsets = torch.atan2( + torch.sin(relative).mean(dim=1), + torch.cos(relative).mean(dim=1), + ) + + reconstructed = torch.stack( + ( + torch.cos(elevations)[:, None] + * torch.cos(azimuths[None] + row_offsets[:, None]), + torch.cos(elevations)[:, None] + * torch.sin(azimuths[None] + row_offsets[:, None]), + torch.sin(elevations)[:, None].expand(-1, rays.shape[1]), + ), + dim=-1, + ) + max_error = torch.linalg.vector_norm( + reconstructed - rays, dim=-1 + ).max() + if not torch.isfinite(max_error): + raise ValueError("reconstructed sensor rays must be finite") + if float(max_error) > 1e-3 and not allow_approximate: + raise ValueError( + "sensor rays are not representable by a spinning-LiDAR row/column " + f"grid (max direction error={float(max_error):.6g})" + ) + return elevations, azimuths, row_offsets + + +def _sample_world_synchronized_bernoulli( + probability: float, + device: torch.device, +) -> Tensor: + """Sample one branch decision shared by every distributed rank.""" + draw = torch.empty((), device=device, dtype=torch.float32) + distributed = ( + torch.distributed.is_available() + and torch.distributed.is_initialized() + ) + if not distributed or torch.distributed.get_rank() == 0: + draw.uniform_() + if distributed: + torch.distributed.broadcast(draw, src=0) + return draw < probability + + +def _sample_world_synchronized_categorical( + probabilities: Tensor, +) -> int: + """Sample one categorical branch shared by every distributed rank.""" + if probabilities.ndim != 1 or probabilities.numel() == 0: + raise ValueError("probabilities must be a non-empty 1-D tensor") + distributed = ( + torch.distributed.is_available() + and torch.distributed.is_initialized() + ) + if not distributed or torch.distributed.get_rank() == 0: + sampled = torch.multinomial(probabilities, 1) + else: + sampled = torch.zeros( + 1, device=probabilities.device, dtype=torch.long + ) + if distributed: + torch.distributed.broadcast(sampled, src=0) + return int(sampled.item()) + + +class _RelativePoseFiLM(nn.Module): + """LaGen relative-pose FiLM for the previous-frame latent.""" + + def __init__(self, latent_channels: int, hidden_channels: int = 256): + super().__init__() + self.latent_channels = int(latent_channels) + self.net = nn.Sequential( + nn.Linear(16, int(hidden_channels)), + nn.SiLU(), + nn.Linear(int(hidden_channels), 2 * self.latent_channels), + ) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + + def forward(self, latent: Tensor, relative_pose: Tensor) -> Tensor: + if relative_pose.shape != (latent.shape[0], 4, 4): + raise ValueError( + "relative pose must be (B,4,4), got " + f"{tuple(relative_pose.shape)}" + ) + pose = relative_pose.flatten(1).to( + device=latent.device, + dtype=self.net[0].weight.dtype, + ) + scale, shift = self.net(pose).chunk(2, dim=1) + shape = (latent.shape[0], self.latent_channels) + (1,) * ( + latent.ndim - 2 + ) + return latent * (1.0 + scale.view(shape)) + shift.view(shape) + + +class HdmapToLidarRectifiedFlowModel(HdmapToLidarModel): + """Rectified-flow version of HdmapToLidarModel. + + Training: velocity-matching loss on the RF interpolation. + Inference: FlowUniPCMultistepScheduler (multi-step ODE solver). + """ + + def __init__(self, config): + super().__init__(config) + self.tensor_kwargs_fp32 = {"device": "cuda", "dtype": torch.float32} + + shift = getattr(config, "shift", 5) + clamp_p = getattr(config, "shift_clamp_percentiles", None) + if clamp_p is not None: + clamp_p = tuple(clamp_p) + stretch_terminal = ( + float(getattr(config, "shift_stretch_terminal", 0.1)) + if getattr(config, "enable_shift_stretch", False) + else None + ) + self.rectified_flow = RectifiedFlow( + velocity_field=self.net, + train_time_distribution=getattr(config, "train_time_distribution", "logitnormal"), + train_time_weight_method=getattr(config, "train_time_weight", "uniform"), + shift=shift, + shift_clamp_percentiles=clamp_p, + shift_stretch_terminal=stretch_terminal, + device=torch.device("cuda"), + dtype=torch.float32, + ) + self.sample_scheduler = FlowUniPCMultistepScheduler( + num_train_timesteps=1000, shift=1, use_dynamic_shifting=False, + ) + self._rf_shift = float(shift) + # RF prediction parameterization: "velocity" (legacy) regresses + # v = noise - clean; "clean" (VGGT-World z-prediction) regresses the + # clean latent x0 directly and converts to velocity for the sampler. + self.rf_prediction_type = getattr(config, "rf_prediction_type", "velocity") + assert self.rf_prediction_type in ("velocity", "clean"), ( + f"rf_prediction_type must be 'velocity' or 'clean', got {self.rf_prediction_type}" + ) + # When ``generate_samples_from_batch`` is called with + # ``early_stop_t > 0`` (LTX-style decoder hand-off), the actual + # exit sigma -- which may not exactly equal early_stop_t because + # the UniPC schedule is discrete -- is recorded here so callers + # can pass it to ``model.decode(z, t=model.last_sampling_exit_t)``. + # Always in [0, 1]. None when no early stop was applied. + self.last_sampling_exit_t: Optional[float] = None + log.info( + f"HdmapToLidarRectifiedFlowModel: shift={shift}, " + f"shift_clamp_percentiles={clamp_p}, " + f"enable_shift_stretch={getattr(config, 'enable_shift_stretch', False)}, " + f"shift_stretch_terminal={self.rectified_flow.shift_stretch_terminal}, " + f"sigma_data={self.sigma_data}, " + f"rf_prediction_type={self.rf_prediction_type}" + ) + + # ------------------------------------------------------------------ + # Training + # ------------------------------------------------------------------ + + def training_step( + self, data_batch: dict[str, Tensor], iteration: int + ) -> tuple[dict[str, Tensor], Tensor]: + return self._rectified_flow_forward(data_batch) + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + raw_state, x0, condition = self.get_data_and_condition(data_batch) + + B = x0.shape[0] + epsilon = torch.randn(x0.size(), **self.tensor_kwargs_fp32) + + t_B = self.rectified_flow.sample_train_time(B).to(**self.tensor_kwargs_fp32) + t_B = rearrange(t_B, "b -> b 1") + + timesteps = self.rectified_flow.get_discrete_timestamp(t_B, self.tensor_kwargs_fp32) + sigmas = self.rectified_flow.get_sigmas(timesteps, self.tensor_kwargs_fp32) + timesteps = rearrange(timesteps, "b -> b 1") + sigmas = rearrange(sigmas, "b -> b 1") + + xt, vt_target = self.rectified_flow.get_interpolation(epsilon, x0, sigmas) + + net_pred = self._rf_network_forward( + xt.to(**self.tensor_kwargs), timesteps, condition, + ).float() + + # "clean": regress x0 directly (VGGT-World z-prediction); uniform-weighted + # clean-target MSE (VGGT eq. 12). "velocity": regress v = noise - clean. + if self.rf_prediction_type == "clean": + target = x0.float() + else: + target = vt_target.float() + + time_weights = self.rectified_flow.train_time_weight( + timesteps, self.tensor_kwargs_fp32 + ) + per_instance_loss = torch.mean( + (net_pred - target) ** 2, + dim=list(range(1, net_pred.dim())), + ) + loss = torch.mean(time_weights.squeeze(-1) * per_instance_loss) + + output_batch = { + "x0": x0, + "xt": xt, + "sigma": sigmas, + "model_pred": net_pred, + "edm_loss": loss, + "timesteps": timesteps, + "per_instance_loss": per_instance_loss, + } + return output_batch, loss + + # ------------------------------------------------------------------ + # Network forward (no EDM preconditioning) + # ------------------------------------------------------------------ + + def _rf_network_forward( + self, + xt: Tensor, + timesteps: Tensor, + condition, + ) -> Tensor: + """Run the network without EDM c_in/c_out/c_skip preconditioning. + + Handles hdmap channel-concat and optional dummy temporal dim, + mirroring the parent ``denoise`` method structure. + """ + if getattr(self.config, "use_dummy_temporal_dim", False): + xt = xt.unsqueeze(2) + + net_input = xt + + if self._current_hdmap is not None: + hdmap = self._current_hdmap.to(net_input.dtype) + if net_input.shape[0] != hdmap.shape[0]: + repeats = net_input.shape[0] // hdmap.shape[0] + hdmap = hdmap.repeat(repeats, *([1] * (hdmap.ndim - 1))) + # Unconditional CFG pass: replace hdmap with zeros (the "null" + # condition the model saw during training with hdmap dropout). + force_null_mask = getattr( + self, "_hdmap_force_null_mask", None + ) + if force_null_mask is not None: + if ( + force_null_mask.ndim != 1 + or force_null_mask.shape[0] != hdmap.shape[0] + ): + raise ValueError( + "HDMap CFG null mask must have one entry per batch " + f"element: mask={tuple(force_null_mask.shape)}, " + f"hdmap={tuple(hdmap.shape)}" + ) + mask_shape = (hdmap.shape[0],) + (1,) * ( + hdmap.ndim - 1 + ) + hdmap = hdmap.masked_fill( + force_null_mask.to( + device=hdmap.device, dtype=torch.bool + ).view(mask_shape), + 0, + ) + elif self._hdmap_force_null: + hdmap = torch.zeros_like(hdmap) + net_input = torch.cat([net_input, hdmap], dim=1) + + geometry_concat = bool( + getattr(self, "blockwise_warped_history_concat", False) + ) + if geometry_concat: + geometry = getattr( + self, "_current_blockwise_warped_history", None + ) + if geometry is None: + raise RuntimeError( + "geometry concat requires an encoded warped-history latent" + ) + geometry = geometry.to( + device=net_input.device, + dtype=net_input.dtype, + ) + if net_input.shape[0] != geometry.shape[0]: + repeats = net_input.shape[0] // geometry.shape[0] + geometry = geometry.repeat( + repeats, *([1] * (geometry.ndim - 1)) + ) + force_null_mask = getattr( + self, "_geometry_force_null_mask", None + ) + if force_null_mask is not None: + if ( + force_null_mask.ndim != 1 + or force_null_mask.shape[0] != geometry.shape[0] + ): + raise ValueError( + "geometry CFG null mask must have one entry per batch " + f"element: mask={tuple(force_null_mask.shape)}, " + f"geometry={tuple(geometry.shape)}" + ) + mask_shape = (geometry.shape[0],) + (1,) * ( + geometry.ndim - 1 + ) + geometry = geometry.masked_fill( + force_null_mask.to( + device=geometry.device, dtype=torch.bool + ).view(mask_shape), + 0, + ) + elif getattr(self, "_geometry_force_null", False): + geometry = torch.zeros_like(geometry) + if geometry.shape[2:] != net_input.shape[2:]: + raise ValueError( + "geometry concat must align with the DiT input: " + f"geometry={tuple(geometry.shape)}, " + f"input={tuple(net_input.shape)}" + ) + net_input = torch.cat([net_input, geometry], dim=1) + + autoregressive_condition = getattr( + self, "_current_autoregressive_condition", None + ) + if autoregressive_condition is not None: + autoregressive_condition = autoregressive_condition.to( + device=net_input.device, dtype=net_input.dtype + ) + if net_input.shape[0] != autoregressive_condition.shape[0]: + repeats = ( + net_input.shape[0] + // autoregressive_condition.shape[0] + ) + autoregressive_condition = autoregressive_condition.repeat( + repeats, + *([1] * (autoregressive_condition.ndim - 1)), + ) + if autoregressive_condition.shape[2:] != net_input.shape[2:]: + raise ValueError( + "autoregressive condition must align with DiT input: " + f"condition={tuple(autoregressive_condition.shape)}, " + f"input={tuple(net_input.shape)}" + ) + net_input = torch.cat( + [net_input, autoregressive_condition], dim=1 + ) + + known_mask_concat = bool( + getattr(self.config, "stage2_known_mask_concat", False) + or getattr( + self.config, + "stage2_multitask_known_mask_concat", + False, + ) + ) + if known_mask_concat: + if net_input.ndim != 5: + raise ValueError( + "known-frame mask concat requires video-shaped DiT input" + ) + known_mask = getattr( + self, "_current_stage2_known_frame_mask", None + ) + if known_mask is None: + known_mask = torch.zeros( + (net_input.shape[0], net_input.shape[2]), + device=net_input.device, + dtype=net_input.dtype, + ) + else: + known_mask = known_mask.to( + device=net_input.device, dtype=net_input.dtype + ) + if known_mask.ndim == 1: + known_mask = known_mask[None] + if known_mask.ndim != 2: + raise ValueError( + "known-frame mask must be (T,) or (B,T), got " + f"{tuple(known_mask.shape)}" + ) + if known_mask.shape[0] != net_input.shape[0]: + repeats = net_input.shape[0] // known_mask.shape[0] + known_mask = known_mask.repeat(repeats, 1) + if known_mask.shape != ( + net_input.shape[0], + net_input.shape[2], + ): + raise ValueError( + "known-frame mask must align with the DiT input, got " + f"{tuple(known_mask.shape)} for " + f"{tuple(net_input.shape)}" + ) + known_channel = known_mask[:, None, :, None, None].expand( + -1, 1, -1, net_input.shape[3], net_input.shape[4] + ) + net_input = torch.cat([net_input, known_channel], dim=1) + + # Legacy RF passes (B,1) and the DiT accepts (B,). Diffusion Forcing + # passes a real per-frame (B,T) tensor which must remain 2-D. + t_for_net = ( + timesteps.squeeze(-1) + if timesteps.ndim == 2 and timesteps.shape[1] == 1 + else timesteps + ) + t_for_net = t_for_net.to(net_input.dtype) + + net_kwargs = condition.to_dict() + side_condition = getattr( + self, "_current_blockwise_warped_history", None + ) + if side_condition is not None and not geometry_concat: + side_condition = side_condition.to( + device=net_input.device, + dtype=net_input.dtype, + ) + if net_input.shape[0] != side_condition.shape[0]: + repeats = net_input.shape[0] // side_condition.shape[0] + side_condition = side_condition.repeat( + repeats, *([1] * (side_condition.ndim - 1)) + ) + net_kwargs["side_condition"] = side_condition + + teacher_forcing_clean_frames = getattr( + self, "_current_teacher_forcing_clean_frames", None + ) + if teacher_forcing_clean_frames is not None: + if getattr(self, "_current_sfdmd_temporal_positions", None) is not None: + raise RuntimeError( + "one-pass teacher forcing and SF-DMD streaming cannot be " + "active in the same network call" + ) + net_kwargs["teacher_forcing_clean_frames"] = int( + teacher_forcing_clean_frames + ) + net_kwargs["temporal_positions"] = getattr( + self, "_current_teacher_forcing_temporal_positions" + ) + frame_type_ids = getattr( + self, "_current_stage2_task_frame_type_ids", None + ) + if frame_type_ids is not None: + if frame_type_ids.shape != (net_input.shape[2],): + raise ValueError( + "Stage-2 task ids must align with the DiT temporal axis, " + f"got {tuple(frame_type_ids.shape)} for " + f"T={net_input.shape[2]}" + ) + net_kwargs["frame_type_ids"] = frame_type_ids + + dataset_ids = getattr( + self, "_current_sensor_dataset_ids", None + ) + if dataset_ids is not None: + dataset_ids = dataset_ids.to( + device=net_input.device, dtype=torch.long + ) + if dataset_ids.shape[0] != net_input.shape[0]: + if net_input.shape[0] % dataset_ids.shape[0] != 0: + raise ValueError( + "dataset ids cannot be repeated to match the DiT batch: " + f"ids={tuple(dataset_ids.shape)}, B={net_input.shape[0]}" + ) + dataset_ids = dataset_ids.repeat( + net_input.shape[0] // dataset_ids.shape[0] + ) + net_kwargs["dataset_ids_B"] = dataset_ids + + # SF-DMD's non-overlapping autoregressive path supplies global RoPE + # positions and an external per-layer self-attention KV cache. These + # attributes are absent in every ordinary training/inference path. + temporal_positions = getattr( + self, "_current_sfdmd_temporal_positions", None + ) + return_self_attn_kv = False + if temporal_positions is not None: + net_kwargs["temporal_positions"] = temporal_positions + net_kwargs["self_attn_kv_cache"] = ( + self._current_sfdmd_self_attn_kv_cache + ) + net_kwargs["store_self_attn_kv"] = bool( + self._current_sfdmd_store_self_attn_kv + ) + net_kwargs["self_attn_kv_max_frames"] = int( + self._current_sfdmd_self_attn_kv_max_frames + ) + net_kwargs["self_attn_kv_sink_frames"] = int( + getattr(self, "_current_sfdmd_self_attn_kv_sink_frames", 0) + ) + net_kwargs["detach_self_attn_kv"] = bool( + getattr(self, "_current_sfdmd_detach_self_attn_kv", True) + ) + return_self_attn_kv = bool( + getattr( + self, + "_current_sfdmd_return_self_attn_kv", + False, + ) + ) + net_kwargs["return_self_attn_kv"] = return_self_attn_kv + + network = self.net + if getattr(network, "skip_crossattn_when_zero", False): + network.validate_zero_crossattn_skip( + net_kwargs["crossattn_emb"], + net_kwargs.get("img_context_emb"), + ) + + net_output = network( + x=net_input, + timesteps=t_for_net, + **net_kwargs, + ) + if return_self_attn_kv: + net_output, updated_cache = net_output + self._current_sfdmd_updated_self_attn_kv_cache = updated_cache + + if getattr(self.config, "use_dummy_temporal_dim", False): + net_output = net_output.squeeze(2) + + return net_output.float() + + @staticmethod + def _batch_cfg_conditions(condition, uncondition): + """Concatenate matching condition dataclasses along batch.""" + if type(condition) is not type(uncondition): + raise TypeError( + "batched CFG requires matching condition types, got " + f"{type(condition).__name__} and " + f"{type(uncondition).__name__}" + ) + + values = {} + for field in fields(condition): + cond_value = getattr(condition, field.name) + uncond_value = getattr(uncondition, field.name) + if isinstance(cond_value, torch.Tensor): + if not isinstance(uncond_value, torch.Tensor): + raise TypeError( + f"CFG condition field {field.name!r} is a tensor " + "only on the conditional branch" + ) + if cond_value.ndim == 0 or uncond_value.ndim == 0: + raise ValueError( + f"CFG condition field {field.name!r} must have a " + "batch dimension" + ) + if cond_value.shape[1:] != uncond_value.shape[1:]: + raise ValueError( + f"CFG condition field {field.name!r} has " + f"incompatible shapes {tuple(cond_value.shape)} and " + f"{tuple(uncond_value.shape)}" + ) + values[field.name] = torch.cat( + [cond_value, uncond_value], dim=0 + ) + elif cond_value is uncond_value or cond_value == uncond_value: + values[field.name] = cond_value + else: + raise ValueError( + f"CFG condition field {field.name!r} differs between " + "branches but is not batchable" + ) + return type(condition)(**values) + + def _cfg_null_modalities(self) -> tuple[bool, bool]: + """Return whether the CFG unconditional branch nulls HDMap/geometry.""" + geometry_only_cfg = bool( + getattr(self, "_geometry_only_cfg", False) + ) + hdmap_only_cfg = bool( + getattr(self, "_hdmap_only_cfg", False) + ) + if geometry_only_cfg and hdmap_only_cfg: + raise ValueError( + "geometry-only and HDMap-only CFG are mutually exclusive" + ) + drop_hdmap_uncond = hdmap_only_cfg or ( + self.hdmap_dropout_prob > 0.0 and not geometry_only_cfg + ) + return drop_hdmap_uncond, geometry_only_cfg + + def _rf_network_forward_batched_cfg( + self, + xt: Tensor, + timesteps: Tensor, + condition, + uncondition, + ) -> tuple[Tensor, Tensor]: + """Run conditional and unconditional CFG branches as one batch.""" + batch_size = xt.shape[0] + batched_condition = self._batch_cfg_conditions( + condition, uncondition + ) + batched_xt = torch.cat([xt, xt], dim=0) + batched_timesteps = torch.cat([timesteps, timesteps], dim=0) + + previous_mask = getattr( + self, "_hdmap_force_null_mask", None + ) + ( + drop_hdmap_uncond, + drop_geometry_uncond, + ) = self._cfg_null_modalities() + branch_null_mask = torch.zeros( + 2 * batch_size, + device=xt.device, + dtype=torch.bool, + ) + if drop_hdmap_uncond: + branch_null_mask[batch_size:] = True + previous_geometry_mask = getattr( + self, "_geometry_force_null_mask", None + ) + geometry_branch_null_mask = torch.zeros_like(branch_null_mask) + if drop_geometry_uncond: + geometry_branch_null_mask[batch_size:] = True + self._hdmap_force_null_mask = branch_null_mask + self._geometry_force_null_mask = geometry_branch_null_mask + try: + batched_out = self._rf_network_forward( + batched_xt, + batched_timesteps, + batched_condition, + ) + finally: + if previous_mask is None: + del self._hdmap_force_null_mask + else: + self._hdmap_force_null_mask = previous_mask + if previous_geometry_mask is None: + del self._geometry_force_null_mask + else: + self._geometry_force_null_mask = previous_geometry_mask + + if batched_out.shape[0] != 2 * batch_size: + raise RuntimeError( + "batched CFG network returned an unexpected batch size: " + f"expected {2 * batch_size}, got {batched_out.shape[0]}" + ) + return batched_out[:batch_size], batched_out[batch_size:] + + # ------------------------------------------------------------------ + # Inference + # ------------------------------------------------------------------ + + def _clean_to_velocity( + self, x0_hat: Tensor, x_t: Tensor, t_input: Tensor, + ) -> Tensor: + """Convert a clean-latent prediction to a flow velocity for the sampler. + + With our interpolation ``x_t = noise*sigma + clean*(1-sigma)`` the + velocity is ``v = noise - clean = (x_t - clean)/sigma``. ``t_input`` is + the discrete timestep in ``[0, num_train]``; ``sigma = t_input/num_train``. + """ + num_train = float(self.rectified_flow.num_train_timesteps) + sigma = (t_input.float() / num_train).clamp(min=1e-3) + sigma = sigma.view(-1, *([1] * (x0_hat.dim() - 1))) + return (x_t.float() - x0_hat.float()) / sigma + + def _get_velocity( + self, latents: Tensor, t_input: Tensor, condition, uncondition, + guidance: float, use_cfg: bool, batched_cfg: bool = False, + ) -> Tensor: + """Single velocity query with optional CFG. + + In ``clean`` mode the network output is the clean latent x0; CFG is + applied on that (affine, so equivalent to CFG on velocity) and the + combined prediction is converted to velocity for the ODE sampler. + + ``guidance == 0`` is pure unconditional sampling, so skip the + conditional query entirely. This is exactly equivalent to + ``uncond + 0 * (cond - uncond)`` but halves the network forwards. + """ + net_latents = latents.to(**self.tensor_kwargs) + if use_cfg and batched_cfg: + cond_out, uncond_out = self._rf_network_forward_batched_cfg( + net_latents, + t_input, + condition, + uncondition, + ) + out = uncond_out + guidance * (cond_out - uncond_out) + elif use_cfg and guidance == 0.0: + ( + drop_hdmap_uncond, + drop_geometry_uncond, + ) = self._cfg_null_modalities() + if drop_hdmap_uncond: + self._hdmap_force_null = True + if drop_geometry_uncond: + self._geometry_force_null = True + try: + out = self._rf_network_forward( + net_latents, t_input, uncondition, + ) + finally: + self._hdmap_force_null = False + self._geometry_force_null = False + else: + cond_out = self._rf_network_forward( + net_latents, t_input, condition, + ) + if use_cfg: + ( + drop_hdmap_uncond, + drop_geometry_uncond, + ) = self._cfg_null_modalities() + if drop_hdmap_uncond: + self._hdmap_force_null = True + if drop_geometry_uncond: + self._geometry_force_null = True + try: + uncond_out = self._rf_network_forward( + net_latents, t_input, uncondition, + ) + finally: + self._hdmap_force_null = False + self._geometry_force_null = False + out = uncond_out + guidance * (cond_out - uncond_out) + else: + out = cond_out + + if self.rf_prediction_type == "clean": + out = self._clean_to_velocity(out, latents, t_input) + return out + + @torch.no_grad() + def generate_samples_from_batch( + self, + data_batch: Dict, + guidance: float = 1.0, + seed: int = 1, + state_shape: Optional[Tuple] = None, + n_sample: Optional[int] = None, + is_negative_prompt: bool = False, + num_steps: int = 35, + shift: Optional[float] = None, + sampler: str = "unipc", + sde_eta: float = 1.0, + sde_eta_first_frac: float = 0.0, + sde_eta_last_frac: float = 0.0, + solver_order: int = 2, + early_stop_t: Optional[float] = None, + noise: Optional[Tensor] = None, + known_latents: Optional[Tensor] = None, + known_mask: Optional[Tensor] = None, + known_latents_mode: Optional[str] = None, + repaint_u: int = 1, + store_kv_exit_query: bool = False, + store_kv_query_sigma: Optional[float] = None, + **kwargs, + ) -> Tensor: + """Generate latents from noise. + + Args: + ``noise``: optional pre-drawn init noise ``(B,) + state_shape``. + When given it overrides the internally seeded + ``arch_invariant_rand`` -- used by the long-video rollout so + overlapping windows share noise on their shared frames. + ``early_stop_t``: if not None, must be a float in (0, 1]. + The UniPC sampler stops as soon as the next-step sigma + drops to or below this value -- intended for hand-off to + an LTX-style denoising decoder that handles the final + ``[exit_sigma, 0]`` step in one forward pass. The actual + exit sigma (always <= ``early_stop_t``) is stored on + ``self.last_sampling_exit_t``; callers should pass that + exact value to ``model.decode(z, t=...)`` so the decoder + sees the same noise level it was trained on. + """ + use_cfg = guidance != 1.0 + + if use_cfg: + if is_negative_prompt: + condition, uncondition = self.conditioner.get_condition_with_negative_prompt(data_batch) + else: + condition, uncondition = self.conditioner.get_condition_uncondition(data_batch) + else: + condition = self.conditioner(data_batch) + uncondition = None + + B = n_sample or data_batch[self.input_data_key].shape[0] + state_shape = state_shape or self.state_shape + + if noise is not None: + noise = noise.to(device="cuda", dtype=torch.float32) + assert tuple(noise.shape) == (B,) + tuple(state_shape), ( + f"noise {tuple(noise.shape)} must be (B={B},) + " + f"state_shape={tuple(state_shape)}" + ) + else: + noise = misc.arch_invariant_rand( + (B,) + tuple(state_shape), torch.float32, "cuda", seed, + ) + + # Reset early-stop bookkeeping before each generate call so the + # caller can't accidentally re-use a stale exit sigma from a + # previous (early-stopped) generation when this one ran to + # completion. + self.last_sampling_exit_t = None + + if known_latents is not None and sampler != "sde": + raise NotImplementedError( + "known_latents (RePaint-style overlap conditioning) is only " + "supported by the sde sampler." + ) + if store_kv_exit_query and sampler not in ("sde", "unipc"): + raise NotImplementedError( + "selected-query K/V commitment is only supported by the SDE " + "and UniPC samplers" + ) + + if sampler == "sde": + sde_kwargs = dict( + latents=noise, + condition=condition, + uncondition=uncondition, + guidance=guidance, + use_cfg=use_cfg, + B=B, + num_steps=num_steps, + shift=shift, + seed=seed, + sde_eta=sde_eta, + early_stop_t=early_stop_t, + known_latents=known_latents, known_mask=known_mask, + repaint_u=repaint_u, + eta_first_frac=sde_eta_first_frac, + eta_last_frac=sde_eta_last_frac, + store_kv_exit_query=store_kv_exit_query, + store_kv_query_sigma=store_kv_query_sigma, + ) + if known_latents_mode is not None: + sde_kwargs["known_latents_mode"] = known_latents_mode + return self._generate_sde(**sde_kwargs) + + if sampler in ("euler", "heun"): + if early_stop_t is not None: + raise NotImplementedError( + "early_stop_t is only supported by the unipc/sde samplers " + "(euler/heun use a fixed uniform linspace and don't " + "have the same early-stop semantics)." + ) + return self._generate_euler_heun( + noise, condition, uncondition, guidance, use_cfg, + B, num_steps, sampler, + ) + + if sampler in ("dpmpp", "dpmpp_sde"): + if early_stop_t is not None: + raise NotImplementedError( + "early_stop_t is not yet supported by the dpmpp samplers." + ) + return self._generate_dpmpp( + noise, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, + algorithm_type=( + "sde-dpmsolver++" if sampler == "dpmpp_sde" else "dpmsolver++" + ), + solver_order=solver_order, + ) + + return self._generate_unipc( + noise, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, + early_stop_t=early_stop_t, + store_kv_exit_query=store_kv_exit_query, + store_kv_query_sigma=store_kv_query_sigma, + ) + + # ---- UniPC sampler ---- + + @torch.no_grad() + def _generate_unipc( + self, latents, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, + early_stop_t: Optional[float] = None, + batched_cfg: bool = False, + store_kv_exit_query: bool = False, + store_kv_query_sigma: Optional[float] = None, + ) -> Tensor: + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + + if shift is None: + shift = self._rf_shift + stretch_terminal = self.rectified_flow.shift_stretch_terminal + self.sample_scheduler.set_timesteps( + num_steps, device="cuda", shift=shift, + stretch_terminal=stretch_terminal, + ) + self.sample_scheduler.set_begin_index(0) + timesteps = self.sample_scheduler.timesteps + sigmas = self.sample_scheduler.sigmas.float() + num_train = float(self.sample_scheduler.config.num_train_timesteps) + + if store_kv_query_sigma is not None and not store_kv_exit_query: + raise ValueError( + "store_kv_query_sigma requires store_kv_exit_query=True" + ) + deferred_store_index = None + deferred_store_query = None + debug_nonfinite = bool( + getattr(self, "_debug_nonfinite_sampling", False) + ) + + def _tensor_stats(value: torch.Tensor) -> str: + value_f = value.detach().float() + finite = value_f[torch.isfinite(value_f)] + if finite.numel() == 0: + return "finite=0.000000%, no finite values" + return ( + f"finite={float(torch.isfinite(value_f).float().mean()):.6%}, " + f"min={float(finite.min()):.6g}, " + f"max={float(finite.max()):.6g}, " + f"mean={float(finite.mean()):.6g}, " + f"std={float(finite.std()):.6g}" + ) + + if store_kv_query_sigma is not None: + target_sigma = torch.as_tensor( + store_kv_query_sigma, + device=sigmas.device, + dtype=sigmas.dtype, + ) + deferred_store_index = int( + torch.argmin((sigmas[:-1] - target_sigma).abs()).item() + ) + + for i, t in enumerate(timesteps): + t_input = t.unsqueeze(0).expand(B) + if deferred_store_index == i: + deferred_store_query = ( + latents.detach().clone(), + t_input.detach().clone(), + ) + store_exit = ( + store_kv_exit_query + and deferred_store_index is None + and i == len(timesteps) - 1 + ) + previous_store = getattr( + self, "_current_sfdmd_store_self_attn_kv", False + ) + if store_exit: + self._current_sfdmd_store_self_attn_kv = True + try: + velocity_pred = self._get_velocity( + latents, + t_input, + condition, + uncondition, + guidance, + use_cfg, + batched_cfg=batched_cfg, + ) + finally: + if store_exit: + self._current_sfdmd_store_self_attn_kv = previous_store + if debug_nonfinite and not torch.isfinite(velocity_pred).all(): + raise FloatingPointError( + "UniPC received a non-finite velocity prediction at " + f"step {i + 1}/{len(timesteps)}, timestep={float(t):.6g}; " + f"latents: {_tensor_stats(latents)}; " + f"velocity: {_tensor_stats(velocity_pred)}" + ) + result = self.sample_scheduler.step( + velocity_pred.unsqueeze(0), t, latents.unsqueeze(0), + return_dict=False, generator=gen, + ) + latents = result[0].squeeze(0) + if debug_nonfinite and not torch.isfinite(latents).all(): + raise FloatingPointError( + "UniPC produced non-finite latents after " + f"step {i + 1}/{len(timesteps)}, timestep={float(t):.6g}; " + f"velocity: {_tensor_stats(velocity_pred)}; " + f"latents: {_tensor_stats(latents)}" + ) + + # After this step the latent's noise level is approximately + # the next schedule timestep (or 0 if this was the last step). + # If that level is at or below ``early_stop_t`` we stop here + # and hand off to the LTX decoder; the EXACT noise level the + # latent is at is recorded so the decoder gets the matching + # ``t`` rather than the user-requested target. + if early_stop_t is not None: + next_t = ( + timesteps[i + 1].item() + if i + 1 < len(timesteps) + else 0.0 + ) + next_t_norm = float(next_t) / num_train + if next_t_norm <= float(early_stop_t): + self.last_sampling_exit_t = next_t_norm + log.info( + f"_generate_unipc: early-stopping at step {i + 1}/" + f"{len(timesteps)} (sigma={next_t_norm:.4f} <= " + f"early_stop_t={early_stop_t})" + ) + break + + if deferred_store_index is not None: + if deferred_store_query is None: + raise RuntimeError( + "UniPC sampling ended before the requested K/V query sigma" + ) + query_latents, query_timestep = deferred_store_query + previous_store = getattr( + self, "_current_sfdmd_store_self_attn_kv", False + ) + self._current_sfdmd_store_self_attn_kv = True + try: + self._get_velocity( + query_latents, + query_timestep, + condition, + uncondition, + guidance, + use_cfg, + batched_cfg=batched_cfg, + ) + finally: + self._current_sfdmd_store_self_attn_kv = previous_store + + return latents + + # ---- Flow-DPM-Solver++ sampler ---- + + @torch.no_grad() + def _generate_dpmpp( + self, latents, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, + algorithm_type: str = "dpmsolver++", + solver_order: int = 2, + ) -> Tensor: + """Flow-DPM-Solver++ (DPM-Solver++ specialized for rectified flow). + + High-order data-prediction exponential integrator. ``algorithm_type`` + selects the deterministic ODE (``"dpmsolver++"``) or the stochastic + variant (``"sde-dpmsolver++"``, fresh noise injected each step). Reuses + the SAME shift/stretch sigma ladder as UniPC/SDE. ``solver_order`` 1-3 + (2 recommended for guided sampling). Lower-order-final is on for + stability at small step counts. + """ + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + + if shift is None: + shift = self._rf_shift + stretch_terminal = self.rectified_flow.shift_stretch_terminal + + scheduler = FlowDPMSolverMultistepScheduler( + num_train_timesteps=1000, + shift=1, + use_dynamic_shifting=False, + solver_order=solver_order, + algorithm_type=algorithm_type, + solver_type="midpoint", + lower_order_final=True, + final_sigmas_type="zero", + ) + scheduler.set_timesteps( + num_steps, device="cuda", shift=shift, stretch_terminal=stretch_terminal, + ) + scheduler.set_begin_index(0) + timesteps = scheduler.timesteps + + for t in timesteps: + t_input = t.unsqueeze(0).expand(B) + velocity_pred = self._get_velocity( + latents, t_input, condition, uncondition, guidance, use_cfg, + ) + result = scheduler.step( + velocity_pred.unsqueeze(0), t, latents.unsqueeze(0), + return_dict=False, generator=gen, + ) + latents = result[0].squeeze(0) + + return latents + + # ---- LTX-style stochastic (SDE) sampler ---- + + @torch.no_grad() + def _generate_sde( + self, latents, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, sde_eta, + early_stop_t: Optional[float] = None, + known_latents: Optional[Tensor] = None, + known_mask: Optional[Tensor] = None, + known_noise: Optional[Tensor] = None, + repaint_u: int = 1, + eta_first_frac: float = 0.0, + eta_last_frac: float = 0.0, + batched_cfg: bool = False, + store_kv_exit_query: bool = False, + store_kv_query_sigma: Optional[float] = None, + geometry_source: Optional[Tensor] = None, + geometry_confidence: Optional[Tensor] = None, + geometry_noise_floor: float = 0.0, + ) -> Tensor: + """LTX-Video-style stochastic (SDE) sampler for rectified flow. + + Mirrors LTX's ``RectifiedFlowScheduler`` stochastic step: at each + step predict the clean latent ``x0`` from the velocity, then re-noise + it forward to the next (lower) sigma with fresh Gaussian noise + (``add_noise(x0, eps, sigma_next) = (1-sigma_next)*x0 + sigma_next*eps``). + Reuses the same shift/stretch sigma ladder as the UniPC sampler so the + only difference vs deterministic sampling is the per-step renoise. + + ``sde_eta`` in ``[0, 1]`` scales how much *fresh* noise is injected: + * ``1.0`` -> full LTX stochastic renoise (fresh noise each step), + * ``0.0`` -> deterministic Euler on the same ladder, + * in-between -> linear blend of the implied and fresh noise. + The final step (``sigma_next == 0``) is always deterministic. + + ``eta_first_frac`` / ``eta_last_frac`` in ``[0, 1]`` force ``eta=0`` + (deterministic) for that fraction of the *leading* / *trailing* steps + of the ladder, leaving stochasticity active only in the middle band. + Use ``eta_last_frac>0`` to test the "lower eta helps as t->0" + hypothesis: a deterministic finish preserves the sharp geometry that a + constant late-step renoise would smear (the injected noise has too few + remaining steps to be removed). + + ``store_kv_query_sigma`` keeps selected-query cache commitment near a + reference sigma when a rollout temporarily uses a different step count. + The query is captured during sampling and committed in one deferred + forward so it cannot enter the history used by later denoising steps. + + ``known_noise`` optionally pins known frames to one forward-diffusion + path instead of drawing a fresh path at every step. + """ + if (geometry_source is None) != (geometry_confidence is None): + raise ValueError( + "geometry_source and geometry_confidence must be provided " + "together" + ) + if geometry_source is not None: + geometry_source = geometry_source.to( + device=latents.device, dtype=latents.dtype + ) + geometry_confidence = geometry_confidence.to( + device=latents.device, dtype=torch.float32 + ) + if geometry_source.shape != latents.shape: + raise ValueError( + "geometry_source must match SDE latents: " + f"source={tuple(geometry_source.shape)}, " + f"latents={tuple(latents.shape)}" + ) + + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + n_steps = num_steps + first_off = int(round(max(0.0, eta_first_frac) * n_steps)) + last_off = int(round(max(0.0, eta_last_frac) * n_steps)) + + if shift is None: + shift = self._rf_shift + stretch_terminal = self.rectified_flow.shift_stretch_terminal + self.sample_scheduler.set_timesteps( + num_steps, device="cuda", shift=shift, + stretch_terminal=stretch_terminal, + ) + # sigmas: (num_steps+1,) in [0,1] with terminal sigma appended; + # timesteps: (num_steps,) discrete int64 in [0, num_train]. + sigmas = self.sample_scheduler.sigmas.to("cuda").float() + timesteps = self.sample_scheduler.timesteps + if store_kv_query_sigma is not None and not store_kv_exit_query: + raise ValueError( + "store_kv_query_sigma requires store_kv_exit_query=True" + ) + deferred_store_index = None + deferred_store_query = None + debug_nonfinite = bool( + getattr(self, "_debug_nonfinite_sampling", False) + ) + + def _tensor_stats(value: torch.Tensor) -> str: + value_f = value.detach().float() + finite_mask = torch.isfinite(value_f) + finite = value_f[finite_mask] + if finite.numel() == 0: + return "finite=0.000000%, no finite values" + return ( + f"finite={float(finite_mask.float().mean()):.6%}, " + f"min={float(finite.min()):.6g}, " + f"max={float(finite.max()):.6g}, " + f"mean={float(finite.mean()):.6g}, " + f"std={float(finite.std()):.6g}" + ) + + if store_kv_query_sigma is not None: + target_sigma = torch.as_tensor( + store_kv_query_sigma, + device=sigmas.device, + dtype=sigmas.dtype, + ) + deferred_store_index = int( + torch.argmin((sigmas[:-1] - target_sigma).abs()).item() + ) + + if known_noise is not None and known_latents is None: + raise ValueError("known_noise requires known_latents") + + # RePaint-style overlap conditioning: ``known_latents`` holds the clean + # (diffusion-space) latent for the frames a previous window already + # generated; ``known_mask`` (T,) marks them. At the start of each step we + # overwrite the known frames with the known latent forward-noised to the + # current sigma, so the new frames denoise conditioned on a fixed, + # consistent history -> no seam between windows. + use_known = known_latents is not None + if use_known: + if known_mask is None: + raise ValueError("known_mask is required with known_latents") + known_latents = known_latents.to( + device=latents.device, dtype=latents.dtype) + if tuple(known_latents.shape) != tuple(latents.shape): + raise ValueError( + f"known_latents {tuple(known_latents.shape)} must match " + f"latents {tuple(latents.shape)}" + ) + known_mask = known_mask.to( + device=latents.device, dtype=torch.bool + ) + if known_mask.ndim == 1: + if known_mask.shape[0] != latents.shape[2]: + raise ValueError( + "known_mask length must match the latent time axis" + ) + km = known_mask.view(1, 1, -1, 1, 1) + elif known_mask.ndim == 2: + if tuple(known_mask.shape) != (B, latents.shape[2]): + raise ValueError( + "known_mask must have shape (T,) or (B,T)" + ) + km = known_mask[:, None, :, None, None] + else: + raise ValueError("known_mask must have shape (T,) or (B,T)") + if known_noise is not None: + known_noise = known_noise.to( + device=latents.device, dtype=latents.dtype + ) + if tuple(known_noise.shape) != tuple(latents.shape): + raise ValueError( + f"known_noise {tuple(known_noise.shape)} must match " + f"latents {tuple(latents.shape)}" + ) + + def _inject(x, sigma): + eps = known_noise + if eps is None: + eps = torch.randn( + x.shape, + generator=gen, + device=x.device, + dtype=x.dtype, + ) + noised = (1.0 - sigma) * known_latents + sigma * eps + return torch.where(km, noised, x) + + # RePaint resampling ("jump-back"): repeat each denoise step + # ``repaint_u`` times, jumping the noise level back up from sigma_next + # to sigma between passes so the generated frames get multiple chances + # to harmonize with the re-injected known frames. Only meaningful with + # overlap conditioning; a no-op (u=1) otherwise. + n_resample = max(1, repaint_u) if use_known else 1 + + for i in range(len(timesteps)): + sigma = sigmas[i] + sigma_next = sigmas[i + 1] + # no jump-back on the final (sigma_next==0) step + u_here = n_resample if float(sigma_next) > 0.0 else 1 + t_input = timesteps[i].unsqueeze(0).expand(B) + + # Mid-band churn: disable stochasticity on the leading/trailing + # steps so the deterministic finish keeps sharp geometry. + in_band = (i >= first_off) and (i < len(timesteps) - last_off) + eta_here = sde_eta if in_band else 0.0 + + for u in range(u_here): + if use_known: + latents = _inject(latents, sigma) + if ( + deferred_store_index == i + and u == u_here - 1 + ): + deferred_store_query = ( + latents.detach().clone(), + t_input.detach().clone(), + ) + store_exit = ( + store_kv_exit_query + and deferred_store_index is None + and i == len(timesteps) - 1 + and u == u_here - 1 + ) + previous_store = getattr( + self, "_current_sfdmd_store_self_attn_kv", False + ) + if store_exit: + self._current_sfdmd_store_self_attn_kv = True + try: + v = self._get_velocity( + latents, + t_input, + condition, + uncondition, + guidance, + use_cfg, + batched_cfg=batched_cfg, + ) + finally: + if store_exit: + self._current_sfdmd_store_self_attn_kv = previous_store + if debug_nonfinite and not torch.isfinite(v).all(): + raise FloatingPointError( + "SDE received a non-finite velocity prediction at " + f"step {i + 1}/{len(timesteps)}, resample={u + 1}/" + f"{u_here}, sigma={float(sigma):.6g}; " + f"latents: {_tensor_stats(latents)}; " + f"velocity: {_tensor_stats(v)}" + ) + # x_t = (1-sigma)*x0 + sigma*eps, v = eps - x0 + # => x0 = x_t - sigma*v ; eps_implied = v + x0 + x0 = latents - sigma * v + eps_implied = v + x0 + if eta_here > 0.0 and float(sigma_next) > 0.0: + eps_fresh = torch.randn( + latents.shape, generator=gen, + device=latents.device, dtype=latents.dtype, + ) + if geometry_source is not None: + eps_fresh = confidence_weighted_geometry_source( + eps_fresh, + geometry_source, + geometry_confidence, + geometry_noise_floor, + ) + eps_used = (1.0 - eta_here) * eps_implied + eta_here * eps_fresh + else: + eps_used = eps_implied + latents = (1.0 - sigma_next) * x0 + sigma_next * eps_used + if debug_nonfinite and not torch.isfinite(latents).all(): + raise FloatingPointError( + "SDE produced non-finite latents after " + f"step {i + 1}/{len(timesteps)}, resample={u + 1}/" + f"{u_here}, sigma={float(sigma):.6g}, " + f"sigma_next={float(sigma_next):.6g}; " + f"velocity: {_tensor_stats(v)}; " + f"latents: {_tensor_stats(latents)}" + ) + + if u < u_here - 1: + # jump back up to sigma (forward-diffuse the current x0 + # estimate) for another harmonization pass. + eps_jb = torch.randn( + latents.shape, generator=gen, + device=latents.device, dtype=latents.dtype, + ) + if geometry_source is not None: + eps_jb = confidence_weighted_geometry_source( + eps_jb, + geometry_source, + geometry_confidence, + geometry_noise_floor, + ) + latents = (1.0 - sigma) * x0 + sigma * eps_jb + + if early_stop_t is not None: + next_t_norm = float(sigma_next) + if next_t_norm <= float(early_stop_t): + self.last_sampling_exit_t = next_t_norm + log.info( + f"_generate_sde: early-stopping at step {i + 1}/" + f"{len(timesteps)} (sigma={next_t_norm:.4f} <= " + f"early_stop_t={early_stop_t})" + ) + break + + if use_known: + latents = torch.where(km, known_latents, latents) + + if deferred_store_index is not None: + if deferred_store_query is None: + raise RuntimeError( + "SDE sampling ended before the requested K/V query sigma" + ) + query_latents, query_timestep = deferred_store_query + previous_store = getattr( + self, "_current_sfdmd_store_self_attn_kv", False + ) + self._current_sfdmd_store_self_attn_kv = True + try: + self._get_velocity( + query_latents, + query_timestep, + condition, + uncondition, + guidance, + use_cfg, + batched_cfg=batched_cfg, + ) + finally: + self._current_sfdmd_store_self_attn_kv = previous_store + + return latents + + # ---- Euler / Heun sampler ---- + + @torch.no_grad() + def _generate_euler_heun( + self, latents, condition, uncondition, guidance, use_cfg, + B, num_steps, sampler, + ) -> Tensor: + # sigma goes from 1 (noise) to 0 (clean); network expects + # discrete timesteps = sigma * 1000. + sigmas = torch.linspace(1.0, 0.0, num_steps + 1, device="cuda") + + for i in range(num_steps): + sigma = sigmas[i] + sigma_next = sigmas[i + 1] + d_sigma = sigma_next - sigma # negative (moving toward clean) + + t_input = (sigma * 1000.0).unsqueeze(0).expand(B) + v = self._get_velocity( + latents, t_input, condition, uncondition, guidance, use_cfg, + ) + + if sampler == "heun" and i < num_steps - 1: + latents_euler = latents + d_sigma * v + t_next_input = (sigma_next * 1000.0).unsqueeze(0).expand(B) + v_next = self._get_velocity( + latents_euler, t_next_input, condition, uncondition, + guidance, use_cfg, + ) + latents = latents + d_sigma * 0.5 * (v + v_next) + else: + latents = latents + d_sigma * v + + return latents + + # ------------------------------------------------------------------ + # Validation — reuses parent's validation_step which calls + # generate_samples_from_batch (now the RF version above). + # ------------------------------------------------------------------ + + +class HdmapToLidarAutoregressiveRFModel(HdmapToLidarRectifiedFlowModel): + """Single-frame RF model conditioned on the preceding LiDAR latent.""" + + def build_model(self) -> torch.nn.ModuleDict: + model = super().build_model() + latent_channels = int(self.config.latent_shape[0]) + condition_count = int( + getattr(self.config, "autoregressive_condition_count", 1) + ) + old_channels = 2 * latent_channels + 1 + new_channels = ( + (2 + condition_count) * latent_channels + 1 + ) + model["net"].x_embedder.proj[ + 1 + ]._checkpoint_zero_init_input_expansion = ( + 2 * latent_channels, + old_channels, + new_channels, + ) + if bool( + getattr(self.config, "autoregressive_pose_film", False) + ): + model["autoregressive_pose_film"] = _RelativePoseFiLM( + latent_channels, + int( + getattr( + self.config, + "autoregressive_pose_film_hidden_channels", + 256, + ) + ), + ) + return model + + def __init__(self, config): + super().__init__(config) + self.autoregressive_condition_count = int( + getattr(config, "autoregressive_condition_count", 1) + ) + self.autoregressive_pose_film = bool( + getattr(config, "autoregressive_pose_film", False) + ) + self.autoregressive_ego_action_only = bool( + getattr(config, "autoregressive_ego_action_only", False) + ) + self.autoregressive_noise_modulation_max = float( + getattr( + config, + "autoregressive_noise_modulation_max", + 0.0, + ) + ) + if self.autoregressive_condition_count <= 0: + raise ValueError( + "autoregressive_condition_count must be positive" + ) + if not 0.0 <= self.autoregressive_noise_modulation_max <= 1.0: + raise ValueError( + "autoregressive_noise_modulation_max must be in [0,1]" + ) + # The LaGen paper applies the same condition-noise distribution during + # autoregressive inference. Keep that behavior opt-in so existing + # checkpoints and sampling commands remain unchanged. + self.autoregressive_noise_modulation_inference = False + self._current_autoregressive_condition: Optional[Tensor] = None + + def _apply_noise_modulation(self, latent: Tensor) -> Tensor: + if ( + self.autoregressive_noise_modulation_max == 0.0 + or ( + not self.training + and not self.autoregressive_noise_modulation_inference + ) + ): + return latent + tau = torch.rand( + (latent.shape[0],), + device=latent.device, + dtype=torch.float32, + ) * self.autoregressive_noise_modulation_max + tau = tau.to(latent.dtype).view( + latent.shape[0], 1, 1, 1, 1 + ) + return (1.0 - tau) * latent + tau * torch.randn_like(latent) + + def _previous_latent( + self, data_batch: dict[str, Tensor] + ) -> Tensor: + previous = data_batch.get("autoregressive_previous_video") + poses = data_batch.get("autoregressive_lidar_to_world") + if previous is None or poses is None: + raise KeyError( + "autoregressive training requires previous video and poses" + ) + previous_z = self.encode(previous) + if self.autoregressive_pose_film: + poses = torch.as_tensor( + poses, device=previous_z.device, dtype=torch.float32 + ) + if poses.shape[1:] != (2, 4, 4): + raise ValueError( + "autoregressive poses must be (B,2,4,4), got " + f"{tuple(poses.shape)}" + ) + relative = torch.linalg.inv(poses[:, 1]) @ poses[:, 0] + previous_z = self.model["autoregressive_pose_film"]( + previous_z, relative.to(previous_z.dtype) + ) + return self._apply_noise_modulation(previous_z) + + def _build_autoregressive_condition( + self, data_batch: dict[str, Tensor] + ) -> Tensor: + return self._previous_latent(data_batch) + + def get_data_and_condition( + self, data_batch: dict[str, Tensor] + ): + raw_state, latent_state, condition = ( + super().get_data_and_condition(data_batch) + ) + if self.autoregressive_ego_action_only: + if self._current_hdmap is None: + raise RuntimeError( + "ego-action-only autoregression requires the retained " + "HDMap latent slot" + ) + self._current_hdmap = torch.zeros_like(self._current_hdmap) + autoregressive = self._build_autoregressive_condition( + data_batch + ) + expected = ( + self.autoregressive_condition_count + * int(self.config.latent_shape[0]) + ) + if autoregressive.shape[1] != expected: + raise ValueError( + "autoregressive condition channel mismatch: " + f"expected {expected}, got {autoregressive.shape[1]}" + ) + self._current_autoregressive_condition = autoregressive + return raw_state, latent_state, condition + + +class HdmapToLidarLaGenSDERFModel( + HdmapToLidarAutoregressiveRFModel +): + """LaGen-SDE adaptation with foreground/background latent conditions.""" + + def __init__(self, config): + super().__init__(config) + if self.autoregressive_condition_count != 3: + raise ValueError( + "LaGen-SDE requires autoregressive_condition_count=3" + ) + if not self.autoregressive_pose_film: + raise ValueError("LaGen-SDE requires autoregressive_pose_film") + self.autoregressive_geometry_root_path = str( + getattr(config, "autoregressive_geometry_root_path", "") + ) + self.autoregressive_geometry_filter_list = str( + getattr(config, "autoregressive_geometry_filter_list", "") + ) + self.autoregressive_min_range = float( + getattr(config, "autoregressive_min_range", 2.5) + ) + self.autoregressive_max_range = float( + getattr(config, "autoregressive_max_range", 75.0) + ) + self.autoregressive_min_value = float( + getattr(config, "autoregressive_min_value", -1.0) + ) + self.autoregressive_inverse_depth = bool( + getattr(config, "autoregressive_inverse_depth", False) + ) + self._autoregressive_geometry = None + + def _geometry(self): + if self._autoregressive_geometry is None: + self._autoregressive_geometry = load_waymo_lidar_geometry( + root_path=self.autoregressive_geometry_root_path, + filter_list_path=( + self.autoregressive_geometry_filter_list or None + ), + resample_width=1024, + ) + return self._autoregressive_geometry + + def _build_autoregressive_condition( + self, data_batch: dict[str, Tensor] + ) -> Tensor: + previous_z = self._previous_latent(data_batch) + required = ( + "autoregressive_previous_video", + "autoregressive_lidar_to_world", + "moving_box_object_to_world", + "moving_box_lwh", + "moving_box_valid", + "moving_box_type", + ) + missing = [key for key in required if key not in data_batch] + if missing: + raise KeyError( + f"LaGen-SDE missing batch fields: {missing}" + ) + ray_dirs, elev, azim, row_off = self._geometry() + foreground_frames = [] + background_frames = [] + batch_size = int(previous_z.shape[0]) + for batch_idx in range(batch_size): + foreground, background, _ = build_lagen_sde_conditions( + data_batch["autoregressive_previous_video"][batch_idx], + data_batch["autoregressive_lidar_to_world"][batch_idx], + data_batch["moving_box_object_to_world"][batch_idx], + data_batch["moving_box_lwh"][batch_idx], + data_batch["moving_box_valid"][batch_idx], + data_batch["moving_box_type"][batch_idx], + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=self.autoregressive_min_range, + max_range=self.autoregressive_max_range, + min_value=self.autoregressive_min_value, + inverse_depth=self.autoregressive_inverse_depth, + ) + foreground_frames.append(foreground) + background_frames.append(background) + foreground_z = self._apply_noise_modulation( + self.encode(torch.stack(foreground_frames, dim=0)) + ) + background_z = self._apply_noise_modulation( + self.encode(torch.stack(background_frames, dim=0)) + ) + return torch.cat( + [previous_z, foreground_z, background_z], dim=1 + ) + + +class HdmapToLidarDiffusionForcingRFModel(HdmapToLidarRectifiedFlowModel): + """Block-causal Diffusion Forcing for HDMap-conditioned LiDAR. + + Training samples one independent RF time per temporal block and keeps the + standard velocity-matching objective. SDE continuation treats + ``known_latents`` as committed clean context (t=0) by default; sparse + resimulation can explicitly select RePaint-style active-sigma clamping. + """ + + def __init__(self, config): + super().__init__(config) + self.df_block_size = int( + getattr(config, "diffusion_forcing_block_size", 0) + ) + self.df_temporal_prefix_frames = int( + getattr(config.net, "temporal_prefix_frames", 0) + ) + self.df_artifixer_matching = bool( + getattr( + config, "diffusion_forcing_artifixer_matching", False + ) + ) + self.input_video_has_prepend = bool( + getattr(config, "input_video_has_prepend", True) + ) + self.blockwise_warped_history_condition = bool( + getattr(config, "blockwise_warped_history_condition", False) + ) + self.blockwise_warped_history_concat = bool( + getattr(config, "blockwise_warped_history_concat", False) + ) + self.blockwise_warped_history_backend = str( + getattr(config, "blockwise_warped_history_backend", "dataloader") + ) + self.blockwise_geometry_source = bool( + getattr(config, "blockwise_geometry_source", False) + ) + self.blockwise_geometry_source_noise_floor = float( + getattr(config, "blockwise_geometry_source_noise_floor", 0.2) + ) + self.blockwise_geometry_source_preencode_confidence = bool( + getattr( + config, + "blockwise_geometry_source_preencode_confidence", + False, + ) + ) + self.blockwise_geometry_source_dropout_prob = float( + getattr( + config, "blockwise_geometry_source_dropout_prob", 0.0 + ) + ) + self.blockwise_geometry_source_density_kernel = int( + getattr(config, "blockwise_geometry_source_density_kernel", 5) + ) + self.blockwise_geometry_source_density_saturation_hits = float( + getattr( + config, + "blockwise_geometry_source_density_saturation_hits", + 5.0, + ) + ) + self._current_blockwise_warped_history: Optional[Tensor] = None + self._current_blockwise_geometry_source: Optional[Tensor] = None + self._current_blockwise_geometry_confidence: Optional[Tensor] = None + self._current_blockwise_self_prediction_fraction: Optional[Tensor] = None + self._capture_blockwise_warped_history_input = False + self._captured_blockwise_warped_history_input: Optional[Tensor] = None + self.blockwise_spatial_map_self_prediction_prob = float( + getattr( + config, + "blockwise_spatial_map_self_prediction_prob", + 0.0, + ) + ) + self._blockwise_spatial_map_geometry = None + assert self.df_block_size > 0, ( + "HdmapToLidarDiffusionForcingRFModel requires " + "diffusion_forcing_block_size > 0" + ) + if self.df_temporal_prefix_frames < 0: + raise ValueError( + "net.temporal_prefix_frames must be non-negative" + ) + if self.blockwise_warped_history_backend not in ( + "dataloader", + "torch_spatial_map", + ): + raise ValueError( + "blockwise_warped_history_backend must be 'dataloader' or " + f"'torch_spatial_map', got " + f"{self.blockwise_warped_history_backend!r}" + ) + if ( + self.blockwise_warped_history_backend == "torch_spatial_map" + and not self.blockwise_warped_history_condition + ): + raise ValueError( + "torch_spatial_map backend requires " + "blockwise_warped_history_condition=True" + ) + if ( + self.blockwise_warped_history_concat + and not self.blockwise_warped_history_condition + ): + raise ValueError( + "blockwise_warped_history_concat requires " + "blockwise_warped_history_condition=True" + ) + if not 0.0 <= self.blockwise_spatial_map_self_prediction_prob <= 1.0: + raise ValueError( + "blockwise_spatial_map_self_prediction_prob must be in [0,1]" + ) + if ( + self.blockwise_spatial_map_self_prediction_prob > 0.0 + and self.blockwise_warped_history_backend != "torch_spatial_map" + ): + raise ValueError( + "blockwise_spatial_map_self_prediction_prob requires the " + "torch_spatial_map history backend" + ) + if self.blockwise_geometry_source: + if self.blockwise_warped_history_backend != "torch_spatial_map": + raise ValueError( + "blockwise_geometry_source requires the " + "torch_spatial_map history backend" + ) + if not 0.0 <= self.blockwise_geometry_source_noise_floor <= 1.0: + raise ValueError( + "blockwise_geometry_source_noise_floor must be in [0,1]" + ) + if not ( + 0.0 + <= self.blockwise_geometry_source_dropout_prob + <= 1.0 + ): + raise ValueError( + "blockwise_geometry_source_dropout_prob must be in [0,1]" + ) + if ( + self.blockwise_geometry_source_density_kernel <= 0 + or self.blockwise_geometry_source_density_kernel % 2 == 0 + ): + raise ValueError( + "blockwise_geometry_source_density_kernel must be a " + "positive odd integer" + ) + if self.blockwise_geometry_source_density_saturation_hits <= 0.0: + raise ValueError( + "blockwise_geometry_source_density_saturation_hits must " + "be positive" + ) + if self.blockwise_warped_history_backend == "torch_spatial_map": + self._blockwise_spatial_map_radius_m = float( + getattr(config, "blockwise_spatial_map_radius_m") + ) + self._blockwise_spatial_map_voxel_m = float( + getattr(config, "blockwise_spatial_map_voxel_m") + ) + self._blockwise_spatial_map_voxel_policy = str( + getattr(config, "blockwise_spatial_map_voxel_policy") + ) + self._blockwise_spatial_map_observation_unit = str( + getattr( + config, + "blockwise_spatial_map_observation_unit", + "block", + ) + ) + if self._blockwise_spatial_map_observation_unit not in ( + "block", + "frame", + ): + raise ValueError( + "blockwise_spatial_map_observation_unit must be " + "'block' or 'frame'" + ) + self._blockwise_spatial_map_static_min_observations = int( + getattr( + config, + "blockwise_spatial_map_static_min_observations", + ) + ) + self._blockwise_spatial_map_candidate_ttl_updates = int( + getattr( + config, + "blockwise_spatial_map_candidate_ttl_updates", + ) + ) + self._blockwise_spatial_map_include_latest = bool( + getattr(config, "blockwise_spatial_map_include_latest") + ) + self._blockwise_spatial_map_free_space_clear = bool( + getattr(config, "blockwise_spatial_map_free_space_clear") + ) + self._blockwise_spatial_map_free_space_margin_m = float( + getattr(config, "blockwise_spatial_map_free_space_margin_m") + ) + self._blockwise_spatial_map_free_space_misses_to_remove = int( + getattr( + config, + "blockwise_spatial_map_free_space_misses_to_remove", + ) + ) + self._blockwise_spatial_map_min_range = float( + getattr(config, "blockwise_spatial_map_min_range") + ) + self._blockwise_spatial_map_max_range = float( + getattr(config, "blockwise_spatial_map_max_range") + ) + self._blockwise_spatial_map_min_value = float( + getattr(config, "blockwise_spatial_map_min_value") + ) + self._blockwise_spatial_map_inverse_depth = bool( + getattr(config, "blockwise_spatial_map_inverse_depth") + ) + self._blockwise_spatial_map_geometry_root_path = str( + getattr(config, "blockwise_spatial_map_geometry_root_path") + ) + self._blockwise_spatial_map_geometry_filter_list_path = str( + getattr( + config, + "blockwise_spatial_map_geometry_filter_list_path", + ) + ) + self._blockwise_spatial_map_geometry_resample_width = int( + getattr( + config, + "blockwise_spatial_map_geometry_resample_width", + -1, + ) + ) + net_block_size = int(getattr(config.net, "temporal_block_size", 0)) + factorized_bidirectional_stage1 = bool( + getattr(config, "factorized_bidirectional_stage1", False) + ) + expected_net_block_size = self.df_block_size + if factorized_bidirectional_stage1: + expected_net_block_size = 0 + assert net_block_size == expected_net_block_size, ( + f"model diffusion_forcing_block_size={self.df_block_size} expects " + f"net.temporal_block_size={expected_net_block_size}, got " + f"{net_block_size}" + ) + assert self.rf_prediction_type == "velocity", ( + "Diffusion Forcing currently supports rf_prediction_type='velocity' " + f"only, got {self.rf_prediction_type!r}" + ) + if ( + self.df_artifixer_matching + and self.rectified_flow.shift_clamp_percentiles is not None + ): + raise ValueError( + "ArtiFixer-matched Diffusion Forcing requires shift-only " + "timesteps; set shift_clamp_percentiles=None" + ) + net = getattr(self.net, "module", self.net) + side_channels = int(getattr(net, "side_condition_channels", 0)) + expected_side_channels = ( + int(config.latent_shape[0]) + if ( + self.blockwise_warped_history_condition + and not self.blockwise_warped_history_concat + ) + else 0 + ) + assert side_channels == expected_side_channels, ( + "net.side_condition_channels must match the lidar latent channels " + "when blockwise warped history is enabled, and must be zero " + f"otherwise; got {side_channels}, expected {expected_side_channels}" + ) + log.info( + "HdmapToLidarDiffusionForcingRFModel: " + f"block_size={self.df_block_size}, " + f"artifixer_matching={self.df_artifixer_matching}, " + f"input_video_has_prepend={self.input_video_has_prepend}, " + "blockwise_warped_history_condition=" + f"{self.blockwise_warped_history_condition}, " + "blockwise_warped_history_concat=" + f"{self.blockwise_warped_history_concat}, " + "blockwise_warped_history_backend=" + f"{self.blockwise_warped_history_backend}, " + f"blockwise_geometry_source={self.blockwise_geometry_source}, " + "geometry_source_preencode_confidence=" + f"{self.blockwise_geometry_source_preencode_confidence}, " + "blockwise_spatial_map_self_prediction_prob=" + f"{self.blockwise_spatial_map_self_prediction_prob}, " + "blockwise_spatial_map_observation_unit=" + f"{getattr(self, '_blockwise_spatial_map_observation_unit', 'block')}" + ) + + @torch.no_grad() + def _build_torch_spatial_map_history( + self, + raw_state: Tensor, + lidar_to_world: Tensor, + ) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + if self._blockwise_spatial_map_geometry is None: + self._blockwise_spatial_map_geometry = load_waymo_lidar_geometry( + root_path=self._blockwise_spatial_map_geometry_root_path, + filter_list_path=( + self._blockwise_spatial_map_geometry_filter_list_path + ), + resample_width=( + self._blockwise_spatial_map_geometry_resample_width + ), + ) + if raw_state.ndim != 5: + raise ValueError( + "Torch spatial-map history requires raw lidar video shaped " + f"(B,C,T,H,W), got {tuple(raw_state.shape)}" + ) + if lidar_to_world.ndim != 4: + raise ValueError( + "Torch spatial-map history requires lidar_to_world shaped " + f"(B,S,4,4), got {tuple(lidar_to_world.shape)}" + ) + if raw_state.shape[0] != lidar_to_world.shape[0]: + raise ValueError( + "raw lidar and pose batch sizes differ: " + f"{raw_state.shape[0]} vs {lidar_to_world.shape[0]}" + ) + + ray_dirs, elev, azim, row_off = self._blockwise_spatial_map_geometry + if ( + not isinstance(ray_dirs, torch.Tensor) + or ray_dirs.device != raw_state.device + ): + self._blockwise_spatial_map_geometry = tuple( + torch.as_tensor( + value, + device=raw_state.device, + dtype=torch.float32, + ) + for value in (ray_dirs, elev, azim, row_off) + ) + ray_dirs, elev, azim, row_off = ( + self._blockwise_spatial_map_geometry + ) + warped = [] + geometry_source = [] + geometry_confidence = [] + for batch_idx in range(raw_state.shape[0]): + result = warp_blockwise_history_with_spatial_map( + video=raw_state[batch_idx], + lidar_to_world=lidar_to_world[batch_idx], + block_size=self.df_block_size, + prefix_frames=self.df_temporal_prefix_frames, + input_has_prepend=self.input_video_has_prepend, + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=self._blockwise_spatial_map_min_range, + max_range=self._blockwise_spatial_map_max_range, + min_value=self._blockwise_spatial_map_min_value, + inverse_depth=self._blockwise_spatial_map_inverse_depth, + radius_m=self._blockwise_spatial_map_radius_m, + voxel_size_m=self._blockwise_spatial_map_voxel_m, + voxel_policy=self._blockwise_spatial_map_voxel_policy, + observation_unit=( + self._blockwise_spatial_map_observation_unit + ), + static_min_observations=( + self._blockwise_spatial_map_static_min_observations + ), + candidate_ttl_updates=( + self._blockwise_spatial_map_candidate_ttl_updates + ), + include_latest=self._blockwise_spatial_map_include_latest, + free_space_clear=self._blockwise_spatial_map_free_space_clear, + free_space_margin_m=( + self._blockwise_spatial_map_free_space_margin_m + ), + free_space_misses_to_remove=( + self._blockwise_spatial_map_free_space_misses_to_remove + ), + return_soft_source=self.blockwise_geometry_source, + soft_density_kernel=( + self.blockwise_geometry_source_density_kernel + ), + soft_density_saturation_hits=( + self.blockwise_geometry_source_density_saturation_hits + ), + ) + if self.blockwise_geometry_source: + ( + warped_i, + _, + geometry_source_i, + _, + confidence_i, + ) = result + geometry_source.append(geometry_source_i) + geometry_confidence.append(confidence_i) + else: + warped_i, _ = result + warped.append(warped_i) + source = ( + torch.stack(geometry_source, dim=0) + if geometry_source + else None + ) + confidence = ( + torch.stack(geometry_confidence, dim=0) + if geometry_confidence + else None + ) + return torch.stack(warped, dim=0), source, confidence + + @torch.no_grad() + def _store_blockwise_spatial_map_history( + self, + warped: Tensor, + geometry_source: Optional[Tensor], + geometry_confidence: Optional[Tensor], + latent_state: Tensor, + ) -> None: + side_history = warped + if self.blockwise_geometry_source: + if geometry_source is None or geometry_confidence is None: + raise RuntimeError( + "geometry-source training did not produce source and confidence" + ) + confidence = geometry_confidence[:, None] + side_history = confidence_composite_geometry( + geometry_source, + confidence, + self._blockwise_spatial_map_min_value, + ) + self._captured_blockwise_warped_history_input = None + if self._capture_blockwise_warped_history_input: + self._captured_blockwise_warped_history_input = ( + side_history.detach().float().cpu().contiguous() + ) + warped_z = self.encode( + side_history.to(device=latent_state.device).float() + ).contiguous() + if warped_z.shape != latent_state.shape: + raise ValueError( + "blockwise warped-history latent must match lidar latent shape: " + f"got {tuple(warped_z.shape)} vs {tuple(latent_state.shape)}" + ) + self._current_blockwise_warped_history = warped_z.to( + self.diffusion_dtype + ) + self._current_blockwise_geometry_source = None + self._current_blockwise_geometry_confidence = None + if not self.blockwise_geometry_source: + return + assert geometry_source is not None + assert geometry_confidence is not None + source_input = ( + side_history + if self.blockwise_geometry_source_preencode_confidence + else geometry_source + ) + source_z = self.encode( + source_input.to(device=latent_state.device).float() + ).contiguous() + if source_z.shape != latent_state.shape: + raise ValueError( + "blockwise geometry-source latent must match lidar latent shape: " + f"got {tuple(source_z.shape)} vs {tuple(latent_state.shape)}" + ) + self._current_blockwise_geometry_source = source_z.to( + self.diffusion_dtype + ) + confidence_5d = geometry_confidence[:, None].to( + device=source_z.device, dtype=torch.float32 + ) + self._current_blockwise_geometry_confidence = ( + torch.nn.functional.adaptive_avg_pool3d( + confidence_5d, source_z.shape[2:] + ).clamp_(0.0, 1.0) + ) + + @torch.no_grad() + def _one_step_euler_history_prediction( + self, + latent_state: Tensor, + condition, + *, + raw_state: Optional[Tensor] = None, + ) -> Tensor: + del raw_state + epsilon = torch.randn( + latent_state.shape, **self.tensor_kwargs_fp32 + ) + source = epsilon + if self.blockwise_geometry_source: + geometry = self._current_blockwise_geometry_source + confidence = self._current_blockwise_geometry_confidence + if geometry is None or confidence is None: + raise RuntimeError( + "one-step history prediction requires geometry and confidence" + ) + source_weight = ( + 1.0 - self.blockwise_geometry_source_noise_floor + ) * confidence.float() + source = ( + source_weight * geometry.float() + + (1.0 - source_weight) * epsilon + ) + timesteps = torch.full( + (latent_state.shape[0], latent_state.shape[2]), + float(self.rectified_flow.num_train_timesteps), + **self.tensor_kwargs_fp32, + ) + velocity = self._rf_network_forward( + source.to(**self.tensor_kwargs), timesteps, condition + ).float() + return self.decode(source - velocity).detach() + + def get_data_and_condition( + self, data_batch: dict[str, Tensor], + ): + raw_state, latent_state, condition = super().get_data_and_condition( + data_batch + ) + self._current_blockwise_geometry_source = None + self._current_blockwise_geometry_confidence = None + self._current_blockwise_self_prediction_fraction = None + if not self.blockwise_warped_history_condition: + self._current_blockwise_warped_history = None + return raw_state, latent_state, condition + + if self.blockwise_warped_history_backend == "torch_spatial_map": + poses = data_batch.get("lidar_to_world") + if poses is None: + raise KeyError( + "torch_spatial_map history requires " + "data_batch['lidar_to_world']" + ) + warped, geometry_source, geometry_confidence = ( + self._build_torch_spatial_map_history(raw_state, poses) + ) + else: + geometry_source = None + geometry_confidence = None + warped = data_batch.get("lidar_blockwise_warped_history") + if warped is None: + raise KeyError( + "blockwise_warped_history_condition=True with dataloader " + "backend requires " + "data_batch['lidar_blockwise_warped_history']" + ) + self._store_blockwise_spatial_map_history( + warped, + geometry_source, + geometry_confidence, + latent_state, + ) + self_prediction_prob = self.blockwise_spatial_map_self_prediction_prob + if self.training and self_prediction_prob > 0.0: + # This branch contains an extra FSDP forward, so every rank in the + # process mesh must preserve the same collective ordering. + use_self_prediction = _sample_world_synchronized_bernoulli( + self_prediction_prob, + raw_state.device, + ) + self_prediction_mask = use_self_prediction.repeat( + raw_state.shape[0] + ) + self._current_blockwise_self_prediction_fraction = ( + self_prediction_mask.float().mean() + ) + if bool(use_self_prediction): + predicted = self._one_step_euler_history_prediction( + latent_state, + condition, + raw_state=raw_state, + ).to(device=raw_state.device, dtype=raw_state.dtype) + if predicted.shape != raw_state.shape: + raise ValueError( + "one-step decoded history must match raw lidar shape: " + f"got {tuple(predicted.shape)} vs " + f"{tuple(raw_state.shape)}" + ) + mask = self_prediction_mask.view( + -1, *([1] * (raw_state.ndim - 1)) + ) + history_state = torch.where(mask, predicted, raw_state) + warped, geometry_source, geometry_confidence = ( + self._build_torch_spatial_map_history( + history_state, poses + ) + ) + self._store_blockwise_spatial_map_history( + warped, + geometry_source, + geometry_confidence, + latent_state, + ) + return raw_state, latent_state, condition + + def _online_condition_inputs( + self, + data_batch: dict[str, Tensor], + *, + allow_training: bool = False, + ) -> tuple[Tensor, Tensor]: + if self.training and not allow_training: + raise RuntimeError("get_online_condition is inference-only") + if not self.blockwise_warped_history_condition: + raise RuntimeError( + "get_online_condition requires blockwise warp conditioning" + ) + if ( + not self.encode_hdmap_with_vae + or self.bev_hdmap_wan is not None + or self.bev_hdmap_pool is not None + ): + raise NotImplementedError( + "online joint encoding currently requires VAE-encoded " + "range-image HDMap conditioning" + ) + + self._normalize_video_databatch_inplace(data_batch) + self._augment_image_dim_inplace(data_batch) + if self.is_image_batch(data_batch): + raise ValueError("online joint encoding requires a video batch") + + hdmap = data_batch.get("lidar_hdmap") + warped = data_batch.get("lidar_blockwise_warped_history") + if hdmap is None or warped is None: + raise KeyError( + "online joint encoding requires lidar_hdmap and " + "lidar_blockwise_warped_history" + ) + if ( + hdmap.shape[0] != warped.shape[0] + or hdmap.shape[2:] != warped.shape[2:] + ): + raise ValueError( + "HDMap and warped-history inputs must align for joint encode: " + f"hdmap={tuple(hdmap.shape)}, warped={tuple(warped.shape)}" + ) + if getattr(self, "intensity_vae", None) is None: + if hdmap.shape[1] != warped.shape[1]: + raise ValueError( + "range-only HDMap and geometry must have equal channels" + ) + elif hdmap.shape[1] != 1 or warped.shape[1] != 2: + raise ValueError( + "paired intensity conditioning requires C=1 HDMap and C=2 " + f"range/intensity geometry, got {tuple(hdmap.shape)} and " + f"{tuple(warped.shape)}" + ) + return hdmap, warped + + def _store_online_condition( + self, + data_batch: dict[str, Tensor], + hdmap_z: Tensor, + warped_z: Tensor, + ): + if ( + hdmap_z.shape[0] != warped_z.shape[0] + or hdmap_z.shape[2:] != warped_z.shape[2:] + ): + raise ValueError( + "HDMap and warp latent grids must align: " + f"hdmap={tuple(hdmap_z.shape)}, " + f"warped={tuple(warped_z.shape)}" + ) + if hdmap_z.shape[1] != self._hdmap_concat_ch: + raise ValueError( + "HDMap condition has incompatible channels: " + f"got {hdmap_z.shape[1]}, expected {self._hdmap_concat_ch}" + ) + if warped_z.shape[1] != self.state_shape[0]: + raise ValueError( + "geometry condition has incompatible channels: " + f"got {warped_z.shape[1]}, expected {self.state_shape[0]}" + ) + if tuple(hdmap_z.shape[3:]) != tuple(self.state_shape[2:]): + raise ValueError( + "condition latent has incompatible spatial shape: " + f"got {tuple(hdmap_z.shape[3:])}, expected " + f"{tuple(self.state_shape[2:])}" + ) + self._store_hdmap_latent(hdmap_z.to(self.diffusion_dtype)) + self._current_blockwise_warped_history = warped_z.to( + self.diffusion_dtype + ) + condition = self.conditioner(data_batch) + condition.data_type = DataType.VIDEO + return condition + + @torch.no_grad() + def get_online_condition(self, data_batch: dict[str, Tensor]): + """Encode full HDMap and generated-warp windows in one VAE call.""" + hdmap, warped = self._online_condition_inputs(data_batch) + if getattr(self, "_hdmap_force_zero_latent", False): + warped_z = self.encode(warped.float()).contiguous() + hdmap_z = warped_z.new_zeros( + warped_z.shape[0], + self._hdmap_concat_ch, + *warped_z.shape[2:], + ) + else: + hdmap_z = self.encode(hdmap.float()).contiguous() + warped_z = self.encode(warped.float()).contiguous() + if hdmap_z.shape[2] != self.state_shape[1]: + raise ValueError( + f"full condition encode returned T={hdmap_z.shape[2]}, " + f"expected {self.state_shape[1]}" + ) + return self._store_online_condition( + data_batch, hdmap_z, warped_z + ) + + @torch.no_grad() + def get_online_condition_stream( + self, + data_batch: dict[str, Tensor], + temporal_kv_cache=None, + max_cache_frames: int | None = None, + allow_training: bool = False, + ): + """Causally encode only the newly active HDMap and warp frames.""" + hdmap, warped = self._online_condition_inputs( + data_batch, + allow_training=allow_training, + ) + cache = temporal_kv_cache + if getattr(self, "intensity_vae", None) is not None: + if cache is None: + cache = {"hdmap": None, "geometry": None} + elif not isinstance(cache, dict) or set(cache) != { + "hdmap", + "geometry", + }: + raise ValueError( + "paired online condition cache must contain exactly " + "'hdmap' and 'geometry'" + ) + warped_z, geometry_cache = self.encode_stream( + warped.float(), + temporal_kv_cache=cache["geometry"], + max_cache_frames=max_cache_frames, + ) + if getattr(self, "_hdmap_force_zero_latent", False): + hdmap_z = warped_z.new_zeros( + warped_z.shape[0], + self._hdmap_concat_ch, + *warped_z.shape[2:], + ) + hdmap_cache = cache["hdmap"] + else: + hdmap_z, hdmap_cache = self.encode_stream( + hdmap.float(), + temporal_kv_cache=cache["hdmap"], + max_cache_frames=max_cache_frames, + ) + condition = self._store_online_condition( + data_batch, hdmap_z.contiguous(), warped_z.contiguous() + ) + return condition, { + "hdmap": hdmap_cache, + "geometry": geometry_cache, + } + + batch_size = hdmap.shape[0] + if getattr(self, "_hdmap_force_zero_latent", False): + warped_z, new_cache = self.encode_stream( + warped.float(), + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + ) + warped_z = warped_z.contiguous() + hdmap_z = torch.zeros_like(warped_z) + else: + joint_z, new_cache = self.encode_stream( + torch.cat([hdmap.float(), warped.float()], dim=0), + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + ) + joint_z = joint_z.contiguous() + hdmap_z, warped_z = joint_z.split(batch_size, dim=0) + condition = self._store_online_condition( + data_batch, hdmap_z, warped_z + ) + return condition, new_cache + + def _sample_block_timesteps( + self, batch_size: int, num_frames: int, + ) -> tuple[Tensor, Tensor, Tensor]: + """Return block-constant timesteps, sigmas, and loss weights.""" + chunks = temporal_chunk_slices( + num_frames, + self.df_block_size, + self.df_temporal_prefix_frames, + ) + num_blocks = len(chunks) + if self.df_artifixer_matching: + num_train_timesteps = self.rectified_flow.num_train_timesteps + timestep_ids_B_K = torch.randint( + 0, + num_train_timesteps, + (batch_size, num_blocks), + device=self.tensor_kwargs_fp32["device"], + ) + timesteps_B_K, sigmas_B_K, weights_B_K = ( + artifixer_flow_schedule( + timestep_ids_B_K, + num_train_timesteps=num_train_timesteps, + shift=float(self.rectified_flow.shift), + ) + ) + return ( + expand_chunkwise( + timesteps_B_K, + num_frames, + self.df_block_size, + self.df_temporal_prefix_frames, + ), + expand_chunkwise( + sigmas_B_K, + num_frames, + self.df_block_size, + self.df_temporal_prefix_frames, + ), + expand_chunkwise( + weights_B_K, + num_frames, + self.df_block_size, + self.df_temporal_prefix_frames, + ), + ) + + u_B_K = self.rectified_flow.sample_train_time( + batch_size * num_blocks + ).reshape(batch_size, num_blocks) + u_B_T = expand_chunkwise( + u_B_K, + num_frames, + self.df_block_size, + self.df_temporal_prefix_frames, + ) + # ``get_discrete_timestamp`` has a legacy squeeze that drops B for B=1. + sigmas_B_T = self.rectified_flow.apply_shift_reparam(u_B_T) + timesteps_B_T = ( + sigmas_B_T * self.rectified_flow.num_train_timesteps + ) + weights_B_T = self.rectified_flow.train_time_weight( + timesteps_B_T, self.tensor_kwargs_fp32, + ) + return timesteps_B_T, sigmas_B_T, weights_B_T + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor], + ) -> tuple[dict[str, Tensor], Tensor]: + _, x0, condition = self.get_data_and_condition(data_batch) + B, _, T = x0.shape[:3] + epsilon = torch.randn(x0.shape, **self.tensor_kwargs_fp32) + timesteps_B_T, sigmas_B_T, time_weights = ( + self._sample_block_timesteps(B, T) + ) + + x0_f = x0.float() + source = epsilon + source_weight = None + source_dropout_fraction = None + if self.blockwise_geometry_source: + geometry = self._current_blockwise_geometry_source + confidence = self._current_blockwise_geometry_confidence + if geometry is None or confidence is None: + raise RuntimeError( + "geometry-source RF requires geometry and confidence" + ) + expected_confidence_shape = (B, 1, *x0.shape[2:]) + if ( + geometry.shape != x0.shape + or confidence.shape != expected_confidence_shape + ): + raise ValueError( + "geometry-source latent/confidence shapes must match x0: " + f"geometry={tuple(geometry.shape)}, " + f"confidence={tuple(confidence.shape)}, " + f"x0={tuple(x0.shape)}" + ) + source_weight = ( + 1.0 - self.blockwise_geometry_source_noise_floor + ) * confidence.float() + dropout_prob = self.blockwise_geometry_source_dropout_prob + if self.training and dropout_prob > 0.0: + chunks = temporal_chunk_slices( + T, + self.df_block_size, + self.df_temporal_prefix_frames, + ) + num_blocks = len(chunks) + keep_B_K = ( + torch.rand( + (B, num_blocks), + device=x0.device, + dtype=torch.float32, + ) + >= dropout_prob + ).float() + keep_B_K[:, 0] = 1.0 + keep_B_T = expand_chunkwise( + keep_B_K, + T, + self.df_block_size, + self.df_temporal_prefix_frames, + ) + source_weight = source_weight * keep_B_T[ + :, None, :, None, None + ] + source_dropout_fraction = ( + 1.0 - keep_B_K[:, 1:].mean() + if num_blocks > 1 + else keep_B_K.new_zeros(()) + ) + source = ( + source_weight * geometry.float() + + (1.0 - source_weight) * epsilon + ) + sigma_5d = sigmas_B_T[:, None, :, None, None] + xt = source * sigma_5d + x0_f * (1.0 - sigma_5d) + vt_target = source - x0_f + + net_pred = self._rf_network_forward( + xt.to(**self.tensor_kwargs), timesteps_B_T, condition, + ).float() + per_frame_loss = torch.mean( + (net_pred - vt_target) ** 2, + dim=(1, 3, 4), + ) + loss = torch.mean(time_weights * per_frame_loss) + per_instance_loss = per_frame_loss.mean(dim=1) + + output_batch = { + "x0": x0, + "xt": xt, + "sigma": sigmas_B_T, + "model_pred": net_pred, + "edm_loss": loss, + "timesteps": timesteps_B_T, + "per_frame_loss": per_frame_loss, + "per_instance_loss": per_instance_loss, + } + if source_weight is not None: + output_batch.update( + { + "metric/geometry_source_confidence_mean": ( + self._current_blockwise_geometry_confidence.mean() + ), + "metric/geometry_source_weight_mean": ( + source_weight.mean() + ), + "metric/geometry_source_coverage": ( + source_weight > 0.0 + ).float().mean(), + "metric/geometry_source_dropout_fraction": ( + source_dropout_fraction + if source_dropout_fraction is not None + else source_weight.new_zeros(()) + ), + } + ) + self_prediction_fraction = getattr( + self, "_current_blockwise_self_prediction_fraction", None + ) + if self_prediction_fraction is not None: + output_batch[ + "metric/spatial_map_self_prediction_fraction" + ] = self_prediction_fraction + return output_batch, loss + + @torch.no_grad() + def _generate_sde( + self, latents, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, sde_eta, + early_stop_t: Optional[float] = None, + known_latents: Optional[Tensor] = None, + known_mask: Optional[Tensor] = None, + known_noise: Optional[Tensor] = None, + known_latents_mode: str = "clean_context", + repaint_u: int = 1, + eta_first_frac: float = 0.0, + eta_last_frac: float = 0.0, + batched_cfg: bool = False, + store_kv_exit_query: bool = False, + store_kv_query_sigma: Optional[float] = None, + geometry_source: Optional[Tensor] = None, + geometry_confidence: Optional[Tensor] = None, + geometry_noise_floor: float = 0.0, + ) -> Tensor: + if known_latents_mode == "repaint": + return super()._generate_sde( + latents, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, sde_eta, + early_stop_t=early_stop_t, + known_latents=known_latents, + known_mask=known_mask, + known_noise=known_noise, + repaint_u=repaint_u, + eta_first_frac=eta_first_frac, + eta_last_frac=eta_last_frac, + batched_cfg=batched_cfg, + store_kv_exit_query=store_kv_exit_query, + store_kv_query_sigma=store_kv_query_sigma, + geometry_source=geometry_source, + geometry_confidence=geometry_confidence, + geometry_noise_floor=geometry_noise_floor, + ) + if known_latents_mode not in ("clean_context", "clean_mask"): + raise ValueError( + "known_latents_mode must be 'clean_context', 'clean_mask', " + "or 'repaint'" + ) + if known_noise is not None: + raise ValueError( + "known_noise is only supported with " + "known_latents_mode='repaint'" + ) + + # The first seed window can be sampled jointly; continuation windows + # use the clean-context schedule below. + if known_latents is None: + return super()._generate_sde( + latents, condition, uncondition, guidance, use_cfg, + B, num_steps, shift, seed, sde_eta, + early_stop_t=early_stop_t, + known_latents=None, + known_mask=None, + known_noise=None, + repaint_u=repaint_u, + eta_first_frac=eta_first_frac, + eta_last_frac=eta_last_frac, + batched_cfg=batched_cfg, + store_kv_exit_query=store_kv_exit_query, + store_kv_query_sigma=store_kv_query_sigma, + geometry_source=geometry_source, + geometry_confidence=geometry_confidence, + geometry_noise_floor=geometry_noise_floor, + ) + if geometry_source is not None or geometry_confidence is not None: + raise ValueError( + "geometry-source SDE renoise is only supported by the " + "non-overlapping cached rollout" + ) + if store_kv_query_sigma is not None: + raise NotImplementedError( + "store_kv_query_sigma is not supported with known-latent " + "Diffusion-Forcing continuation" + ) + if repaint_u != 1: + raise ValueError( + "Diffusion-Forcing continuation does not use RePaint " + f"jump-backs; expected repaint_u=1, got {repaint_u}" + ) + if known_mask is None: + raise ValueError("known_mask is required with known_latents") + + T = latents.shape[2] + mask_B_T = known_mask.to(device=latents.device, dtype=torch.bool) + if mask_B_T.ndim == 1: + mask_B_T = mask_B_T.unsqueeze(0).expand(B, -1) + if tuple(mask_B_T.shape) != (B, T): + raise ValueError( + f"known_mask {tuple(mask_B_T.shape)} must be (T={T},) or " + f"(B={B},T={T})" + ) + if known_latents_mode == "clean_context": + try: + validate_prefix_mask(mask_B_T, self.df_block_size) + except ValueError as exc: + raise ValueError( + f"{exc}; use overlap >= " + f"window_frames-{self.df_block_size}" + ) from exc + + known_latents = known_latents.to( + device=latents.device, dtype=latents.dtype, + ) + if tuple(known_latents.shape) != tuple(latents.shape): + raise ValueError( + f"known_latents {tuple(known_latents.shape)} must match " + f"latents {tuple(latents.shape)}" + ) + known_5d = mask_B_T[:, None, :, None, None] + active_5d = ~known_5d + latents = torch.where(known_5d, known_latents, latents) + + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + if shift is None: + shift = self._rf_shift + self.sample_scheduler.set_timesteps( + num_steps, + device="cuda", + shift=shift, + stretch_terminal=self.rectified_flow.shift_stretch_terminal, + ) + sigmas = self.sample_scheduler.sigmas.to("cuda").float() + timesteps = self.sample_scheduler.timesteps + first_off = int(round(max(0.0, eta_first_frac) * num_steps)) + last_off = int(round(max(0.0, eta_last_frac) * num_steps)) + + for i, timestep in enumerate(timesteps): + sigma = sigmas[i] + sigma_next = sigmas[i + 1] + active_timestep_B = timestep.to( + device=latents.device, + ).expand(B) + t_input = build_clean_context_timesteps( + active_timestep_B, + mask_B_T, + ) + latents = torch.where(known_5d, known_latents, latents) + store_exit = store_kv_exit_query and i == len(timesteps) - 1 + previous_store = getattr( + self, "_current_sfdmd_store_self_attn_kv", False + ) + if store_exit: + self._current_sfdmd_store_self_attn_kv = True + try: + velocity = self._get_velocity( + latents, + t_input, + condition, + uncondition, + guidance, + use_cfg, + batched_cfg=batched_cfg, + ) + finally: + if store_exit: + self._current_sfdmd_store_self_attn_kv = previous_store + x0 = latents - sigma * velocity + eps_implied = velocity + x0 + + in_band = ( + i >= first_off and i < len(timesteps) - last_off + ) + eta_here = sde_eta if in_band else 0.0 + if eta_here > 0.0 and float(sigma_next) > 0.0: + eps_fresh = torch.randn( + latents.shape, + generator=gen, + device=latents.device, + dtype=latents.dtype, + ) + eps_used = ( + (1.0 - eta_here) * eps_implied + + eta_here * eps_fresh + ) + else: + eps_used = eps_implied + next_latents = ( + (1.0 - sigma_next) * x0 + sigma_next * eps_used + ) + latents = torch.where( + active_5d, next_latents, known_latents, + ) + + if early_stop_t is not None: + next_t_norm = float(sigma_next) + if next_t_norm <= float(early_stop_t): + self.last_sampling_exit_t = next_t_norm + break + + return torch.where(known_5d, known_latents, latents) + + +class HdmapToLidarTeacherForcingRFModel( + HdmapToLidarDiffusionForcingRFModel +): + """Legacy interleaved clean-prefix teacher forcing for the LiDAR DiT. + + Each noisy block queries K/V produced by clean earlier blocks. One RF time + is shared by the complete sequence. This implementation interleaves each + noisy query and clean cache write; the separate Imaginaire class below uses + a literal complete clean pass followed by a noisy replay pass. + """ + + def __init__(self, config): + super().__init__(config) + self.teacher_forcing_detach_clean_kv = bool( + getattr(config, "teacher_forcing_detach_clean_kv", False) + ) + self.teacher_forcing_loss_scale = float( + getattr(config, "teacher_forcing_loss_scale", 1.0) + ) + if self.teacher_forcing_loss_scale <= 0.0: + raise ValueError("teacher_forcing_loss_scale must be positive") + log.info( + "HdmapToLidarTeacherForcingRFModel: " + "detach_clean_kv=" + f"{self.teacher_forcing_detach_clean_kv}, " + f"loss_scale={self.teacher_forcing_loss_scale}" + ) + + def new_teacher_forcing_kv_cache( + self, + ) -> list[dict[str, Tensor] | None]: + net = self.net + while hasattr(net, "module"): + net = net.module + return [None] * len(net.blocks) + + def _teacher_forcing_block_velocity( + self, + x_t: Tensor, + timesteps: Tensor, + condition, + *, + block_index: int, + total_frames: int, + kv_cache: list[dict[str, Tensor] | None], + store_kv: bool, + detach_kv: bool, + ) -> Tensor: + start = block_index * self.df_block_size + end = start + self.df_block_size + return self._teacher_forcing_chunk_velocity( + x_t, + timesteps, + condition, + start=start, + end=end, + total_frames=total_frames, + kv_cache=kv_cache, + store_kv=store_kv, + detach_kv=detach_kv, + ) + + def _teacher_forcing_chunk_velocity( + self, + x_t: Tensor, + timesteps: Tensor, + condition, + *, + start: int, + end: int, + total_frames: int, + kv_cache: list[dict[str, Tensor] | None], + store_kv: bool, + detach_kv: bool, + ) -> Tensor: + chunk_frames = end - start + if ( + start < 0 + or end > total_frames + or chunk_frames <= 0 + or x_t.shape[2] != chunk_frames + ): + raise ValueError( + "teacher-forcing call does not match its temporal chunk: " + f"chunk=({start},{end}), x_t={tuple(x_t.shape)}, " + f"total_frames={total_frames}" + ) + if self._current_hdmap is None: + raise RuntimeError("teacher forcing requires encoded HDMap") + full_hdmap = self._current_hdmap + full_side = self._current_blockwise_warped_history + if full_hdmap.shape[2] != total_frames: + raise ValueError( + "teacher-forcing HDMap length must match the latent sequence: " + f"hdmap={full_hdmap.shape[2]}, latent={total_frames}" + ) + if full_side is not None and full_side.shape[2] != total_frames: + raise ValueError( + "teacher-forcing side-condition length must match the latent " + f"sequence: side={full_side.shape[2]}, latent={total_frames}" + ) + + names = ( + "_current_hdmap", + "_current_blockwise_warped_history", + "_current_sfdmd_temporal_positions", + "_current_sfdmd_self_attn_kv_cache", + "_current_sfdmd_store_self_attn_kv", + "_current_sfdmd_self_attn_kv_max_frames", + "_current_sfdmd_self_attn_kv_sink_frames", + "_current_sfdmd_detach_self_attn_kv", + "_current_sfdmd_return_self_attn_kv", + "_current_sfdmd_updated_self_attn_kv_cache", + ) + missing = object() + previous = { + name: getattr(self, name, missing) + for name in names + } + self._current_hdmap = full_hdmap[:, :, start:end].contiguous() + self._current_blockwise_warped_history = ( + None + if full_side is None + else full_side[:, :, start:end].contiguous() + ) + self._current_sfdmd_temporal_positions = torch.arange( + start, end, device=x_t.device + ) + self._current_sfdmd_self_attn_kv_cache = kv_cache + self._current_sfdmd_store_self_attn_kv = store_kv + self._current_sfdmd_self_attn_kv_max_frames = total_frames + self._current_sfdmd_self_attn_kv_sink_frames = 0 + self._current_sfdmd_detach_self_attn_kv = detach_kv + self._current_sfdmd_return_self_attn_kv = store_kv + self._current_sfdmd_updated_self_attn_kv_cache = None + try: + velocity = self._rf_network_forward( + x_t.to(**self.tensor_kwargs), timesteps, condition + ).float() + if store_kv: + updated_cache = ( + self._current_sfdmd_updated_self_attn_kv_cache + ) + if updated_cache is None: + raise RuntimeError( + "teacher-forcing clean forward did not return its " + "updated K/V cache" + ) + kv_cache[:] = updated_cache + return velocity + finally: + for name, value in previous.items(): + if value is missing: + if hasattr(self, name): + delattr(self, name) + else: + setattr(self, name, value) + + def _teacher_forcing_chunk_slices( + self, num_frames: int + ) -> list[tuple[int, int]]: + return temporal_chunk_slices(num_frames, self.df_block_size) + + def _sample_teacher_forcing_source( + self, + x0: Tensor, + epsilon: Tensor, + ) -> tuple[Tensor, Tensor | None, Tensor]: + if not self.blockwise_geometry_source: + return epsilon, None, epsilon.new_zeros(()) + geometry = self._current_blockwise_geometry_source + confidence = self._current_blockwise_geometry_confidence + if geometry is None or confidence is None: + raise RuntimeError( + "geometry-source teacher forcing requires geometry and " + "confidence" + ) + expected_confidence_shape = (x0.shape[0], 1, *x0.shape[2:]) + if ( + geometry.shape != x0.shape + or confidence.shape != expected_confidence_shape + ): + raise ValueError( + "geometry-source latent/confidence shapes must match x0: " + f"geometry={tuple(geometry.shape)}, " + f"confidence={tuple(confidence.shape)}, " + f"x0={tuple(x0.shape)}" + ) + source_weight = ( + 1.0 - self.blockwise_geometry_source_noise_floor + ) * confidence.float() + batch_size, _, num_frames = x0.shape[:3] + chunks = self._teacher_forcing_chunk_slices(num_frames) + num_blocks = len(chunks) + dropout_prob = self.blockwise_geometry_source_dropout_prob + dropout_fraction = source_weight.new_zeros(()) + if self.training and dropout_prob > 0.0: + keep_B_K = ( + torch.rand( + (batch_size, num_blocks), + device=x0.device, + dtype=torch.float32, + ) + >= dropout_prob + ).float() + keep_B_K[:, 0] = 1.0 + keep_B_T = keep_B_K.new_empty((batch_size, num_frames)) + for chunk_index, (start, end) in enumerate(chunks): + keep_B_T[:, start:end] = keep_B_K[:, chunk_index, None] + source_weight = source_weight * keep_B_T[ + :, None, :, None, None + ] + if num_blocks > 1: + dropout_fraction = 1.0 - keep_B_K[:, 1:].mean() + source = ( + source_weight * geometry.float() + + (1.0 - source_weight) * epsilon + ) + return source, source_weight, dropout_fraction + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + _, x0, condition = self.get_data_and_condition(data_batch) + batch_size, _, num_frames = x0.shape[:3] + if num_frames % self.df_block_size != 0: + raise ValueError( + "teacher forcing requires complete causal blocks, got " + f"T={num_frames}, block_size={self.df_block_size}" + ) + + epsilon = torch.randn(x0.shape, **self.tensor_kwargs_fp32) + source, source_weight, source_dropout_fraction = ( + self._sample_teacher_forcing_source(x0, epsilon) + ) + sampled_time = self.rectified_flow.sample_train_time(batch_size) + timesteps_B = self.rectified_flow.get_discrete_timestamp( + sampled_time, self.tensor_kwargs_fp32 + ).reshape(batch_size) + sigmas_B = self.rectified_flow.get_sigmas( + timesteps_B, self.tensor_kwargs_fp32 + ).reshape(batch_size) + time_weights = self.rectified_flow.train_time_weight( + timesteps_B[:, None], self.tensor_kwargs_fp32 + ).reshape(batch_size, -1).mean(dim=1) + + x0_float = x0.float() + sigma_5d = sigmas_B[:, None, None, None, None] + x_t = sigma_5d * source + (1.0 - sigma_5d) * x0_float + target = source - x0_float + clean_timesteps = torch.zeros( + (batch_size, self.df_block_size), + device=x0.device, + dtype=torch.float32, + ) + active_timesteps = timesteps_B[:, None].expand( + -1, self.df_block_size + ) + clean_cache = self.new_teacher_forcing_kv_cache() + prediction_blocks = [] + for block_index, start in enumerate( + range(0, num_frames, self.df_block_size) + ): + end = start + self.df_block_size + prediction_blocks.append( + self._teacher_forcing_block_velocity( + x_t[:, :, start:end], + active_timesteps, + condition, + block_index=block_index, + total_frames=num_frames, + kv_cache=clean_cache, + store_kv=False, + detach_kv=self.teacher_forcing_detach_clean_kv, + ) + ) + self._teacher_forcing_block_velocity( + x0[:, :, start:end], + clean_timesteps, + condition, + block_index=block_index, + total_frames=num_frames, + kv_cache=clean_cache, + store_kv=True, + detach_kv=self.teacher_forcing_detach_clean_kv, + ) + + prediction = torch.cat(prediction_blocks, dim=2) + per_frame_loss = ( + prediction - target + ).square().mean(dim=(1, 3, 4)) + per_instance_loss = per_frame_loss.mean(dim=1) + raw_loss = (time_weights * per_instance_loss).mean() + loss = self.teacher_forcing_loss_scale * raw_loss + output_batch = { + "x0": x0, + "xt": x_t, + "sigma": sigmas_B, + "model_pred": prediction, + "edm_loss": loss, + "teacher_forcing_loss": raw_loss, + "timesteps": timesteps_B, + "per_frame_loss": per_frame_loss, + "per_instance_loss": per_instance_loss, + } + if source_weight is not None: + output_batch.update( + { + "metric/geometry_source_confidence_mean": ( + self._current_blockwise_geometry_confidence.mean() + ), + "metric/geometry_source_weight_mean": ( + source_weight.mean() + ), + "metric/geometry_source_coverage": ( + source_weight > 0.0 + ).float().mean(), + "metric/geometry_source_dropout_fraction": ( + source_dropout_fraction + ), + } + ) + return output_batch, loss + + +class HdmapToLidarImaginaireTeacherForcingRFModel( + HdmapToLidarTeacherForcingRFModel +): + """Imaginaire-style two-pass teacher forcing with a singleton prefix.""" + + def __init__(self, config): + super().__init__(config) + if self.input_video_has_prepend: + raise ValueError( + "Imaginaire teacher forcing requires unique input frames; " + "set input_video_has_prepend=False" + ) + if self.blockwise_geometry_source: + raise ValueError( + "Imaginaire teacher forcing requires pure Gaussian RF source" + ) + map_observation_unit = getattr( + self, "_blockwise_spatial_map_observation_unit", "block" + ) + map_static_min_observations = getattr( + self, "_blockwise_spatial_map_static_min_observations", 0 + ) + minimum_map_observations = ( + 3 if map_observation_unit == "block" else 2 + ) + insufficient_map_observations = ( + map_static_min_observations < minimum_map_observations + ) + if ( + not self.blockwise_warped_history_condition + or self.blockwise_warped_history_backend != "torch_spatial_map" + or self._blockwise_spatial_map_include_latest + or insufficient_map_observations + ): + raise ValueError( + "Imaginaire teacher forcing requires strict accumulated " + "geometry side conditioning with no latest sweep and at " + "least three independent map observations in block mode or " + "two distinct-frame observations in frame mode" + ) + self.teacher_forcing_prefix_frames = int( + getattr(config, "teacher_forcing_prefix_frames", 1) + ) + factorized_bidirectional_stage1 = bool( + getattr(config, "factorized_bidirectional_stage1", False) + ) + if self.teacher_forcing_prefix_frames < 0 or ( + self.teacher_forcing_prefix_frames == 0 + and not factorized_bidirectional_stage1 + ): + raise ValueError( + "Imaginaire teacher forcing requires a positive prefix unless " + "the isolated factorized bidirectional Stage 1 is enabled" + ) + self.imaginaire_conditioned_prefix_frames = tuple( + int(value) + for value in getattr( + config, + "imaginaire_conditioned_prefix_frames", + [0, 1], + ) + ) + prefix_probs = tuple( + float(value) + for value in getattr( + config, + "imaginaire_conditioned_prefix_probs", + [0.7, 0.3], + ) + ) + if not self.imaginaire_conditioned_prefix_frames: + self.imaginaire_conditioned_prefix_frames = (0, 1) + if not prefix_probs: + prefix_probs = (0.7, 0.3) + if len(self.imaginaire_conditioned_prefix_frames) != len( + prefix_probs + ): + raise ValueError( + "Imaginaire prefix frames/probabilities must have the same " + "length" + ) + if ( + any(value < 0 for value in self.imaginaire_conditioned_prefix_frames) + or any(value < 0.0 for value in prefix_probs) + or sum(prefix_probs) <= 0.0 + ): + raise ValueError( + "Imaginaire prefix frames must be non-negative and prefix " + "probabilities must have positive mass" + ) + self.imaginaire_conditioned_prefix_probs = torch.tensor( + prefix_probs, dtype=torch.float32 + ) / sum(prefix_probs) + net = self.net + while hasattr(net, "module"): + net = net.module + if factorized_bidirectional_stage1: + invalid_layout = ( + net.temporal_block_size != 0 + or net.temporal_prefix_frames != 0 + ) + else: + invalid_layout = ( + net.temporal_block_size != self.df_block_size + or net.temporal_prefix_frames + != self.teacher_forcing_prefix_frames + ) + if invalid_layout: + raise ValueError( + "Imaginaire teacher-forcing model/network temporal layouts " + "must match: " + f"model={self.teacher_forcing_prefix_frames}+N*" + f"{self.df_block_size}, net={net.temporal_prefix_frames}+N*" + f"{net.temporal_block_size}" + ) + + def _sample_imaginaire_conditioned_prefix( + self, + *, + num_frames: int, + device: torch.device, + ) -> tuple[int, Tensor]: + # Stage 2/3 keep the same graph for every K, so sample independently + # per rank just as Imaginaire samples a plan per training example. + index = int( + torch.multinomial( + self.imaginaire_conditioned_prefix_probs, 1 + ).item() + ) + prefix_frames = self.imaginaire_conditioned_prefix_frames[index] + if prefix_frames >= num_frames: + raise ValueError( + "Imaginaire conditioned prefix must leave at least one noisy " + f"frame, got K={prefix_frames} for T={num_frames}" + ) + noisy_mask = torch.ones( + num_frames, device=device, dtype=torch.float32 + ) + noisy_mask[:prefix_frames] = 0.0 + return prefix_frames, noisy_mask + + def _teacher_forcing_chunk_slices( + self, num_frames: int + ) -> list[tuple[int, int]]: + return temporal_chunk_slices( + num_frames, + self.df_block_size, + self.teacher_forcing_prefix_frames, + ) + + @staticmethod + def _teacher_forcing_prefix_cache( + full_cache: list[dict[str, Tensor] | None], + *, + prefix_frames: int, + total_frames: int, + ) -> list[dict[str, Tensor] | None]: + if prefix_frames == 0: + return [None] * len(full_cache) + prefix_cache = [] + for layer_index, entry in enumerate(full_cache): + if entry is None: + raise RuntimeError( + "clean teacher-forcing cache is incomplete at layer " + f"{layer_index}" + ) + num_tokens = entry["k"].shape[1] + if num_tokens % total_frames != 0: + raise ValueError( + "clean K/V length is not divisible by temporal frames: " + f"tokens={num_tokens}, frames={total_frames}" + ) + prefix_tokens = prefix_frames * (num_tokens // total_frames) + prefix_cache.append( + { + "k": entry["k"][:, :prefix_tokens], + "v": entry["v"][:, :prefix_tokens], + } + ) + return prefix_cache + + def _build_complete_clean_cache( + self, + x0: Tensor, + condition, + ) -> list[dict[str, Tensor] | None]: + batch_size, _, num_frames = x0.shape[:3] + clean_cache = self.new_teacher_forcing_kv_cache() + for frame_index in range(num_frames): + clean_timesteps = torch.zeros( + (batch_size, 1), + device=x0.device, + dtype=torch.float32, + ) + self._teacher_forcing_chunk_velocity( + x0[:, :, frame_index : frame_index + 1], + clean_timesteps, + condition, + start=frame_index, + end=frame_index + 1, + total_frames=num_frames, + kv_cache=clean_cache, + store_kv=True, + detach_kv=self.teacher_forcing_detach_clean_kv, + ) + return clean_cache + + def _reduce_teacher_forcing_per_frame_loss( + self, + per_frame_loss: Tensor, + noisy_mask_T: Tensor, + ) -> Tensor: + del noisy_mask_T + return per_frame_loss.mean(dim=1) + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + _, x0, condition = self.get_data_and_condition(data_batch) + batch_size, _, num_frames = x0.shape[:3] + chunks = self._teacher_forcing_chunk_slices(num_frames) + conditioned_prefix_frames, noisy_mask_T = ( + self._sample_imaginaire_conditioned_prefix( + num_frames=num_frames, + device=x0.device, + ) + ) + + epsilon = torch.randn(x0.shape, **self.tensor_kwargs_fp32) + source, source_weight, source_dropout_fraction = ( + self._sample_teacher_forcing_source(x0, epsilon) + ) + sampled_time = self.rectified_flow.sample_train_time(batch_size) + timesteps_B = self.rectified_flow.get_discrete_timestamp( + sampled_time, self.tensor_kwargs_fp32 + ).reshape(batch_size) + sigmas_B = self.rectified_flow.get_sigmas( + timesteps_B, self.tensor_kwargs_fp32 + ).reshape(batch_size) + time_weights = self.rectified_flow.train_time_weight( + timesteps_B[:, None], self.tensor_kwargs_fp32 + ).reshape(batch_size, -1).mean(dim=1) + + x0_float = x0.float() + sigma_B_T = sigmas_B[:, None] * noisy_mask_T[None] + sigma_5d = sigma_B_T[:, None, :, None, None] + x_t = sigma_5d * source + (1.0 - sigma_5d) * x0_float + target = source - x0_float + + # Pass 1 builds complete clean replay K/V. Pass 2 gives each noisy + # chunk only the clean chunks that precede it. + clean_cache = self._build_complete_clean_cache(x0, condition) + prediction_blocks = [] + for start, end in chunks: + active_timesteps = ( + timesteps_B[:, None] + * noisy_mask_T[None, start:end] + ) + prefix_cache = self._teacher_forcing_prefix_cache( + clean_cache, + prefix_frames=start, + total_frames=num_frames, + ) + prediction_blocks.append( + self._teacher_forcing_chunk_velocity( + x_t[:, :, start:end], + active_timesteps, + condition, + start=start, + end=end, + total_frames=num_frames, + kv_cache=prefix_cache, + store_kv=False, + detach_kv=self.teacher_forcing_detach_clean_kv, + ) + ) + + prediction = torch.cat(prediction_blocks, dim=2) + per_frame_loss = ( + prediction - target + ).square().mean(dim=(1, 3, 4)) * noisy_mask_T[None] + per_instance_loss = self._reduce_teacher_forcing_per_frame_loss( + per_frame_loss, noisy_mask_T + ) + raw_loss = (time_weights * per_instance_loss).mean() + loss = self.teacher_forcing_loss_scale * raw_loss + output_batch = { + "x0": x0, + "xt": x_t, + "sigma": sigmas_B, + "model_pred": prediction, + "edm_loss": loss, + "teacher_forcing_loss": raw_loss, + "timesteps": timesteps_B, + "per_frame_loss": per_frame_loss, + "per_instance_loss": per_instance_loss, + "condition_mask": 1.0 - noisy_mask_T, + "metric/conditioned_prefix_frames": loss.new_tensor( + float(conditioned_prefix_frames) + ), + } + if source_weight is not None: + output_batch.update( + { + "metric/geometry_source_confidence_mean": ( + self._current_blockwise_geometry_confidence.mean() + ), + "metric/geometry_source_weight_mean": source_weight.mean(), + "metric/geometry_source_coverage": ( + source_weight > 0.0 + ).float().mean(), + "metric/geometry_source_dropout_fraction": ( + source_dropout_fraction + ), + } + ) + return output_batch, loss + + +class HdmapToLidarImaginaireOnePassTeacherForcingRFModel( + HdmapToLidarImaginaireTeacherForcingRFModel +): + """Chunkwise teacher forcing in one ``[clean | noisy]`` DiT pass. + + This preserves the paper pipeline's singleton-prefix/chunk-4 visibility + while using a packed one-pass execution: clean queries are frame-causal, + and noisy queries see strictly earlier clean chunks plus their own noisy + chunk. Gradients from noisy predictions flow through the clean stream + without retaining mutable replay caches. + """ + + def _teacher_forcing_one_pass_velocity( + self, + x0: Tensor, + x_t: Tensor, + active_timesteps: Tensor, + condition, + ) -> Tensor: + if x0.shape != x_t.shape: + raise ValueError( + "clean and noisy teacher-forcing tensors must match: " + f"clean={tuple(x0.shape)}, noisy={tuple(x_t.shape)}" + ) + batch_size, _, num_frames = x0.shape[:3] + if active_timesteps.shape != (batch_size, num_frames): + raise ValueError( + "teacher-forcing timesteps must be (B,T), got " + f"{tuple(active_timesteps.shape)} for B={batch_size}, " + f"T={num_frames}" + ) + # Validate the configured [prefix, chunk, ...] partition before the + # compiled mask sees it. + self._teacher_forcing_chunk_slices(num_frames) + + hdmap = self._current_hdmap + side_condition = self._current_blockwise_warped_history + if hdmap is None or side_condition is None: + raise RuntimeError( + "one-pass teacher forcing requires HDMap and geometry side " + "conditions" + ) + if hdmap.shape[2] != num_frames or side_condition.shape[2] != num_frames: + raise ValueError( + "teacher-forcing conditions must match the clean sequence: " + f"hdmap={tuple(hdmap.shape)}, " + f"side={tuple(side_condition.shape)}, T={num_frames}" + ) + + packed_x = torch.cat([x0, x_t.to(x0.dtype)], dim=2) + packed_timesteps = torch.cat( + [torch.zeros_like(active_timesteps), active_timesteps], dim=1 + ) + positions = torch.arange(num_frames, device=x0.device) + + names = ( + "_current_hdmap", + "_current_blockwise_warped_history", + "_current_teacher_forcing_clean_frames", + "_current_teacher_forcing_temporal_positions", + "_current_stage2_known_frame_mask", + "_current_stage2_task_frame_type_ids", + ) + missing = object() + previous = {name: getattr(self, name, missing) for name in names} + self._current_hdmap = torch.cat([hdmap, hdmap], dim=2) + self._current_blockwise_warped_history = torch.cat( + [side_condition, side_condition], dim=2 + ) + self._current_teacher_forcing_clean_frames = num_frames + self._current_teacher_forcing_temporal_positions = torch.cat( + [positions, positions], dim=0 + ) + known_mask = getattr( + self, "_current_stage2_known_frame_mask", None + ) + if known_mask is not None: + self._current_stage2_known_frame_mask = torch.cat( + [known_mask, known_mask], dim=-1 + ) + task_ids = getattr( + self, "_current_stage2_task_frame_type_ids", None + ) + if task_ids is not None: + self._current_stage2_task_frame_type_ids = torch.cat( + [task_ids, task_ids], dim=0 + ) + try: + packed_prediction = self._rf_network_forward( + packed_x.to(**self.tensor_kwargs), + packed_timesteps, + condition, + ) + finally: + for name, value in previous.items(): + if value is missing: + if hasattr(self, name): + delattr(self, name) + else: + setattr(self, name, value) + + if packed_prediction.shape[2] != 2 * num_frames: + raise RuntimeError( + "one-pass teacher forcing returned the wrong temporal length: " + f"{tuple(packed_prediction.shape)}" + ) + return packed_prediction[:, :, num_frames:] + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + _, x0, condition = self.get_data_and_condition(data_batch) + batch_size, _, num_frames = x0.shape[:3] + conditioned_prefix_frames, noisy_mask_T = ( + self._sample_imaginaire_conditioned_prefix( + num_frames=num_frames, + device=x0.device, + ) + ) + + epsilon = torch.randn(x0.shape, **self.tensor_kwargs_fp32) + source, source_weight, source_dropout_fraction = ( + self._sample_teacher_forcing_source(x0, epsilon) + ) + sampled_time = self.rectified_flow.sample_train_time(batch_size) + timesteps_B = self.rectified_flow.get_discrete_timestamp( + sampled_time, self.tensor_kwargs_fp32 + ).reshape(batch_size) + sigmas_B = self.rectified_flow.get_sigmas( + timesteps_B, self.tensor_kwargs_fp32 + ).reshape(batch_size) + time_weights = self.rectified_flow.train_time_weight( + timesteps_B[:, None], self.tensor_kwargs_fp32 + ).reshape(batch_size, -1).mean(dim=1) + + x0_float = x0.float() + sigma_B_T = sigmas_B[:, None] * noisy_mask_T[None] + sigma_5d = sigma_B_T[:, None, :, None, None] + x_t = sigma_5d * source + (1.0 - sigma_5d) * x0_float + target = source - x0_float + active_timesteps = timesteps_B[:, None] * noisy_mask_T[None] + prediction = self._teacher_forcing_one_pass_velocity( + x0, + x_t, + active_timesteps, + condition, + ) + + per_frame_loss = ( + prediction - target + ).square().mean(dim=(1, 3, 4)) * noisy_mask_T[None] + per_instance_loss = self._reduce_teacher_forcing_per_frame_loss( + per_frame_loss, noisy_mask_T + ) + raw_loss = (time_weights * per_instance_loss).mean() + loss = self.teacher_forcing_loss_scale * raw_loss + output_batch = { + "x0": x0, + "xt": x_t, + "sigma": sigmas_B, + "model_pred": prediction, + "edm_loss": loss, + "teacher_forcing_loss": raw_loss, + "timesteps": timesteps_B, + "per_frame_loss": per_frame_loss, + "per_instance_loss": per_instance_loss, + "condition_mask": 1.0 - noisy_mask_T, + "metric/conditioned_prefix_frames": loss.new_tensor( + float(conditioned_prefix_frames) + ), + } + if source_weight is not None: + output_batch.update( + { + "metric/geometry_source_confidence_mean": ( + self._current_blockwise_geometry_confidence.mean() + ), + "metric/geometry_source_weight_mean": source_weight.mean(), + "metric/geometry_source_coverage": ( + source_weight > 0.0 + ).float().mean(), + "metric/geometry_source_dropout_fraction": ( + source_dropout_fraction + ), + } + ) + return output_batch, loss + + +class HdmapToLidarConcatGeometryTeacherForcingRFModel( + HdmapToLidarImaginaireOnePassTeacherForcingRFModel +): + """Canonical Stage 2 TF with concatenated GT accumulated geometry.""" + + def build_model(self) -> torch.nn.ModuleDict: + model = super().build_model() + latent_channels = int(self.config.latent_shape[0]) + model["net"].x_embedder.proj[ + 1 + ]._checkpoint_zero_init_input_expansion = ( + 2 * latent_channels, + 2 * latent_channels + 2, + 3 * latent_channels + 2, + ) + return model + + def __init__(self, config): + super().__init__(config) + if not self.blockwise_warped_history_concat: + raise ValueError( + "concat-geometry teacher forcing requires geometry concat" + ) + if self.blockwise_spatial_map_self_prediction_prob != 0.0: + raise ValueError( + "GT-accumulation teacher forcing requires " + "blockwise_spatial_map_self_prediction_prob=0" + ) + + +class HdmapToLidarMultiTaskTeacherForcingRFModel( + HdmapToLidarConcatGeometryTeacherForcingRFModel +): + """Explicit world, forecast, and resimulation Stage-2 mixture.""" + + _ALLOWED_TASKS = ("world", "forecast", "resimulation") + + def build_model(self) -> torch.nn.ModuleDict: + model = super().build_model() + latent_channels = int(self.config.latent_shape[0]) + model["net"].x_embedder.proj[ + 1 + ]._checkpoint_zero_init_input_expansion = ( + 2 * latent_channels, + 2 * latent_channels + 2, + 3 * latent_channels + 3, + ) + return model + + def __init__(self, config): + super().__init__(config) + self.stage2_multitask_modes = tuple( + str(mode) for mode in config.stage2_multitask_modes + ) + probabilities = tuple( + float(value) for value in config.stage2_multitask_probs + ) + if ( + not self.stage2_multitask_modes + or len(self.stage2_multitask_modes) != len(probabilities) + or len(set(self.stage2_multitask_modes)) + != len(self.stage2_multitask_modes) + or any( + mode not in self._ALLOWED_TASKS + for mode in self.stage2_multitask_modes + ) + or any(value < 0.0 for value in probabilities) + or sum(probabilities) <= 0.0 + ): + raise ValueError( + "Stage-2 multi-task modes must be unique members of " + f"{self._ALLOWED_TASKS} with matching positive probability " + "mass" + ) + self.stage2_multitask_probs = torch.tensor( + probabilities, dtype=torch.float32 + ) / sum(probabilities) + self.stage2_multitask_sampling = str( + config.stage2_multitask_sampling + ) + if self.stage2_multitask_sampling not in ( + "categorical", + "round_robin", + ): + raise ValueError( + "stage2_multitask_sampling must be categorical or round_robin" + ) + self._stage2_multitask_round_robin_index = 0 + self.stage2_forecast_observed_frames = int( + config.stage2_multitask_forecast_observed_frames + ) + self.stage2_resim_known_min = int( + config.stage2_multitask_resim_known_min_per_block + ) + self.stage2_resim_known_max = int( + config.stage2_multitask_resim_known_max_per_block + ) + self.stage2_resim_drop_block_prob = float( + config.stage2_multitask_resim_drop_block_prob + ) + self.stage2_world_hdmap_dropout_prob = float( + config.stage2_multitask_world_hdmap_dropout_prob + ) + self.stage2_hdmap_bbox_channel_start = int( + config.stage2_multitask_hdmap_bbox_channel_start + ) + if not config.stage2_multitask_known_mask_concat: + raise ValueError( + "multi-task Stage 2 requires the known-frame mask channel" + ) + if self.hdmap_dropout_prob != 0.0: + raise ValueError( + "multi-task Stage 2 controls HDMap availability per task; " + "set the generic hdmap_dropout_prob to zero" + ) + if self.stage2_forecast_observed_frames <= 0: + raise ValueError( + "forecast observed-frame count must be positive" + ) + if ( + self.stage2_resim_known_min < 0 + or self.stage2_resim_known_max < self.stage2_resim_known_min + or self.stage2_resim_known_max > self.df_block_size + or not 0.0 <= self.stage2_resim_drop_block_prob <= 1.0 + or not 0.0 <= self.stage2_world_hdmap_dropout_prob <= 1.0 + or self.stage2_hdmap_bbox_channel_start < 0 + ): + raise ValueError("invalid Stage-2 multi-task mask/HDMap settings") + net = self.net + while hasattr(net, "module"): + net = net.module + if net.num_frame_type_embeddings < len( + self.stage2_multitask_modes + ): + raise ValueError( + "the DiT needs one frame-type embedding per Stage-2 task" + ) + self._current_stage2_task_id = 0 + self._current_stage2_task_name = self.stage2_multitask_modes[0] + self._current_stage2_known_frame_mask: Optional[Tensor] = None + self._current_stage2_task_frame_type_ids: Optional[Tensor] = None + self._current_stage2_data_batch = None + self._current_stage2_dynamic_removed_fraction = torch.tensor(0.0) + self._current_stage2_truncated_boxes = 0.0 + + def _sample_stage2_task(self, device: torch.device) -> int: + if self.stage2_multitask_sampling == "round_robin": + task_id = ( + self._stage2_multitask_round_robin_index + % len(self.stage2_multitask_modes) + ) + self._stage2_multitask_round_robin_index += 1 + return task_id + return _sample_world_synchronized_categorical( + self.stage2_multitask_probs.to(device=device) + ) + + def _sample_stage2_known_mask( + self, + task_name: str, + *, + num_frames: int, + device: torch.device, + ) -> Tensor: + known = torch.zeros( + num_frames, device=device, dtype=torch.float32 + ) + if task_name == "world": + return known + if task_name == "forecast": + if self.stage2_forecast_observed_frames >= num_frames: + raise ValueError( + "forecast observations must leave at least one target " + f"frame, got {self.stage2_forecast_observed_frames}/" + f"{num_frames}" + ) + known[: self.stage2_forecast_observed_frames] = 1.0 + return known + + chunks = self._teacher_forcing_chunk_slices(num_frames) + known[0] = 1.0 + for start, end in chunks[1:]: + if ( + torch.rand((), device=device) + < self.stage2_resim_drop_block_prob + ): + continue + count = int( + torch.randint( + self.stage2_resim_known_min, + self.stage2_resim_known_max + 1, + (1,), + device=device, + ).item() + ) + if count == 0: + continue + selected = torch.randperm( + end - start, device=device + )[:count] + known[start + selected] = 1.0 + return known + + def _sample_imaginaire_conditioned_prefix( + self, + *, + num_frames: int, + device: torch.device, + ) -> tuple[int, Tensor]: + known = self._current_stage2_known_frame_mask + if known is None or known.shape != (num_frames,): + raise RuntimeError( + "Stage-2 task mask was not prepared before RF training" + ) + known = known.to(device=device, dtype=torch.float32) + noisy = 1.0 - known + if not bool(noisy.any()): + raise ValueError("Stage-2 task mask must leave a prediction target") + return int(known.sum().item()), noisy + + def _reduce_teacher_forcing_per_frame_loss( + self, + per_frame_loss: Tensor, + noisy_mask_T: Tensor, + ) -> Tensor: + return per_frame_loss.sum(dim=1) / noisy_mask_T.sum().clamp_min(1.0) + + def _stage2_spatial_map_geometry( + self, raw_state: Tensor + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + if self._blockwise_spatial_map_geometry is None: + self._blockwise_spatial_map_geometry = load_waymo_lidar_geometry( + root_path=self._blockwise_spatial_map_geometry_root_path, + filter_list_path=( + self._blockwise_spatial_map_geometry_filter_list_path + ), + resample_width=( + self._blockwise_spatial_map_geometry_resample_width + ), + ) + if not isinstance( + self._blockwise_spatial_map_geometry[0], torch.Tensor + ) or self._blockwise_spatial_map_geometry[0].device != raw_state.device: + self._blockwise_spatial_map_geometry = tuple( + torch.as_tensor( + value, + device=raw_state.device, + dtype=torch.float32, + ) + for value in self._blockwise_spatial_map_geometry + ) + return self._blockwise_spatial_map_geometry + + def _remove_dynamic_returns( + self, + raw_state: Tensor, + lidar_to_world: Tensor, + ray_dirs: Tensor, + ) -> Tensor: + data_batch = self._current_stage2_data_batch + if data_batch is None: + raise RuntimeError("Stage-2 task batch is unavailable") + required = ( + "moving_box_object_to_world", + "moving_box_lwh", + "moving_box_valid", + ) + missing = [key for key in required if key not in data_batch] + if missing: + raise KeyError( + "dynamic filtering is missing dataset fields " + f"{missing}" + ) + filtered = [] + fractions = [] + for batch_idx in range(raw_state.shape[0]): + filtered_i, fraction_i = remove_points_inside_moving_boxes( + raw_state[batch_idx], + lidar_to_world[batch_idx], + data_batch["moving_box_object_to_world"][batch_idx], + data_batch["moving_box_lwh"][batch_idx], + data_batch["moving_box_valid"][batch_idx], + ray_dirs=ray_dirs, + min_range=self._blockwise_spatial_map_min_range, + max_range=self._blockwise_spatial_map_max_range, + min_value=self._blockwise_spatial_map_min_value, + inverse_depth=self._blockwise_spatial_map_inverse_depth, + ) + filtered.append(filtered_i) + fractions.append(fraction_i) + self._current_stage2_dynamic_removed_fraction = torch.stack( + fractions + ).mean() + return torch.stack(filtered) + + @torch.no_grad() + def _build_torch_spatial_map_history( + self, + raw_state: Tensor, + lidar_to_world: Tensor, + ) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + ray_dirs, elev, azim, row_off = self._stage2_spatial_map_geometry( + raw_state + ) + task_name = self._current_stage2_task_name + self._current_stage2_dynamic_removed_fraction = raw_state.new_tensor( + 0.0, dtype=torch.float32 + ) + if task_name == "world": + static_state = self._remove_dynamic_returns( + raw_state, lidar_to_world, ray_dirs + ) + return super()._build_torch_spatial_map_history( + static_state, lidar_to_world + ) + + observed_mask = self._current_stage2_known_frame_mask + if observed_mask is None: + raise RuntimeError("Stage-2 observed mask is unavailable") + history_state = raw_state + if task_name == "resimulation": + history_state = self._remove_dynamic_returns( + raw_state, lidar_to_world, ray_dirs + ) + warped = [] + for batch_idx in range(raw_state.shape[0]): + warped_i, _ = warp_frozen_observed_history_with_spatial_map( + history_state[batch_idx], + lidar_to_world[batch_idx], + observed_mask, + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=self._blockwise_spatial_map_min_range, + max_range=self._blockwise_spatial_map_max_range, + min_value=self._blockwise_spatial_map_min_value, + inverse_depth=self._blockwise_spatial_map_inverse_depth, + radius_m=self._blockwise_spatial_map_radius_m, + voxel_size_m=self._blockwise_spatial_map_voxel_m, + ) + warped.append(warped_i) + return torch.stack(warped), None, None + + def get_data_and_condition( + self, data_batch: dict[str, Tensor] + ): + video = data_batch.get(self.input_data_key) + if video is None or video.ndim != 5: + raise ValueError( + "multi-task Stage 2 requires video input (B,C,T,H,W)" + ) + task_id = self._sample_stage2_task(video.device) + task_name = self.stage2_multitask_modes[task_id] + num_frames = int(video.shape[2]) + known_mask = self._sample_stage2_known_mask( + task_name, + num_frames=num_frames, + device=video.device, + ) + self._current_stage2_task_id = task_id + self._current_stage2_task_name = task_name + self._current_stage2_known_frame_mask = known_mask + self._current_stage2_task_frame_type_ids = torch.full( + (num_frames,), + task_id, + device=video.device, + dtype=torch.long, + ) + self._current_stage2_data_batch = data_batch + + if task_name == "resimulation": + semantic = data_batch.get("lidar_hdmap_semantic") + if semantic is None or semantic.ndim != 5: + raise KeyError( + "resimulation task requires semantic HDMap (B,K,T,H,W)" + ) + if self.stage2_hdmap_bbox_channel_start >= semantic.shape[1]: + raise ValueError( + "bbox HDMap channel start is outside the semantic tensor" + ) + data_batch["lidar_hdmap"] = compose_normalized_range_channels( + semantic[:, self.stage2_hdmap_bbox_channel_start :], + channel_dim=1, + min_value=self._blockwise_spatial_map_min_value, + inverse_depth=self._blockwise_spatial_map_inverse_depth, + ) + + previous_force_zero = getattr( + self, "_hdmap_force_zero_latent", False + ) + force_zero = task_name == "forecast" + if task_name == "world" and self.training: + force_zero = bool( + torch.rand((), device=video.device) + < self.stage2_world_hdmap_dropout_prob + ) + self._hdmap_force_zero_latent = force_zero + try: + result = super().get_data_and_condition(data_batch) + truncated = data_batch.get("moving_box_truncated") + if truncated is not None: + if isinstance(truncated, Tensor): + self._current_stage2_truncated_boxes = float( + truncated.float().sum().item() + ) + else: + self._current_stage2_truncated_boxes = float( + sum(truncated) + ) + return result + finally: + self._hdmap_force_zero_latent = previous_force_zero + self._current_stage2_data_batch = None + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + output_batch, loss = super()._rectified_flow_forward(data_batch) + for task_id, task_name in enumerate(self.stage2_multitask_modes): + output_batch[f"metric/stage2_task_{task_name}"] = loss.new_tensor( + float(task_id == self._current_stage2_task_id) + ) + known = self._current_stage2_known_frame_mask + if known is not None: + output_batch["metric/stage2_known_frames"] = known.sum() + output_batch["metric/stage2_known_fraction"] = known.mean() + output_batch["metric/stage2_dynamic_removed_fraction"] = ( + self._current_stage2_dynamic_removed_fraction.to( + device=loss.device + ) + ) + output_batch["metric/stage2_truncated_moving_boxes"] = ( + loss.new_tensor(self._current_stage2_truncated_boxes) + ) + return output_batch, loss + + +class HdmapToLidarFactorizedTeacherForcingRFModel( + HdmapToLidarConcatGeometryTeacherForcingRFModel +): + """Task-free Stage 2 with factorized prefix, map, and geometry choices.""" + + _HDMAP_MODES = ("null", "full", "boxes") + _GEOMETRY_MODES = ( + "null", + "rolling_static", + "frozen_raw", + "frozen_object", + ) + + def build_model(self) -> torch.nn.ModuleDict: + model = super().build_model() + latent_channels = int(self.config.latent_shape[0]) + model["net"].x_embedder.proj[ + 1 + ]._checkpoint_zero_init_input_expansion = ( + 2 * latent_channels, + 2 * latent_channels + 2, + 3 * latent_channels + 3, + ) + return model + + @staticmethod + def _validated_distribution( + names, + probabilities, + *, + allowed, + label: str, + ) -> tuple[tuple, Tensor]: + names = tuple(names) + probabilities = tuple(float(value) for value in probabilities) + if ( + not names + or len(names) != len(probabilities) + or len(set(names)) != len(names) + or any(name not in allowed for name in names) + or any(value < 0.0 for value in probabilities) + or sum(probabilities) <= 0.0 + ): + raise ValueError( + f"invalid {label} distribution: names={names}, " + f"probabilities={probabilities}" + ) + probs = torch.tensor(probabilities, dtype=torch.float32) + return names, probs / probs.sum() + + def __init__(self, config): + super().__init__(config) + prefix_frames = tuple( + int(value) for value in config.stage2_factorized_prefix_frames + ) + prefix_probs = tuple( + float(value) for value in config.stage2_factorized_prefix_probs + ) + if ( + not prefix_frames + or len(prefix_frames) != len(prefix_probs) + or len(set(prefix_frames)) != len(prefix_frames) + or any(value < 0 for value in prefix_frames) + or any(value < 0.0 for value in prefix_probs) + or sum(prefix_probs) <= 0.0 + ): + raise ValueError( + "invalid factorized Stage-2 prefix distribution" + ) + self.stage2_factorized_prefix_frames = prefix_frames + self.stage2_factorized_prefix_probs = torch.tensor( + prefix_probs, dtype=torch.float32 + ) + self.stage2_factorized_prefix_probs /= ( + self.stage2_factorized_prefix_probs.sum() + ) + ( + self.stage2_factorized_hdmap_modes, + self.stage2_factorized_hdmap_probs, + ) = self._validated_distribution( + config.stage2_factorized_hdmap_modes, + config.stage2_factorized_hdmap_probs, + allowed=self._HDMAP_MODES, + label="HDMap", + ) + ( + self.stage2_factorized_geometry_modes_k0, + self.stage2_factorized_geometry_probs_k0, + ) = self._validated_distribution( + config.stage2_factorized_geometry_modes_k0, + config.stage2_factorized_geometry_probs_k0, + allowed=self._GEOMETRY_MODES, + label="K=0 geometry", + ) + ( + self.stage2_factorized_geometry_modes_known, + self.stage2_factorized_geometry_probs_known, + ) = self._validated_distribution( + config.stage2_factorized_geometry_modes_known, + config.stage2_factorized_geometry_probs_known, + allowed=self._GEOMETRY_MODES, + label="K>0 geometry", + ) + self.factorized_decouple_geometry_observations = bool( + config.factorized_decouple_geometry_observations + ) + geometry_observation_frames = tuple( + int(value) + for value in config.factorized_geometry_observation_frames + ) + geometry_observation_probs = tuple( + float(value) + for value in config.factorized_geometry_observation_probs + ) + if self.factorized_decouple_geometry_observations: + if ( + not geometry_observation_frames + or len(geometry_observation_frames) + != len(geometry_observation_probs) + or len(set(geometry_observation_frames)) + != len(geometry_observation_frames) + or any(value <= 0 for value in geometry_observation_frames) + or any(value < 0.0 for value in geometry_observation_probs) + or sum(geometry_observation_probs) <= 0.0 + ): + raise ValueError( + "invalid factorized geometry-observation distribution" + ) + if ( + self.stage2_factorized_geometry_modes_k0 + != self.stage2_factorized_geometry_modes_known + or not torch.allclose( + self.stage2_factorized_geometry_probs_k0, + self.stage2_factorized_geometry_probs_known, + ) + ): + raise ValueError( + "decoupled geometry requires one K-independent geometry " + "mode distribution" + ) + self.factorized_geometry_observation_frames = ( + geometry_observation_frames + ) + self.factorized_geometry_observation_probs = torch.tensor( + geometry_observation_probs, dtype=torch.float32 + ) + if geometry_observation_probs: + self.factorized_geometry_observation_probs /= ( + self.factorized_geometry_observation_probs.sum() + ) + invalid_k0 = {"frozen_raw", "frozen_object"}.intersection( + self.stage2_factorized_geometry_modes_k0 + ) + if invalid_k0 and not self.factorized_decouple_geometry_observations: + raise ValueError( + "K=0 geometry cannot use frozen observations: " + f"{sorted(invalid_k0)}" + ) + self.stage2_factorized_hdmap_bbox_channel_start = int( + config.stage2_factorized_hdmap_bbox_channel_start + ) + self.factorized_geometry_block_size = int( + config.factorized_geometry_block_size + ) + self.factorized_geometry_prefix_frames = int( + config.factorized_geometry_prefix_frames + ) + self.factorized_geometry_rolling_shutter = bool( + config.factorized_geometry_rolling_shutter + ) + self.factorized_geometry_actor_box_time_mode = str( + config.factorized_geometry_actor_box_time_mode + ) + if self.factorized_geometry_actor_box_time_mode not in ( + "frame", + "current_to_next", + "previous_to_current", + ): + raise ValueError( + "unsupported factorized_geometry_actor_box_time_mode " + f"{self.factorized_geometry_actor_box_time_mode!r}" + ) + self.stage2_factorized_force_prefix_k = int( + config.stage2_factorized_force_prefix_k + ) + self.stage2_factorized_force_hdmap_mode = str( + config.stage2_factorized_force_hdmap_mode + ) + self.stage2_factorized_force_geometry_mode = str( + config.stage2_factorized_force_geometry_mode + ) + self.factorized_force_geometry_observations = int( + config.factorized_force_geometry_observations + ) + self.factorized_force_geometry_source_indices: Optional[ + tuple[int, ...] + ] = None + if ( + self.stage2_factorized_force_prefix_k >= 0 + and self.stage2_factorized_force_prefix_k + not in self.stage2_factorized_prefix_frames + ): + raise ValueError( + "forced prefix K must be one of the configured prefix lengths" + ) + if ( + self.stage2_factorized_force_hdmap_mode + and self.stage2_factorized_force_hdmap_mode + not in self._HDMAP_MODES + ): + raise ValueError("invalid forced HDMap mode") + if ( + self.stage2_factorized_force_geometry_mode + and self.stage2_factorized_force_geometry_mode + not in self._GEOMETRY_MODES + ): + raise ValueError("invalid forced geometry mode") + if ( + self.factorized_force_geometry_observations >= 0 + and ( + not self.factorized_decouple_geometry_observations + or self.factorized_force_geometry_observations + not in self.factorized_geometry_observation_frames + ) + ): + raise ValueError( + "forced geometry observations require the decoupled mode and " + "must use a configured G" + ) + if not config.stage2_known_mask_concat: + raise ValueError( + "factorized Stage 2 requires the known-frame mask channel" + ) + if self.hdmap_dropout_prob != 0.0: + raise ValueError( + "factorized Stage 2 samples HDMap form explicitly; set " + "hdmap_dropout_prob=0" + ) + if self.stage2_factorized_hdmap_bbox_channel_start < 0: + raise ValueError("HDMap bbox channel start must be non-negative") + if self.factorized_geometry_block_size <= 0: + raise ValueError( + "factorized geometry block size must be positive" + ) + if self.factorized_geometry_prefix_frames < 0: + raise ValueError( + "factorized geometry prefix frames must be non-negative" + ) + net = self.net + while hasattr(net, "module"): + net = net.module + if net.num_frame_type_embeddings != 0: + raise ValueError( + "factorized Stage 2 must not use task/frame-type embeddings" + ) + + self._current_stage2_known_frame_mask: Optional[Tensor] = None + self._current_stage2_task_frame_type_ids: Optional[Tensor] = None + self._current_stage2_data_batch = None + self._current_stage2_prefix_k = 0 + self._current_stage2_geometry_prefix_g = 0 + self._current_stage2_geometry_source_mask: Optional[Tensor] = None + self._current_stage2_hdmap_mode = "full" + self._current_stage2_geometry_mode = "rolling_static" + self._current_stage2_geometry_diagnostics: dict[str, Tensor] = {} + self._current_stage2_truncated_boxes = 0.0 + self.factorized_rolling_geometry_known_prefix_only = False + self.factorized_static_only_geometry = False + self._sensor_spatial_map_geometry: dict[ + tuple[int, int, int, str], + tuple[Tensor, Tensor, Tensor, Tensor], + ] = {} + + def _sample_factorized_modes( + self, + *, + num_frames: int, + device: torch.device, + ) -> tuple[int, str, str, Tensor, int, Tensor]: + if self.stage2_factorized_force_prefix_k >= 0: + prefix_k = self.stage2_factorized_force_prefix_k + else: + prefix_index = _sample_world_synchronized_categorical( + self.stage2_factorized_prefix_probs.to(device=device) + ) + prefix_k = self.stage2_factorized_prefix_frames[prefix_index] + if prefix_k >= num_frames: + raise ValueError( + "factorized Stage-2 prefix must leave a prediction target, " + f"got K={prefix_k} for T={num_frames}" + ) + + if self.stage2_factorized_force_hdmap_mode: + hdmap_mode = self.stage2_factorized_force_hdmap_mode + else: + hdmap_index = _sample_world_synchronized_categorical( + self.stage2_factorized_hdmap_probs.to(device=device) + ) + hdmap_mode = self.stage2_factorized_hdmap_modes[hdmap_index] + + if self.factorized_decouple_geometry_observations: + geometry_modes = self.stage2_factorized_geometry_modes_known + geometry_probs = self.stage2_factorized_geometry_probs_known + else: + geometry_modes = ( + self.stage2_factorized_geometry_modes_k0 + if prefix_k == 0 + else self.stage2_factorized_geometry_modes_known + ) + geometry_probs = ( + self.stage2_factorized_geometry_probs_k0 + if prefix_k == 0 + else self.stage2_factorized_geometry_probs_known + ) + if self.stage2_factorized_force_geometry_mode: + geometry_mode = self.stage2_factorized_force_geometry_mode + if geometry_mode not in geometry_modes: + raise ValueError( + f"forced geometry mode {geometry_mode!r} is invalid for " + f"K={prefix_k}; allowed={geometry_modes}" + ) + else: + geometry_index = _sample_world_synchronized_categorical( + geometry_probs.to(device=device) + ) + geometry_mode = geometry_modes[geometry_index] + + known_mask = torch.zeros( + num_frames, device=device, dtype=torch.float32 + ) + known_mask[:prefix_k] = 1.0 + geometry_prefix_g = ( + prefix_k + if geometry_mode in ("frozen_raw", "frozen_object") + else 0 + ) + geometry_source_mask = known_mask.clone() + if self.factorized_decouple_geometry_observations: + geometry_source_mask.zero_() + if geometry_mode in ("frozen_raw", "frozen_object"): + if self.factorized_force_geometry_observations >= 0: + geometry_prefix_g = ( + self.factorized_force_geometry_observations + ) + else: + geometry_index = _sample_world_synchronized_categorical( + self.factorized_geometry_observation_probs.to( + device=device + ) + ) + geometry_prefix_g = ( + self.factorized_geometry_observation_frames[ + geometry_index + ] + ) + if geometry_prefix_g > num_frames: + raise ValueError( + "factorized geometry observations exceed the clip: " + f"G={geometry_prefix_g}, T={num_frames}" + ) + geometry_source_mask[:geometry_prefix_g] = 1.0 + elif self.factorized_force_geometry_observations >= 0: + raise ValueError( + "forced geometry observations require frozen geometry" + ) + else: + geometry_prefix_g = 0 + forced_source_indices = ( + self.factorized_force_geometry_source_indices + ) + if forced_source_indices is not None: + if ( + not self.factorized_decouple_geometry_observations + or geometry_mode not in ("frozen_raw", "frozen_object") + ): + raise ValueError( + "explicit geometry source indices require decoupled " + "frozen geometry" + ) + if ( + len(forced_source_indices) != geometry_prefix_g + or not forced_source_indices + or forced_source_indices[0] < 0 + or forced_source_indices[-1] >= num_frames + ): + raise ValueError( + "explicit geometry source indices must contain exactly " + f"G={geometry_prefix_g} valid frame indices" + ) + geometry_source_mask.zero_() + geometry_source_mask[list(forced_source_indices)] = 1.0 + return ( + prefix_k, + hdmap_mode, + geometry_mode, + known_mask, + geometry_prefix_g, + geometry_source_mask, + ) + + def _sample_imaginaire_conditioned_prefix( + self, + *, + num_frames: int, + device: torch.device, + ) -> tuple[int, Tensor]: + known = self._current_stage2_known_frame_mask + if known is None or known.shape != (num_frames,): + raise RuntimeError( + "factorized Stage-2 prefix was not prepared before RF training" + ) + known = known.to(device=device, dtype=torch.float32) + noisy = 1.0 - known + return self._current_stage2_prefix_k, noisy + + def _reduce_teacher_forcing_per_frame_loss( + self, + per_frame_loss: Tensor, + noisy_mask_T: Tensor, + ) -> Tensor: + return per_frame_loss.sum(dim=1) / noisy_mask_T.sum().clamp_min(1.0) + + def _stage2_spatial_map_geometry( + self, raw_state: Tensor + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + data_batch = self._current_stage2_data_batch + sensor_rays = ( + None + if data_batch is None + else data_batch.get("sensor_ray_directions") + ) + if sensor_rays is not None: + rays = torch.as_tensor( + sensor_rays, + device=raw_state.device, + dtype=torch.float32, + ) + if rays.ndim != 4 or rays.shape[-1] != 3: + raise ValueError( + "sensor_ray_directions must be (B,H,W,3), got " + f"{tuple(rays.shape)}" + ) + if tuple(rays.shape[1:3]) != tuple(raw_state.shape[-2:]): + raise ValueError( + "sensor rays must match the native range grid: " + f"rays={tuple(rays.shape[1:3])}, " + f"video={tuple(raw_state.shape[-2:])}" + ) + dataset_ids = data_batch.get("sensor_dataset_id") + if dataset_ids is None: + raise KeyError( + "sensor rays require sensor_dataset_id metadata" + ) + dataset_ids = torch.as_tensor( + dataset_ids, device=raw_state.device, dtype=torch.long + ).reshape(-1) + if dataset_ids.shape[0] != rays.shape[0] or not bool( + (dataset_ids == dataset_ids[0]).all() + ): + raise ValueError( + "native-grid batches must contain one homogeneous sensor" + ) + dataset_id = int(dataset_ids[0].item()) + key = ( + dataset_id, + int(rays.shape[1]), + int(rays.shape[2]), + str(raw_state.device), + ) + geometry = self._sensor_spatial_map_geometry.get(key) + if geometry is None: + ray_grid = rays[0].contiguous() + elev, azim, row_off = ( + _sensor_tables_from_ray_directions( + ray_grid, allow_approximate=True + ) + ) + geometry = (ray_grid, elev, azim, row_off) + self._sensor_spatial_map_geometry[key] = geometry + return geometry + + if self._blockwise_spatial_map_geometry is None: + self._blockwise_spatial_map_geometry = load_waymo_lidar_geometry( + root_path=self._blockwise_spatial_map_geometry_root_path, + filter_list_path=( + self._blockwise_spatial_map_geometry_filter_list_path + ), + resample_width=( + self._blockwise_spatial_map_geometry_resample_width + ), + ) + if not isinstance( + self._blockwise_spatial_map_geometry[0], torch.Tensor + ) or self._blockwise_spatial_map_geometry[0].device != raw_state.device: + self._blockwise_spatial_map_geometry = tuple( + torch.as_tensor( + value, + device=raw_state.device, + dtype=torch.float32, + ) + for value in self._blockwise_spatial_map_geometry + ) + return self._blockwise_spatial_map_geometry + + @torch.no_grad() + def _store_blockwise_spatial_map_history( + self, + warped: Tensor, + geometry_source: Optional[Tensor], + geometry_confidence: Optional[Tensor], + latent_state: Tensor, + ) -> None: + super()._store_blockwise_spatial_map_history( + warped, + geometry_source, + geometry_confidence, + latent_state, + ) + if self._current_stage2_geometry_mode == "null": + self._current_blockwise_warped_history = torch.zeros_like( + self._current_blockwise_warped_history + ) + + @torch.no_grad() + def _build_torch_spatial_map_history( + self, + raw_state: Tensor, + lidar_to_world: Tensor, + ) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + data_batch = self._current_stage2_data_batch + if data_batch is None: + raise RuntimeError("factorized Stage-2 batch is unavailable") + geometry_source_mask = self._current_stage2_geometry_source_mask + if geometry_source_mask is None: + geometry_source_mask = self._current_stage2_known_frame_mask + if geometry_source_mask is None: + raise RuntimeError( + "factorized Stage-2 geometry source mask is unavailable" + ) + ray_dirs, elev, azim, row_off = self._stage2_spatial_map_geometry( + raw_state + ) + required = () + if self._current_stage2_geometry_mode in ( + "rolling_static", + "frozen_object", + ): + required = ( + "moving_box_object_to_world", + "moving_box_lwh", + "moving_box_valid", + "moving_box_track_id", + ) + if self.factorized_geometry_rolling_shutter: + required = (*required, "pose_sensor_start_end") + missing = [name for name in required if data_batch.get(name) is None] + if missing: + raise KeyError( + f"factorized Stage-2 geometry is missing batch fields {missing}" + ) + warped = [] + diagnostics: dict[str, list[Tensor]] = {} + motion_batch = ( + data_batch.get("pose_sensor_start_end") + if self.factorized_geometry_rolling_shutter + else None + ) + geometry_source_pose_batch = data_batch.get( + "factorized_geometry_source_lidar_to_world" + ) + geometry_source_motion_batch = ( + data_batch.get( + "factorized_geometry_source_pose_sensor_start_end" + ) + if self.factorized_geometry_rolling_shutter + else None + ) + depth_bounds_batch = data_batch.get("sensor_depth_bounds") + if depth_bounds_batch is not None: + depth_bounds_batch = torch.as_tensor( + depth_bounds_batch, + device=raw_state.device, + dtype=torch.float32, + ) + if depth_bounds_batch.shape != (raw_state.shape[0], 2): + raise ValueError( + "sensor_depth_bounds must be (B,2), got " + f"{tuple(depth_bounds_batch.shape)}" + ) + for batch_idx in range(raw_state.shape[0]): + geometry_state = raw_state[batch_idx] + if ( + self.factorized_rolling_geometry_known_prefix_only + and self._current_stage2_geometry_mode == "rolling_static" + ): + known = self._current_stage2_known_frame_mask + if known is None: + raise RuntimeError( + "known-prefix-only rolling geometry requires a " + "known-frame mask" + ) + geometry_state = geometry_state.clone() + geometry_state[ + :, + ~known.to( + device=geometry_state.device, + dtype=torch.bool, + ), + ] = float(self._blockwise_spatial_map_min_value) + box_object_to_world = data_batch.get( + "moving_box_object_to_world" + ) + box_lwh = data_batch.get("moving_box_lwh") + box_valid = data_batch.get("moving_box_valid") + box_track_id = data_batch.get("moving_box_track_id") + min_range = self._blockwise_spatial_map_min_range + max_range = self._blockwise_spatial_map_max_range + radius_m = self._blockwise_spatial_map_radius_m + if depth_bounds_batch is not None: + min_range = float(depth_bounds_batch[batch_idx, 0].item()) + max_range = float(depth_bounds_batch[batch_idx, 1].item()) + radius_m = max_range + geometry_i, _, diagnostic_i = ( + build_stage2_factorized_geometry( + geometry_state, + lidar_to_world[batch_idx], + geometry_source_mask, + self._current_stage2_geometry_mode, + pose_sensor_start_end=( + motion_batch[batch_idx] + if motion_batch is not None + else None + ), + geometry_source_lidar_to_world=( + geometry_source_pose_batch[batch_idx] + if geometry_source_pose_batch is not None + else None + ), + geometry_source_pose_sensor_start_end=( + geometry_source_motion_batch[batch_idx] + if geometry_source_motion_batch is not None + else None + ), + actor_box_time_mode=( + self.factorized_geometry_actor_box_time_mode + ), + static_only_geometry=( + self.factorized_static_only_geometry + ), + box_object_to_world=( + None + if box_object_to_world is None + else box_object_to_world[batch_idx] + ), + box_lwh=( + None if box_lwh is None else box_lwh[batch_idx] + ), + box_valid=( + None if box_valid is None else box_valid[batch_idx] + ), + box_track_id=( + None + if box_track_id is None + else box_track_id[batch_idx] + ), + block_size=self.factorized_geometry_block_size, + prefix_frames=self.factorized_geometry_prefix_frames, + input_has_prepend=self.input_video_has_prepend, + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=min_range, + max_range=max_range, + min_value=self._blockwise_spatial_map_min_value, + inverse_depth=self._blockwise_spatial_map_inverse_depth, + radius_m=radius_m, + voxel_size_m=self._blockwise_spatial_map_voxel_m, + voxel_policy=self._blockwise_spatial_map_voxel_policy, + observation_unit=( + self._blockwise_spatial_map_observation_unit + ), + static_min_observations=( + self._blockwise_spatial_map_static_min_observations + ), + candidate_ttl_updates=( + self._blockwise_spatial_map_candidate_ttl_updates + ), + include_latest=self._blockwise_spatial_map_include_latest, + free_space_clear=( + self._blockwise_spatial_map_free_space_clear + ), + free_space_margin_m=( + self._blockwise_spatial_map_free_space_margin_m + ), + free_space_misses_to_remove=( + self._blockwise_spatial_map_free_space_misses_to_remove + ), + ) + ) + warped.append(geometry_i) + for name, value in diagnostic_i.items(): + diagnostics.setdefault(name, []).append(value) + self._current_stage2_geometry_diagnostics = { + name: torch.stack(values).mean() + for name, values in diagnostics.items() + } + return torch.stack(warped), None, None + + def get_data_and_condition( + self, data_batch: dict[str, Tensor] + ): + video = data_batch.get(self.input_data_key) + if video is None or video.ndim != 5: + raise ValueError( + "factorized Stage 2 requires video input (B,C,T,H,W)" + ) + ( + prefix_k, + hdmap_mode, + geometry_mode, + known_mask, + geometry_prefix_g, + geometry_source_mask, + ) = self._sample_factorized_modes( + num_frames=int(video.shape[2]), + device=video.device, + ) + self._current_stage2_prefix_k = prefix_k + self._current_stage2_geometry_prefix_g = geometry_prefix_g + self._current_stage2_geometry_source_mask = geometry_source_mask + self._current_stage2_hdmap_mode = hdmap_mode + self._current_stage2_geometry_mode = geometry_mode + self._current_stage2_known_frame_mask = known_mask + self._current_stage2_task_frame_type_ids = None + self._current_stage2_data_batch = data_batch + + if hdmap_mode == "boxes": + semantic = data_batch.get("lidar_hdmap_semantic") + if semantic is None or semantic.ndim != 5: + raise KeyError( + "boxes-only HDMap requires semantic HDMap (B,K,T,H,W)" + ) + channel_start = self.stage2_factorized_hdmap_bbox_channel_start + if channel_start >= semantic.shape[1]: + raise ValueError( + "bbox HDMap channel start is outside the semantic tensor" + ) + data_batch["lidar_hdmap"] = compose_normalized_range_channels( + semantic[:, channel_start:], + channel_dim=1, + min_value=self._blockwise_spatial_map_min_value, + inverse_depth=self._blockwise_spatial_map_inverse_depth, + ) + + previous_force_zero = getattr( + self, "_hdmap_force_zero_latent", False + ) + self._hdmap_force_zero_latent = hdmap_mode == "null" + try: + result = super().get_data_and_condition(data_batch) + truncated = data_batch.get("moving_box_truncated") + if truncated is not None: + if isinstance(truncated, Tensor): + self._current_stage2_truncated_boxes = float( + truncated.float().sum().item() + ) + else: + self._current_stage2_truncated_boxes = float( + sum(truncated) + ) + return result + finally: + self._hdmap_force_zero_latent = previous_force_zero + self._current_stage2_data_batch = None + + def _append_factorized_metrics( + self, + output_batch: dict[str, Tensor], + loss: Tensor, + ) -> tuple[dict[str, Tensor], Tensor]: + namespace = getattr( + self, "_factorized_metric_namespace", "stage2" + ) + output_batch[f"metric/{namespace}_prefix_k"] = loss.new_tensor( + float(self._current_stage2_prefix_k) + ) + output_batch[ + f"metric/{namespace}_geometry_prefix_g" + ] = loss.new_tensor(float(self._current_stage2_geometry_prefix_g)) + output_batch[ + f"metric/{namespace}_geometry_observations_decoupled" + ] = loss.new_tensor( + float(self.factorized_decouple_geometry_observations) + ) + output_batch[ + f"metric/{namespace}_geometry_rolling_shutter" + ] = loss.new_tensor( + float(self.factorized_geometry_rolling_shutter) + ) + for mode in self._HDMAP_MODES: + output_batch[ + f"metric/{namespace}_hdmap_{mode}" + ] = loss.new_tensor( + float(mode == self._current_stage2_hdmap_mode) + ) + for mode in self._GEOMETRY_MODES: + output_batch[ + f"metric/{namespace}_geometry_{mode}" + ] = loss.new_tensor( + float(mode == self._current_stage2_geometry_mode) + ) + for name, value in self._current_stage2_geometry_diagnostics.items(): + output_batch[f"metric/{namespace}_{name}"] = value.to( + device=loss.device + ) + output_batch[f"metric/{namespace}_truncated_moving_boxes"] = ( + loss.new_tensor(self._current_stage2_truncated_boxes) + ) + return output_batch, loss + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + output_batch, loss = super()._rectified_flow_forward(data_batch) + return self._append_factorized_metrics(output_batch, loss) + + +class HdmapToLidarFactorizedBidirectionalRFModel( + HdmapToLidarFactorizedTeacherForcingRFModel +): + """Bidirectional RF foundation with the factorized Stage-2 contract.""" + + def __init__(self, config): + super().__init__(config) + self._factorized_metric_namespace = "stage1" + if not config.factorized_bidirectional_stage1: + raise ValueError( + "factorized bidirectional Stage 1 requires its explicit opt-in" + ) + full_attention_frames = int(config.latent_shape[1]) + net = self.net + while hasattr(net, "module"): + net = net.module + if ( + self.df_block_size != full_attention_frames + or net.temporal_block_size != 0 + or net.temporal_prefix_frames != 0 + ): + raise ValueError( + "factorized bidirectional Stage 1 requires native unmasked " + "attention over the complete latent sequence: " + f"model_block={self.df_block_size}, " + f"net={net.temporal_prefix_frames}+N*" + f"{net.temporal_block_size}, T={full_attention_frames}" + ) + + def _rectified_flow_forward( + self, data_batch: dict[str, Tensor] + ) -> tuple[dict[str, Tensor], Tensor]: + _, x0, condition = self.get_data_and_condition(data_batch) + batch_size, _, num_frames = x0.shape[:3] + if num_frames != self.df_block_size: + raise ValueError( + "factorized bidirectional Stage 1 requires the complete " + f"training clip, got T={num_frames}, " + f"expected={self.df_block_size}" + ) + conditioned_prefix_frames, noisy_mask_T = ( + self._sample_imaginaire_conditioned_prefix( + num_frames=num_frames, + device=x0.device, + ) + ) + + epsilon = torch.randn(x0.shape, **self.tensor_kwargs_fp32) + source, source_weight, source_dropout_fraction = ( + self._sample_teacher_forcing_source(x0, epsilon) + ) + sampled_time = self.rectified_flow.sample_train_time(batch_size) + timesteps_B = self.rectified_flow.get_discrete_timestamp( + sampled_time, self.tensor_kwargs_fp32 + ).reshape(batch_size) + sigmas_B = self.rectified_flow.get_sigmas( + timesteps_B, self.tensor_kwargs_fp32 + ).reshape(batch_size) + time_weights = self.rectified_flow.train_time_weight( + timesteps_B[:, None], self.tensor_kwargs_fp32 + ).reshape(batch_size, -1).mean(dim=1) + + x0_float = x0.float() + sigma_B_T = sigmas_B[:, None] * noisy_mask_T[None] + sigma_5d = sigma_B_T[:, None, :, None, None] + x_t = sigma_5d * source + (1.0 - sigma_5d) * x0_float + target = source - x0_float + active_timesteps = timesteps_B[:, None] * noisy_mask_T[None] + prediction = self._rf_network_forward( + x_t.to(**self.tensor_kwargs), + active_timesteps, + condition, + ).float() + + per_frame_loss = ( + prediction - target + ).square().mean(dim=(1, 3, 4)) * noisy_mask_T[None] + per_instance_loss = self._reduce_teacher_forcing_per_frame_loss( + per_frame_loss, noisy_mask_T + ) + raw_loss = (time_weights * per_instance_loss).mean() + loss = self.teacher_forcing_loss_scale * raw_loss + output_batch = { + "x0": x0, + "xt": x_t, + "sigma": sigmas_B, + "model_pred": prediction, + "edm_loss": loss, + "teacher_forcing_loss": raw_loss, + "timesteps": timesteps_B, + "per_frame_loss": per_frame_loss, + "per_instance_loss": per_instance_loss, + "condition_mask": 1.0 - noisy_mask_T, + "metric/conditioned_prefix_frames": loss.new_tensor( + float(conditioned_prefix_frames) + ), + "metric/stage1_bidirectional_full_attention": loss.new_tensor( + 1.0 + ), + } + if source_weight is not None: + output_batch.update( + { + "metric/geometry_source_confidence_mean": ( + self._current_blockwise_geometry_confidence.mean() + ), + "metric/geometry_source_weight_mean": source_weight.mean(), + "metric/geometry_source_coverage": ( + source_weight > 0.0 + ).float().mean(), + "metric/geometry_source_dropout_fraction": ( + source_dropout_fraction + ), + } + ) + return self._append_factorized_metrics(output_batch, loss) + + +class HdmapToLidarFactorizedBidirectionalIntensityRFModel( + HdmapToLidarFactorizedBidirectionalRFModel +): + """Bidirectional factorized model with separate range/intensity VAEs.""" + + def build_model(self) -> torch.nn.ModuleDict: + model = super().build_model() + range_channels = int(self.vae.latent_ch) + intensity_vae = getattr(self, "intensity_vae", None) + if intensity_vae is None: + raise ValueError("intensity model requires config.intensity_vae") + intensity_channels = int(intensity_vae.latent_ch) + if range_channels <= 0 or intensity_channels <= 0: + raise ValueError( + "range and intensity tokenizer widths must both be positive" + ) + combined_channels = range_channels + intensity_channels + old_external_channels = 3 * range_channels + 1 + new_external_channels = 3 * range_channels + 2 * intensity_channels + 1 + internal_channels = 2 + # Old external input: [range target, HDMap, range geometry, known mask]. + # New external input: [range target, intensity target, HDMap, + # range geometry, intensity geometry, known mask]. + # LVG then appends its condition mask and MinimalV4 appends its padding + # mask; preserve both pretrained internal channels at the end. + input_projection = model["net"].x_embedder.proj[1] + input_projection._checkpoint_channel_remap = ( + "input", + old_external_channels + internal_channels, + new_external_channels + internal_channels, + ( + (0, range_channels, 0, range_channels), + ( + range_channels, + 2 * range_channels, + combined_channels, + combined_channels + range_channels, + ), + ( + 2 * range_channels, + 3 * range_channels, + combined_channels + range_channels, + combined_channels + 2 * range_channels, + ), + ( + 3 * range_channels, + old_external_channels, + new_external_channels - 1, + new_external_channels, + ), + ( + old_external_channels, + old_external_channels + internal_channels, + new_external_channels, + new_external_channels + internal_channels, + ), + ), + ) + # Preserve the pretrained range head exactly. The new intensity head + # starts at zero and is learned during fine-tuning. + model["net"].final_layer.linear._checkpoint_channel_remap = ( + "output", + range_channels, + combined_channels, + ((0, range_channels, 0, range_channels),), + ) + return model + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarRectifiedFlowModel(HdmapToLidarRectifiedFlowModel): + inference_model_cls = HdmapToLidarRectifiedFlowModel + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarAutoregressiveRFModel( + HdmapToLidarAutoregressiveRFModel +): + inference_model_cls = HdmapToLidarAutoregressiveRFModel + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarLaGenSDERFModel( + HdmapToLidarLaGenSDERFModel +): + inference_model_cls = HdmapToLidarLaGenSDERFModel + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarDiffusionForcingRFModel( + HdmapToLidarDiffusionForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarTeacherForcingRFModel( + HdmapToLidarTeacherForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarImaginaireTeacherForcingRFModel( + HdmapToLidarImaginaireTeacherForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarImaginaireOnePassTeacherForcingRFModel( + HdmapToLidarImaginaireOnePassTeacherForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarConcatGeometryTeacherForcingRFModel( + HdmapToLidarConcatGeometryTeacherForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarMultiTaskTeacherForcingRFModel( + HdmapToLidarMultiTaskTeacherForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarFactorizedTeacherForcingRFModel( + HdmapToLidarFactorizedTeacherForcingRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarFactorizedBidirectionalRFModel( + HdmapToLidarFactorizedBidirectionalRFModel +): + pass + + +@diffusion_fsdp_class_decorator +class FSDPHdmapToLidarFactorizedBidirectionalIntensityRFModel( + HdmapToLidarFactorizedBidirectionalIntensityRFModel +): + pass diff --git a/diffusion/training/models/hdmaptolidar_model_sf_dmd.py b/diffusion/training/models/hdmaptolidar_model_sf_dmd.py new file mode 100644 index 0000000000000000000000000000000000000000..12765c2ad009a911a67db0977d91e5211649341c --- /dev/null +++ b/diffusion/training/models/hdmaptolidar_model_sf_dmd.py @@ -0,0 +1,4105 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Self-forcing DMD for block-causal HDMap-to-LiDAR generation. + +A frozen bidirectional teacher and a trainable copy provide the real and fake +score functions used by DMD. The student generates non-overlapping causal +chunks with bounded per-layer K/V history. ArtiFixer mode normally stores the +selected noisy-query K/V; the TF handoff can instead commit finalized clean +history while retaining the first chunk as an attention sink and supporting +graph-connected replay through the full generated rollout. Long rollouts always +use generated latent/range history; target LiDAR is retained only to define +tensor shapes. +""" + +from __future__ import annotations + +import copy +import functools +import os +from dataclasses import dataclass +from typing import Any + +import torch +from megatron.core import parallel_state +from torch import Tensor, nn +from torch.nn import functional as F +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import ShardingStrategy +from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy + +from diffusion.training.datasets.lidar_dataset.forecast_warp import ( + TorchSpatialPointMap, + build_stage2_factorized_geometry, + lidar_poses_for_global_tokens, + local_hit_density_confidence, + spatial_warp_window, + warp_blockwise_history_to_video, +) +from diffusion.training.models.hdmaptolidar_model import ( + diffusion_fsdp_class_decorator, +) +from diffusion.training.models.hdmaptolidar_model_rf import ( + HdmapToLidarDiffusionForcingRFModel, + _sensor_tables_from_ray_directions, + _sample_world_synchronized_categorical, +) +from diffusion.training.utils.diffusion_forcing import temporal_chunk_slices +from diffusion.training.utils.sf_dmd import ( + active_slice_loss, + complete_score_state_dict, + confidence_composite_geometry, + confidence_weighted_geometry_source, + dmd_pseudo_target, + fixed_sde_sigmas, + rf_velocity_to_x0, + sde_renoise, + sfdmd_nonoverlap_layout, +) +from utils import distributed, log +from utils.lazy_config import instantiate as lazy_instantiate + + +_DIRECT_FORWARD_KEY = "__sfdmd_direct_student_forward__" + + +@dataclass +class SFDMDReplayRecord: + """Everything needed to replay one selected three-latent query.""" + + block_index: int + window_start: int + global_start: int + score_active_start: int + score_active_end: int + replay_xt: Tensor + replay_sigma: float + student_condition: Any + student_hdmap: Tensor + student_side_condition: Tensor + student_known_mask: Tensor | None = None + student_active_start: int = 0 + student_active_end: int = -1 + generated_block: Tensor | None = None + history_commit_block: Tensor | None = None + generated_window: Tensor | None = None + score_condition: Any = None + score_hdmap: Tensor | None = None + score_side_condition: Tensor | None = None + score_known_mask: Tensor | None = None + conditioned_prefix_frames: int = 0 + + +@dataclass +class SFDMDLongRollout: + """One cached self-forced trajectory shared by a complete DMD cycle.""" + + records: list[SFDMDReplayRecord] + generated_latents: Tensor + generated_real_latents: Tensor + num_real_frames: int + exit_step: int + conditioned_prefix_frames: int = 0 + kv_seed_frames: int = 0 + conditioned_prefix_latents: Tensor | None = None + conditioned_prefix_condition: Any = None + conditioned_prefix_hdmap: Tensor | None = None + conditioned_prefix_side_condition: Tensor | None = None + geometry_source_latents: Tensor | None = None + geometry_confidence_latents: Tensor | None = None + factorized_hdmap_mode: str = "" + factorized_geometry_mode: str = "" + factorized_geometry_observations: int = 0 + + +@dataclass +class SFDMDScoreBatch: + """One ArtiFixer-style critic source draw shared by the full rollout.""" + + sigma: Tensor + timestep: Tensor + source: Tensor + + +class _RFScoreModule(nn.Module): + """Bidirectional RF velocity network with Stage-2 conditioning.""" + + def __init__( + self, + net: nn.Module, + *, + concat_geometry: bool = False, + concat_known_mask: bool = False, + ): + super().__init__() + self.net = net + self.concat_geometry = concat_geometry + self.concat_known_mask = concat_known_mask + + def forward( + self, + x_t: Tensor, + timesteps: Tensor, + hdmap: Tensor, + side_condition: Tensor | None, + known_mask: Tensor | None, + condition_dict: dict[str, Any], + ) -> Tensor: + if x_t.shape[:1] != hdmap.shape[:1] or x_t.shape[2:] != hdmap.shape[2:]: + raise ValueError( + "score hdmap must align with x_t except channels: " + f"x_t={tuple(x_t.shape)}, hdmap={tuple(hdmap.shape)}" + ) + net_input = torch.cat([x_t, hdmap.to(x_t.dtype)], dim=1) + if self.concat_geometry: + if side_condition is None: + raise ValueError( + "score network requires concatenated geometry" + ) + if side_condition.shape[:1] != x_t.shape[:1] or ( + side_condition.shape[2:] != x_t.shape[2:] + ): + raise ValueError( + "score geometry must align with x_t except channels: " + f"x_t={tuple(x_t.shape)}, " + f"geometry={tuple(side_condition.shape)}" + ) + net_input = torch.cat( + [net_input, side_condition.to(x_t.dtype)], dim=1 + ) + if self.concat_known_mask: + if known_mask is None: + known_mask = x_t.new_zeros((x_t.shape[0], x_t.shape[2])) + else: + known_mask = known_mask.to( + device=x_t.device, dtype=x_t.dtype + ) + if known_mask.ndim == 1: + known_mask = known_mask[None] + if known_mask.shape[0] == 1 and x_t.shape[0] != 1: + known_mask = known_mask.expand(x_t.shape[0], -1) + if known_mask.shape != (x_t.shape[0], x_t.shape[2]): + raise ValueError( + "score known mask must be (B,T), got " + f"{tuple(known_mask.shape)} for {tuple(x_t.shape)}" + ) + known_channel = known_mask[:, None, :, None, None].expand( + -1, 1, -1, x_t.shape[3], x_t.shape[4] + ) + net_input = torch.cat([net_input, known_channel], dim=1) + t_for_net = ( + timesteps.squeeze(-1) + if timesteps.ndim == 2 and timesteps.shape[1] == 1 + else timesteps + ) + network_condition = dict(condition_dict) + if ( + not self.concat_geometry + and int(getattr(self.net, "side_condition_channels", 0)) > 0 + ): + if side_condition is None: + raise ValueError( + "score network requires accumulated-geometry side condition" + ) + network_condition["side_condition"] = side_condition.to( + net_input.dtype + ) + return self.net( + x=net_input, + timesteps=t_for_net.to(net_input.dtype), + **network_condition, + ).float() + + +class HdmapToLidarSFDMDModel(HdmapToLidarDiffusionForcingRFModel): + """Fixed-step, long-rollout Self-Forcing DMD model.""" + + def __init__(self, config): + super().__init__(config) + self.sfdmd_num_real_frames = int( + getattr(config, "sfdmd_num_real_frames", 41) + ) + self.sfdmd_window_frames = int( + getattr(config, "sfdmd_window_frames", 8) + ) + self.sfdmd_fake_updates = int( + getattr(config, "sfdmd_fake_updates_per_cycle", 5) + ) + self.sfdmd_kv_cache_frames = int( + getattr( + config, + "sfdmd_kv_cache_frames", + 2 * self.df_block_size, + ) + ) + self.sfdmd_kv_sink_frames = int( + getattr(config, "sfdmd_kv_sink_frames", 0) + ) + self.sfdmd_tbptt_blocks = int( + getattr(config, "sfdmd_tbptt_blocks", 1) + ) + self.sfdmd_allow_truncated_bptt = bool( + getattr(config, "sfdmd_allow_truncated_bptt", False) + ) + self.sfdmd_run_kv_equivalence_gate = bool( + getattr(config, "sfdmd_run_kv_equivalence_gate", True) + ) + self.sfdmd_skip_zero_crossattn = bool( + getattr(config, "sfdmd_skip_zero_crossattn", False) + ) + self.sfdmd_stream_condition_vae_encode = bool( + getattr(config, "sfdmd_stream_condition_vae_encode", False) + ) + self.sfdmd_condition_vae_cache_frames = int( + getattr(config, "sfdmd_condition_vae_cache_frames", 6) + ) + self.sfdmd_accumulated_geometry_warp = bool( + getattr(config, "sfdmd_accumulated_geometry_warp", False) + ) + self.sfdmd_geometry_source = bool( + getattr(config, "sfdmd_geometry_source", False) + ) + self.sfdmd_geometry_source_noise_floor = float( + getattr(config, "sfdmd_geometry_source_noise_floor", 0.1) + ) + self.sfdmd_geometry_source_preencode_confidence = bool( + getattr( + config, + "sfdmd_geometry_source_preencode_confidence", + False, + ) + ) + self.sfdmd_geometry_source_density_kernel = int( + getattr(config, "sfdmd_geometry_source_density_kernel", 5) + ) + self.sfdmd_geometry_source_density_saturation_hits = float( + getattr( + config, + "sfdmd_geometry_source_density_saturation_hits", + 5.0, + ) + ) + self.sfdmd_spatial_map_radius_m = float( + getattr(config, "sfdmd_spatial_map_radius_m", 75.0) + ) + self.sfdmd_spatial_map_voxel_m = float( + getattr(config, "sfdmd_spatial_map_voxel_m", 0.2) + ) + self.sfdmd_spatial_map_voxel_policy = str( + getattr(config, "sfdmd_spatial_map_voxel_policy", "newest") + ) + self.sfdmd_spatial_map_observation_unit = str( + getattr(config, "sfdmd_spatial_map_observation_unit", "block") + ) + self.sfdmd_spatial_map_static_min_observations = int( + getattr(config, "sfdmd_spatial_map_static_min_observations", 2) + ) + self.sfdmd_spatial_map_candidate_ttl_updates = int( + getattr(config, "sfdmd_spatial_map_candidate_ttl_updates", 1) + ) + self.sfdmd_spatial_map_include_latest = bool( + getattr(config, "sfdmd_spatial_map_include_latest", True) + ) + self.sfdmd_spatial_map_free_space_clear = bool( + getattr(config, "sfdmd_spatial_map_free_space_clear", False) + ) + self.sfdmd_spatial_map_free_space_margin_m = float( + getattr(config, "sfdmd_spatial_map_free_space_margin_m", 0.75) + ) + self.sfdmd_spatial_map_free_space_misses_to_remove = int( + getattr( + config, + "sfdmd_spatial_map_free_space_misses_to_remove", + 2, + ) + ) + self.sfdmd_sde_eta = float( + getattr(config, "sfdmd_sde_eta", 1.0) + ) + self.sfdmd_num_steps = int( + getattr(config, "sfdmd_num_steps", 4) + ) + self.sfdmd_artifixer_matching = bool( + getattr(config, "sfdmd_artifixer_matching", False) + ) + self.sfdmd_imaginaire_matching = bool( + getattr(config, "sfdmd_imaginaire_matching", False) + ) + self.sfdmd_clean_x0_kv_commit = bool( + getattr(config, "sfdmd_clean_x0_kv_commit", False) + ) + self.sfdmd_factorized_conditioning = bool( + getattr(config, "sfdmd_factorized_conditioning", False) + ) + self.sfdmd_temporal_history_source = str( + getattr(config, "sfdmd_temporal_history_source", "generated") + ) + self.sfdmd_geometry_history_source = str( + getattr(config, "sfdmd_geometry_history_source", "generated") + ) + self.sfdmd_factorized_prefix_frames = tuple( + int(value) for value in config.stage2_factorized_prefix_frames + ) + self.sfdmd_factorized_prefix_probs = torch.tensor( + tuple( + float(value) + for value in config.stage2_factorized_prefix_probs + ), + dtype=torch.float32, + ) + self.sfdmd_factorized_hdmap_modes = tuple( + str(value) for value in config.stage2_factorized_hdmap_modes + ) + self.sfdmd_factorized_hdmap_probs = torch.tensor( + tuple( + float(value) + for value in config.stage2_factorized_hdmap_probs + ), + dtype=torch.float32, + ) + self.sfdmd_factorized_geometry_modes = tuple( + str(value) + for value in config.stage2_factorized_geometry_modes_known + ) + self.sfdmd_factorized_geometry_probs = torch.tensor( + tuple( + float(value) + for value in config.stage2_factorized_geometry_probs_known + ), + dtype=torch.float32, + ) + self.sfdmd_factorized_geometry_observation_frames = tuple( + int(value) + for value in config.factorized_geometry_observation_frames + ) + self.sfdmd_factorized_geometry_observation_probs = torch.tensor( + tuple( + float(value) + for value in config.factorized_geometry_observation_probs + ), + dtype=torch.float32, + ) + self.sfdmd_factorized_actor_box_time_mode = str( + getattr( + config, + "factorized_geometry_actor_box_time_mode", + "frame", + ) + ) + if self.sfdmd_factorized_actor_box_time_mode not in ( + "frame", + "current_to_next", + "previous_to_current", + ): + raise ValueError( + "unsupported factorized_geometry_actor_box_time_mode " + f"{self.sfdmd_factorized_actor_box_time_mode!r}" + ) + self.imaginaire_conditioned_prefix_frames = tuple( + int(value) + for value in getattr( + config, + "imaginaire_conditioned_prefix_frames", + [0, 1], + ) + ) + prefix_probs = tuple( + float(value) + for value in getattr( + config, + "imaginaire_conditioned_prefix_probs", + [0.7, 0.3], + ) + ) + if not self.imaginaire_conditioned_prefix_frames: + self.imaginaire_conditioned_prefix_frames = (0, 1) + if not prefix_probs: + prefix_probs = (0.7, 0.3) + if len(self.imaginaire_conditioned_prefix_frames) != len( + prefix_probs + ): + raise ValueError( + "Imaginaire prefix frames/probabilities must have the same " + "length" + ) + if ( + any(value < 0 for value in self.imaginaire_conditioned_prefix_frames) + or any(value < 0.0 for value in prefix_probs) + or sum(prefix_probs) <= 0.0 + ): + raise ValueError( + "Imaginaire prefix frames must be non-negative and prefix " + "probabilities must have positive mass" + ) + self.imaginaire_conditioned_prefix_probs = torch.tensor( + prefix_probs, dtype=torch.float32 + ) / sum(prefix_probs) + self.sfdmd_temporal_prefix_frames = int( + getattr(config, "sfdmd_temporal_prefix_frames", 0) + ) + self.sfdmd_student_update_freq = int( + getattr(config, "sfdmd_student_update_freq", 5) + ) + self.sfdmd_ema_start_cycle = int( + getattr(config, "sfdmd_ema_start_cycle", 0) + ) + self.sfdmd_teacher_guidance = float( + getattr(config, "sfdmd_teacher_guidance", 1.0) + ) + self.sfdmd_critic_min_sigma = float( + getattr(config, "sfdmd_critic_min_sigma", 0.02) + ) + self.sfdmd_critic_max_sigma = float( + getattr(config, "sfdmd_critic_max_sigma", 0.98) + ) + self.sfdmd_max_grad_norm = float( + getattr(config, "sfdmd_max_grad_norm", 1.0) + ) + self.sfdmd_teacher_checkpoint = str( + getattr(config, "sfdmd_teacher_checkpoint") + ) + if self._sfdmd_window_tokens() != int(config.latent_shape[1]): + raise ValueError( + "SF-DMD window length must match the trained latent shape: " + f"window_tokens={self._sfdmd_window_tokens()}, " + f"latent T={config.latent_shape[1]}" + ) + if ( + self.sfdmd_num_real_frames - self.sfdmd_window_frames + ) % self.df_block_size != 0: + raise ValueError( + "num_real_frames-window_frames must be divisible by the DF " + f"block size: ({self.sfdmd_num_real_frames}-" + f"{self.sfdmd_window_frames}) % {self.df_block_size} != 0" + ) + if self.sfdmd_fake_updates <= 0: + raise ValueError("sfdmd_fake_updates_per_cycle must be positive") + if self.sfdmd_condition_vae_cache_frames <= 0: + raise ValueError( + "sfdmd_condition_vae_cache_frames must be positive" + ) + if self.sfdmd_stream_condition_vae_encode: + vae_net = getattr(getattr(self, "vae", None), "vae_net", None) + if not getattr( + vae_net, "supports_encoder_temporal_kv_cache", False + ): + raise ValueError( + "streamed SF-DMD condition encoding requires a " + "1x-temporal causal-attention TransformerVAE encoder" + ) + if not 0.0 <= self.sfdmd_sde_eta <= 1.0: + raise ValueError( + f"sfdmd_sde_eta must be in [0,1], got {self.sfdmd_sde_eta}" + ) + if self.sfdmd_artifixer_matching and self.sfdmd_sde_eta != 1.0: + raise ValueError( + "ArtiFixer matching uses a fresh source endpoint at every " + "transition; set sfdmd_sde_eta=1.0" + ) + if self.sfdmd_artifixer_matching and self.sfdmd_geometry_source: + student_side_channels = int( + getattr(config.net, "side_condition_channels", 0) + ) + score_side_channels = int( + getattr(config.sfdmd_teacher_net, "side_condition_channels", 0) + ) + if ( + not self.sfdmd_accumulated_geometry_warp + or student_side_channels <= 0 + or score_side_channels != student_side_channels + ): + raise ValueError( + "geometry-source ArtiFixer matching requires accumulated " + "geometry and identical positive student/score side " + "projection widths" + ) + if self.sfdmd_num_steps <= 0: + raise ValueError( + f"sfdmd_num_steps must be positive, got {self.sfdmd_num_steps}" + ) + if self.sfdmd_student_update_freq <= 0: + raise ValueError("sfdmd_student_update_freq must be positive") + if ( + self.sfdmd_artifixer_matching + and self.sfdmd_imaginaire_matching + ): + raise ValueError( + "ArtiFixer and Imaginaire SF-DMD matching are exclusive" + ) + if ( + self.sfdmd_clean_x0_kv_commit + and not self.sfdmd_artifixer_matching + ): + raise ValueError( + "explicit clean-x0 K/V commitment is only supported by the " + "ArtiFixer-matched TF handoff" + ) + if self.sfdmd_factorized_conditioning: + distributions = ( + ( + self.sfdmd_factorized_prefix_frames, + self.sfdmd_factorized_prefix_probs, + "prefix", + ), + ( + self.sfdmd_factorized_hdmap_modes, + self.sfdmd_factorized_hdmap_probs, + "HDMap", + ), + ( + self.sfdmd_factorized_geometry_modes, + self.sfdmd_factorized_geometry_probs, + "geometry", + ), + ( + self.sfdmd_factorized_geometry_observation_frames, + self.sfdmd_factorized_geometry_observation_probs, + "geometry observations", + ), + ) + for values, probabilities, label in distributions: + if ( + not values + or len(values) != probabilities.numel() + or bool((probabilities < 0).any()) + or float(probabilities.sum()) <= 0.0 + ): + raise ValueError( + f"invalid factorized SF-DMD {label} distribution" + ) + probabilities /= probabilities.sum() + if ( + not self.sfdmd_artifixer_matching + or self.sfdmd_imaginaire_matching + or not self.sfdmd_clean_x0_kv_commit + ): + raise ValueError( + "factorized SF-DMD requires the ArtiFixer clean-commit " + "handoff" + ) + if self.input_video_has_prepend: + raise ValueError( + "factorized SF-DMD requires unique input frames" + ) + if not bool(config.stage2_known_mask_concat) or not bool( + config.blockwise_warped_history_concat + ): + raise ValueError( + "factorized SF-DMD requires concatenated geometry and " + "the known-frame mask channel" + ) + if not bool(config.factorized_decouple_geometry_observations): + raise ValueError( + "factorized SF-DMD requires K-independent geometry " + "observations" + ) + if tuple(config.stage2_factorized_geometry_modes_k0) != ( + self.sfdmd_factorized_geometry_modes + ) or not torch.allclose( + torch.tensor( + config.stage2_factorized_geometry_probs_k0, + dtype=torch.float32, + ) + / sum(config.stage2_factorized_geometry_probs_k0), + self.sfdmd_factorized_geometry_probs, + ): + raise ValueError( + "factorized SF-DMD requires one K-independent geometry " + "mode distribution" + ) + if set(self.sfdmd_factorized_hdmap_modes) - {"null", "full"}: + raise ValueError( + "factorized SF-DMD supports null/full HDMap modes" + ) + if set(self.sfdmd_factorized_geometry_modes) - { + "null", + "rolling_static", + "frozen_object", + }: + raise ValueError( + "factorized SF-DMD supports null, rolling_static, and " + "frozen_object geometry" + ) + if any( + value < 0 or value >= self._sfdmd_total_tokens() + for value in self.sfdmd_factorized_prefix_frames + ): + raise ValueError( + "factorized SF-DMD prefixes must leave a generated frame" + ) + if any( + value <= 0 or value > self._sfdmd_total_tokens() + for value in ( + self.sfdmd_factorized_geometry_observation_frames + ) + ): + raise ValueError( + "factorized SF-DMD geometry observation counts must fit " + "the rollout" + ) + if ( + int(getattr(config.net, "side_condition_channels", 0)) != 0 + or int( + getattr( + config.sfdmd_teacher_net, + "side_condition_channels", + 0, + ) + ) + != 0 + ): + raise ValueError( + "factorized SF-DMD concatenates geometry and must not use " + "a side projection" + ) + valid_history_sources = {"generated", "ground_truth"} + if self.sfdmd_temporal_history_source not in valid_history_sources: + raise ValueError( + "sfdmd_temporal_history_source must be 'generated' or " + f"'ground_truth', got {self.sfdmd_temporal_history_source!r}" + ) + if self.sfdmd_geometry_history_source not in valid_history_sources: + raise ValueError( + "sfdmd_geometry_history_source must be 'generated' or " + f"'ground_truth', got {self.sfdmd_geometry_history_source!r}" + ) + if ( + self.sfdmd_temporal_history_source == "ground_truth" + and not self.sfdmd_clean_x0_kv_commit + ): + raise ValueError( + "ground-truth temporal history requires clean-x0 K/V commits" + ) + if ( + self.sfdmd_geometry_history_source == "ground_truth" + and not self.sfdmd_factorized_conditioning + ): + raise ValueError( + "ground-truth geometry history requires factorized conditioning" + ) + if self.sfdmd_ema_start_cycle < 0: + raise ValueError("sfdmd_ema_start_cycle must be non-negative") + if self.sfdmd_teacher_guidance < 1.0: + raise ValueError("sfdmd_teacher_guidance must be at least 1") + if not ( + 0.0 + <= self.sfdmd_critic_min_sigma + < self.sfdmd_critic_max_sigma + <= 1.0 + ): + raise ValueError( + "SF-DMD critic sigma bounds must satisfy " + "0 <= min < max <= 1, got " + f"{self.sfdmd_critic_min_sigma}/" + f"{self.sfdmd_critic_max_sigma}" + ) + if self.sfdmd_max_grad_norm <= 0.0: + raise ValueError("sfdmd_max_grad_norm must be positive") + if self.sfdmd_spatial_map_radius_m <= 0.0: + raise ValueError("sfdmd_spatial_map_radius_m must be positive") + if not 0.0 <= self.sfdmd_geometry_source_noise_floor <= 1.0: + raise ValueError( + "sfdmd_geometry_source_noise_floor must be in [0,1]" + ) + if ( + self.sfdmd_geometry_source_density_kernel <= 0 + or self.sfdmd_geometry_source_density_kernel % 2 == 0 + ): + raise ValueError( + "sfdmd_geometry_source_density_kernel must be positive and odd" + ) + if self.sfdmd_geometry_source_density_saturation_hits <= 0.0: + raise ValueError( + "sfdmd_geometry_source_density_saturation_hits must be positive" + ) + if self.sfdmd_spatial_map_voxel_m <= 0.0: + raise ValueError("sfdmd_spatial_map_voxel_m must be positive") + if self.sfdmd_spatial_map_voxel_policy not in ( + "newest", + "persistent_static", + ): + raise ValueError( + "sfdmd_spatial_map_voxel_policy must be 'newest' or " + "'persistent_static'" + ) + if self.sfdmd_spatial_map_observation_unit not in ( + "block", + "frame", + ): + raise ValueError( + "sfdmd_spatial_map_observation_unit must be 'block' or 'frame'" + ) + if self.sfdmd_spatial_map_static_min_observations < 2: + raise ValueError( + "sfdmd_spatial_map_static_min_observations must be at least 2" + ) + if self.sfdmd_spatial_map_candidate_ttl_updates < 1: + raise ValueError( + "sfdmd_spatial_map_candidate_ttl_updates must be positive" + ) + if ( + self.sfdmd_spatial_map_free_space_clear + and self.sfdmd_spatial_map_voxel_policy != "persistent_static" + ): + raise ValueError( + "sfdmd_spatial_map_free_space_clear requires " + "sfdmd_spatial_map_voxel_policy='persistent_static'" + ) + if self.sfdmd_spatial_map_free_space_margin_m <= 0.0: + raise ValueError( + "sfdmd_spatial_map_free_space_margin_m must be positive" + ) + if self.sfdmd_spatial_map_free_space_misses_to_remove < 1: + raise ValueError( + "sfdmd_spatial_map_free_space_misses_to_remove must be positive" + ) + temporal_chunk_slices( + self._sfdmd_total_tokens(), + self.df_block_size, + self.sfdmd_temporal_prefix_frames, + ) + temporal_chunk_slices( + self._sfdmd_window_tokens(), + self.df_block_size, + self.sfdmd_temporal_prefix_frames, + ) + if self.sfdmd_imaginaire_matching: + temporal_chunk_slices( + self.sfdmd_kv_cache_frames, + self.df_block_size, + self.sfdmd_temporal_prefix_frames, + ) + if self.sfdmd_kv_sink_frames != 0: + raise ValueError( + "Imaginaire-matched SF-DMD does not use a KV sink" + ) + else: + if self.sfdmd_temporal_prefix_frames: + if ( + self.sfdmd_kv_cache_frames + < self.sfdmd_temporal_prefix_frames + self.df_block_size + or ( + self.sfdmd_kv_cache_frames + - self.sfdmd_temporal_prefix_frames + ) + % self.df_block_size + != 0 + ): + raise ValueError( + "prefix-aware sfdmd_kv_cache_frames must retain the " + "prefix and a positive whole number of causal blocks" + ) + if ( + self.sfdmd_kv_sink_frames + != self.sfdmd_temporal_prefix_frames + ): + raise ValueError( + "prefix-aware sfdmd_kv_sink_frames must equal the " + "temporal prefix width" + ) + else: + if ( + self.sfdmd_kv_cache_frames < self.df_block_size + or self.sfdmd_kv_cache_frames % self.df_block_size != 0 + ): + raise ValueError( + "sfdmd_kv_cache_frames must retain a positive whole " + "number of causal blocks" + ) + if ( + self.sfdmd_kv_sink_frames < 0 + or self.sfdmd_kv_sink_frames + >= self.sfdmd_kv_cache_frames + or self.sfdmd_kv_sink_frames % self.df_block_size != 0 + ): + raise ValueError( + "sfdmd_kv_sink_frames must retain a non-negative whole " + "number of causal blocks and be smaller than the " + "persistent cache" + ) + if self.sfdmd_tbptt_blocks <= 0: + raise ValueError("sfdmd_tbptt_blocks must be positive") + full_bptt_blocks = len( + self._sfdmd_chunk_slices(self._sfdmd_total_tokens()) + ) + artifixer_sink_frames = ( + self.sfdmd_temporal_prefix_frames or self.df_block_size + ) + artifixer_cache_frames = ( + self.sfdmd_temporal_prefix_frames + 2 * self.df_block_size + if self.sfdmd_temporal_prefix_frames + else 2 * self.df_block_size + ) + if ( + self.sfdmd_allow_truncated_bptt + and not self.sfdmd_artifixer_matching + ): + raise ValueError( + "truncated SF-DMD BPTT is only supported by the explicit " + "ArtiFixer handoff" + ) + if self.sfdmd_artifixer_matching and ( + self.sfdmd_kv_sink_frames != artifixer_sink_frames + or self.sfdmd_kv_cache_frames != artifixer_cache_frames + ): + raise ValueError( + "ArtiFixer-aligned LiDAR SF-DMD requires the first chunk as " + "an attention sink and two chunks of retained history" + ) + if ( + self.sfdmd_artifixer_matching + and self.sfdmd_tbptt_blocks != full_bptt_blocks + and not self.sfdmd_allow_truncated_bptt + ): + raise ValueError( + "canonical ArtiFixer-aligned LiDAR SF-DMD requires " + f"full-rollout BPTT ({full_bptt_blocks} blocks); set " + "sfdmd_allow_truncated_bptt=True only for an explicit " + "memory-bounded handoff" + ) + if self.sfdmd_imaginaire_matching: + if self.input_video_has_prepend: + raise ValueError( + "Imaginaire-matched SF-DMD requires unique input frames; " + "set input_video_has_prepend=False" + ) + if self.sfdmd_temporal_prefix_frames <= 0: + raise ValueError( + "Imaginaire-matched SF-DMD requires a positive temporal " + "prefix" + ) + allowed_conditioned_prefixes = { + 0, + self.sfdmd_temporal_prefix_frames, + } + if not set(self.imaginaire_conditioned_prefix_frames).issubset( + allowed_conditioned_prefixes + ): + raise ValueError( + "Imaginaire SF-DMD conditioned prefixes must contain " + "whole initial chunks; expected only " + f"{sorted(allowed_conditioned_prefixes)}, got " + f"{self.imaginaire_conditioned_prefix_frames}" + ) + if ( + int(getattr(config.net, "temporal_block_size", 0)) + != self.df_block_size + or int( + getattr(config.net, "temporal_prefix_frames", 0) + ) + != self.sfdmd_temporal_prefix_frames + ): + raise ValueError( + "Imaginaire SF-DMD model/network temporal layouts must " + "match" + ) + if self.sfdmd_num_real_frames != self.sfdmd_window_frames: + raise ValueError( + "Imaginaire-matched SF-DMD scores one complete rollout; " + "sfdmd_num_real_frames must equal sfdmd_window_frames" + ) + if ( + self.sfdmd_kv_cache_frames + != self._sfdmd_window_tokens() + or self.sfdmd_kv_sink_frames != 0 + or self.sfdmd_tbptt_blocks != 1 + ): + raise ValueError( + "Imaginaire-matched SF-DMD requires a full-sequence " + "clean K/V cache, no sink, and one-block replay" + ) + insufficient_map_observations = ( + self.sfdmd_spatial_map_static_min_observations < 3 + if self.sfdmd_spatial_map_observation_unit == "block" + else self.sfdmd_spatial_map_static_min_observations < 2 + ) + if ( + not self.sfdmd_accumulated_geometry_warp + or self.sfdmd_spatial_map_include_latest + or insufficient_map_observations + or self.sfdmd_geometry_source + ): + raise ValueError( + "Imaginaire-matched LiDAR SF-DMD requires accumulated " + "strict geometry side conditioning, no latest sweep, " + "and pure Gaussian initialization" + ) + + self._warp_min_range = float(getattr(config, "sfdmd_min_range")) + self._warp_max_range = float(getattr(config, "sfdmd_max_range")) + self._warp_min_value = float(getattr(config, "sfdmd_min_value")) + self._warp_inverse_depth = bool( + getattr(config, "sfdmd_inverse_depth", False) + ) + geometry_root = str( + getattr(config, "sfdmd_geometry_root_path", "") or "" + ) + geometry_filter = str( + getattr(config, "sfdmd_geometry_filter_list_path", "") or "" + ) + self._warp_geometry = None + if geometry_root and geometry_filter: + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_lidar_geometry, + ) + + self._warp_geometry = load_waymo_lidar_geometry( + root_path=geometry_root, + filter_list_path=geometry_filter, + resample_width=int( + getattr(config, "sfdmd_geometry_resample_width", -1) + ), + ) + if self.sfdmd_skip_zero_crossattn: + if not hasattr(self.net, "enable_zero_crossattn_skip"): + raise NotImplementedError( + f"{type(self.net).__name__} does not support zero text " + "cross-attention bypass" + ) + student_blocks = self.net.enable_zero_crossattn_skip() + log.info( + "Enabled exact zero-text cross-attention bypass on " + f"{student_blocks} student blocks" + ) + self._set_up_score_models() + log.info( + "HdmapToLidarSFDMDModel: " + f"real_frames={self.sfdmd_num_real_frames}, " + f"input_video_has_prepend={self.input_video_has_prepend}, " + f"blocks={len(self._sfdmd_chunk_slices(self._sfdmd_total_tokens()))}, " + f"kv_cache_frames={self.sfdmd_kv_cache_frames}, " + f"kv_sink_frames={self.sfdmd_kv_sink_frames}, " + f"tbptt_blocks={self.sfdmd_tbptt_blocks}, " + "allow_truncated_bptt=" + f"{self.sfdmd_allow_truncated_bptt}, " + f"skip_zero_crossattn={self.sfdmd_skip_zero_crossattn}, " + f"stream_condition_encode=" + f"{self.sfdmd_stream_condition_vae_encode}, " + f"condition_cache_frames=" + f"{self.sfdmd_condition_vae_cache_frames}, " + f"accumulated_geometry={self.sfdmd_accumulated_geometry_warp}, " + f"geometry_source={self.sfdmd_geometry_source}, " + "geometry_source_preencode_confidence=" + f"{self.sfdmd_geometry_source_preencode_confidence}, " + "geometry_noise_floor=" + f"{self.sfdmd_geometry_source_noise_floor}, " + f"spatial_radius_m={self.sfdmd_spatial_map_radius_m}, " + f"spatial_voxel_m={self.sfdmd_spatial_map_voxel_m}, " + f"spatial_voxel_policy={self.sfdmd_spatial_map_voxel_policy}, " + "spatial_observation_unit=" + f"{self.sfdmd_spatial_map_observation_unit}, " + "spatial_static_min_obs=" + f"{self.sfdmd_spatial_map_static_min_observations}, " + "spatial_candidate_ttl=" + f"{self.sfdmd_spatial_map_candidate_ttl_updates}, " + f"spatial_include_latest={self.sfdmd_spatial_map_include_latest}, " + "spatial_free_clear=" + f"{self.sfdmd_spatial_map_free_space_clear}, " + "spatial_free_margin_m=" + f"{self.sfdmd_spatial_map_free_space_margin_m}, " + "spatial_free_misses=" + f"{self.sfdmd_spatial_map_free_space_misses_to_remove}, " + f"num_steps={self.sfdmd_num_steps}, " + f"sde_eta={self.sfdmd_sde_eta}, " + f"artifixer_matching={self.sfdmd_artifixer_matching}, " + f"imaginaire_matching={self.sfdmd_imaginaire_matching}, " + f"clean_x0_kv_commit={self.sfdmd_clean_x0_kv_commit}, " + "factorized_conditioning=" + f"{self.sfdmd_factorized_conditioning}, " + "temporal_history_source=" + f"{self.sfdmd_temporal_history_source}, " + "geometry_history_source=" + f"{self.sfdmd_geometry_history_source}, " + f"student_update_freq={self.sfdmd_student_update_freq}, " + f"ema_start_cycle={self.sfdmd_ema_start_cycle}, " + f"teacher_guidance={self.sfdmd_teacher_guidance}, " + f"max_grad_norm={self.sfdmd_max_grad_norm}, " + f"fake_updates={self.sfdmd_fake_updates}, " + f"teacher={self.sfdmd_teacher_checkpoint}" + ) + + def _configure_warp_geometry( + self, + data_batch: dict[str, Any], + reference: Tensor, + ) -> None: + """Select calibrated spinning-LiDAR geometry for this sensor batch.""" + sensor_rays = data_batch.get("sensor_ray_directions") + if sensor_rays is None: + if self._warp_geometry is None: + raise KeyError( + "SF-DMD requires sensor_ray_directions when no legacy " + "geometry fallback is configured" + ) + return + rays = torch.as_tensor( + sensor_rays, + device=reference.device, + dtype=torch.float32, + ) + if rays.ndim != 4 or rays.shape[-1] != 3: + raise ValueError( + "sensor_ray_directions must be (B,H,W,3), got " + f"{tuple(rays.shape)}" + ) + if tuple(rays.shape[1:3]) != tuple(reference.shape[-2:]): + raise ValueError( + "sensor rays and range images must use the same native grid: " + f"rays={tuple(rays.shape[1:3])}, " + f"video={tuple(reference.shape[-2:])}" + ) + dataset_ids = data_batch.get("sensor_dataset_id") + if dataset_ids is not None: + ids = torch.as_tensor(dataset_ids).reshape(-1) + if ids.shape[0] != rays.shape[0] or not bool( + (ids == ids[0]).all() + ): + raise ValueError( + "SF-DMD batches must be homogeneous in sensor_dataset_id" + ) + depth_bounds = data_batch.get("sensor_depth_bounds") + if depth_bounds is None: + raise KeyError( + "cross-sensor SF-DMD requires sensor_depth_bounds" + ) + depth_bounds = torch.as_tensor( + depth_bounds, device=reference.device, dtype=torch.float32 + ) + if depth_bounds.ndim == 1: + depth_bounds = depth_bounds[None] + if depth_bounds.shape != (rays.shape[0], 2): + raise ValueError( + "sensor_depth_bounds must be (B,2), got " + f"{tuple(depth_bounds.shape)}" + ) + if not bool( + torch.isclose( + depth_bounds, depth_bounds[:1].expand_as(depth_bounds) + ).all() + ): + raise ValueError( + "SF-DMD batches must share one sensor depth contract" + ) + self._warp_min_range = float(depth_bounds[0, 0].item()) + self._warp_max_range = float(depth_bounds[0, 1].item()) + ray_grid = rays[0].contiguous() + elevations, azimuths, row_offsets = ( + _sensor_tables_from_ray_directions( + ray_grid, allow_approximate=True + ) + ) + self._warp_geometry = ( + ray_grid, + elevations, + azimuths, + row_offsets, + ) + + def _sfdmd_chunk_slices( + self, total_tokens: int + ) -> list[tuple[int, int]]: + return temporal_chunk_slices( + total_tokens, + self.df_block_size, + self.sfdmd_temporal_prefix_frames, + ) + + def _sfdmd_total_tokens(self) -> int: + return self.sfdmd_num_real_frames + int( + self.input_video_has_prepend + ) + + def _sfdmd_window_tokens(self) -> int: + return self.sfdmd_window_frames + int( + self.input_video_has_prepend + ) + + def _sfdmd_chunk_frames(self, global_start: int) -> int: + if self.sfdmd_temporal_prefix_frames and global_start == 0: + return self.sfdmd_temporal_prefix_frames + return self.df_block_size + + def _sample_imaginaire_conditioned_prefix( + self, *, num_frames: int, device: torch.device + ) -> int: + if not self.sfdmd_imaginaire_matching: + return 0 + index = _sample_world_synchronized_categorical( + self.imaginaire_conditioned_prefix_probs.to(device=device) + ) + prefix_frames = self.imaginaire_conditioned_prefix_frames[index] + if prefix_frames >= num_frames: + raise ValueError( + "Imaginaire conditioned prefix must leave at least one " + f"generated frame, got K={prefix_frames} for T={num_frames}" + ) + return prefix_frames + + def _sample_factorized_rollout_modes( + self, + *, + num_frames: int, + device: torch.device, + ) -> tuple[int, str, str, int, Tensor]: + prefix_index = _sample_world_synchronized_categorical( + self.sfdmd_factorized_prefix_probs.to(device=device) + ) + prefix_frames = self.sfdmd_factorized_prefix_frames[prefix_index] + if prefix_frames >= num_frames: + raise ValueError( + "factorized SF-DMD prefix must leave a generated frame" + ) + hdmap_index = _sample_world_synchronized_categorical( + self.sfdmd_factorized_hdmap_probs.to(device=device) + ) + geometry_index = _sample_world_synchronized_categorical( + self.sfdmd_factorized_geometry_probs.to(device=device) + ) + hdmap_mode = self.sfdmd_factorized_hdmap_modes[hdmap_index] + geometry_mode = self.sfdmd_factorized_geometry_modes[geometry_index] + geometry_observations = 0 + geometry_source_mask = torch.zeros( + num_frames, device=device, dtype=torch.float32 + ) + if geometry_mode == "frozen_object": + observation_index = _sample_world_synchronized_categorical( + self.sfdmd_factorized_geometry_observation_probs.to( + device=device + ) + ) + geometry_observations = ( + self.sfdmd_factorized_geometry_observation_frames[ + observation_index + ] + ) + geometry_source_mask[:geometry_observations] = 1.0 + return ( + prefix_frames, + hdmap_mode, + geometry_mode, + geometry_observations, + geometry_source_mask, + ) + + def _factorized_known_mask_window( + self, + known_mask: Tensor, + window_start: int, + ) -> Tensor: + mask_video = known_mask[None, None, :, None, None] + return self._window_clip( + mask_video, + window_start, + self.sfdmd_window_frames, + )[0, 0, :, 0, 0].contiguous() + + @torch.no_grad() + def _build_factorized_rollout_geometry( + self, + source_video: Tensor, + data_batch: dict[str, Any], + poses: Tensor, + geometry_mode: str, + geometry_source_mask: Tensor, + ) -> Tensor: + ray_dirs, elev, azim, row_off = self._warp_geometry + motion_batch = ( + data_batch.get("pose_sensor_start_end") + if bool(self.config.factorized_geometry_rolling_shutter) + else None + ) + if ( + bool(self.config.factorized_geometry_rolling_shutter) + and motion_batch is None + ): + raise KeyError( + "factorized SF-DMD rolling-shutter geometry requires " + "pose_sensor_start_end" + ) + required_boxes = ( + "moving_box_object_to_world", + "moving_box_lwh", + "moving_box_valid", + "moving_box_track_id", + ) + missing = [ + name for name in required_boxes if data_batch.get(name) is None + ] + if missing: + raise KeyError( + "factorized SF-DMD geometry is missing batch fields " + f"{missing}" + ) + source_pose_batch = data_batch.get( + "factorized_geometry_source_lidar_to_world" + ) + source_motion_batch = data_batch.get( + "factorized_geometry_source_pose_sensor_start_end" + ) + warped = [] + for batch_idx in range(source_video.shape[0]): + geometry_i, _, _ = build_stage2_factorized_geometry( + source_video[batch_idx, :1], + poses[batch_idx], + geometry_source_mask, + geometry_mode, + pose_sensor_start_end=( + motion_batch[batch_idx] + if motion_batch is not None + else None + ), + geometry_source_lidar_to_world=( + source_pose_batch[batch_idx] + if source_pose_batch is not None + else None + ), + geometry_source_pose_sensor_start_end=( + source_motion_batch[batch_idx] + if source_motion_batch is not None + else None + ), + actor_box_time_mode=( + self.sfdmd_factorized_actor_box_time_mode + ), + box_object_to_world=data_batch[ + "moving_box_object_to_world" + ][batch_idx], + box_lwh=data_batch["moving_box_lwh"][batch_idx], + box_valid=data_batch["moving_box_valid"][batch_idx], + box_track_id=data_batch["moving_box_track_id"][batch_idx], + block_size=int(self.config.factorized_geometry_block_size), + prefix_frames=int( + self.config.factorized_geometry_prefix_frames + ), + input_has_prepend=self.input_video_has_prepend, + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=float( + self.config.blockwise_spatial_map_min_range + ), + max_range=float( + self.config.blockwise_spatial_map_max_range + ), + min_value=float( + self.config.blockwise_spatial_map_min_value + ), + inverse_depth=bool( + self.config.blockwise_spatial_map_inverse_depth + ), + radius_m=float( + self.config.blockwise_spatial_map_radius_m + ), + voxel_size_m=float( + self.config.blockwise_spatial_map_voxel_m + ), + voxel_policy=str( + self.config.blockwise_spatial_map_voxel_policy + ), + observation_unit=str( + self.config.blockwise_spatial_map_observation_unit + ), + static_min_observations=int( + self.config.blockwise_spatial_map_static_min_observations + ), + candidate_ttl_updates=int( + self.config.blockwise_spatial_map_candidate_ttl_updates + ), + include_latest=bool( + self.config.blockwise_spatial_map_include_latest + ), + free_space_clear=bool( + self.config.blockwise_spatial_map_free_space_clear + ), + free_space_margin_m=float( + self.config.blockwise_spatial_map_free_space_margin_m + ), + free_space_misses_to_remove=int( + self.config.blockwise_spatial_map_free_space_misses_to_remove + ), + ) + warped.append(geometry_i) + return torch.stack(warped).to( + device=source_video.device, dtype=source_video.dtype + ) + + # ------------------------------------------------------------------ + # Teacher / fake-score setup + # ------------------------------------------------------------------ + + def _sfdmd_sigmas( + self, + *, + device: torch.device | str | None = None, + dtype: torch.dtype = torch.float32, + ) -> Tensor: + return fixed_sde_sigmas( + num_steps=self.sfdmd_num_steps, + shift=self._rf_shift, + device=device, + dtype=dtype, + ) + + def _sfdmd_sigmas_for_block( + self, + block_index: int, + *, + device: torch.device | str, + ) -> Tensor: + if not self.sfdmd_imaginaire_matching: + return self._sfdmd_sigmas(device=device) + values = ( + [1.0, 15.0 / 16.0, 5.0 / 6.0, 5.0 / 8.0, 0.0] + if block_index == 0 + else [1.0, 5.0 / 6.0, 0.0] + ) + return torch.tensor(values, device=device, dtype=torch.float32) + + def _sample_rollout_exit_step(self, device: torch.device) -> int: + """Sample one shared ArtiFixer exit step for every block and rank.""" + if not self.sfdmd_artifixer_matching: + return self.sfdmd_num_steps - 1 + if distributed.get_rank() == 0: + exit_step = torch.randint( + self.sfdmd_num_steps, + (1,), + device=device, + dtype=torch.long, + ) + else: + exit_step = torch.zeros(1, device=device, dtype=torch.long) + torch.distributed.broadcast(exit_step, src=0) + return int(exit_step.item()) + + def _build_score_module(self) -> _RFScoreModule: + return _RFScoreModule( + lazy_instantiate(copy.deepcopy(self.config.sfdmd_teacher_net)), + concat_geometry=bool( + self.config.blockwise_warped_history_concat + ), + concat_known_mask=bool(self.config.stage2_known_mask_concat), + ) + + @staticmethod + def _net_state_from_checkpoint(path: str) -> dict[str, Tensor]: + model_path = path.replace(".pt", "_reg_model.pt") + if os.path.exists(model_path): + path = model_path + state = torch.load( + path, + map_location=lambda storage, loc: storage, + weights_only=False, + ) + if isinstance(state, dict) and "model" in state and isinstance( + state["model"], dict + ): + state = state["model"] + if not isinstance(state, dict): + raise TypeError(f"checkpoint {path} is not a state dict") + prefixes = ("module.net.", "model.net.", "net.") + for prefix in prefixes: + selected = { + f"net.{key[len(prefix):]}": value + for key, value in state.items() + if key.startswith(prefix) + } + if selected: + return selected + # A dedicated fake-score checkpoint is already an _RFScoreModule state. + if any(key.startswith("net.") for key in state): + return state + raise KeyError(f"checkpoint {path} contains no net.* tensors") + + def _load_score_module( + self, + module: _RFScoreModule, + path: str, + fallback_state: dict[str, Tensor] | None = None, + ) -> None: + state, dropped = complete_score_state_dict( + self._net_state_from_checkpoint(path), + module.state_dict(), + fallback_state, + ) + result = module.load_state_dict(state, strict=True) + if dropped: + log.info( + f"Ignored {len(dropped)} score-checkpoint tensors absent from " + "the bidirectional critic" + ) + log.info(f"Loaded score network {path}: {result}") + + @staticmethod + def _score_wrap_policy(module: _RFScoreModule): + classes = module.net.fsdp_wrap_block_cls + if not isinstance(classes, (list, tuple, set)): + classes = [classes] + return functools.partial( + transformer_auto_wrap_policy, + transformer_layer_cls=set(classes), + ) + + def _sync_full_module(self, module: nn.Module) -> None: + mesh = parallel_state.fsdp_device_mesh + distributed.sync_model_states(module, mesh.get_group(mesh_dim="shard")) + distributed.sync_model_states( + module, mesh.get_group(mesh_dim="replicate") + ) + + @staticmethod + def _rank0_action_or_raise(action, description: str) -> None: + error = None + if distributed.get_rank() == 0: + try: + action() + except Exception as exc: # noqa: BLE001 + error = f"{description}: {exc!r}" + objects = [error] + torch.distributed.broadcast_object_list(objects, src=0) + if objects[0] is not None: + raise RuntimeError(objects[0]) + + def _set_up_score_models(self) -> None: + teacher = self._build_score_module().cuda().to(**self.tensor_kwargs) + self._rank0_action_or_raise( + lambda: self._load_score_module( + teacher, self.sfdmd_teacher_checkpoint + ), + "teacher checkpoint load failed", + ) + teacher.eval().requires_grad_(False) + + fake_score = self._build_score_module().cuda().to(**self.tensor_kwargs) + fake_load_path = None + checkpointer = getattr(self, "fsdp_checkpointer", None) + if hasattr(checkpointer, "get_fake_score_load_path"): + fake_load_path = checkpointer.get_fake_score_load_path() + + def _initialize_fake_score(): + if fake_load_path is not None: + self._load_score_module( + fake_score, + fake_load_path, + fallback_state=teacher.state_dict(), + ) + else: + fake_score.load_state_dict(teacher.state_dict(), strict=True) + self._rank0_action_or_raise( + _initialize_fake_score, + "fake-score initialization failed", + ) + if self.sfdmd_skip_zero_crossattn: + teacher_blocks = teacher.net.enable_zero_crossattn_skip() + fake_blocks = fake_score.net.enable_zero_crossattn_skip() + log.info( + "Enabled exact zero-text cross-attention bypass on " + f"{teacher_blocks} teacher and {fake_blocks} fake-score blocks" + ) + if isinstance(self.model, FSDP): + self._sync_full_module(teacher) + self._sync_full_module(fake_score) + config = self.config + strategy = { + "full": ShardingStrategy.FULL_SHARD, + "hybrid": ShardingStrategy.HYBRID_SHARD, + }[config.fsdp.sharding_strategy] + mesh = parallel_state.fsdp_device_mesh + if config.fsdp.sharding_strategy == "hybrid": + process_group = ( + mesh.get_group(mesh_dim="shard"), + mesh.get_group(mesh_dim="replicate"), + ) + else: + process_group = mesh.get_group(mesh_dim="shard") + teacher = FSDP( + teacher, + sync_module_states=True, + sharding_strategy=strategy, + auto_wrap_policy=self._score_wrap_policy(teacher), + process_group=process_group, + device_id=torch.cuda.current_device(), + limit_all_gathers=True, + ) + fake_score = FSDP( + fake_score, + sync_module_states=True, + sharding_strategy=strategy, + auto_wrap_policy=self._score_wrap_policy(fake_score), + process_group=process_group, + device_id=torch.cuda.current_device(), + limit_all_gathers=True, + ) + log.info("Sharded frozen teacher score model with FSDP") + self.teacher_score = teacher + self.fake_score = fake_score + + def train(self, mode: bool = True): + super().train(mode) + self.teacher_score.eval() + return self + + # ------------------------------------------------------------------ + # FSDP-safe student and score forwards + # ------------------------------------------------------------------ + + def _direct_student_forward(self, payload: dict[str, Any]) -> Tensor: + previous_known_mask = getattr( + self, "_current_stage2_known_frame_mask", None + ) + self._current_hdmap = payload["hdmap"] + self._current_blockwise_warped_history = payload["side_condition"] + self._current_stage2_known_frame_mask = payload.get("known_mask") + self._current_sfdmd_temporal_positions = payload.get( + "temporal_positions" + ) + self._current_sfdmd_self_attn_kv_cache = payload.get("kv_cache") + self._current_sfdmd_store_self_attn_kv = payload.get( + "store_kv", False + ) + self._current_sfdmd_self_attn_kv_max_frames = ( + self.sfdmd_kv_cache_frames + ) + self._current_sfdmd_self_attn_kv_sink_frames = ( + self.sfdmd_kv_sink_frames + ) + self._current_sfdmd_detach_self_attn_kv = payload.get( + "detach_kv", True + ) + try: + return self._rf_network_forward( + payload["x_t"], + payload["timesteps"], + payload["condition"], + ) + finally: + self._current_stage2_known_frame_mask = previous_known_mask + self._current_sfdmd_temporal_positions = None + self._current_sfdmd_self_attn_kv_cache = None + self._current_sfdmd_store_self_attn_kv = False + self._current_sfdmd_self_attn_kv_sink_frames = 0 + self._current_sfdmd_detach_self_attn_kv = True + + def training_step( + self, data_batch: dict[str, Any], iteration: int + ) -> tuple[dict[str, Any], Tensor]: + if data_batch.get(_DIRECT_FORWARD_KEY, False): + velocity = self._direct_student_forward(data_batch) + output = {"velocity": velocity} + if data_batch.get("store_kv", False): + # FSDP rebuilds nested input containers while moving them to the + # compute device, so mutations to the input cache list do not + # propagate to the caller. Return the updated list explicitly. + output["kv_cache"] = data_batch["kv_cache"] + return output, velocity.new_zeros(()) + raise RuntimeError( + "HdmapToLidarSFDMDModel is driven by SFDMDTrainer cycles, not the " + "single-loss Trainer.training_step path" + ) + + def _student_velocity( + self, + x_t: Tensor, + timesteps: Tensor, + condition: Any, + hdmap: Tensor, + side_condition: Tensor, + kv_cache: list[dict[str, Tensor] | None], + global_start: int, + *, + store_kv: bool = False, + detach_kv: bool = True, + framewise_clean_commit: bool = False, + known_mask: Tensor | None = None, + ) -> Tensor: + block_size = x_t.shape[2] + expected_block_size = self._sfdmd_chunk_frames(global_start) + if framewise_clean_commit: + if ( + not ( + self.sfdmd_imaginaire_matching + or self.sfdmd_clean_x0_kv_commit + ) + or not store_kv + or block_size != 1 + ): + raise ValueError( + "framewise clean commits require a clean-commit mode, " + "store_kv=True, and exactly one frame" + ) + elif block_size != expected_block_size: + raise ValueError( + f"student KV call must contain {expected_block_size} frames, " + f"got {block_size}" + ) + payload = { + _DIRECT_FORWARD_KEY: True, + "x_t": x_t.to(**self.tensor_kwargs), + "timesteps": timesteps, + "condition": condition, + "hdmap": hdmap, + "side_condition": side_condition, + "known_mask": known_mask, + "kv_cache": kv_cache, + "store_kv": store_kv, + "detach_kv": detach_kv, + "temporal_positions": torch.arange( + global_start, + global_start + block_size, + device=x_t.device, + ), + } + if isinstance(self.model, FSDP): + output, _ = self.model(payload, 0) + if store_kv: + updated_cache = output.get("kv_cache") + if updated_cache is None: + raise RuntimeError( + "FSDP student forward did not return its updated KV cache" + ) + kv_cache[:] = updated_cache + return output["velocity"].float() + return self._direct_student_forward(payload).float() + + def new_student_kv_cache(self) -> list[dict[str, Tensor] | None]: + net = self.net + while hasattr(net, "module"): + net = net.module + return [None] * len(net.blocks) + + @torch.no_grad() + def seed_student_conditioned_prefix( + self, + rollout: SFDMDLongRollout, + kv_cache: list[dict[str, Tensor] | None], + ) -> None: + """Restore observed clean-prefix K/V before generated replay.""" + seed_frames = ( + rollout.kv_seed_frames + if rollout.kv_seed_frames > 0 + else rollout.conditioned_prefix_frames + ) + if seed_frames == 0: + return + if ( + rollout.conditioned_prefix_latents is None + or rollout.conditioned_prefix_condition is None + or rollout.conditioned_prefix_hdmap is None + or rollout.conditioned_prefix_side_condition is None + ): + raise RuntimeError( + "conditioned SF-DMD rollout is missing prefix replay state" + ) + self._seed_student_clean_history( + rollout.conditioned_prefix_latents, + rollout.conditioned_prefix_condition, + rollout.conditioned_prefix_hdmap, + rollout.conditioned_prefix_side_condition, + kv_cache, + 0, + known_mask=rollout.conditioned_prefix_latents.new_ones( + seed_frames + ), + ) + + def _seed_student_clean_history( + self, + clean_block: Tensor, + condition: Any, + hdmap: Tensor, + side_condition: Tensor, + kv_cache: list[dict[str, Tensor] | None], + global_start: int, + *, + detach_kv: bool = True, + known_mask: Tensor | None = None, + ) -> None: + """Commit finalized clean history one frame at a time.""" + block_frames = clean_block.shape[2] + if ( + hdmap.shape[2] != block_frames + or side_condition.shape[2] != block_frames + ): + raise ValueError( + "clean-history conditions must match the finalized block: " + f"clean={tuple(clean_block.shape)}, hdmap={tuple(hdmap.shape)}, " + f"side={tuple(side_condition.shape)}" + ) + total_frames = self._sfdmd_total_tokens() + if global_start < 0 or global_start + block_frames > total_frames: + raise ValueError( + f"clean-history block [{global_start}:" + f"{global_start + block_frames}] exceeds T={total_frames}" + ) + for offset in range(block_frames): + frame_index = global_start + offset + if frame_index == total_frames - 1: + break + clean_timesteps = torch.zeros( + (clean_block.shape[0], 1), + device=clean_block.device, + dtype=torch.float32, + ) + self._student_velocity( + ( + clean_block[:, :, offset : offset + 1].detach() + if detach_kv + else clean_block[:, :, offset : offset + 1] + ), + clean_timesteps, + condition, + hdmap[:, :, offset : offset + 1].contiguous(), + side_condition[:, :, offset : offset + 1].contiguous(), + kv_cache, + frame_index, + store_kv=True, + detach_kv=detach_kv, + framewise_clean_commit=True, + known_mask=( + None + if known_mask is None + else known_mask[offset : offset + 1] + ), + ) + + @staticmethod + def detach_student_kv_cache( + kv_cache: list[dict[str, Tensor] | None], + ) -> None: + """Cut the replay graph while preserving the bounded cache contents.""" + for layer_idx, layer_cache in enumerate(kv_cache): + if layer_cache is None: + continue + kv_cache[layer_idx] = { + "k": layer_cache["k"].detach(), + "v": layer_cache["v"].detach(), + } + + @torch.no_grad() + def verify_student_kv_equivalence( + self, data_batch: dict[str, Any] + ) -> dict[str, Tensor]: + """Gate the real checkpoint on full versus cached chunkwise output.""" + self._set_sfdmd_dataset_ids(data_batch, data_batch["video"]) + self._configure_warp_geometry(data_batch, data_batch["video"]) + window = self.sfdmd_window_frames + window_tokens = self._sfdmd_window_tokens() + chunks = self._sfdmd_chunk_slices(window_tokens) + poses = torch.as_tensor( + data_batch["lidar_to_world"], + device=data_batch["video"].device, + dtype=torch.float32, + ) + wb = dict(data_batch) + wb["video"] = self._window_clip(data_batch["video"], 0, window) + wb["lidar_hdmap"] = self._window_clip( + data_batch["lidar_hdmap"], 0, window + ) + spatial_maps = ( + self._new_spatial_maps( + data_batch["video"].shape[0], + data_batch["video"].device, + ) + if self.sfdmd_accumulated_geometry_warp + else None + ) + global_warp = ( + data_batch["video"][:, :1, :window_tokens].new_full( + ( + data_batch["video"].shape[0], + 1, + window_tokens, + data_batch["video"].shape[-2], + data_batch["video"].shape[-1], + ), + self._warp_min_value, + ) + if self.sfdmd_accumulated_geometry_warp + else None + ) + condition, hdmap, side, _, _ = self._prepare_stage_context( + wb, + poses, + 0, + 0, + window_tokens, + None, + spatial_maps, + global_warp, + None, + None, + ) + batch_size = hdmap.shape[0] + generator = torch.Generator(device=hdmap.device) + generator.manual_seed(20260713) + x = torch.randn( + ( + batch_size, + int(self.state_shape[0]), + window_tokens, + int(self.state_shape[2]), + int(self.state_shape[3]), + ), + generator=generator, + device=hdmap.device, + dtype=torch.float32, + ) + timestep_values = torch.linspace( + 125.0, + 875.0, + len(chunks), + device=hdmap.device, + dtype=torch.float32, + ) + timesteps = torch.cat( + [ + timestep_values[index].expand(end - start) + for index, (start, end) in enumerate(chunks) + ] + )[None].expand(batch_size, -1) + full_payload = { + _DIRECT_FORWARD_KEY: True, + "x_t": x.to(**self.tensor_kwargs), + "timesteps": timesteps, + "condition": condition, + "hdmap": hdmap, + "side_condition": side, + } + if isinstance(self.model, FSDP): + full_output, _ = self.model(full_payload, 0) + full = full_output["velocity"].float() + else: + full = self._direct_student_forward(full_payload).float() + + cache = self.new_student_kv_cache() + cached_parts = [] + cache_token_counts = [] + for start, end in chunks: + cached_parts.append( + self._student_velocity( + x[:, :, start:end], + timesteps[:, start:end], + condition, + hdmap[:, :, start:end], + side[:, :, start:end], + cache, + start, + store_kv=True, + ) + ) + missing_layers = [ + index for index, entry in enumerate(cache) + if entry is None + ] + if missing_layers: + raise RuntimeError( + "DiT KV-cache store did not persist through the student " + f"forward; missing layers={missing_layers}" + ) + cache_token_counts.append(int(cache[0]["k"].shape[1])) + cached = torch.cat(cached_parts, dim=2) + abs_error = (cached - full).abs() + max_abs = abs_error.max() + mean_abs = abs_error.mean() + per_block = [] + for start, end in chunks: + error = abs_error[:, :, start:end] + per_block.append( + { + "start": start, + "max": float(error.max()), + "mean": float(error.mean()), + } + ) + atol = float( + getattr(self.config, "sfdmd_kv_equivalence_atol", 2.0e-2) + ) + # Block 0 has no cached history, so its discrepancy measures only the + # BF16 FlexAttention drift caused by changing the compiled query shape + # from a masked full sequence to one unmasked causal chunk. Cached + # blocks must remain within that baseline instead of satisfying + # elementwise allclose near zero, where relative tolerance cannot help. + baseline_max = per_block[0]["max"] + baseline_mean = per_block[0]["mean"] + history_max = max(row["max"] for row in per_block[1:]) + history_mean = max(row["mean"] for row in per_block[1:]) + history_max_budget = max(baseline_max, 1.25 * atol) + history_mean_budget = max(baseline_mean, 0.25 * atol) + local_gate_passed = ( + bool(torch.isfinite(max_abs)) + and bool(torch.isfinite(mean_abs)) + and history_max <= history_max_budget + and history_mean <= history_mean_budget + ) + local_failure = None + if not local_gate_passed: + rank = ( + torch.distributed.get_rank() + if torch.distributed.is_initialized() + else 0 + ) + local_failure = ( + f"rank={rank}: max_abs={float(max_abs):.6g}, " + f"mean_abs={float(mean_abs):.6g}, base_atol={atol}, " + f"history_budgets=(max={history_max_budget:.6g}, " + f"mean={history_mean_budget:.6g}), " + f"cache_tokens={cache_token_counts}, per_block={per_block}" + ) + failures = [local_failure] + if torch.distributed.is_initialized(): + failures = [None] * torch.distributed.get_world_size() + torch.distributed.all_gather_object(failures, local_failure) + failures = [failure for failure in failures if failure is not None] + if failures: + raise RuntimeError( + "actual student failed the distributed chunkwise DiT KV-cache " + "gate: " + "; ".join(failures) + ) + gate_metrics = torch.stack( + [ + max_abs.detach(), + mean_abs.detach(), + max_abs.new_tensor(baseline_max), + max_abs.new_tensor(history_max), + ] + ) + if torch.distributed.is_initialized(): + torch.distributed.all_reduce( + gate_metrics, op=torch.distributed.ReduceOp.MAX + ) + log.info( + "Student DiT KV-cache gate passed: " + f"global_max_abs={float(gate_metrics[0]):.6g}, " + f"global_mean_abs_max={float(gate_metrics[1]):.6g}, " + f"cache_tokens={cache_token_counts}, per_block={per_block}" + ) + return { + "sfdmd/kv_gate_max_abs": gate_metrics[0], + "sfdmd/kv_gate_mean_abs": gate_metrics[1], + "sfdmd/kv_gate_baseline_max": gate_metrics[2], + "sfdmd/kv_gate_history_max": gate_metrics[3], + } + + def _set_sfdmd_dataset_ids( + self, + data_batch: dict[str, Any], + reference: Tensor, + ) -> None: + self._current_sensor_dataset_ids = None + if self._num_dataset_embeddings == 0: + return + dataset_ids = data_batch.get("sensor_dataset_id") + if dataset_ids is None: + raise KeyError( + "dataset-conditioned SF-DMD requires sensor_dataset_id" + ) + dataset_ids = torch.as_tensor( + dataset_ids, device=reference.device, dtype=torch.long + ).reshape(-1) + if dataset_ids.shape != (reference.shape[0],): + raise ValueError( + "sensor_dataset_id must have one value per SF-DMD sample, " + f"got {tuple(dataset_ids.shape)} for B={reference.shape[0]}" + ) + if bool( + ( + (dataset_ids < 0) + | (dataset_ids >= self._num_dataset_embeddings) + ).any() + ): + raise ValueError( + "sensor_dataset_id contains a value outside [0, " + f"{self._num_dataset_embeddings})" + ) + self._current_sensor_dataset_ids = dataset_ids + + def _condition_dict( + self, + condition: Any, + *, + batch_size: int, + device: torch.device, + ) -> dict[str, Any]: + condition_dict = condition.to_dict() + dataset_ids = self._current_sensor_dataset_ids + if dataset_ids is not None: + dataset_ids = dataset_ids.to(device=device, dtype=torch.long) + if dataset_ids.shape[0] != batch_size: + if batch_size % dataset_ids.shape[0] != 0: + raise ValueError( + "dataset ids cannot be repeated to match the score " + f"batch: ids={tuple(dataset_ids.shape)}, B={batch_size}" + ) + dataset_ids = dataset_ids.repeat( + batch_size // dataset_ids.shape[0] + ) + condition_dict["dataset_ids_B"] = dataset_ids + return condition_dict + + def _score_velocity( + self, + score_model: nn.Module, + x_t: Tensor, + timesteps: Tensor, + hdmap: Tensor, + side_condition: Tensor | None, + condition: Any, + conditioned_prefix_frames: int = 0, + known_mask: Tensor | None = None, + ) -> Tensor: + score_timesteps = timesteps + if known_mask is not None or conditioned_prefix_frames > 0: + if timesteps.ndim == 1: + score_timesteps = timesteps[:, None].expand( + -1, x_t.shape[2] + ).clone() + elif timesteps.shape == (x_t.shape[0], 1): + score_timesteps = timesteps.expand(-1, x_t.shape[2]).clone() + elif timesteps.shape != (x_t.shape[0], x_t.shape[2]): + raise ValueError( + "score timesteps must be (B,), (B,1), or (B,T), got " + f"{tuple(timesteps.shape)}" + ) + if known_mask is None: + score_timesteps[:, :conditioned_prefix_frames] = 0.0 + else: + known = known_mask.to( + device=x_t.device, dtype=torch.bool + ) + if known.ndim == 1: + known = known[None] + if known.shape[0] == 1 and x_t.shape[0] != 1: + known = known.expand(x_t.shape[0], -1) + if known.shape != (x_t.shape[0], x_t.shape[2]): + raise ValueError( + "score known mask must align with x_t, got " + f"{tuple(known.shape)} for {tuple(x_t.shape)}" + ) + score_timesteps.masked_fill_(known, 0.0) + return score_model( + x_t.to(**self.tensor_kwargs), + score_timesteps, + hdmap.to(**self.tensor_kwargs), + None + if side_condition is None + else side_condition.to(**self.tensor_kwargs), + known_mask, + self._condition_dict( + condition, + batch_size=x_t.shape[0], + device=x_t.device, + ), + ).float() + + # ------------------------------------------------------------------ + # Long generated-history rollout + # ------------------------------------------------------------------ + + def _window_clip( + self, x_long: Tensor, start: int, window_frames: int + ) -> Tensor: + """Return one model-aligned temporal window.""" + num_real = x_long.shape[2] - int(self.input_video_has_prepend) + if start < 0 or start + window_frames > num_real: + raise ValueError( + f"window [{start}:{start + window_frames}] outside " + f"{num_real} real frames" + ) + if not self.input_video_has_prepend: + return x_long[ + :, :, start : start + window_frames + ].contiguous() + real = x_long[:, :, 1 + start : 1 + start + window_frames] + return torch.cat([real[:, :, :1], real], dim=2).contiguous() + + def _generated_warp( + self, + target_video: Tensor, + poses: Tensor, + window_start: int, + global_start: int, + decoded_prefix: Tensor | None, + spatial_maps: list[TorchSpatialPointMap] | None, + global_warp: Tensor | None, + global_geometry_source: Tensor | None, + global_geometry_confidence: Tensor | None, + block_frames: int | None = None, + ) -> tuple[Tensor, Tensor | None, Tensor | None]: + batch_size, _, t_cur, height, width = target_video.shape + if block_frames is None: + block_frames = self._sfdmd_chunk_frames(global_start) + ray_dirs, elev, azim, row_off = self._warp_geometry + if self.sfdmd_accumulated_geometry_warp: + if spatial_maps is None or len(spatial_maps) != batch_size: + raise ValueError( + "accumulated geometry requires one spatial map per batch" + ) + if global_warp is None: + raise ValueError( + "accumulated geometry requires a global raw-warp cache" + ) + active_warp = [] + active_source = [] + active_confidence = [] + for batch_idx in range(batch_size): + target_poses = lidar_poses_for_global_tokens( + poses[batch_idx], + global_start, + block_frames, + input_has_prepend=self.input_video_has_prepend, + ) + if self.sfdmd_geometry_source: + source, hit, temporal_confidence = spatial_maps[ + batch_idx + ].render_soft_proposal(target_poses) + density_confidence = local_hit_density_confidence( + hit, + kernel_size=( + self.sfdmd_geometry_source_density_kernel + ), + saturation_hits=( + self.sfdmd_geometry_source_density_saturation_hits + ), + ) + confidence = ( + temporal_confidence * density_confidence + ).clamp_(0.0, 1.0) + empty = source.new_full((), self._warp_min_value) + active_warp.append( + confidence.unsqueeze(0) * source + + (1.0 - confidence.unsqueeze(0)) * empty + ) + active_source.append(source) + active_confidence.append(confidence.unsqueeze(0)) + else: + warped, _ = spatial_maps[batch_idx].render(target_poses) + active_warp.append(warped) + active = torch.stack(active_warp, dim=0).to( + device=target_video.device, dtype=target_video.dtype + ) + global_end = global_start + block_frames + global_warp[:, :, global_start:global_end] = active + source_window = None + confidence_window = None + if self.sfdmd_geometry_source: + if ( + global_geometry_source is None + or global_geometry_confidence is None + ): + raise ValueError( + "soft geometry requires global source/confidence caches" + ) + source = torch.stack(active_source, dim=0).to( + device=target_video.device, dtype=target_video.dtype + ) + confidence = torch.stack(active_confidence, dim=0).to( + device=target_video.device, dtype=torch.float32 + ) + global_geometry_source[ + :, :, global_start:global_end + ] = source + global_geometry_confidence[ + :, :, global_start:global_end + ] = confidence + source_window = spatial_warp_window( + global_geometry_source, + window_start=window_start, + window_frames=( + t_cur - int(self.input_video_has_prepend) + ), + input_has_prepend=self.input_video_has_prepend, + ) + confidence_window = spatial_warp_window( + global_geometry_confidence, + window_start=window_start, + window_frames=( + t_cur - int(self.input_video_has_prepend) + ), + input_has_prepend=self.input_video_has_prepend, + ) + return spatial_warp_window( + global_warp, + window_start=window_start, + window_frames=t_cur - int(self.input_video_has_prepend), + input_has_prepend=self.input_video_has_prepend, + ), source_window, confidence_window + + source = target_video[:, :1].new_full( + (batch_size, 1, t_cur, height, width), + self._warp_min_value, + ) + if decoded_prefix is not None: + source[:, :, : decoded_prefix.shape[2]] = decoded_prefix[:, :1] + warped_batch = [] + for batch_idx in range(batch_size): + warped, _ = warp_blockwise_history_to_video( + video=source[batch_idx], + lidar_to_world=poses[ + batch_idx, + window_start : window_start + t_cur - 1, + ], + block_size=self.df_block_size, + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=self._warp_min_range, + max_range=self._warp_max_range, + min_value=self._warp_min_value, + inverse_depth=self._warp_inverse_depth, + history_mode="all", + ) + warped_batch.append(torch.from_numpy(warped)) + return ( + torch.stack(warped_batch).to( + device=target_video.device, dtype=target_video.dtype + ), + None, + None, + ) + + def _new_spatial_maps( + self, batch_size: int, device: torch.device + ) -> list[TorchSpatialPointMap]: + ray_dirs, elev, azim, row_off = self._warp_geometry + return [ + TorchSpatialPointMap( + ray_dirs=ray_dirs, + row_elevations_rad=elev, + column_azimuths_rad=azim, + row_azimuth_offsets_rad=row_off, + min_range=self._warp_min_range, + max_range=self._warp_max_range, + min_value=self._warp_min_value, + inverse_depth=self._warp_inverse_depth, + radius_m=self.sfdmd_spatial_map_radius_m, + voxel_size_m=self.sfdmd_spatial_map_voxel_m, + voxel_policy=self.sfdmd_spatial_map_voxel_policy, + observation_unit=self.sfdmd_spatial_map_observation_unit, + static_min_observations=( + self.sfdmd_spatial_map_static_min_observations + ), + candidate_ttl_updates=( + self.sfdmd_spatial_map_candidate_ttl_updates + ), + include_latest=self.sfdmd_spatial_map_include_latest, + free_space_clear=self.sfdmd_spatial_map_free_space_clear, + free_space_margin_m=( + self.sfdmd_spatial_map_free_space_margin_m + ), + free_space_misses_to_remove=( + self.sfdmd_spatial_map_free_space_misses_to_remove + ), + device=device, + ) + for _ in range(batch_size) + ] + + def _append_generated_geometry( + self, + spatial_maps: list[TorchSpatialPointMap], + decoded_new: Tensor, + poses: Tensor, + global_start: int, + ) -> None: + """Append newly committed real sweeps using the model token layout.""" + for batch_idx, spatial_map in enumerate(spatial_maps): + spatial_map.append_block( + normalized_block=decoded_new[batch_idx, :1], + lidar_to_world=poses[batch_idx], + global_start=global_start, + input_has_prepend=self.input_video_has_prepend, + ) + + def _prepare_stage_context( + self, + window_batch: dict[str, Any], + poses: Tensor, + window_start: int, + global_start: int, + t_cur: int, + decoded_prefix: Tensor | None, + spatial_maps: list[TorchSpatialPointMap] | None, + global_warp: Tensor | None, + global_geometry_source: Tensor | None, + global_geometry_confidence: Tensor | None, + *, + fixed_condition: Any = None, + fixed_hdmap: Tensor | None = None, + fixed_warp: Tensor | None = None, + block_frames: int | None = None, + ) -> tuple[Any, Tensor, Tensor, Tensor | None, Tensor | None]: + stage_batch = dict(window_batch) + target = window_batch["video"][:, :, :t_cur].contiguous() + stage_batch["video"] = torch.full_like(target, self._warp_min_value) + stage_batch["lidar_hdmap"] = window_batch["lidar_hdmap"][ + :, :, :t_cur + ].contiguous() + if fixed_warp is None: + warped, geometry_source, geometry_confidence = ( + self._generated_warp( + target, + poses, + window_start, + global_start, + decoded_prefix, + spatial_maps, + global_warp, + global_geometry_source, + global_geometry_confidence, + block_frames, + ) + ) + else: + if fixed_warp.shape != target[:, :1].shape: + raise ValueError( + "fixed factorized geometry must match the condition " + f"window: geometry={tuple(fixed_warp.shape)}, " + f"target={tuple(target[:, :1].shape)}" + ) + warped = fixed_warp + geometry_source = None + geometry_confidence = None + geometry_z = None + confidence_z = None + if self.sfdmd_geometry_source: + if geometry_source is None or geometry_confidence is None: + raise RuntimeError( + "SF-DMD geometry source/confidence was not rendered" + ) + geometry_input = ( + confidence_composite_geometry( + geometry_source, + geometry_confidence, + self._warp_min_value, + ) + if self.sfdmd_geometry_source_preencode_confidence + else geometry_source + ) + geometry_z = self.encode(geometry_input.float()).contiguous() + confidence_z = F.adaptive_avg_pool3d( + geometry_confidence.float(), geometry_z.shape[2:] + ).clamp_(0.0, 1.0) + if fixed_condition is not None: + if fixed_hdmap is None: + raise ValueError("fixed_hdmap is required with fixed_condition") + side_z = self.encode(warped.float()).contiguous().to( + self.diffusion_dtype + ) + return ( + fixed_condition, + fixed_hdmap[:, :, :t_cur].detach().clone(), + side_z, + None if geometry_z is None else geometry_z.detach(), + None if confidence_z is None else confidence_z.detach(), + ) + stage_batch["lidar_blockwise_warped_history"] = warped + _, _, condition = self.get_data_and_condition(stage_batch) + if self._current_hdmap is None: + raise RuntimeError("SF-DMD requires VAE-encoded HDMap conditioning") + if self._current_blockwise_warped_history is None: + raise RuntimeError("SF-DMD requires generated warp-history conditioning") + return ( + condition, + self._current_hdmap.detach().clone(), + self._current_blockwise_warped_history.detach().clone(), + None if geometry_z is None else geometry_z.detach(), + None if confidence_z is None else confidence_z.detach(), + ) + + def _prepare_stream_stage_context( + self, + window_batch: dict[str, Any], + poses: Tensor, + window_start: int, + global_start: int, + t_cur: int, + decoded_prefix: Tensor | None, + spatial_maps: list[TorchSpatialPointMap] | None, + global_warp: Tensor | None, + global_geometry_source: Tensor | None, + global_geometry_confidence: Tensor | None, + active: slice, + temporal_kv_cache, + geometry_temporal_kv_cache, + *, + fixed_warp: Tensor | None = None, + ) -> tuple[ + Any, + Tensor, + Tensor, + Tensor | None, + Tensor | None, + Any, + Any, + ]: + """Encode only the active student condition block with VAE KV cache.""" + stage_batch = dict(window_batch) + target = window_batch["video"][:, :, :t_cur].contiguous() + if fixed_warp is None: + warped, geometry_source, geometry_confidence = ( + self._generated_warp( + target, + poses, + window_start, + global_start, + decoded_prefix, + spatial_maps, + global_warp, + global_geometry_source, + global_geometry_confidence, + active.stop - active.start, + ) + ) + else: + if fixed_warp.shape != target[:, :1].shape: + raise ValueError( + "fixed factorized geometry must match the streamed " + f"condition window: geometry={tuple(fixed_warp.shape)}, " + f"target={tuple(target[:, :1].shape)}" + ) + warped = fixed_warp + geometry_source = None + geometry_confidence = None + active_batch = dict(stage_batch) + active_batch["video"] = torch.full_like( + target[:, :, active], self._warp_min_value + ) + active_batch["lidar_hdmap"] = window_batch["lidar_hdmap"][ + :, :, active + ].contiguous() + active_batch["lidar_blockwise_warped_history"] = warped[ + :, :, active + ].contiguous() + condition, new_cache = self.get_online_condition_stream( + active_batch, + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=self.sfdmd_condition_vae_cache_frames, + allow_training=True, + ) + geometry_z = None + confidence_z = None + new_geometry_cache = geometry_temporal_kv_cache + if self.sfdmd_geometry_source: + if geometry_source is None or geometry_confidence is None: + raise RuntimeError( + "streamed SF-DMD geometry source/confidence was not rendered" + ) + geometry_input = ( + confidence_composite_geometry( + geometry_source[:, :, active], + geometry_confidence[:, :, active], + self._warp_min_value, + ) + if self.sfdmd_geometry_source_preencode_confidence + else geometry_source[:, :, active] + ) + geometry_z, new_geometry_cache = self.encode_stream( + geometry_input.contiguous().float(), + temporal_kv_cache=geometry_temporal_kv_cache, + max_cache_frames=self.sfdmd_condition_vae_cache_frames, + ) + geometry_z = geometry_z.contiguous() + confidence_z = F.adaptive_avg_pool3d( + geometry_confidence[:, :, active].float(), + geometry_z.shape[2:], + ).clamp_(0.0, 1.0) + if self._current_hdmap is None: + raise RuntimeError( + "streamed SF-DMD condition encode did not store HDMap" + ) + if self._current_blockwise_warped_history is None: + raise RuntimeError( + "streamed SF-DMD condition encode did not store warp history" + ) + active_frames = active.stop - active.start + if self._current_hdmap.shape[2] != active_frames: + raise RuntimeError( + "streamed SF-DMD HDMap returned the wrong block length: " + f"{tuple(self._current_hdmap.shape)}" + ) + return ( + condition, + self._current_hdmap.detach().clone(), + self._current_blockwise_warped_history.detach().clone(), + None if geometry_z is None else geometry_z.detach(), + None if confidence_z is None else confidence_z.detach(), + new_cache, + new_geometry_cache, + ) + + @torch.no_grad() + def _encode_score_hdmap(self, hdmap_window: Tensor) -> Tensor: + """Keep teacher/fake-score HDMap conditioning on the trained layout.""" + hdmap_z = self.encode(hdmap_window.float()).contiguous().to( + self.diffusion_dtype + ) + if hdmap_z.shape[2] != self._sfdmd_window_tokens(): + raise RuntimeError( + "score HDMap encode returned the wrong window length: " + f"{tuple(hdmap_z.shape)}" + ) + return hdmap_z.detach() + + def _sample_stage( + self, + *, + block_index: int, + window_start: int, + global_start: int, + score_active_start: int, + condition: Any, + hdmap: Tensor, + side_condition: Tensor, + geometry_source: Tensor | None, + geometry_confidence: Tensor | None, + kv_cache: list[dict[str, Tensor] | None], + exit_step: int, + known_prefix_latents: Tensor | None = None, + known_mask: Tensor | None = None, + history_commit_latents: Tensor | None = None, + ) -> tuple[Tensor, SFDMDReplayRecord]: + batch_size = hdmap.shape[0] + block_frames = hdmap.shape[2] + if ( + side_condition.shape[2] != block_frames + or block_frames != self._sfdmd_chunk_frames(global_start) + ): + raise ValueError( + "SF-DMD student conditions do not match the rollout chunk: " + f"hdmap={tuple(hdmap.shape)}, " + f"side={tuple(side_condition.shape)}, " + f"global_start={global_start}" + ) + channels, height, width = ( + int(self.state_shape[0]), + int(self.state_shape[2]), + int(self.state_shape[3]), + ) + noise = torch.randn( + batch_size, + channels, + block_frames, + height, + width, + device=hdmap.device, + dtype=torch.float32, + ) + latents = noise + known_frames = 0 + if known_prefix_latents is not None: + known_frames = int(known_prefix_latents.shape[2]) + if ( + known_prefix_latents.shape[:2] != latents.shape[:2] + or known_prefix_latents.shape[3:] != latents.shape[3:] + or known_frames <= 0 + or known_frames >= block_frames + ): + raise ValueError( + "mixed SF-DMD blocks require a non-empty proper latent " + "prefix aligned with the active block" + ) + latents[:, :, :known_frames] = known_prefix_latents.float() + if known_mask is None: + known_mask = latents.new_zeros(block_frames) + known_mask[:known_frames] = 1.0 + else: + known_mask = known_mask.to( + device=latents.device, dtype=torch.float32 + ) + if known_mask.shape != (block_frames,) or int( + known_mask.sum().item() + ) != known_frames: + raise ValueError( + "student known mask must identify the contiguous clean " + f"prefix, got mask={known_mask.tolist()}, " + f"known_frames={known_frames}" + ) + if history_commit_latents is not None and ( + history_commit_latents.shape != latents.shape + ): + raise ValueError( + "history commit latents must match the sampled block: " + f"commit={tuple(history_commit_latents.shape)}, " + f"sample={tuple(latents.shape)}" + ) + if self.sfdmd_geometry_source: + if geometry_source is None or geometry_confidence is None: + raise RuntimeError( + "SF-DMD geometry-source sampling requires source/confidence" + ) + if geometry_source.shape != noise.shape or ( + geometry_confidence.shape + != (batch_size, 1, *noise.shape[2:]) + ): + raise ValueError( + "SF-DMD geometry source/confidence shape mismatch: " + f"source={tuple(geometry_source.shape)}, " + f"confidence={tuple(geometry_confidence.shape)}, " + f"noise={tuple(noise.shape)}" + ) + latents = confidence_weighted_geometry_source( + noise, + geometry_source, + geometry_confidence, + self.sfdmd_geometry_source_noise_floor, + ) + sigmas = self._sfdmd_sigmas_for_block( + block_index, device=latents.device + ) + replay_step = ( + len(sigmas) - 2 + if self.sfdmd_imaginaire_matching + else exit_step + ) + replay_xt = None + replay_sigma = None + for step_idx in range(len(sigmas) - 1): + sigma = sigmas[step_idx] + sigma_next = sigmas[step_idx + 1] + if step_idx == replay_step: + replay_xt = latents.detach().clone() + replay_sigma = float(sigma) + active_t = torch.full( + (batch_size,), + float(sigma * self.rectified_flow.num_train_timesteps), + device=latents.device, + dtype=torch.float32, + ) + timesteps = active_t[:, None].expand( + -1, block_frames + ).clone() + if known_frames: + timesteps[:, :known_frames] = 0.0 + velocity = self._student_velocity( + latents, + timesteps, + condition, + hdmap, + side_condition, + kv_cache, + global_start, + store_kv=( + not self.sfdmd_imaginaire_matching + and not self.sfdmd_clean_x0_kv_commit + and history_commit_latents is None + and step_idx == exit_step + ), + known_mask=known_mask, + ) + x0 = rf_velocity_to_x0(latents, velocity, sigma) + if known_frames: + x0[:, :, :known_frames] = known_prefix_latents.float() + if self.sfdmd_artifixer_matching and step_idx == exit_step: + latents = x0 + break + if float(sigma_next) > 0.0: + eps_fresh = torch.randn_like(latents) + transition_source = eps_fresh + if self.sfdmd_artifixer_matching and self.sfdmd_geometry_source: + assert geometry_source is not None + assert geometry_confidence is not None + transition_source = confidence_weighted_geometry_source( + eps_fresh, + geometry_source, + geometry_confidence, + self.sfdmd_geometry_source_noise_floor, + ) + if ( + self.sfdmd_artifixer_matching + or self.sfdmd_imaginaire_matching + ): + # Matched recipes redraw their source endpoint every step. + next_latents = ( + (1.0 - sigma_next) * x0 + + sigma_next * transition_source + ) + else: + next_latents = sde_renoise( + x0=x0, + eps_implied=velocity + x0, + eps_fresh=eps_fresh, + sigma_next=sigma_next, + eta=self.sfdmd_sde_eta, + ) + else: + next_latents = x0 + if known_frames: + next_latents[:, :, :known_frames] = ( + known_prefix_latents.float() + ) + latents = next_latents + + assert replay_xt is not None and replay_sigma is not None + if ( + self.sfdmd_imaginaire_matching + or self.sfdmd_clean_x0_kv_commit + or history_commit_latents is not None + ): + self._seed_student_clean_history( + ( + latents + if history_commit_latents is None + else history_commit_latents.float() + ), + condition, + hdmap, + side_condition, + kv_cache, + global_start, + known_mask=known_mask, + ) + record = SFDMDReplayRecord( + block_index=block_index, + window_start=window_start, + global_start=global_start, + score_active_start=score_active_start, + score_active_end=( + score_active_start + block_frames - known_frames + ), + replay_xt=replay_xt, + replay_sigma=replay_sigma, + student_condition=condition, + student_hdmap=hdmap, + student_side_condition=side_condition, + student_known_mask=known_mask.detach().clone(), + student_active_start=known_frames, + student_active_end=block_frames, + generated_block=latents.detach().clone(), + history_commit_block=( + None + if history_commit_latents is None + else history_commit_latents.detach().clone() + ), + ) + return latents.detach(), record + + @torch.no_grad() + def rollout_sfdmd( + self, data_batch: dict[str, Any], cycle: int + ) -> SFDMDLongRollout: + del cycle + video = data_batch["video"] + hdmap = data_batch["lidar_hdmap"] + self._set_sfdmd_dataset_ids(data_batch, video) + self._configure_warp_geometry(data_batch, video) + poses = torch.as_tensor( + data_batch["lidar_to_world"], + device=video.device, + dtype=torch.float32, + ) + if video.shape[0] != 1: + raise ValueError( + f"SF-DMD currently requires batch_size=1, got {video.shape[0]}" + ) + total_tokens = self._sfdmd_total_tokens() + if video.shape[2] != total_tokens: + raise ValueError( + f"expected model-aligned video T={total_tokens}, " + f"got {video.shape[2]}" + ) + if tuple(poses.shape[1:]) != ( + self.sfdmd_num_real_frames, + 4, + 4, + ): + raise ValueError( + "lidar_to_world must contain one pose per real frame, got " + f"{tuple(poses.shape)}" + ) + + window = self.sfdmd_window_frames + window_tokens = self._sfdmd_window_tokens() + chunks = self._sfdmd_chunk_slices(total_tokens) + num_blocks = len(chunks) + factorized_hdmap_mode = "full" + factorized_geometry_mode = "rolling_static" + factorized_geometry_observations = 0 + factorized_geometry_source_mask = torch.zeros( + total_tokens, device=video.device, dtype=torch.float32 + ) + if self.sfdmd_factorized_conditioning: + ( + conditioned_prefix_frames, + factorized_hdmap_mode, + factorized_geometry_mode, + factorized_geometry_observations, + factorized_geometry_source_mask, + ) = self._sample_factorized_rollout_modes( + num_frames=total_tokens, + device=video.device, + ) + else: + conditioned_prefix_frames = ( + self._sample_imaginaire_conditioned_prefix( + num_frames=total_tokens, + device=video.device, + ) + ) + if any( + start < conditioned_prefix_frames < end + for start, end in chunks + ) and not self.sfdmd_factorized_conditioning: + raise NotImplementedError( + "Imaginaire SF-DMD does not support a chunk that mixes " + "conditioned and generated frames" + ) + kv_seed_frames = max( + ( + end + for _, end in chunks + if end <= conditioned_prefix_frames + ), + default=0, + ) + exit_step = self._sample_rollout_exit_step(video.device) + channels, _, height, width = map(int, self.state_shape) + global_z = torch.zeros( + 1, + channels, + total_tokens, + height, + width, + device=video.device, + dtype=torch.float32, + ) + global_side_z = None + global_geometry_z = None + global_geometry_confidence_z = None + global_decoded = torch.full( + ( + 1, + video.shape[1], + total_tokens, + video.shape[-2], + video.shape[-1], + ), + ( + self._warp_min_value + if self.sfdmd_factorized_conditioning + else 0.0 + ), + device=video.device, + dtype=torch.float32, + ) + ground_truth_z = None + if self.sfdmd_temporal_history_source == "ground_truth": + ground_truth_z = self.encode(video.float()).float() + if ground_truth_z.shape != global_z.shape: + raise RuntimeError( + "ground-truth history VAE encode returned the wrong shape: " + f"{tuple(ground_truth_z.shape)} != {tuple(global_z.shape)}" + ) + conditioned_prefix_z = None + if conditioned_prefix_frames > 0: + conditioned_prefix_z = ( + self.encode( + video[:, :, :conditioned_prefix_frames].float() + ).float() + if ground_truth_z is None + else ground_truth_z[:, :, :conditioned_prefix_frames] + ) + expected_shape = ( + global_z.shape[0], + global_z.shape[1], + conditioned_prefix_frames, + global_z.shape[3], + global_z.shape[4], + ) + if conditioned_prefix_z.shape != expected_shape: + raise RuntimeError( + "conditioned prefix VAE encode returned the wrong shape: " + f"{tuple(conditioned_prefix_z.shape)} != " + f"{expected_shape}" + ) + if self.sfdmd_factorized_conditioning: + global_decoded[:, :, :conditioned_prefix_frames] = video[ + :, :, :conditioned_prefix_frames + ].float() + records: list[SFDMDReplayRecord] = [] + conditioned_prefix_condition = None + conditioned_prefix_hdmap = None + conditioned_prefix_side = None + vae_cache = None + condition_vae_kv_cache = None + geometry_vae_kv_cache = None + student_kv_cache = self.new_student_kv_cache() + global_hdmap_z = None + spatial_maps = ( + self._new_spatial_maps(video.shape[0], video.device) + if ( + self.sfdmd_accumulated_geometry_warp + and not self.sfdmd_factorized_conditioning + ) + else None + ) + global_warp = ( + video[:, :1].new_full( + ( + video.shape[0], + 1, + total_tokens, + video.shape[-2], + video.shape[-1], + ), + self._warp_min_value, + ) + if ( + self.sfdmd_accumulated_geometry_warp + and not self.sfdmd_factorized_conditioning + ) + else None + ) + global_geometry_source = ( + video[:, :1].new_full( + ( + video.shape[0], + 1, + total_tokens, + video.shape[-2], + video.shape[-1], + ), + self._warp_min_value, + ) + if self.sfdmd_geometry_source + else None + ) + global_geometry_confidence = ( + video[:, :1].new_zeros( + ( + video.shape[0], + 1, + total_tokens, + video.shape[-2], + video.shape[-1], + ), + dtype=torch.float32, + ) + if self.sfdmd_geometry_source + else None + ) + seed_score_condition = None + seed_score_hdmap = None + fixed_factorized_geometry = None + if self.sfdmd_factorized_conditioning and ( + factorized_geometry_mode != "rolling_static" + or self.sfdmd_geometry_history_source == "ground_truth" + ): + fixed_factorized_geometry = ( + self._build_factorized_rollout_geometry( + video, + data_batch, + poses, + factorized_geometry_mode, + factorized_geometry_source_mask, + ) + ) + seed_blocks = ( + num_blocks + if self.sfdmd_imaginaire_matching + else len(self._sfdmd_chunk_slices(window_tokens)) + ) + + for block_index, (chunk_start, chunk_end) in enumerate(chunks): + if self.sfdmd_imaginaire_matching: + global_start = chunk_start + global_end = chunk_end + window_start = 0 + score_active_start = chunk_start + score_active_end = chunk_end + else: + ( + global_start, + window_start, + score_active_start, + score_active_end, + ) = sfdmd_nonoverlap_layout( + block_index, + block_size=self.df_block_size, + score_window_tokens=window_tokens, + prefix_frames=self.sfdmd_temporal_prefix_frames, + ) + if global_start != chunk_start: + raise RuntimeError( + "SF-DMD chunk/layout disagreement: " + f"chunk={chunk_start}:{chunk_end}, " + f"layout_start={global_start}" + ) + global_end = chunk_end + wb = dict(data_batch) + wb["video"] = self._window_clip( + video, window_start, window + ) + wb["lidar_hdmap"] = self._window_clip( + hdmap, window_start, window + ) + factorized_window_geometry = None + if self.sfdmd_factorized_conditioning: + factorized_geometry = fixed_factorized_geometry + if ( + factorized_geometry_mode == "rolling_static" + and self.sfdmd_geometry_history_source == "generated" + ): + factorized_geometry = ( + self._build_factorized_rollout_geometry( + global_decoded, + data_batch, + poses, + factorized_geometry_mode, + factorized_geometry_source_mask, + ) + ) + assert factorized_geometry is not None + factorized_window_geometry = self._window_clip( + factorized_geometry, + window_start, + window, + ) + + if block_index == 0: + decoded_prefix = None + elif block_index < seed_blocks: + decoded_prefix = global_decoded[ + :, :, :global_start + ].contiguous() + else: + first_real_token = window_start + 1 + prefix_real_frames = score_active_start - 1 + decoded_prefix = torch.cat( + [ + global_decoded[ + :, + :, + first_real_token : first_real_token + 1, + ], + global_decoded[ + :, + :, + first_real_token : ( + first_real_token + prefix_real_frames + ), + ], + ], + dim=2, + ) + + active = slice( + score_active_start, + score_active_end, + ) + # Score networks consume their bidirectional training layout. The + # student sees one active block and carries clean history in K/V. + if self.sfdmd_stream_condition_vae_encode: + ( + condition, + student_hdmap, + student_side, + student_geometry, + student_geometry_confidence, + condition_vae_kv_cache, + geometry_vae_kv_cache, + ) = self._prepare_stream_stage_context( + wb, + poses, + window_start, + global_start, + window_tokens, + decoded_prefix, + spatial_maps, + global_warp, + global_geometry_source, + global_geometry_confidence, + active, + condition_vae_kv_cache, + geometry_vae_kv_cache, + fixed_warp=factorized_window_geometry, + ) + if self.sfdmd_factorized_conditioning: + if factorized_hdmap_mode == "null": + student_hdmap.zero_() + if factorized_geometry_mode == "null": + student_side.zero_() + if block_index == 0 or block_index >= seed_blocks: + score_condition = condition + score_hdmap = self._encode_score_hdmap( + wb["lidar_hdmap"] + ) + if ( + self.sfdmd_factorized_conditioning + and factorized_hdmap_mode == "null" + ): + score_hdmap.zero_() + else: + assert seed_score_condition is not None + assert seed_score_hdmap is not None + score_condition = seed_score_condition + score_hdmap = seed_score_hdmap + if block_index == 0: + seed_score_condition = score_condition + seed_score_hdmap = score_hdmap + else: + if block_index == 0 or block_index >= seed_blocks: + ( + score_condition, + score_hdmap, + score_side, + score_geometry, + score_geometry_confidence, + ) = self._prepare_stage_context( + wb, + poses, + window_start, + global_start, + window_tokens, + decoded_prefix, + spatial_maps, + global_warp, + global_geometry_source, + global_geometry_confidence, + fixed_warp=factorized_window_geometry, + block_frames=global_end - global_start, + ) + if block_index == 0: + seed_score_condition = score_condition + seed_score_hdmap = score_hdmap + condition, hdmap_z, side_z, geometry_z, confidence_z = ( + score_condition, + score_hdmap, + score_side, + score_geometry, + score_geometry_confidence, + ) + else: + assert seed_score_condition is not None + assert seed_score_hdmap is not None + ( + condition, + hdmap_z, + side_z, + geometry_z, + confidence_z, + ) = ( + self._prepare_stage_context( + wb, + poses, + window_start, + global_start, + window_tokens, + decoded_prefix, + spatial_maps, + global_warp, + global_geometry_source, + global_geometry_confidence, + block_frames=global_end - global_start, + fixed_condition=seed_score_condition, + fixed_hdmap=seed_score_hdmap, + fixed_warp=factorized_window_geometry, + ) + ) + if self.sfdmd_factorized_conditioning: + if factorized_hdmap_mode == "null": + hdmap_z.zero_() + if factorized_geometry_mode == "null": + side_z.zero_() + student_hdmap = hdmap_z[:, :, active].contiguous() + student_side = side_z[:, :, active].contiguous() + student_geometry = ( + None + if geometry_z is None + else geometry_z[:, :, active].contiguous() + ) + student_geometry_confidence = ( + None + if confidence_z is None + else confidence_z[:, :, active].contiguous() + ) + + if global_side_z is None: + global_side_z = student_side.new_zeros( + ( + student_side.shape[0], + student_side.shape[1], + total_tokens, + student_side.shape[3], + student_side.shape[4], + ), + dtype=torch.float32, + ) + global_hdmap_z = student_hdmap.new_zeros( + ( + student_hdmap.shape[0], + student_hdmap.shape[1], + total_tokens, + student_hdmap.shape[3], + student_hdmap.shape[4], + ), + dtype=torch.float32, + ) + global_side_z[:, :, global_start:global_end] = ( + student_side.float() + ) + assert global_hdmap_z is not None + global_hdmap_z[:, :, global_start:global_end] = ( + student_hdmap.float() + ) + if self.sfdmd_geometry_source: + if ( + student_geometry is None + or student_geometry_confidence is None + ): + raise RuntimeError( + "geometry-source rollout did not produce latent source " + "and confidence" + ) + if global_geometry_z is None: + global_geometry_z = student_geometry.new_zeros( + ( + student_geometry.shape[0], + student_geometry.shape[1], + total_tokens, + student_geometry.shape[3], + student_geometry.shape[4], + ), + dtype=torch.float32, + ) + global_geometry_confidence_z = ( + student_geometry_confidence.new_zeros( + ( + student_geometry_confidence.shape[0], + 1, + total_tokens, + student_geometry_confidence.shape[3], + student_geometry_confidence.shape[4], + ), + dtype=torch.float32, + ) + ) + global_geometry_z[:, :, global_start:global_end] = ( + student_geometry.float() + ) + assert global_geometry_confidence_z is not None + global_geometry_confidence_z[ + :, :, global_start:global_end + ] = student_geometry_confidence.float() + + record = None + if global_end <= conditioned_prefix_frames: + if conditioned_prefix_z is None: + raise RuntimeError( + "conditioned SF-DMD chunk has no clean latent" + ) + sampled = conditioned_prefix_z[ + :, :, global_start:global_end + ].contiguous() + self._seed_student_clean_history( + sampled, + condition, + student_hdmap, + student_side, + student_kv_cache, + global_start, + known_mask=sampled.new_ones(sampled.shape[2]), + ) + conditioned_prefix_condition = condition + conditioned_prefix_hdmap = student_hdmap.detach().clone() + conditioned_prefix_side = student_side.detach().clone() + else: + known_in_block = max( + 0, + min( + global_end, + conditioned_prefix_frames, + ) + - global_start, + ) + block_known_mask = video.new_zeros( + global_end - global_start, + dtype=torch.float32, + ) + block_known_mask[:known_in_block] = 1.0 + sampled, record = self._sample_stage( + block_index=block_index, + window_start=window_start, + global_start=global_start, + score_active_start=( + score_active_start + known_in_block + ), + condition=condition, + hdmap=student_hdmap, + side_condition=student_side, + geometry_source=student_geometry, + geometry_confidence=student_geometry_confidence, + kv_cache=student_kv_cache, + exit_step=exit_step, + known_prefix_latents=( + None + if known_in_block == 0 + else conditioned_prefix_z[ + :, + :, + global_start : global_start + known_in_block, + ].contiguous() + ), + known_mask=block_known_mask, + history_commit_latents=( + None + if ground_truth_z is None + else ground_truth_z[ + :, :, global_start:global_end + ].contiguous() + ), + ) + global_z[:, :, global_start:global_end] = sampled + decoded_new, vae_cache = self.decode_stream( + sampled, vae_cache + ) + if decoded_new.ndim == 4: + decoded_new = decoded_new.unsqueeze(2) + if decoded_new.shape[2] != global_end - global_start: + raise RuntimeError( + "streaming VAE returned the wrong block length: " + f"{tuple(decoded_new.shape)}" + ) + global_decoded[:, :, global_start:global_end] = ( + decoded_new.float() + ) + if ( + self.sfdmd_factorized_conditioning + and global_start < conditioned_prefix_frames + ): + known_end = min(global_end, conditioned_prefix_frames) + global_decoded[:, :, global_start:known_end] = video[ + :, :, global_start:known_end + ].float() + if spatial_maps is not None: + self._append_generated_geometry( + spatial_maps, + decoded_new, + poses, + global_start, + ) + if record is not None: + record.conditioned_prefix_frames = ( + conditioned_prefix_frames + ) + if self.sfdmd_factorized_conditioning: + global_known_mask = video.new_zeros( + total_tokens, dtype=torch.float32 + ) + global_known_mask[:conditioned_prefix_frames] = 1.0 + record.score_known_mask = ( + self._factorized_known_mask_window( + global_known_mask, + window_start, + ) + ) + record.score_condition = ( + seed_score_condition + if block_index < seed_blocks + else score_condition + ) + record.score_hdmap = ( + seed_score_hdmap + if block_index < seed_blocks + else score_hdmap + ) + records.append(record) + + if block_index == seed_blocks - 1: + first_window = global_z[ + :, :, :window_tokens + ].detach().clone() + assert global_side_z is not None + first_side_window = global_side_z[ + :, :, :window_tokens + ].detach().clone() + for seed_record in records: + seed_record.generated_window = first_window + seed_record.score_side_condition = first_side_window + elif block_index >= seed_blocks: + assert record is not None + record.generated_window = self._window_clip( + global_z, window_start, window + ).detach().clone() + assert global_side_z is not None + record.score_side_condition = self._window_clip( + global_side_z, window_start, window + ).detach().clone() + + expected_records = sum( + end > conditioned_prefix_frames for _, end in chunks + ) + if len(records) != expected_records: + raise RuntimeError( + f"expected {expected_records} replay blocks, " + f"got {len(records)}" + ) + if any(record.generated_window is None for record in records): + raise RuntimeError("SF-DMD rollout left score windows incomplete") + if any(record.score_side_condition is None for record in records): + raise RuntimeError( + "SF-DMD rollout left score side conditions incomplete" + ) + return SFDMDLongRollout( + records=records, + generated_latents=global_z.detach(), + generated_real_latents=global_z[ + :, :, int(self.input_video_has_prepend) : + ].detach(), + num_real_frames=self.sfdmd_num_real_frames, + exit_step=exit_step, + conditioned_prefix_frames=conditioned_prefix_frames, + kv_seed_frames=kv_seed_frames, + conditioned_prefix_latents=( + None + if conditioned_prefix_z is None or kv_seed_frames == 0 + else conditioned_prefix_z[ + :, :, :kv_seed_frames + ].detach() + ), + conditioned_prefix_condition=conditioned_prefix_condition, + conditioned_prefix_hdmap=( + None + if global_hdmap_z is None or kv_seed_frames == 0 + else global_hdmap_z[:, :, :kv_seed_frames].detach() + ), + conditioned_prefix_side_condition=( + None + if global_side_z is None or kv_seed_frames == 0 + else global_side_z[:, :, :kv_seed_frames].detach() + ), + geometry_source_latents=( + None + if global_geometry_z is None + else global_geometry_z.detach() + ), + geometry_confidence_latents=( + None + if global_geometry_confidence_z is None + else global_geometry_confidence_z.detach() + ), + factorized_hdmap_mode=( + factorized_hdmap_mode + if self.sfdmd_factorized_conditioning + else "" + ), + factorized_geometry_mode=( + factorized_geometry_mode + if self.sfdmd_factorized_conditioning + else "" + ), + factorized_geometry_observations=( + factorized_geometry_observations + if self.sfdmd_factorized_conditioning + else 0 + ), + ) + + # ------------------------------------------------------------------ + # DMD losses + # ------------------------------------------------------------------ + + @staticmethod + def _rollout_noisy_mask( + rollout: SFDMDLongRollout, + reference: Tensor, + ) -> Tensor: + mask = reference.new_ones( + (1, 1, reference.shape[2], 1, 1), + dtype=torch.float32, + ) + mask[:, :, : rollout.conditioned_prefix_frames] = 0.0 + return mask + + def _sample_critic_sigma(self, batch_size: int) -> tuple[Tensor, Tensor]: + if self.sfdmd_artifixer_matching: + # ArtiFixer draws an integer base timestep, applies only the + # rational RF shift, then clamps the resulting float timestep. + # Do not use apply_shift_reparam(): the inherited student config + # also enables LTX percentile stretching, which ArtiFixer omits. + num_timesteps = int(self.rectified_flow.num_train_timesteps) + base_timestep = torch.randint( + 0, + num_timesteps, + (batch_size,), + device=self.tensor_kwargs_fp32["device"], + ).to(dtype=torch.float32) + raw_u = base_timestep / num_timesteps + sigma = self._rf_shift * raw_u / ( + 1.0 + (self._rf_shift - 1.0) * raw_u + ) + timestep = (sigma * num_timesteps).clamp( + int(self.sfdmd_critic_min_sigma * num_timesteps), + int(self.sfdmd_critic_max_sigma * num_timesteps), + ) + sigma = timestep / num_timesteps + return sigma, timestep + + raw_u = self.rectified_flow.sample_train_time(batch_size).to( + **self.tensor_kwargs_fp32 + ) + sigma = self.rectified_flow.apply_shift_reparam(raw_u) + timestep = sigma * self.rectified_flow.num_train_timesteps + return sigma, timestep + + def new_score_batch(self, rollout: SFDMDLongRollout) -> SFDMDScoreBatch: + """Draw one critic timestep/source field for the complete trajectory.""" + sigma, timestep = self._sample_critic_sigma( + rollout.generated_latents.shape[0] + ) + noise = torch.randn_like(rollout.generated_latents) + source = noise + if self.sfdmd_artifixer_matching and self.sfdmd_geometry_source: + if ( + rollout.geometry_source_latents is None + or rollout.geometry_confidence_latents is None + ): + raise RuntimeError( + "geometry-source critic batch requires rollout geometry" + ) + source = confidence_weighted_geometry_source( + noise, + rollout.geometry_source_latents, + rollout.geometry_confidence_latents, + self.sfdmd_geometry_source_noise_floor, + ) + return SFDMDScoreBatch( + sigma=sigma, + timestep=timestep, + source=source, + ) + + def _score_window_from_global( + self, tensor: Tensor, record: SFDMDReplayRecord + ) -> Tensor: + if record.window_start == 0: + return tensor[:, :, : self._sfdmd_window_tokens()] + return self._window_clip( + tensor, + record.window_start, + self.sfdmd_window_frames, + ) + + @staticmethod + def _score_noisy_state( + generated: Tensor, + source: Tensor, + sigma_5d: Tensor, + record: SFDMDReplayRecord, + ) -> tuple[Tensor, Tensor]: + effective_sigma = sigma_5d + if record.score_known_mask is not None: + known = record.score_known_mask.to( + device=generated.device, dtype=generated.dtype + ) + if known.ndim == 1: + known = known[None] + if known.shape[0] == 1 and generated.shape[0] != 1: + known = known.expand(generated.shape[0], -1) + if known.shape != (generated.shape[0], generated.shape[2]): + raise ValueError( + "score known mask must align with generated window" + ) + effective_sigma = sigma_5d * ( + 1.0 - known[:, None, :, None, None] + ) + return ( + effective_sigma * source + + (1.0 - effective_sigma) * generated, + effective_sigma, + ) + + def fake_score_loss( + self, + rollout: SFDMDLongRollout, + update_index: int, + score_batch: SFDMDScoreBatch | None = None, + ) -> tuple[Tensor, dict[str, Tensor]]: + if self.sfdmd_imaginaire_matching: + record = rollout.records[0] + assert record.score_hdmap is not None + generated = rollout.generated_latents.float() + if score_batch is None: + score_batch = self.new_score_batch(rollout) + sigma_5d = score_batch.sigma[:, None, None, None, None] + noisy_mask = self._rollout_noisy_mask(rollout, generated) + sigma_effective = sigma_5d * noisy_mask + x_t = ( + sigma_effective * score_batch.source + + (1.0 - sigma_effective) * generated + ) + target_v = score_batch.source - generated + fake_v = self._score_velocity( + self.fake_score, + x_t, + score_batch.timestep, + record.score_hdmap, + record.score_side_condition, + record.score_condition, + record.conditioned_prefix_frames, + record.score_known_mask, + ) + squared_error = (fake_v - target_v).square() + active_count = noisy_mask.expand_as(squared_error).sum().clamp_min( + 1.0 + ) + loss = (squared_error * noisy_mask).sum() / active_count + return loss, { + "fake_score_loss": loss.detach(), + "critic_sigma": score_batch.sigma.mean().detach(), + "critic_block": loss.new_tensor(-1.0), + "conditioned_prefix_frames": loss.new_tensor( + float(rollout.conditioned_prefix_frames) + ), + } + + record = rollout.records[update_index % len(rollout.records)] + assert record.generated_window is not None + assert record.score_hdmap is not None + generated = record.generated_window.float() + if score_batch is None: + score_batch = self.new_score_batch(rollout) + sigma, timestep = score_batch.sigma, score_batch.timestep + source = self._score_window_from_global(score_batch.source, record) + sigma_5d = sigma[:, None, None, None, None] + x_t, _ = self._score_noisy_state( + generated, source, sigma_5d, record + ) + target_v = source - generated + fake_v = self._score_velocity( + self.fake_score, + x_t, + timestep, + record.score_hdmap, + record.score_side_condition, + record.score_condition, + record.conditioned_prefix_frames, + record.score_known_mask, + ) + loss = active_slice_loss( + fake_v, + target_v, + record.score_active_start, + record.score_active_end, + ) + return loss, { + "fake_score_loss": loss.detach(), + "critic_sigma": sigma.mean().detach(), + "critic_block": loss.new_tensor(float(record.block_index)), + } + + @torch.no_grad() + def _guided_score_x0( + self, + score_model: nn.Module, + x_t: Tensor, + timestep: Tensor, + sigma_5d: Tensor, + record: SFDMDReplayRecord, + guidance_override: float | None = None, + ) -> Tensor: + assert record.score_hdmap is not None + cond_v = self._score_velocity( + score_model, + x_t, + timestep, + record.score_hdmap, + record.score_side_condition, + record.score_condition, + record.conditioned_prefix_frames, + record.score_known_mask, + ) + guidance = ( + self.sfdmd_teacher_guidance + if guidance_override is None + else guidance_override + ) + if guidance > 1.0: + uncond_v = self._score_velocity( + score_model, + x_t, + timestep, + torch.zeros_like(record.score_hdmap), + record.score_side_condition, + record.score_condition, + record.conditioned_prefix_frames, + record.score_known_mask, + ) + cond_v = uncond_v + guidance * (cond_v - uncond_v) + return rf_velocity_to_x0(x_t, cond_v, sigma_5d) + + @torch.no_grad() + def artifixer_student_targets( + self, rollout: SFDMDLongRollout + ) -> dict[int, tuple[Tensor, dict[str, Tensor]]]: + """Build globally normalized DMD targets over the full generated rollout.""" + if self.sfdmd_imaginaire_matching: + record = rollout.records[0] + assert record.score_hdmap is not None + generated = rollout.generated_latents.float() + score_batch = self.new_score_batch(rollout) + sigma_5d = score_batch.sigma[:, None, None, None, None] + noisy_mask = self._rollout_noisy_mask(rollout, generated) + sigma_effective = sigma_5d * noisy_mask + x_t = ( + sigma_effective * score_batch.source + + (1.0 - sigma_effective) * generated + ) + fake_x0 = self._guided_score_x0( + self.fake_score, + x_t, + score_batch.timestep, + sigma_effective, + record, + guidance_override=1.0, + ) + teacher_x0 = self._guided_score_x0( + self.teacher_score, + x_t, + score_batch.timestep, + sigma_effective, + record, + ) + normalizer_count = noisy_mask.expand_as(generated).sum( + dim=(1, 2, 3, 4), keepdim=True + ).clamp_min(1.0) + normalizer = ( + (generated - teacher_x0).abs() * noisy_mask + ).sum( + dim=(1, 2, 3, 4), keepdim=True + ) / normalizer_count + 1.0e-6 + vsd_grad = torch.nan_to_num( + (fake_x0 - teacher_x0) / normalizer + ) * noisy_mask + pseudo_target = generated - vsd_grad + targets = {} + for replay_record in rollout.records: + start = replay_record.global_start + end = start + replay_record.replay_xt.shape[2] + targets[replay_record.block_index] = ( + pseudo_target[:, :, start:end].detach(), + { + "vsd_weight": normalizer.reciprocal().mean(), + "teacher_fake_x0_l1": ( + teacher_x0[:, :, start:end] + - fake_x0[:, :, start:end] + ).abs().mean(), + "teacher_gen_x0_l1": ( + teacher_x0[:, :, start:end] + - generated[:, :, start:end] + ).abs().mean(), + "global_vsd_normalizer": normalizer.mean(), + "critic_sigma": score_batch.sigma.mean(), + }, + ) + return targets + + score_batch = self.new_score_batch(rollout) + sigma_5d = score_batch.sigma[:, None, None, None, None] + generated_parts = [] + teacher_parts = [] + fake_parts = [] + for record in rollout.records: + assert record.generated_window is not None + generated = record.generated_window.float() + source = self._score_window_from_global( + score_batch.source, record + ) + x_t, sigma_effective = self._score_noisy_state( + generated, + source, + sigma_5d, + record, + ) + fake_x0 = self._guided_score_x0( + self.fake_score, + x_t, + score_batch.timestep, + sigma_effective, + record, + ) + teacher_x0 = self._guided_score_x0( + self.teacher_score, + x_t, + score_batch.timestep, + sigma_effective, + record, + ) + active = slice( + record.score_active_start, record.score_active_end + ) + generated_parts.append(generated[:, :, active]) + teacher_parts.append(teacher_x0[:, :, active]) + fake_parts.append(fake_x0[:, :, active]) + + generated_all = torch.cat(generated_parts, dim=2) + teacher_all = torch.cat(teacher_parts, dim=2) + fake_all = torch.cat(fake_parts, dim=2) + normalizer = ( + generated_all - teacher_all + ).abs().mean(dim=(1, 2, 3, 4), keepdim=True) + 1.0e-6 + vsd_grad = torch.nan_to_num( + (fake_all - teacher_all) / normalizer + ) + pseudo_target = generated_all - vsd_grad + + targets = {} + offset = 0 + for record in rollout.records: + active_frames = ( + record.score_active_end - record.score_active_start + ) + end = offset + active_frames + target = pseudo_target[:, :, offset:end].detach() + targets[record.block_index] = ( + target, + { + "vsd_weight": ( + normalizer.clamp_min(1.0e-12).reciprocal().mean() + ), + "teacher_fake_x0_l1": ( + teacher_all[:, :, offset:end] + - fake_all[:, :, offset:end] + ).abs().mean(), + "teacher_gen_x0_l1": ( + teacher_all[:, :, offset:end] + - generated_all[:, :, offset:end] + ).abs().mean(), + "global_vsd_normalizer": normalizer.mean(), + "critic_sigma": score_batch.sigma.mean(), + }, + ) + offset = end + return targets + + @torch.no_grad() + def _student_pseudo_target( + self, record: SFDMDReplayRecord + ) -> tuple[Tensor, dict[str, Tensor]]: + assert record.generated_window is not None + assert record.score_hdmap is not None + generated = record.generated_window.float() + sigma, timestep = self._sample_critic_sigma(generated.shape[0]) + sigma_5d = sigma[:, None, None, None, None] + epsilon = torch.randn_like(generated) + x_t, sigma_effective = self._score_noisy_state( + generated, epsilon, sigma_5d, record + ) + fake_v = self._score_velocity( + self.fake_score, + x_t, + timestep, + record.score_hdmap, + record.score_side_condition, + record.score_condition, + record.conditioned_prefix_frames, + record.score_known_mask, + ) + teacher_v = self._score_velocity( + self.teacher_score, + x_t, + timestep, + record.score_hdmap, + record.score_side_condition, + record.score_condition, + record.conditioned_prefix_frames, + record.score_known_mask, + ) + fake_x0 = rf_velocity_to_x0(x_t, fake_v, sigma_effective) + teacher_x0 = rf_velocity_to_x0( + x_t, teacher_v, sigma_effective + ) + active = slice( + record.score_active_start, record.score_active_end + ) + target_active, weight = dmd_pseudo_target( + generated[:, :, active], + teacher_x0[:, :, active], + fake_x0[:, :, active], + ) + return target_active, { + "vsd_weight": weight.mean(), + "teacher_fake_x0_l1": ( + teacher_x0[:, :, active] - fake_x0[:, :, active] + ).abs().mean(), + "teacher_gen_x0_l1": ( + teacher_x0[:, :, active] - generated[:, :, active] + ).abs().mean(), + } + + def student_replay_loss( + self, + record: SFDMDReplayRecord, + kv_cache: list[dict[str, Tensor] | None], + target_payload: tuple[Tensor, dict[str, Tensor]] | None = None, + ) -> tuple[Tensor, dict[str, Tensor]]: + if target_payload is None: + if ( + self.sfdmd_artifixer_matching + or self.sfdmd_imaginaire_matching + ): + raise RuntimeError( + "matched SF-DMD replay requires the trajectory-wide " + "precomputed target payload" + ) + target_active, metrics = self._student_pseudo_target(record) + else: + target_active, metrics = target_payload + replay_sigma = record.replay_xt.new_tensor(record.replay_sigma) + active_t = replay_sigma * self.rectified_flow.num_train_timesteps + timesteps = torch.full( + ( + record.replay_xt.shape[0], + record.replay_xt.shape[2], + ), + float(active_t), + device=record.replay_xt.device, + dtype=torch.float32, + ) + if record.student_known_mask is not None: + known = record.student_known_mask.to( + device=timesteps.device, dtype=torch.bool + ) + timesteps[:, known] = 0.0 + velocity = self._student_velocity( + record.replay_xt, + timesteps, + record.student_condition, + record.student_hdmap, + record.student_side_condition, + kv_cache, + record.global_start, + store_kv=( + not self.sfdmd_imaginaire_matching + and not self.sfdmd_clean_x0_kv_commit + and record.history_commit_block is None + ), + detach_kv=self.sfdmd_imaginaire_matching, + known_mask=record.student_known_mask, + ) + x0_pred = rf_velocity_to_x0( + record.replay_xt, + velocity, + replay_sigma, + ) + if record.history_commit_block is not None: + self._seed_student_clean_history( + record.history_commit_block, + record.student_condition, + record.student_hdmap, + record.student_side_condition, + kv_cache, + record.global_start, + detach_kv=False, + known_mask=record.student_known_mask, + ) + elif self.sfdmd_clean_x0_kv_commit: + clean_commit = x0_pred + if ( + record.student_active_start > 0 + and record.generated_block is not None + ): + clean_commit = x0_pred.clone() + clean_commit[ + :, :, : record.student_active_start + ] = record.generated_block[ + :, :, : record.student_active_start + ] + self._seed_student_clean_history( + clean_commit, + record.student_condition, + record.student_hdmap, + record.student_side_condition, + kv_cache, + record.global_start, + detach_kv=False, + known_mask=record.student_known_mask, + ) + elif self.sfdmd_imaginaire_matching: + if record.generated_block is None: + raise RuntimeError( + "Imaginaire replay record has no finalized clean block" + ) + with torch.no_grad(): + self._seed_student_clean_history( + record.generated_block, + record.student_condition, + record.student_hdmap, + record.student_side_condition, + kv_cache, + record.global_start, + ) + if self.sfdmd_imaginaire_matching: + per_frame_loss = ( + 0.5 + * (x0_pred.float() - target_active.float()).square() + ).mean(dim=(0, 1, 3, 4)) + loss = per_frame_loss.sum() + elif self.sfdmd_artifixer_matching: + # Match ArtiFixer's FP64 pseudo-target MSE. Casting the scalar back + # is unnecessary; autograd propagates through the double cast. + active_start = record.student_active_start + active_end = ( + x0_pred.shape[2] + if record.student_active_end < 0 + else record.student_active_end + ) + active_x0 = x0_pred[:, :, active_start:active_end] + loss = 0.5 * F.mse_loss( + active_x0.double(), + target_active.double(), + reduction="mean", + ) + else: + loss = active_slice_loss( + x0_pred, + target_active, + 0, + x0_pred.shape[2], + half=True, + ) + metrics.update( + { + "student_vsd_loss": loss.detach(), + "student_block": loss.new_tensor(float(record.block_index)), + "student_x0_abs": x0_pred.abs().mean().detach(), + } + ) + return loss, metrics + + +@diffusion_fsdp_class_decorator +class _FSDPHdmapToLidarSFDMDModel(HdmapToLidarSFDMDModel): + pass + + +class FSDPHdmapToLidarSFDMDModel(_FSDPHdmapToLidarSFDMDModel): + """Named public FSDP class used by Hydra experiment configs.""" + + pass + + +class HdmapToLidarImaginaireSFDMDModel(HdmapToLidarSFDMDModel): + """Explicit entry point for the Imaginaire-matched SF-DMD recipe.""" + + def __init__(self, config): + super().__init__(config) + if not self.sfdmd_imaginaire_matching: + raise ValueError( + "Imaginaire SF-DMD model requires " + "sfdmd_imaginaire_matching=True" + ) + + +@diffusion_fsdp_class_decorator +class _FSDPHdmapToLidarImaginaireSFDMDModel( + HdmapToLidarImaginaireSFDMDModel +): + pass + + +class FSDPHdmapToLidarImaginaireSFDMDModel( + _FSDPHdmapToLidarImaginaireSFDMDModel +): + pass diff --git a/diffusion/training/models/model.py b/diffusion/training/models/model.py new file mode 100644 index 0000000000000000000000000000000000000000..875f3c2b6f452ef3fe7ef7bde27d09503fce5ac1 --- /dev/null +++ b/diffusion/training/models/model.py @@ -0,0 +1,663 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union + +import amp_C +import torch +from apex.multi_tensor_apply import multi_tensor_applier +from einops import rearrange +from megatron.core import parallel_state +from torch import Tensor +from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors +from torch.distributed import broadcast_object_list, get_process_group_ranks +from torch.distributed.utils import _verify_param_shape_across_processes + +from diffusion.conditioner import DataType +from diffusion.modules.res_sampler import COMMON_SOLVER_OPTIONS +from diffusion.training.conditioner import BaseVideoCondition +from diffusion.training.context_parallel import cat_outputs_cp, split_inputs_cp +from diffusion.training.models.model_image import CosmosCondition +from diffusion.training.models.model_image import DiffusionModel as ImageModel +from diffusion.training.models.model_image import diffusion_fsdp_class_decorator +from utils import distributed, log, misc + +l2_norm_impl = amp_C.multi_tensor_l2norm +multi_tensor_scale_impl = amp_C.multi_tensor_scale + +# key to check if the video data is normalized or image data is converted to video data +# to avoid apply normalization or augment image dimension multiple times +# It is due to we do not have normalization and augment image dimension in the dataloader and move it to the model +IS_PREPROCESSED_KEY = "is_preprocessed" + + +def robust_broadcast(tensor: torch.Tensor, src: int, pg, is_check_shape: bool = False) -> torch.Tensor: + """ + Perform a robust broadcast operation that works regardless of tensor shapes on different ranks. + + Args: + tensor (torch.Tensor): The tensor to broadcast (on src rank) or receive (on other ranks). + src (int): The source rank for the broadcast. Defaults to 0. + + Returns: + torch.Tensor: The broadcasted tensor on all ranks. + """ + # First, broadcast the shape of the tensor + if distributed.get_rank() == src: + shape = torch.tensor(tensor.shape).cuda() + else: + shape = torch.empty(tensor.dim(), dtype=torch.long).cuda() + if is_check_shape: + _verify_param_shape_across_processes(pg, [shape]) + torch.distributed.broadcast(shape, src, group=pg) + + # Resize the tensor on non-src ranks if necessary + if distributed.get_rank() != src: + tensor = tensor.new_empty(shape.tolist()).type_as(tensor) + + # Now broadcast the tensor data + torch.distributed.broadcast(tensor, src, group=pg) + + return tensor + + +def _broadcast(item: torch.Tensor | str | None, to_tp: bool = True, to_cp: bool = True) -> torch.Tensor | str | None: + """ + Broadcast the item from the minimum rank in the specified group(s). + Since global rank = tp_rank + cp_rank * tp_size + ... + First broadcast in the tp_group and then in the cp_group will + ensure that the item is broadcasted across ranks in cp_group and tp_group. + + Parameters: + - item: The item to broadcast (can be a torch.Tensor, str, or None). + - to_tp: Whether to broadcast to the tensor model parallel group. + - to_cp: Whether to broadcast to the context parallel group. + """ + if not parallel_state.is_initialized(): + return item + tp_group = parallel_state.get_tensor_model_parallel_group() + cp_group = parallel_state.get_context_parallel_group() + + to_tp = to_tp and parallel_state.get_tensor_model_parallel_world_size() > 1 + to_cp = to_cp and parallel_state.get_context_parallel_world_size() > 1 + + if to_tp: + min_tp_rank = min(get_process_group_ranks(tp_group)) + + if to_cp: + min_cp_rank = min(get_process_group_ranks(cp_group)) + + if isinstance(item, torch.Tensor): # assume the device is cuda + # log.info(f"{item.shape}", rank0_only=False) + if to_tp: + # torch.distributed.broadcast(item, min_tp_rank, group=tp_group) + item = robust_broadcast(item, min_tp_rank, tp_group) + if to_cp: + # torch.distributed.broadcast(item, min_cp_rank, group=cp_group) + item = robust_broadcast(item, min_cp_rank, cp_group) + elif item is not None: + broadcastable_list = [item] + if to_tp: + # log.info(f"{broadcastable_list}", rank0_only=False) + broadcast_object_list(broadcastable_list, min_tp_rank, group=tp_group) + if to_cp: + broadcast_object_list(broadcastable_list, min_cp_rank, group=cp_group) + + item = broadcastable_list[0] + return item + + +def broadcast_condition(condition: BaseVideoCondition, to_tp: bool = True, to_cp: bool = True) -> BaseVideoCondition: + condition_kwargs = {} + for k, v in condition.to_dict().items(): + if isinstance(v, torch.Tensor): + assert not v.requires_grad, f"{k} requires gradient. the current impl does not support it" + condition_kwargs[k] = _broadcast(v, to_tp=to_tp, to_cp=to_cp) + condition = type(condition)(**condition_kwargs) + return condition + + +class DiffusionModel(ImageModel): + def __init__(self, config): + super().__init__(config) + # Initialize trained_data_record with defaultdict, key: image, video, iteration + self.trained_data_record = { + "image": 0, + "video": 0, + "iteration": 0, + } + if parallel_state.is_initialized(): + self.data_parallel_size = parallel_state.get_data_parallel_world_size() + else: + self.data_parallel_size = 1 + + if self.config.adjust_video_noise: + self.video_noise_multiplier = math.sqrt(self.state_shape[1]) + else: + self.video_noise_multiplier = 1.0 + + def setup_data_key(self) -> None: + self.input_data_key = self.config.input_data_key # by default it is video key for Video diffusion model + self.input_image_key = self.config.input_image_key + + def is_image_batch(self, data_batch: dict[str, Tensor]) -> bool: + """We hanlde two types of data_batch. One comes from a joint_dataloader where "dataset_name" can be used to differenciate image_batch and video_batch. + Another comes from a dataloader which we by default assumes as video_data for video model training. + """ + is_image = self.input_image_key in data_batch + is_video = self.input_data_key in data_batch + assert ( + is_image != is_video + ), "Only one of the input_image_key or input_data_key should be present in the data_batch." + return is_image + + def draw_training_sigma_and_epsilon(self, size: int, condition: BaseVideoCondition) -> Tensor: + sigma_B, epsilon = super().draw_training_sigma_and_epsilon(size, condition) + is_video_batch = condition.data_type == DataType.VIDEO + multiplier = self.video_noise_multiplier if is_video_batch else 1 + sigma_B = _broadcast(sigma_B * multiplier, to_tp=True, to_cp=is_video_batch) + epsilon = _broadcast(epsilon, to_tp=True, to_cp=is_video_batch) + return sigma_B, epsilon + + @torch.no_grad() + def validation_step( + self, data: dict[str, torch.Tensor], iteration: int + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + """ + save generated videos + """ + raw_data, x0, condition = self.get_data_and_condition(data) + guidance = data["guidance"] + data = misc.to(data, **self.tensor_kwargs) + sample = self.generate_samples_from_batch( + data, + guidance=guidance, + # make sure no mismatch and also works for cp + state_shape=x0.shape[1:], + n_sample=x0.shape[0], + ) + sample = self.decode(sample) + gt = raw_data + caption = data["ai_caption"] + return {"gt": gt, "result": sample, "caption": caption}, torch.tensor([0]).to(**self.tensor_kwargs) + + def training_step(self, data_batch: Dict[str, Tensor], iteration: int) -> Tuple[Dict[str, Tensor] | Tensor]: + input_key = self.input_data_key # by default it is video key + if self.is_image_batch(data_batch): + input_key = self.input_image_key + batch_size = data_batch[input_key].shape[0] + self.trained_data_record["image" if self.is_image_batch(data_batch) else "video"] += ( + batch_size * self.data_parallel_size + ) + self.trained_data_record["iteration"] += 1 + return super().training_step(data_batch, iteration) + + def state_dict(self) -> Dict[str, Any]: + state_dict = super().state_dict() + state_dict["trained_data_record"] = self.trained_data_record + return state_dict + + def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False): + if "trained_data_record" in state_dict and hasattr(self, "trained_data_record"): + trained_data_record = state_dict.pop("trained_data_record") + if trained_data_record: + assert set(trained_data_record.keys()) == set(self.trained_data_record.keys()) + for k, v in trained_data_record.items(): + self.trained_data_record[k] = v + else: + log.warning("trained_data_record not found in the state_dict.") + return super().load_state_dict(state_dict, strict, assign) + + def _normalize_video_databatch_inplace(self, data_batch: dict[str, Tensor], input_key: str = None) -> None: + """ + Normalizes video data in-place on a CUDA device to reduce data loading overhead. + + This function modifies the video data tensor within the provided data_batch dictionary + in-place, scaling the uint8 data from the range [0, 255] to the normalized range [-1, 1]. + + Warning: + A warning is issued if the data has not been previously normalized. + + Args: + data_batch (dict[str, Tensor]): A dictionary containing the video data under a specific key. + This tensor is expected to be on a CUDA device and have dtype of torch.uint8. + + Side Effects: + Modifies the 'input_data_key' tensor within the 'data_batch' dictionary in-place. + + Note: + This operation is performed directly on the CUDA device to avoid the overhead associated + with moving data to/from the GPU. Ensure that the tensor is already on the appropriate device + and has the correct dtype (torch.uint8) to avoid unexpected behaviors. + """ + input_key = self.input_data_key if input_key is None else input_key + # only handle video batch + if input_key in data_batch: + # Check if the data has already been normalized and avoid re-normalizing + if IS_PREPROCESSED_KEY in data_batch and data_batch[IS_PREPROCESSED_KEY] is True: + assert torch.is_floating_point(data_batch[input_key]), "Video data is not in float format." + assert torch.all( + (data_batch[input_key] >= -1.0001) & (data_batch[input_key] <= 1.0001) + ), f"Video data is not in the range [-1, 1]. get data range [{data_batch[input_key].min()}, {data_batch[input_key].max()}]" + else: + assert data_batch[input_key].dtype == torch.uint8, "Video data is not in uint8 format." + data_batch[input_key] = data_batch[input_key].to(**self.tensor_kwargs) / 127.5 - 1.0 + data_batch[IS_PREPROCESSED_KEY] = True + + def _augment_image_dim_inplace(self, data_batch: dict[str, Tensor], input_key: str = None) -> None: + input_key = self.input_image_key if input_key is None else input_key + if input_key in data_batch: + # Check if the data has already been augmented and avoid re-augmenting + if IS_PREPROCESSED_KEY in data_batch and data_batch[IS_PREPROCESSED_KEY] is True: + assert ( + data_batch[input_key].shape[2] == 1 + ), f"Image data is claimed be augmented while its shape is {data_batch[input_key].shape}" + return + else: + data_batch[input_key] = rearrange(data_batch[input_key], "b c h w -> b c 1 h w").contiguous() + data_batch[IS_PREPROCESSED_KEY] = True + + def get_data_and_condition(self, data_batch: dict[str, Tensor]) -> Tuple[Tensor, BaseVideoCondition]: + self._normalize_video_databatch_inplace(data_batch) + self._augment_image_dim_inplace(data_batch) + input_key = self.input_data_key # by default it is video key + is_image_batch = self.is_image_batch(data_batch) + is_video_batch = not is_image_batch + + # Broadcast data and condition across TP and CP groups. + # sort keys to make sure the order is same, IMPORTANT! otherwise, nccl will hang! + local_keys = sorted(list(data_batch.keys())) + # log.critical(f"all keys {local_keys}", rank0_only=False) + for key in local_keys: + data_batch[key] = _broadcast(data_batch[key], to_tp=True, to_cp=is_video_batch) + + if is_image_batch: + input_key = self.input_image_key + + # Latent state + raw_state = data_batch[input_key] + latent_state = self.encode(raw_state).contiguous() + + # Condition + condition = self.conditioner(data_batch) + if is_image_batch: + condition.data_type = DataType.IMAGE + else: + condition.data_type = DataType.VIDEO + + # VAE has randomness. CP/TP group should have the same encoded output. + + latent_state = _broadcast(latent_state, to_tp=True, to_cp=is_video_batch) + condition = broadcast_condition(condition, to_tp=True, to_cp=is_video_batch) + + return raw_state, latent_state, condition + + def on_train_start(self, memory_format: torch.memory_format = torch.preserve_format) -> None: + super().on_train_start(memory_format) + if parallel_state.is_initialized() and parallel_state.get_tensor_model_parallel_world_size() > 1: + sequence_parallel = getattr(parallel_state, "sequence_parallel", False) + if sequence_parallel: + self.net.enable_sequence_parallel() + + def compute_loss_with_epsilon_and_sigma( + self, + data_batch: dict[str, torch.Tensor], + x0_from_data_batch: torch.Tensor, + x0: torch.Tensor, + condition: CosmosCondition, + epsilon: torch.Tensor, + sigma: torch.Tensor, + ): + if self.is_image_batch(data_batch): + # Turn off CP + self.net.disable_context_parallel() + else: + if parallel_state.is_initialized(): + if parallel_state.get_context_parallel_world_size() > 1: + # Turn on CP + cp_group = parallel_state.get_context_parallel_group() + self.net.enable_context_parallel(cp_group) + log.debug("[CP] Split x0 and epsilon") + x0 = split_inputs_cp(x=x0, seq_dim=2, cp_group=self.net.cp_group) + epsilon = split_inputs_cp(x=epsilon, seq_dim=2, cp_group=self.net.cp_group) + + output_batch, kendall_loss, pred_mse, edm_loss = super().compute_loss_with_epsilon_and_sigma( + data_batch, x0_from_data_batch, x0, condition, epsilon, sigma + ) + if not self.is_image_batch(data_batch): + if self.loss_reduce == "sum" and parallel_state.get_context_parallel_world_size() > 1: + kendall_loss *= parallel_state.get_context_parallel_world_size() + + return output_batch, kendall_loss, pred_mse, edm_loss + + def get_x0_fn_from_batch( + self, + data_batch: Dict, + guidance: float = 1.5, + is_negative_prompt: bool = False, + ) -> Callable: + """ + Generates a callable function `x0_fn` based on the provided data batch and guidance factor. + + This function first processes the input data batch through a conditioning workflow (`conditioner`) to obtain conditioned and unconditioned states. It then defines a nested function `x0_fn` which applies a denoising operation on an input `noise_x` at a given noise level `sigma` using both the conditioned and unconditioned states. + + Args: + - data_batch (Dict): A batch of data used for conditioning. The format and content of this dictionary should align with the expectations of the `self.conditioner` + - guidance (float, optional): A scalar value that modulates the influence of the conditioned state relative to the unconditioned state in the output. Defaults to 1.5. + - is_negative_prompt (bool): use negative prompt t5 in uncondition if true + + Returns: + - Callable: A function `x0_fn(noise_x, sigma)` that takes two arguments, `noise_x` and `sigma`, and return x0 predictoin + + The returned function is suitable for use in scenarios where a denoised state is required based on both conditioned and unconditioned inputs, with an adjustable level of guidance influence. + """ + if is_negative_prompt: + condition, uncondition = self.conditioner.get_condition_with_negative_prompt(data_batch) + else: + condition, uncondition = self.conditioner.get_condition_uncondition(data_batch) + + to_cp = self.net.is_context_parallel_enabled + # For inference, check if parallel_state is initialized + if parallel_state.is_initialized(): + condition = broadcast_condition(condition, to_tp=True, to_cp=to_cp) + uncondition = broadcast_condition(uncondition, to_tp=True, to_cp=to_cp) + else: + assert not to_cp, "parallel_state is not initialized, context parallel should be turned off." + + def x0_fn(noise_x: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor: + cond_x0 = self.denoise(noise_x, sigma, condition).x0 + uncond_x0 = self.denoise(noise_x, sigma, uncondition).x0 + raw_x0 = cond_x0 + guidance * (cond_x0 - uncond_x0) + if "guided_image" in data_batch: + # replacement trick that enables inpainting with base model + assert "guided_mask" in data_batch, "guided_mask should be in data_batch if guided_image is present" + guide_image = data_batch["guided_image"] + guide_mask = data_batch["guided_mask"] + raw_x0 = guide_mask * guide_image + (1 - guide_mask) * raw_x0 + return raw_x0 + + return x0_fn + + def get_x_from_clean( + self, + in_clean_img: torch.Tensor, + sigma_max: float | None, + seed: int = 1, + ) -> Tensor: + """ + in_clean_img (torch.Tensor): input clean image for image-to-image/video-to-video by adding noise then denoising + sigma_max (float): maximum sigma applied to in_clean_image for image-to-image/video-to-video + """ + if in_clean_img is None: + return None + generator = torch.Generator(device=self.tensor_kwargs["device"]) + generator.manual_seed(seed) + noise = torch.randn(*in_clean_img.shape, **self.tensor_kwargs, generator=generator) + if sigma_max is None: + sigma_max = self.sde.sigma_max + x_sigma_max = in_clean_img + noise * sigma_max + return x_sigma_max + + def generate_samples_from_batch( + self, + data_batch: Dict, + guidance: float = 1.5, + seed: int = 1, + state_shape: Tuple | None = None, + n_sample: int | None = None, + is_negative_prompt: bool = False, + num_steps: int = 35, + solver_option: COMMON_SOLVER_OPTIONS = "2ab", + x_sigma_max: Optional[torch.Tensor] = None, + sigma_max: float | None = None, + return_noise: bool = False, + ) -> Tensor | Tuple[Tensor, Tensor]: + """ + Generate samples from the batch. Based on given batch, it will automatically determine whether to generate image or video samples. + Args: + data_batch (dict): raw data batch draw from the training data loader. + iteration (int): Current iteration number. + guidance (float): guidance weights + seed (int): random seed + state_shape (tuple): shape of the state, default to self.state_shape if not provided + n_sample (int): number of samples to generate + is_negative_prompt (bool): use negative prompt t5 in uncondition if true + num_steps (int): number of steps for the diffusion process + solver_option (str): differential equation solver option, default to "2ab"~(mulitstep solver) + return_noise (bool): return the initial noise or not, used for ODE pairs generation + """ + self._normalize_video_databatch_inplace(data_batch) + self._augment_image_dim_inplace(data_batch) + is_image_batch = self.is_image_batch(data_batch) + if n_sample is None: + input_key = self.input_image_key if is_image_batch else self.input_data_key + n_sample = data_batch[input_key].shape[0] + if state_shape is None: + if is_image_batch: + state_shape = (self.state_shape[0], 1, *self.state_shape[2:]) # C,T,H,W + + x0_fn = self.get_x0_fn_from_batch(data_batch, guidance, is_negative_prompt=is_negative_prompt) + + x_sigma_max = ( + misc.arch_invariant_rand( + (n_sample,) + tuple(state_shape), + torch.float32, + self.tensor_kwargs["device"], + seed, + ) + * self.sde.sigma_max + ) + + if self.net.is_context_parallel_enabled: + x_sigma_max = split_inputs_cp(x=x_sigma_max, seq_dim=2, cp_group=self.net.cp_group) + + samples = self.sampler( + x0_fn, x_sigma_max, num_steps=num_steps, sigma_max=self.sde.sigma_max, solver_option=solver_option + ) + if self.net.is_context_parallel_enabled: + samples = cat_outputs_cp(samples, seq_dim=2, cp_group=self.net.cp_group) + + if return_noise: + if self.net.is_context_parallel_enabled: + x_sigma_max = cat_outputs_cp(x_sigma_max, seq_dim=2, cp_group=self.net.cp_group) + return samples, x_sigma_max / self.sde.sigma_max + + return samples + + def on_after_backward(self, iteration: int = 0): + finalize_model_grads([self]) + + def get_grad_norm( + self, + norm_type: Union[int, float] = 2, + filter_fn: Callable[[str, torch.nn.Parameter], bool] | None = None, + ) -> float: + """Calculate the norm of gradients, handling model parallel parameters. + + This function is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ + with added functionality to handle model parallel parameters. + + Args: + norm_type (float or int): Type of norm to use. Can be 2 for L2 norm. + 'inf' for infinity norm is not supported. + filter_fn (callable, optional): Function to filter parameters for norm calculation. + Takes parameter name and parameter as input, returns True if this parameter is sharded else False. + + Returns: + float: Total norm of the parameters (viewed as a single vector). + + Note: + - Uses NVIDIA's multi-tensor applier for efficient norm calculation. + - Handles both model parallel and non-model parallel parameters separately. + - Currently only supports L2 norm (norm_type = 2). + """ + # Get model parallel group if parallel state is initialized + if parallel_state.is_initialized(): + model_parallel_group = parallel_state.get_model_parallel_group() + else: + model_parallel_group = None + + # Default filter function to identify tensor parallel parameters + if filter_fn is None: + + def is_tp(name, param): + return ( + any(key in name for key in ["to_q.0", "to_k.0", "to_v.0", "to_out.0", "layer1", "layer2"]) + and "_extra_state" not in name + ) + + filter_fn = is_tp + + # Separate gradients into model parallel and non-model parallel + without_mp_grads_for_norm = [] + with_mp_grads_for_norm = [] + for name, param in self.named_parameters(): + if param.grad is not None: + if filter_fn(name, param): + with_mp_grads_for_norm.append(param.grad.detach()) + else: + without_mp_grads_for_norm.append(param.grad.detach()) + + # Only L2 norm is currently supported + if norm_type != 2.0: + raise NotImplementedError(f"Norm type {norm_type} is not supported. Only L2 norm (2.0) is implemented.") + + # Calculate L2 norm using NVIDIA's multi-tensor applier + dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device="cuda") + + # Calculate norm for non-model parallel gradients + without_mp_grad_norm = torch.tensor([0], dtype=torch.float, device="cuda") + if without_mp_grads_for_norm: + without_mp_grad_norm, _ = multi_tensor_applier( + l2_norm_impl, + dummy_overflow_buf, + [without_mp_grads_for_norm], + False, # no per-parameter norm + ) + + # Calculate norm for model parallel gradients + with_mp_grad_norm = torch.tensor([0], dtype=torch.float, device="cuda") + if with_mp_grads_for_norm: + with_mp_grad_norm, _ = multi_tensor_applier( + l2_norm_impl, + dummy_overflow_buf, + [with_mp_grads_for_norm], + False, # no per-parameter norm + ) + + # Square the norms as we'll be summing across model parallel GPUs + total_without_mp_norm = without_mp_grad_norm**2 + total_with_mp_norm = with_mp_grad_norm**2 + + # Sum across all model-parallel GPUs + torch.distributed.all_reduce(total_with_mp_norm, op=torch.distributed.ReduceOp.SUM, group=model_parallel_group) + + # Combine norms from model parallel and non-model parallel gradients + total_norm = (total_with_mp_norm.item() + total_without_mp_norm.item()) ** 0.5 + + return total_norm + + def clip_grad_norm_(self, max_norm: float): + """ + This function performs gradient clipping to prevent exploding gradients. + It calculates the total norm of the gradients, and if it exceeds the + specified max_norm, scales the gradients down proportionally. + + Args: + max_norm (float): The maximum allowed norm for the gradients. + + Returns: + torch.Tensor: The total norm of the gradients before clipping. + + Note: + This implementation uses NVIDIA's multi-tensor applier for efficiency. + """ + # Collect gradients from all parameters that require gradients + grads = [] + for param in self.parameters(): + if param.grad is not None: + grads.append(param.grad.detach()) + + # Calculate the total norm of the gradients + total_norm = self.get_grad_norm() + + # Compute the clipping coefficient + clip_coeff = max_norm / (total_norm + 1.0e-6) + + # Apply gradient clipping if the total norm exceeds max_norm + if clip_coeff < 1.0: + dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device="cuda") + # Apply the scaling to the gradients using multi_tensor_applier for efficiency + multi_tensor_applier(multi_tensor_scale_impl, dummy_overflow_buf, [grads, grads], clip_coeff) + + return torch.tensor([total_norm]) + + +def _allreduce_layernorm_grads(model: List[torch.nn.Module]): + """ + All-reduce the following layernorm grads: + - When tensor parallel is enabled, all-reduce grads of QK-layernorm + - When sequence parallel, all-reduce grads of AdaLN, t_embedder, additional_timestamp_embedder, + and affline_norm. + """ + sequence_parallel = getattr(parallel_state, "sequence_parallel", False) + + if parallel_state.get_tensor_model_parallel_world_size() > 1: + grads = [] + for model_chunk in model: + for name, param in model_chunk.named_parameters(): + if not param.requires_grad: + continue + + if "to_q.1" in name or "to_k.1" in name: # TP # Q-layernorm # K-layernorm + # grad = param.main_grad + grad = param.grad + if grad is not None: + grads.append(grad.data) + + if sequence_parallel: # TP + SP + if ( + "t_embedder" in name + or "adaLN_modulation" in name + or "additional_timestamp_embedder" in name + or "affline_norm" in name + or "input_hint_block" in name + or "zero_blocks" in name + ): + # grad = param.main_grad + grad = param.grad + if grad is not None: + grads.append(grad.data) + + if grads: + coalesced = _flatten_dense_tensors(grads) + torch.distributed.all_reduce(coalesced, group=parallel_state.get_tensor_model_parallel_group()) + for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)): + buf.copy_(synced) + + +def finalize_model_grads(model: List[torch.nn.Module]): + """ + All-reduce layernorm grads for tensor/sequence parallelism. + Reference implementation: https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/distributed/finalize_model_grads.py#L99 + """ + + _allreduce_layernorm_grads(model) + + +@diffusion_fsdp_class_decorator +class FSDPDiffusionModel(DiffusionModel): + pass diff --git a/diffusion/training/models/model_image.py b/diffusion/training/models/model_image.py new file mode 100644 index 0000000000000000000000000000000000000000..519fc6fae902e3943a3a59caad2cdc47ceccbc3d --- /dev/null +++ b/diffusion/training/models/model_image.py @@ -0,0 +1,1009 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +from contextlib import contextmanager +from dataclasses import dataclass, fields +from typing import Any, Callable, Dict, Mapping, Optional, Tuple, Type, TypeVar + +import numpy as np +import torch +import torch.nn.functional as F +from megatron.core import parallel_state +from torch.distributed.fsdp import FullStateDictConfig +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import ShardingStrategy, StateDictType +from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy +from torch.nn.modules.module import _IncompatibleKeys + +from diffusion.functional.batch_ops import batch_mul +from diffusion.module.blocks import FourierFeatures +from diffusion.training.module.pretrained_vae_base import BaseVAE +from diffusion.modules.denoiser_scaling import EDMScaling +from diffusion.modules.res_sampler import COMMON_SOLVER_OPTIONS, Sampler +from diffusion.training.functional.loss import create_per_sample_loss_mask +from diffusion.training.utils.fsdp_helper import apply_fsdp_checkpointing, hsdp_device_mesh +from diffusion.training.utils.optim_instantiate import get_base_scheduler +from diffusion.types import DenoisePrediction +from utils import distributed, log, misc +from utils.ema import FastEmaModelUpdater +from utils.lazy_config import LazyDict +from utils.lazy_config import instantiate as lazy_instantiate +from utils.model import Model + + +@dataclass +class CosmosCondition: + crossattn_emb: torch.Tensor + crossattn_mask: torch.Tensor + padding_mask: Optional[torch.Tensor] = None + scalar_feature: Optional[torch.Tensor] = None + + def to_dict(self) -> Dict[str, Optional[torch.Tensor]]: + return {f.name: getattr(self, f.name) for f in fields(self)} + + +class DiffusionModel(Model): + def __init__(self, config): + super().__init__() + + self.config = config + + # how many sample have been processed + self.sample_counter = 0 + self.precision = { + "float32": torch.float32, + "float16": torch.float16, + "bfloat16": torch.bfloat16, + }[config.precision] + self.tensor_kwargs = {"device": "cuda", "dtype": self.precision} + log.warning(f"DiffusionModel: precision {self.precision}") + # Timer passed to network to detect slow ranks. + # 1. set data keys and data information + self.sigma_data = config.sigma_data + self.state_shape = list(config.latent_shape) + self.setup_data_key() + + # 2. setup up diffusion processing and scaling~(pre-condition), sampler + self.sde = lazy_instantiate(config.sde) + self.sampler = Sampler() + self.scaling = EDMScaling(self.sigma_data) + + # 3. vae + with misc.timer("DiffusionModel: set_up_vae"): + self.vae: BaseVAE = lazy_instantiate(config.vae) + self.intensity_vae: BaseVAE | None = None + intensity_vae_config = getattr(config, "intensity_vae", None) + if intensity_vae_config is not None: + self.intensity_vae = lazy_instantiate(intensity_vae_config) + expected_latent_ch = self.vae.latent_ch + ( + 0 + if self.intensity_vae is None + else self.intensity_vae.latent_ch + ) + assert ( + expected_latent_ch == self.state_shape[0] + ), ( + f"combined latent_ch {expected_latent_ch} != state_shape " + f"{self.state_shape[0]}" + ) + + # 4. Set up loss options, including loss masking, loss reduce and loss scaling + self.loss_masking: Optional[Dict] = config.loss_masking + self.loss_reduce = getattr(config, "loss_reduce", "mean") + assert self.loss_reduce in ["mean", "sum"] + self.loss_scale = getattr(config, "loss_scale", 1.0) + log.critical(f"Using {self.loss_reduce} loss reduce with loss scale {self.loss_scale}") + log.critical(f"Enable loss masking: {config.loss_mask_enabled}") + + # 5. diffusion neural networks part + self.set_up_model() + + def setup_data_key(self) -> None: + self.input_data_key = self.config.input_data_key + + def build_model(self) -> torch.nn.ModuleDict: + config = self.config + net = lazy_instantiate(config.net) + conditioner = lazy_instantiate(config.conditioner) + logvar = torch.nn.Sequential( + FourierFeatures(num_channels=128, normalize=True), torch.nn.Linear(128, 1, bias=False) + ) + if bool(getattr(config, "optimizer_net_only", False)): + conditioner.requires_grad_(False) + logvar.requires_grad_(False) + + return torch.nn.ModuleDict( + { + "net": net, + "conditioner": conditioner, + "logvar": logvar, + } + ) + + @misc.timer("DiffusionModel: set_up_model") + def set_up_model(self): + config = self.config + self.model = self.build_model() + if config.ema.enabled: + with misc.timer("DiffusionModel: instantiate ema"): + config.ema.model = self.model + self.model_ema = lazy_instantiate(config.ema) + config.ema.model = None + else: + self.model_ema = None + + @property + def net(self): + return self.model.net + + @property + def conditioner(self): + return self.model.conditioner + + def on_before_zero_grad( + self, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler.LRScheduler, iteration: int + ) -> None: + """ + update the model_ema + """ + if self.config.ema.enabled: + self.model_ema.update_average(self.model, iteration) + + def on_train_start(self, memory_format: torch.memory_format = torch.preserve_format) -> None: + if self.config.ema.enabled: + self.model_ema.to(dtype=torch.float32) + if hasattr(self.vae, "reset_dtype"): + self.vae.reset_dtype() + if self.intensity_vae is not None and hasattr( + self.intensity_vae, "reset_dtype" + ): + self.intensity_vae.reset_dtype() + self.model = self.model.to(memory_format=memory_format, **self.tensor_kwargs) + + if hasattr(self.config, "use_torch_compile") and self.config.use_torch_compile: # compatible with old config + if torch.__version__ < "2.3": + log.warning( + "torch.compile in Pytorch version older than 2.3 doesn't work well with activation checkpointing.\n" + "It's very likely there will be no significant speedup from torch.compile.\n" + "Please use at least 24.04 Pytorch container." + ) + # Increasing cache size. It's required because of the model size and dynamic input shapes resulting in + # multiple different triton kernels. For 28 TransformerBlocks, the cache limit of 256 should be enough for + # up to 9 different input shapes, as 28*9 < 256. If you have more Blocks or input shapes, and you observe + # graph breaks at each Block (detectable with torch._dynamo.explain) or warnings about + # exceeding cache limit, you may want to increase this size. + # Starting with 24.05 Pytorch container, the default value is 256 anyway. + # You can read more about it in the comments in Pytorch source code under path torch/_dynamo/cache_size.py. + torch._dynamo.config.accumulated_cache_size_limit = 256 + # dynamic=False means that a separate kernel is created for each shape. It incurs higher compilation costs + # at initial iterations, but can result in more specialized and efficient kernels. + # dynamic=True currently throws errors in pytorch 2.3. + self.model.net = torch.compile(self.model.net, dynamic=False, disable=not self.config.use_torch_compile) + + def compute_loss_with_epsilon_and_sigma( + self, + data_batch: dict[str, torch.Tensor], + x0_from_data_batch: torch.Tensor, + x0: torch.Tensor, + condition: CosmosCondition, + epsilon: torch.Tensor, + sigma: torch.Tensor, + ): + """ + Compute loss givee epsilon and sigma + + This method is responsible for computing loss give epsilon and sigma. It involves: + 1. Adding noise to the input data using the SDE process. + 2. Passing the noisy data through the network to generate predictions. + 3. Computing the loss based on the difference between the predictions and the original data, \ + considering any configured loss weighting. + + Args: + data_batch (dict): raw data batch draw from the training data loader. + x0_from_data_batch: raw image/video + x0: image/video latent + condition: text condition + epsilon: noise + sigma: noise level + + Returns: + tuple: A tuple containing four elements: + - dict: additional data that used to debug / logging / callbacks + - Tensor 1: kendall loss, + - Tensor 2: MSE loss, + - Tensor 3: EDM loss + + Raises: + AssertionError: If the class is conditional, \ + but no number of classes is specified in the network configuration. + + Notes: + - The method handles different types of conditioning + - The method also supports Kendall's loss + """ + # Get the mean and stand deviation of the marginal probability distribution. + mean, std = self.sde.marginal_prob(x0, sigma) + # Generate noisy observations + xt = mean + batch_mul(std, epsilon) # corrupted data + # make prediction + model_pred = self.denoise(xt, sigma, condition) + # loss weights for different noise levels + weights_per_sigma = self.get_per_sigma_loss_weights(sigma=sigma) + # extra weight for each sample, for example, aesthetic weight, camera weight + weights_per_sample = self.get_per_sample_weight(data_batch, x0_from_data_batch.shape[0]) + # extra loss mask for each sample, for example, human faces, hands + loss_mask_per_sample = self.get_per_sample_loss_mask(data_batch, x0_from_data_batch.shape, x0.shape) + pred_mse = (x0 - model_pred.x0) ** 2 * loss_mask_per_sample + edm_loss = batch_mul(pred_mse, weights_per_sigma * weights_per_sample) + if self.config.loss_add_logvar: + kendall_loss = batch_mul(edm_loss, torch.exp(-model_pred.logvar).view(-1)).flatten( + start_dim=1 + ) + model_pred.logvar.view(-1, 1) + else: + kendall_loss = edm_loss.flatten(start_dim=1) + output_batch = { + "x0": x0, + "xt": xt, + "sigma": sigma, + "weights_per_sigma": weights_per_sigma, + "weights_per_sample": weights_per_sample, + "loss_mask_per_sample": loss_mask_per_sample, + "condition": condition, + "model_pred": model_pred, + "mse_loss": pred_mse.mean(), + "edm_loss": edm_loss.mean(), + } + return output_batch, kendall_loss, pred_mse, edm_loss + + def training_step( + self, data_batch: dict[str, torch.Tensor], iteration: int + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + """ + Performs a single training step for the diffusion model. + + This method is responsible for executing one iteration of the model's training. It involves: + 1. Adding noise to the input data using the SDE process. + 2. Passing the noisy data through the network to generate predictions. + 3. Computing the loss based on the difference between the predictions and the original data, \ + considering any configured loss weighting. + + Args: + data_batch (dict): raw data batch draw from the training data loader. + iteration (int): Current iteration number. + + Returns: + tuple: A tuple containing two elements: + - dict: additional data that used to debug / logging / callbacks + - Tensor: The computed loss for the training step as a PyTorch Tensor. + + Raises: + AssertionError: If the class is conditional, \ + but no number of classes is specified in the network configuration. + + Notes: + - The method handles different types of conditioning + - The method also supports Kendall's loss + """ + # Get the input data to noise and denoise~(image, video) and the corresponding conditioner. + x0_from_data_batch, x0, condition = self.get_data_and_condition(data_batch) + + # Sample pertubation noise levels and N(0, 1) noises + sigma, epsilon = self.draw_training_sigma_and_epsilon(x0.size(), condition) + + output_batch, kendall_loss, pred_mse, edm_loss = self.compute_loss_with_epsilon_and_sigma( + data_batch, x0_from_data_batch, x0, condition, epsilon, sigma + ) + + if self.loss_reduce == "mean": + kendall_loss = kendall_loss.mean() * self.loss_scale + elif self.loss_reduce == "sum": + kendall_loss = kendall_loss.sum(dim=1).mean() * self.loss_scale + else: + raise ValueError(f"Invalid loss_reduce: {self.loss_reduce}") + + return output_batch, kendall_loss + + def denoise(self, xt: torch.Tensor, sigma: torch.Tensor, condition: CosmosCondition) -> DenoisePrediction: + """ + Performs denoising on the input noise data, noise level, and condition + + Args: + xt (torch.Tensor): The input noise data. + sigma (torch.Tensor): The noise level. + condition (CosmosCondition): conditional information, generated from self.conditioner + + Returns: + DenoisePrediction: The denoised prediction, it includes clean data predicton (x0), \ + noise prediction (eps_pred) and optional confidence (logvar). + """ + + if getattr(self.config, "use_dummy_temporal_dim", False): + # When using video DiT model for image, we need to use a dummy temporal dimension. + xt = xt.unsqueeze(2) + + xt = xt.to(**self.tensor_kwargs) + sigma = sigma.to(**self.tensor_kwargs) + # get precondition for the network + c_skip, c_out, c_in, c_noise = self.scaling(sigma=sigma) + + # forward pass through the network + net_output = self.net( + x=batch_mul(c_in, xt), # Eq. 7 of https://arxiv.org/pdf/2206.00364.pdf + timesteps=c_noise, # Eq. 7 of https://arxiv.org/pdf/2206.00364.pdf + **condition.to_dict(), + ) + + logvar = self.model.logvar(c_noise) + x0_pred = batch_mul(c_skip, xt) + batch_mul(c_out, net_output) + + # get noise prediction based on sde + eps_pred = batch_mul(xt - x0_pred, 1.0 / sigma) + + if getattr(self.config, "use_dummy_temporal_dim", False): + x0_pred = x0_pred.squeeze(2) + eps_pred = eps_pred.squeeze(2) + + return DenoisePrediction(x0_pred, eps_pred, logvar) + + @torch.no_grad() + def encode(self, state: torch.Tensor) -> torch.Tensor: + assert state.shape[2] == 1, "Lidar should have 1 frame" + return self.vae.encode(state.squeeze(2)).unsqueeze(2) * self.sigma_data + + @torch.no_grad() + def decode(self, latent: torch.Tensor) -> torch.Tensor: + assert latent.shape[2] == 1, "Lidar should have 1 frame" + return self.vae.decode(latent.squeeze(2) / self.sigma_data).unsqueeze(2) + + def draw_training_sigma_and_epsilon(self, x0_size: int, condition: Any) -> torch.Tensor: + del condition + batch_size = x0_size[0] + epsilon = torch.randn(x0_size, **self.tensor_kwargs) + return self.sde.sample_t(batch_size).to(**self.tensor_kwargs), epsilon + + def get_data_and_condition(self, data_batch: dict[str, torch.Tensor]) -> Tuple[torch.Tensor, CosmosCondition]: + """ + processing data batch draw from data loader and return data and condition that used for denoising task + + Returns: + raw_state (tensor): the image / video data that feed to vae + latent_state (tensor): nosie-free state, the vae latent state + condition (CosmosCondition): condition information for conditional generation. Generated from conditioner + """ + raw_state = data_batch[self.input_data_key] + latent_state = self.encode(raw_state) + condition = self.conditioner(data_batch) + return raw_state, latent_state, condition + + def get_per_sample_weight(self, data_batch: dict[str, torch.Tensor], batch_size: int): + r""" + extra weight for each sample, for example, aesthetic weight + Args: + data_batch: raw data batch draw from the training data loader. + batch_size: int, the batch size of the input data + """ + aesthetic_cfg = getattr(self.config, "aesthetic_finetuning", None) + if (aesthetic_cfg is not None) and getattr(aesthetic_cfg, "enabled", False): + sample_weight = data_batch["aesthetic_weight"] + else: + sample_weight = torch.ones(batch_size, **self.tensor_kwargs) + + camera_cfg = getattr(self.config, "camera_sample_weight", None) + if (camera_cfg is not None) and getattr(camera_cfg, "enabled", False): + sample_weight *= 1 + (data_batch["camera_attributes"][:, 1:].sum(dim=1) != 0) * (camera_cfg.weight - 1) + return sample_weight + + def get_per_sample_loss_mask(self, data_batch, raw_x_shape, latent_x_shape): + """ + extra loss mask for each sample, for example, human faces, hands. + + Args: + data_batch (dict): raw data batch draw from the training data loader. + raw_x_shape (tuple): shape of the input data. We need the raw_x_shape for necessary resize operation. + latent_x_shape (tuple): shape of the latent data + """ + if self.config.loss_mask_enabled: + raw_x_shape = [raw_x_shape[0], 1, *raw_x_shape[2:]] + weights = create_per_sample_loss_mask( + self.loss_masking, data_batch, raw_x_shape, torch.get_default_dtype(), "cuda" + ) + return F.interpolate(weights, size=latent_x_shape[2:], mode="bilinear") + + return 1.0 + + def get_per_sigma_loss_weights(self, sigma: torch.Tensor): + """ + Args: + sigma (tensor): noise level + + Returns: + loss weights per sigma noise level + """ + return (sigma**2 + self.sigma_data**2) / (sigma * self.sigma_data) ** 2 + + def generate_samples(self, batch_size: int, condition: CosmosCondition) -> torch.Tensor: + """ + Generate samples with given condition. It is WITHOUT classifier-free-guidance. + + Args: + batch_size (int): + condition (CosmosCondition): condition information generated from self.conditioner + """ + x_sigma_max = torch.randn(batch_size, *self.state_shape, **self.tensor_kwargs) * self.sde.sigma_max + + def x0_fn(x, t): + return self.denoise(x, t, condition).x0 # ODE function + + return self.sampler(x0_fn, x_sigma_max, sigma_max=self.sde.sigma_max) + + def generate_cfg_samples( + self, batch_size: int, condition: CosmosCondition, uncondition: CosmosCondition, guidance=1.5 + ) -> torch.Tensor: + """ + Generate samples with with classifier-free-guidance. + + Args: + batch_size (int): + condition (CosmosCondition): condition information generated from self.conditioner + uncondition (CosmosCondition): uncondition information, possibily generated from self.conditioner + """ + x_sigma_max = torch.randn(batch_size, *self.state_shape, **self.tensor_kwargs) * self.sde.sigma_max + + def x0_fn(x, t): + cond_x0 = self.denoise(x, t, condition).x0 + uncond_x0 = self.denoise(x, t, uncondition).x0 + return cond_x0 + guidance * (cond_x0 - uncond_x0) + + return self.sampler(x0_fn, x_sigma_max, sigma_max=self.sde.sigma_max) + + def get_x0_fn_from_batch( + self, + data_batch: Dict, + guidance: float = 1.5, + is_negative_prompt: bool = False, + ) -> Callable: + """ + Generates a callable function `x0_fn` based on the provided data batch and guidance factor. + + This function first processes the input data batch through a conditioning workflow (`conditioner`) to obtain conditioned and unconditioned states. It then defines a nested function `x0_fn` which applies a denoising operation on an input `noise_x` at a given noise level `sigma` using both the conditioned and unconditioned states. + + Args: + - data_batch (Dict): A batch of data used for conditioning. The format and content of this dictionary should align with the expectations of the `self.conditioner` + - guidance (float, optional): A scalar value that modulates the influence of the conditioned state relative to the unconditioned state in the output. Defaults to 1.5. + - is_negative_prompt (bool): use negative prompt t5 in uncondition if true + + Returns: + - Callable: A function `x0_fn(noise_x, sigma)` that takes two arguments, `noise_x` and `sigma`, and return x0 predictoin + + The returned function is suitable for use in scenarios where a denoised state is required based on both conditioned and unconditioned inputs, with an adjustable level of guidance influence. + """ + if is_negative_prompt: + condition, uncondition = self.conditioner.get_condition_with_negative_prompt(data_batch) + else: + condition, uncondition = self.conditioner.get_condition_uncondition(data_batch) + + def x0_fn(noise_x: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor: + cond_x0 = self.denoise(noise_x, sigma, condition).x0 + uncond_x0 = self.denoise(noise_x, sigma, uncondition).x0 + return cond_x0 + guidance * (cond_x0 - uncond_x0) + + return x0_fn + + def generate_samples_from_batch( + self, + data_batch: Dict, + guidance: float = 1.5, + seed: int = 1, + state_shape: Optional[Tuple] = None, + n_sample: Optional[int] = None, + is_negative_prompt: bool = False, + num_steps: int = 35, + solver_option: COMMON_SOLVER_OPTIONS = "2ab", + ) -> torch.Tensor: + """ + Args: + data_batch (dict): raw data batch draw from the training data loader. + iteration (int): Current iteration number. + guidance (float): guidance weights + seed (int): random seed + state_shape (tuple): shape of the state, default to self.state_shape if not provided + n_sample (int): number of samples to generate + is_negative_prompt (bool): use negative prompt t5 in uncondition if true + num_steps (int): number of steps for the diffusion process + solver_option (str): differential equation solver option, default to "2ab"~(mulitstep solver) + """ + x0_fn = self.get_x0_fn_from_batch(data_batch, guidance, is_negative_prompt=is_negative_prompt) + batch_size = n_sample or data_batch[self.input_data_key].shape[0] + state_shape = state_shape or self.state_shape + x_sigma_max = ( + misc.arch_invariant_rand( + (batch_size,) + tuple(state_shape), + torch.float32, + self.tensor_kwargs["device"], + seed, + ) + * self.sde.sigma_max + ) + return self.sampler( + x0_fn, x_sigma_max, sigma_max=self.sde.sigma_max, num_steps=num_steps, solver_option=solver_option + ) + + @torch.no_grad() + def validation_step( + self, data: dict[str, torch.Tensor], iteration: int + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + """ + Current code does nothing. + """ + return {}, torch.tensor(0).to(**self.tensor_kwargs) + + @torch.no_grad() + def forward(self, xt, t, condition: CosmosCondition): + """ + Performs denoising on the input noise data, noise level, and condition + + Args: + xt (torch.Tensor): The input noise data. + sigma (torch.Tensor): The noise level. + condition (CosmosCondition): conditional information, generated from self.conditioner + + Returns: + DenoisePrediction: The denoised prediction, it includes clean data predicton (x0), \ + noise prediction (eps_pred) and optional confidence (logvar). + """ + return self.denoise(xt, t, condition) + + def init_optimizer_scheduler( + self, optimizer_config: LazyDict, scheduler_config: LazyDict + ) -> tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler]: + """Creates the optimizer and scheduler for the model. + + Args: + config_model (ModelConfig): The config object for the model. + + Returns: + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + """ + optimizer = lazy_instantiate(optimizer_config, model=self.model) + scheduler = get_base_scheduler(optimizer, self, scheduler_config) + return optimizer, scheduler + + def state_dict(self) -> Dict[str, Any]: + """ + Returns the current state of the model as a dictionary. + + Returns: + Dict: The current state of the model as a dictionary. + """ + return { + "model": self.model.state_dict(), + "ema": self.model_ema.state_dict() if self.config.ema.enabled else None, + } + + def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False): + """ + Loads a state dictionary into the model and optionally its EMA counterpart. + Different from torch strict=False mode, the method will not raise error for unmatched state shape while raise warning. + + Parameters: + state_dict (Mapping[str, Any]): A dictionary containing separate state dictionaries for the model and + potentially for an EMA version of the model under the keys 'model' and 'ema', respectively. + strict (bool, optional): If True, the method will enforce that the keys in the state dict match exactly + those in the model and EMA model (if applicable). Defaults to True. + assign (bool, optional): If True and in strict mode, will assign the state dictionary directly rather than + matching keys one-by-one. This is typically used when loading parts of state dicts + or using customized loading procedures. Defaults to False. + """ + if strict: + # the converted tpsp checkpoint has "ema" and it is None + if self.config.ema.enabled and state_dict["ema"] is not None: + ema_results: _IncompatibleKeys = self.model_ema.load_state_dict( + state_dict["ema"], strict=strict, assign=assign + ) + reg_results: _IncompatibleKeys = self.model.load_state_dict( + state_dict["model"], strict=strict, assign=assign + ) + if self.config.ema.enabled and state_dict["ema"] is not None: + return _IncompatibleKeys( + ema_results.missing_keys + reg_results.missing_keys, + ema_results.unexpected_keys + reg_results.unexpected_keys, + ) + return reg_results + else: + from diffusion.training.utils.checkpointer import non_strict_load_model + + log.critical("load model in non-strict mode") + if "model" in state_dict: + log.critical(non_strict_load_model(self.model, state_dict["model"]), rank0_only=False) + else: + log.critical(non_strict_load_model(self.model, state_dict), rank0_only=False) + if self.config.ema.enabled and "ema" in state_dict and state_dict["ema"] is not None: + log.critical("load ema model in non-strict mode") + log.critical(non_strict_load_model(self.model_ema, state_dict["ema"]), rank0_only=False) + + def get_ckpt_postfix(self) -> Tuple[str, int, int]: + """Get the checkpoint file postfix. + + Args: + iteration (int): The current iteration number. + + Returns: + postfix (str): The postfix of the checkpoint file. + rank_to_save ema (int), we will not save each ema model in each rank, \ + ema model with same rate will be saved once + total_ema_num (int) + """ + total_ema_num = min(self.config.ema.num, distributed.get_world_size()) + rank = distributed.get_rank() + if rank == 0: + return "", 0, total_ema_num + if self.config.ema.enabled: + if rank < self.config.ema.num: + return f"_RANK{rank}", rank, total_ema_num + return "", 0, total_ema_num # use rank 0 to save the checkpoint + + @contextmanager + def ema_scope(self, context=None, is_cpu=False): + if self.config.ema.enabled: + self.model_ema.cache(self.model.parameters(), is_cpu=is_cpu) + self.model_ema.copy_to(self.model) + if context is not None: + log.info(f"{context}: Switched to EMA weights") + try: + yield None + finally: + if self.config.ema.enabled: + self.model_ema.restore(self.model.parameters()) + if context is not None: + log.info(f"{context}: Restored training weights") + + +T = TypeVar("T", bound=DiffusionModel) + + +def diffusion_fsdp_class_decorator(base_class: Type[T]) -> Type[T]: + """ + Decorator for the FSDP class for the diffusion model, which handles the FSDP specific logic for the diffusion model. + """ + + class FSDPClass(base_class): + """ + Handle FSDP specific logic for the diffusion model. Including: + - FSDP model initialization + - FSDP model / optimizer save and loading + - Different from the original DiffusionModel, the impl of multi-rank EMA is a bit hacky. \ + We need to make sure sharded model weights for EMA and regular model are the same. + """ + + def __init__(self, config, fsdp_checkpointer: Any): + self.fsdp_checkpointer = fsdp_checkpointer + super().__init__(config) + + def set_up_model(self): + config = self.config + + # 1. build FSDP sharding strategy and device_mesh + strategy = { + "full": ShardingStrategy.FULL_SHARD, + "hybrid": ShardingStrategy.HYBRID_SHARD, + }[config.fsdp.sharding_strategy] + log.critical(f"Using {strategy} sharding strategy for FSDP") + + if config.fsdp.sharding_strategy == "hybrid": + sharding_group_size = getattr(config.fsdp, "sharding_group_size", 8) + device_mesh = hsdp_device_mesh( + sharding_group_size=sharding_group_size, + ) + shard_group = device_mesh.get_group(mesh_dim="shard") + replicate_group = device_mesh.get_group(mesh_dim="replicate") + fsdp_process_group = (shard_group, replicate_group) + else: + device_mesh = hsdp_device_mesh( + sharding_group_size=distributed.get_world_size(), + ) + shard_group = device_mesh.get_group(mesh_dim="shard") + fsdp_process_group = shard_group + + # We piggyback the `device_mesh` to megatron-core's `parallel_state` for global access. + # This is not megatron-core's original API. + parallel_state.fsdp_device_mesh = device_mesh + + def get_wrap_policy(_model): + if not hasattr(_model.net, "fsdp_wrap_block_cls"): + raise ValueError( + "Networks does not have fsdp_wrap_block_cls attribute, please check the net definition" + ) + fsdp_blocks_cls = _model.net.fsdp_wrap_block_cls + fsdp_blocks_cls = ( + list(fsdp_blocks_cls) if isinstance(fsdp_blocks_cls, (list, tuple, set)) else [fsdp_blocks_cls] + ) + log.critical(f"Using FSDP blocks {fsdp_blocks_cls}") + + log.critical(f"Using wrap policy {config.fsdp.policy}") + if config.fsdp.policy == "size": + min_num_params = getattr(config.fsdp, "min_num_params", 100) + log.critical(f"Using {min_num_params} as the minimum number of parameters for auto-wrap policy") + wrap_policy = functools.partial(size_based_auto_wrap_policy, min_num_params=min_num_params) + else: + from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy + + wrap_policy = functools.partial( + transformer_auto_wrap_policy, + transformer_layer_cls=set(fsdp_blocks_cls), + ) + return wrap_policy + + # 2. build naive pytorch model and load weights if exists + replica_idx, shard_idx = device_mesh.get_coordinate() + # 2.1 handle ema case first, since float32 is more expensive + if config.ema.enabled: + with misc.timer("Creating PyTorch model and loading weights for ema"): + model_ema = self.build_model().float() + model_ema.cuda().eval().requires_grad_(False) + load_error = None + if distributed.get_rank() == 0: + # only load model in rank0 to reduce network traffic + try: + self.fsdp_checkpointer.load_model_during_init( + model_ema, is_ema=True + ) + except Exception as exc: # noqa: BLE001 + load_error = repr(exc) + load_errors = [load_error] + torch.distributed.broadcast_object_list( + load_errors, src=0 + ) + if load_errors[0] is not None: + raise RuntimeError( + "EMA model initialization failed on rank 0: " + f"{load_errors[0]}" + ) + # sync ema model weights from rank0 + with misc.timer("Sync model states for EMA model"): + #! this is IMPORTANT, see the following comment about regular model for details + #! we broadcast the ema model first, since it is fp32 and costs more memory + distributed.sync_model_states(model_ema, device_mesh.get_group(mesh_dim="shard")) + torch.cuda.empty_cache() + distributed.sync_model_states(model_ema, device_mesh.get_group(mesh_dim="replicate")) + torch.cuda.empty_cache() + # for ema model with dfiferent rate, we download the model when necessary + replica_load_error = None + if shard_idx == 0 and replica_idx > 0 and replica_idx < config.ema.num: + print("loading ema model in rank", replica_idx) + try: + self.fsdp_checkpointer.load_model_during_init( + model_ema, + is_ema=True, + ema_id=replica_idx, + ) + print( + "finish loading ema model in rank", + replica_idx, + ) + except Exception as exc: # noqa: BLE001 + replica_load_error = repr(exc) + replica_errors = [None] * distributed.get_world_size() + torch.distributed.all_gather_object( + replica_errors, replica_load_error + ) + replica_failures = [ + item for item in replica_errors if item is not None + ] + if replica_failures: + raise RuntimeError( + "replica EMA initialization failed: " + f"{replica_failures}" + ) + # 2.1.2 create FSDP model for ema model + with misc.timer("Creating FSDP model for EMA model"): + self.model_ema = FSDP( + model_ema, + sync_module_states=True, # it can reduce network traffic by only loading model in rank0 and sync + process_group=device_mesh.get_group(mesh_dim=1), + sharding_strategy=ShardingStrategy.FULL_SHARD, + auto_wrap_policy=get_wrap_policy(model_ema), + device_id=torch.cuda.current_device(), + limit_all_gathers=True, + use_orig_params=bool( + getattr(config.fsdp, "use_orig_params", False) + ), + ) + + # extra ema model upate logic to the model + self.model_ema_worker = FastEmaModelUpdater() + s = 0.1 + replica_idx, shard_idx = device_mesh.get_coordinate() + divider = 2**replica_idx if replica_idx < config.ema.num else 1 + if replica_idx < config.ema.num: + if shard_idx == 0: + print(f"EMA: rank {replica_idx}, rate {config.ema.rate / divider}") + s = config.ema.rate / divider + self.ema_exp_coefficient = np.roots([1, 7, 16 - s**-2, 12 - s**-2]).real.max() + + torch.cuda.empty_cache() + + # 2.2 handle regular model + with misc.timer("Creating PyTorch model and loading weights for regular model"): + model = self.build_model().cuda().to(**self.tensor_kwargs) + + load_error = None + if distributed.get_rank() == 0: + # only load model in rank0 to reduce network traffic and sync later + try: + self.fsdp_checkpointer.load_model_during_init( + model, is_ema=False + ) + except Exception as exc: # noqa: BLE001 + load_error = repr(exc) + load_errors = [load_error] + torch.distributed.broadcast_object_list( + load_errors, src=0 + ) + if load_errors[0] is not None: + raise RuntimeError( + "regular model initialization failed on rank 0: " + f"{load_errors[0]}" + ) + + #! overwrite the forward method so that it will invoke the FSDP-specific pre- and post-forward sharding logic + model.forward = super().training_step + #! this is IMPORTANT, though following two lines are identical to sync_module_states=True in FSDP + #! we do it twice so that following line can warm up and avoid OOM in aws 128+ nodes settings + #! qsh hypothesize that it is due to overhead of initialization of nccl network communication; + #! without it, peak mem : reg_model + ema_model + FSDP overhead + nccl communication initialization overhead + #! with it, peak men: reg_model + ema_model + FSDP overhead + #! it is tricky, but it works! + with misc.timer("Sync model states for regular model"): + distributed.sync_model_states(model, device_mesh.get_group(mesh_dim="shard")) + torch.cuda.empty_cache() + distributed.sync_model_states(model, device_mesh.get_group(mesh_dim="replicate")) + torch.cuda.empty_cache() + + with misc.timer("Creating FSDP model"): + self.model = FSDP( + model.to(**self.tensor_kwargs), + sync_module_states=True, # it can reduce network traffic by only loading model in rank0 and sync + sharding_strategy=strategy, + auto_wrap_policy=get_wrap_policy(model), + process_group=fsdp_process_group, + limit_all_gathers=True, + use_orig_params=bool( + getattr(config.fsdp, "use_orig_params", False) + ), + ) + + if self.config.fsdp.checkpoint: + fsdp_blocks_cls = model.net.fsdp_wrap_block_cls + fsdp_blocks_cls = ( + list(fsdp_blocks_cls) + if isinstance(fsdp_blocks_cls, (list, tuple, set)) + else [fsdp_blocks_cls] + ) + log.critical(f"Applying FSDP checkpointing with FSDP blocks: {fsdp_blocks_cls}") + apply_fsdp_checkpointing(self.model, list_block_cls=fsdp_blocks_cls) + + torch.cuda.empty_cache() + + def on_before_zero_grad( + self, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler.LRScheduler, iteration: int + ) -> None: + del scheduler, optimizer + + if self.config.ema.enabled: + # calculate beta for EMA update + if iteration == 0: + beta = 0.0 + else: + i = iteration + 1 + beta = (1 - 1 / i) ** (self.ema_exp_coefficient + 1) + self.model_ema_worker.update_average(self.model, self.model_ema, beta=beta) + + def training_step( + self, data_batch: Dict[str, torch.Tensor], iteration: int + ) -> Tuple[Dict[str, torch.Tensor] | torch.Tensor]: + # ! Important!!! + # ! make sure the training step is the same as the forward method~(training_step in the super class) + # ! this is necessary to trigger the FSDP-specific pre- and post-forward sharding logic + return self.model(data_batch, iteration) + + def state_dict(self) -> Dict: + raise NotImplementedError( + "FSDPDiffModle does not support state_dict, use state_dict_model and FSDPCheckpointer" + ) + + @misc.timer("FSDP state_dict_model") + def state_dict_model(self) -> Dict: + with FSDP.summon_full_params(self.model): + pass + with FSDP.state_dict_type( + self.model, StateDictType.FULL_STATE_DICT, FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + ): + model_state = self.model.state_dict() + if self.config.ema.enabled: + with FSDP.summon_full_params(self.model_ema): + pass + with FSDP.state_dict_type( + self.model_ema, + StateDictType.FULL_STATE_DICT, + FullStateDictConfig(offload_to_cpu=True, rank0_only=True), + ): + ema_model_state = self.model_ema.state_dict() + else: + ema_model_state = None + return { + "model": model_state, + "ema": ema_model_state, + } + + def load_state_dict(self, state_dict: Dict, strict: bool = True, assign: bool = False) -> None: + raise NotImplementedError("FSDPDiffModle does not support load_state_dict, using FSDPCheckpointer") + + def init_optimizer_scheduler( + self, optimizer_config: LazyDict, scheduler_config: LazyDict + ) -> tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler]: + optimizer, scheduler = super().init_optimizer_scheduler(optimizer_config, scheduler_config) + self.fsdp_checkpointer.load_optim_scheduler_during_init( + self.model, + optimizer, + scheduler, + ) + return optimizer, scheduler + + @contextmanager + def ema_scope(self, context=None, is_cpu=False): + if self.config.ema.enabled: + self.model_ema_worker.cache(self.model.parameters(), is_cpu=is_cpu) + self.model_ema_worker.copy_to(src_model=self.model_ema, tgt_model=self.model) + if context is not None: + log.info(f"{context}: Switched to EMA weights") + try: + yield None + finally: + if self.config.ema.enabled: + self.model_ema_worker.restore(self.model.parameters()) + if context is not None: + log.info(f"{context}: Restored training weights") + + def get_ckpt_postfix(self) -> Tuple[str, int]: + """Get the checkpoint file postfix. check FSDPCheckpointer for more details + + Args: + iteration (int): The current iteration number. + + Returns: + postfix (str): The postfix of the checkpoint file. + replicate_idx, shard_idx (int), current gpu replicate_idx, shard_idx in FSDP \ + we will not save each ema model in each GPU, \ + ema model with same rate will be saved once + total_ema_num (int) + """ + mesh_shape = parallel_state.fsdp_device_mesh.shape + total_ema_num = min(self.config.ema.num, mesh_shape[0]) + replicate_idx, shard_idx = parallel_state.fsdp_device_mesh.get_coordinate() + if replicate_idx == 0: + return "", 0, shard_idx, total_ema_num + if self.config.ema.enabled: + if replicate_idx < self.config.ema.num: + return f"_RANK{replicate_idx}", replicate_idx, shard_idx, total_ema_num + return "", replicate_idx, shard_idx, total_ema_num + + return FSDPClass + + +@diffusion_fsdp_class_decorator +class FSDPDiffusionModel(DiffusionModel): + pass diff --git a/diffusion/training/module/pretrained_vae_base.py b/diffusion/training/module/pretrained_vae_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5aca9e7b39a679de1eba5bae082aabceb22e40fb --- /dev/null +++ b/diffusion/training/module/pretrained_vae_base.py @@ -0,0 +1,844 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from abc import ABC, abstractmethod + +import torch +import torch.nn.functional as F + +from utils.distributed import rank0_first +from utils.misc import load_from_s3_with_cache + + +class BaseVAE(torch.nn.Module, ABC): + """ + Abstract base class for a Variational Autoencoder (VAE). + + All subclasses should implement the methods to define the behavior for encoding + and decoding, along with specifying the latent channel size. + """ + + def __init__(self, channel: int = 3, name: str = "vae"): + super().__init__() + self.channel = channel + self.name = name + + @property + def latent_ch(self) -> int: + """ + Returns the number of latent channels in the VAE. + """ + return self.channel + + @abstractmethod + def encode(self, state: torch.Tensor) -> torch.Tensor: + """ + Encodes the input tensor into a latent representation. + + Args: + - state (torch.Tensor): The input tensor to encode. + + Returns: + - torch.Tensor: The encoded latent tensor. + """ + pass + + @abstractmethod + def decode(self, latent: torch.Tensor) -> torch.Tensor: + """ + Decodes the latent representation back to the original space. + + Args: + - latent (torch.Tensor): The latent tensor to decode. + + Returns: + - torch.Tensor: The decoded tensor. + """ + pass + + @property + def spatial_compression_factor(self) -> int: + """ + Returns the spatial reduction factor for the VAE. + """ + raise NotImplementedError("The spatial_compression_factor property must be implemented in the derived class.") + + +class BasePretrainedImageVAE(BaseVAE): + """ + A base class for pretrained Variational Autoencoder (VAE) that loads mean and standard deviation values + from a remote store, handles data type conversions, and normalization + using provided mean and standard deviation values for latent space representation. + Derived classes should load pre-trained encoder and decoder components from a remote store + + Attributes: + latent_mean (Tensor): The mean used for normalizing the latent representation. + latent_std (Tensor): The standard deviation used for normalizing the latent representation. + dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled. + + Args: + mean_std_fp (str): File path to the pickle file containing mean and std of the latent space. + latent_ch (int, optional): Number of latent channels (default is 16). + is_image (bool, optional): Flag to indicate whether the output is an image (default is True). + is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True). + """ + + def __init__( + self, + name: str, + mean_std_fp: str, + latent_ch: int = 16, + is_image: bool = True, + is_bf16: bool = True, + ) -> None: + super().__init__(latent_ch, name) + dtype = torch.bfloat16 if is_bf16 else torch.float32 + self.dtype = dtype + self.is_image = is_image + self.mean_std_fp = mean_std_fp + self.name = name + + self.backend_args = None + + self.register_mean_std(mean_std_fp) + + def register_mean_std(self, mean_std_fp: str) -> None: + latent_mean, latent_std = torch.load(mean_std_fp, map_location="cuda", weights_only=True) + target_shape = [1, self.latent_ch, 1, 1] if self.is_image else [1, self.latent_ch, 1, 1, 1] + self.register_buffer( + "latent_mean", + latent_mean.to(self.dtype).reshape(*target_shape), + persistent=False, + ) + self.register_buffer( + "latent_std", + latent_std.to(self.dtype).reshape(*target_shape), + persistent=False, + ) + + @torch.no_grad() + def encode(self, state: torch.Tensor) -> torch.Tensor: + """ + Encode the input state to latent space; also handle the dtype conversion, mean and std scaling + """ + in_dtype = state.dtype + latent_mean = self.latent_mean.to(in_dtype) + latent_std = self.latent_std.to(in_dtype) + encoded_state = self.encoder(state.to(self.dtype)) + if isinstance(encoded_state, torch.Tensor): + pass + elif isinstance(encoded_state, tuple): + assert isinstance(encoded_state[0], torch.Tensor) + encoded_state = encoded_state[0] + else: + raise ValueError("Invalid type of encoded state") + return (encoded_state.to(in_dtype) - latent_mean) / latent_std + + @torch.no_grad() + def decode(self, latent: torch.Tensor) -> torch.Tensor: + """ + Decode the input latent to state; also handle the dtype conversion, mean and std scaling + """ + in_dtype = latent.dtype + latent = latent * self.latent_std.to(in_dtype) + self.latent_mean.to(in_dtype) + return self.decoder(latent.to(self.dtype)).to(in_dtype) + + def reset_dtype(self, *args, **kwargs): + """ + Resets the data type of the encoder and decoder to the model's default data type. + + Args: + *args, **kwargs: Unused, present to allow flexibility in method calls. + """ + del args, kwargs + self.decoder.to(self.dtype) + self.encoder.to(self.dtype) + + +class JITVAE(BasePretrainedImageVAE): + """ + A JIT compiled Variational Autoencoder (VAE) that loads pre-trained encoder + and decoder components from a remote store, handles data type conversions, and normalization + using provided mean and standard deviation values for latent space representation. + + Attributes: + encoder (Module): The JIT compiled encoder loaded from storage. + decoder (Module): The JIT compiled decoder loaded from storage. + latent_mean (Tensor): The mean used for normalizing the latent representation. + latent_std (Tensor): The standard deviation used for normalizing the latent representation. + dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled. + + Args: + enc_fp (str): File path to the encoder's JIT file on the remote store. + dec_fp (str): File path to the decoder's JIT file on the remote store. + name (str): Name of the model, used for differentiating cache file paths. + mean_std_fp (str): File path to the pickle file containing mean and std of the latent space. + latent_ch (int, optional): Number of latent channels (default is 16). + is_image (bool, optional): Flag to indicate whether the output is an image (default is True). + is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True). + """ + + def __init__( + self, + enc_fp: str, + dec_fp: str, + name: str, + mean_std_fp: str, + latent_ch: int = 16, + is_image: bool = True, + is_bf16: bool = True, + ): + super().__init__(name, mean_std_fp, latent_ch, is_image, is_bf16) + self.load_encoder(enc_fp) + self.load_decoder(dec_fp) + + def load_encoder(self, enc_fp: str) -> None: + """ + Load the encoder from the remote store. + + Args: + - enc_fp (str): File path to the encoder's JIT file on the remote store. + """ + self.encoder = torch.jit.load(enc_fp, map_location="cuda") + self.encoder.eval() + for param in self.encoder.parameters(): + param.requires_grad = False + self.encoder.to(self.dtype) + + def load_decoder(self, dec_fp: str) -> None: + """ + Load the decoder from the remote store. + + Args: + - dec_fp (str): File path to the decoder's JIT file on the remote store. + """ + self.decoder = torch.jit.load(dec_fp, map_location="cuda") + self.decoder.eval() + for param in self.decoder.parameters(): + param.requires_grad = False + self.decoder.to(self.dtype) + + +class StateDictVAE(BasePretrainedImageVAE): + """ + A Variational Autoencoder (VAE) that loads pre-trained weights into + provided encoder and decoder components from a remote store, handles data type conversions, + and normalization using provided mean and standard deviation values for latent space representation. + + Attributes: + encoder (Module): The encoder with weights loaded from storage. + decoder (Module): The decoder with weights loaded from storage. + latent_mean (Tensor): The mean used for normalizing the latent representation. + latent_std (Tensor): The standard deviation used for normalizing the latent representation. + dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled. + + Args: + enc_fp (str): File path to the encoder's JIT file on the remote store. + dec_fp (str): File path to the decoder's JIT file on the remote store. + vae (Module): Instance of VAE with not loaded weights + name (str): Name of the model, used for differentiating cache file paths. + mean_std_fp (str): File path to the pickle file containing mean and std of the latent space. + latent_ch (int, optional): Number of latent channels (default is 16). + is_image (bool, optional): Flag to indicate whether the output is an image (default is True). + is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True). + """ + + def __init__( + self, + enc_fp: str, + dec_fp: str, + vae: torch.nn.Module, + name: str, + mean_std_fp: str, + latent_ch: int = 16, + is_image: bool = True, + is_bf16: bool = True, + ): + super().__init__(name, mean_std_fp, latent_ch, is_image, is_bf16) + + self.load_encoder_and_decoder(enc_fp, dec_fp, vae) + + def load_encoder_and_decoder(self, enc_fp: str, dec_fp: str, vae: torch.nn.Module) -> None: + """ + Load the encoder from the remote store. + + Args: + - vae_fp (str): File path to the vae's state dict file on the remote store. + - vae (str): VAE module into which weights will be loaded. + """ + state_dict_enc = load_from_s3_with_cache( + enc_fp, + f"vae/{self.name}_enc.jit", + easy_io_kwargs={"map_location": torch.device(torch.cuda.current_device())}, + backend_args=self.backend_args, + ) + + state_dict_dec = load_from_s3_with_cache( + dec_fp, + f"vae/{self.name}_dec.jit", + easy_io_kwargs={"map_location": torch.device(torch.cuda.current_device())}, + backend_args=self.backend_args, + ) + + jit_weights_state_dict = state_dict_enc.state_dict() | state_dict_dec.state_dict() + jit_weights_state_dict = { + k: v + for k, v in jit_weights_state_dict.items() + # Global variables captured by JIT + if k + not in ( + "encoder.patcher.wavelets", + "encoder.patcher._arange", + "decoder.unpatcher.wavelets", + "decoder.unpatcher._arange", + ) + } + + vae.load_state_dict(jit_weights_state_dict) + vae.eval() + for param in vae.parameters(): + param.requires_grad = False + vae.to(self.dtype) + + self.vae = vae + self.encoder = self.vae.encode + self.decoder = self.vae.decode + + def reset_dtype(self, *args, **kwargs): + """ + Resets the data type of the encoder and decoder to the model's default data type. + + Args: + *args, **kwargs: Unused, present to allow flexibility in method calls. + """ + del args, kwargs + self.vae.to(self.dtype) + + +class ConfigBasedVideoVAE(BaseVAE): + """VAE loaded from a tokenizer experiment config + training checkpoint. + + Works with any tokenizer that exposes `encode(x) -> (sample, (mu, logvar))` + and `decode(z) -> x`, including WanVAE2P1 and TransformerVAE. + + Latent statistics can be supplied either via ``mean_std_fp`` (a saved + ``(mean, std)`` tuple / ``{"mean", "std"}`` dict) or via inline + ``latent_mean`` / ``latent_std`` lists. Inline values take precedence + so callers that don't have a ``latent_stats.pt`` next to their + checkpoint (e.g. the public ``Wan2.1_VAE.pth`` release) can pass the + per-channel statistics directly from a constant. + """ + + def __init__( + self, + experiment_name: str, + checkpoint_path: str, + mean_std_fp: str | None = None, + latent_ch: int = 64, + is_bf16: bool = False, + spatial_compression: int = 8, + latent_mean: list[float] | tuple[float, ...] | None = None, + latent_std: list[float] | tuple[float, ...] | None = None, + apply_validity_mask: bool = False, + intensity_pad_value: float = 0.0, + network_overrides: dict | None = None, + use_ema: bool = False, + per_frame: bool = False, + encoder_is_bf16: bool | None = None, + decoder_is_bf16: bool | None = None, + strict_checkpoint: bool = False, + ): + super().__init__(channel=latent_ch, name=f"config_vae_{experiment_name}") + from diffusion.training.module.vae_utils import ( + build_vae_from_tokenizer_experiment, + ) + + self.is_image = False + self._spatial_compression = spatial_compression + # per_frame: the wrapped net is a 2D (single-frame) tokenizer (cosmos CI, + # LiDM) whose encode/decode take (B, C, H, W). encode/decode fold the clip's + # T axis into the batch, run the net per frame, and reshape the latent back + # to (B, Cz, T, Hz, Wz) so the rest of the video pipeline (5D latent-stat + # buffers, DiT) is unchanged. The first-frame prepend still happens in the + # dataset (is_video_tokenizer=True) -> T frames each encoded independently. + self.per_frame = bool(per_frame) + encoder_is_bf16 = ( + is_bf16 if encoder_is_bf16 is None else encoder_is_bf16 + ) + decoder_is_bf16 = ( + is_bf16 if decoder_is_bf16 is None else decoder_is_bf16 + ) + self.encoder_dtype = ( + torch.bfloat16 if encoder_is_bf16 else torch.float32 + ) + self.decoder_dtype = ( + torch.bfloat16 if decoder_is_bf16 else torch.float32 + ) + # Keep the legacy public dtype tied to decode. Encode paths use the + # explicit encoder dtype below. + self.dtype = self.decoder_dtype + + # ``network_overrides`` are applied AFTER the experiment's own network + # overrides (e.g. ``utonia_align=False`` to skip building the training-only + # VF/PTv3 teacher -- encode/decode is bit-identical and the leftover + # ``utonia.*`` ckpt keys drop harmlessly under the strict=False load below). + self.vae_net = build_vae_from_tokenizer_experiment( + experiment_name, **(network_overrides or {}) + ) + + # Validity-head support: predict_validity VAEs return a per-pixel raydrop + # logit from decode(); when ``apply_validity_mask`` is set we fill the + # predicted-invalid pixels with the depth sentinel so the decoded range + # map carries raydrop directly (matches the trained 2-channel output). + self.predict_validity = bool(getattr(self.vae_net, "predict_validity", False)) + # decoder_validity_head: a SEPARATE additive head taps the decoder recon + # and emits a raydrop logit via decode(z, return_validity=True) (does NOT + # widen the main conv). Mutually exclusive with predict_validity. Handled + # on the same masking path below. + self.decoder_validity_head = bool(getattr(self.vae_net, "decoder_validity_head", False)) + self.apply_validity_mask = bool(apply_validity_mask) + self.invalid_fill = float(getattr(self.vae_net, "mask_input_min_value", -1.0)) + # Fill value for DATA channels missing from the input (e.g. the intensity + # channel when encoding a mono-depth hdmap through a [depth, intensity] + # VAE). Intensity is normalized to [-1, 1]; a flat plane is OOD, so this + # is exposed for A/B tuning. Default 0.0 preserves prior behavior. + self.intensity_pad_value = float(intensity_pad_value) + + # ``is_ltx`` flags whether the wrapped VAE supports LTX-style + # timestep-conditioned decoding (``decode(z, t=...)`` with a + # rectified-flow t threading through AdaLN). Detected from the + # underlying net's ``denoising_t_max`` attr -- the LTX + # TransformerVAELTX sets it to > 0 when AdaLN is built. + # Callers should gate any ``t`` they want to pass to + # ``decode`` on this flag rather than guessing from the model + # class or ``is_image``. + self.is_ltx = bool(getattr(self.vae_net, "denoising_t_max", 0.0) > 0) + + ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + state = ckpt.get("model", ckpt) + vae_state = {} + for k, v in state.items(): + for prefix in ("network.", "vae.", "model.network.", "model.vae."): + if k.startswith(prefix): + k = k[len(prefix):] + break + vae_state[k] = v + from tokenizer.networks.transformers.transformer_vae_cross_dataset import ( + CrossDatasetTransformerVAE, + ) + + if isinstance(self.vae_net, CrossDatasetTransformerVAE): + # Cross-dataset encode/decode regenerate this nonlearned grid at + # the input resolution; its saved shape is not a model constraint. + saved_coords = vae_state.pop("coords", None) + if saved_coords is not None: + print( + "[ConfigBasedVideoVAE] ignoring derived cross-dataset " + f"coords buffer {tuple(saved_coords.shape)}; " + "coordinates are regenerated for each input grid" + ) + incompatible = self.vae_net.load_state_dict(vae_state, strict=False) + if strict_checkpoint: + allowed_missing = ( + {"coords"} + if isinstance(self.vae_net, CrossDatasetTransformerVAE) + else set() + ) + missing = sorted(set(incompatible.missing_keys) - allowed_missing) + unexpected = incompatible.unexpected_keys + if missing or unexpected: + raise RuntimeError( + "Tokenizer checkpoint/config mismatch: " + f"missing={missing[:12]}, unexpected={unexpected[:12]}. " + "Refusing inference with partially loaded weights." + ) + print("[ConfigBasedVideoVAE] checkpoint/config match: all weights loaded") + + # Optional: overlay the EMA shadow weights bundled in the same tokenizer + # ckpt (``ema.network-`` where is the param name with "." + # replaced by "-"; see utils/ema.py). Only trainable params are EMA'd, so + # buffers stay at their reg values -- hence overlay onto the reg-loaded net + # with strict=False rather than a from-scratch load. NOTE: the diffusion + # model was trained on reg-encoded latents, so this only swaps the DECODER + # weights at inference -- an EMA-vs-reg decode A/B, not a latent-space change. + if use_ema: + ema_state = { + k[len("ema.network-"):].replace("-", "."): v + for k, v in state.items() + if k.startswith("ema.network-") + } + if not ema_state: + raise RuntimeError( + f"use_ema=True but no 'ema.network-*' keys in {checkpoint_path} " + "(EMA was not enabled for this tokenizer run)." + ) + _, unexpected = self.vae_net.load_state_dict(ema_state, strict=False) + if unexpected: + raise RuntimeError( + f"EMA overlay had {len(unexpected)} unexpected keys, e.g. " + f"{unexpected[:5]} -- ema->net name remap is wrong for this arch." + ) + print(f"[ConfigBasedVideoVAE] use_ema=True: overlaid {len(ema_state)} " + "EMA params onto the decoder/vae_net") + + self.vae_net.eval() + for p in self.vae_net.parameters(): + p.requires_grad = False + self._reset_module_dtypes() + + if latent_mean is not None and latent_std is not None: + assert len(latent_mean) == latent_ch and len(latent_std) == latent_ch, ( + f"Inline latent_mean/latent_std must have length latent_ch={latent_ch}, " + f"got {len(latent_mean)}/{len(latent_std)}" + ) + latent_mean_t = torch.tensor(list(latent_mean), dtype=torch.float32) + latent_std_t = torch.tensor(list(latent_std), dtype=torch.float32) + else: + assert mean_std_fp is not None, ( + "ConfigBasedVideoVAE requires either mean_std_fp or " + "(latent_mean, latent_std)." + ) + stats = torch.load(mean_std_fp, map_location="cpu", weights_only=False) + if isinstance(stats, (tuple, list)): + latent_mean_t, latent_std_t = stats + else: + latent_mean_t = stats["mean"] + latent_std_t = stats["std"] + shape = [1, latent_ch, 1, 1, 1] + self.register_buffer( + "latent_mean", + latent_mean_t.to(self.dtype).reshape(*shape), + persistent=False, + ) + self.register_buffer( + "latent_std", + latent_std_t.to(self.dtype).reshape(*shape), + persistent=False, + ) + + def _reset_module_dtypes(self) -> None: + self.vae_net.to(self.decoder_dtype) + if self.encoder_dtype == self.decoder_dtype: + return + if not all( + hasattr(self.vae_net, name) for name in ("encoder", "quant_conv") + ): + raise ValueError( + "mixed VAE precision requires separate encoder and " + "quant_conv modules" + ) + self.vae_net.encoder.to(self.encoder_dtype) + self.vae_net.quant_conv.to(self.encoder_dtype) + + def _prepare_encoder_input(self, state: torch.Tensor) -> torch.Tensor: + x = state.to(self.encoder_dtype) + # mask_as_input VAEs expect a [data..., mask] encoder input, but + # vae_net.encode() does NOT build the mask (forward() does). The net + # reconstructs ``out_channels`` DATA channels (1 = [depth] mono, 2 = + # [depth, intensity]); build the full encoder input to match training: + # * pad missing data channels with zeros (e.g. hdmap is mono depth even + # for an intensity VAE -> [depth, 0(intensity)] before the mask), + # * derive the validity mask from depth (ch0, same threshold as the + # loss/forward) and concat it. + # No-op for non-mask VAEs and for inputs that already carry the mask + # channel (x.shape[1] == data_ch + 1). Bit-identical to the old 1ch path + # for mono mask VAEs (out_channels == 1). + if getattr(self.vae_net, "mask_as_input", False): + data_ch = int(getattr(self.vae_net, "out_channels", 1)) + if x.shape[1] <= data_ch: + if x.shape[1] < data_ch: # pad missing data channels (intensity) + pad = x.new_full( + (x.shape[0], data_ch - x.shape[1]) + tuple(x.shape[2:]), + self.intensity_pad_value) + x = torch.cat([x, pad], dim=1) + thr = self.vae_net.mask_input_min_value + self.vae_net.mask_input_eps + valid = (x[:, :1] > thr).to(x.dtype) + x = torch.cat([x, valid], dim=1) + return x + + @torch.no_grad() + def encode( + self, + state: torch.Tensor, + sensor_dataset_id: torch.Tensor | int | None = None, + ) -> torch.Tensor: + if sensor_dataset_id is not None: + setter = getattr(self.vae_net, "set_dataset_id", None) + if setter is not None: + setter(sensor_dataset_id) + elif getattr(self.vae_net, "uses_dataset_id", False): + raise TypeError( + f"{type(self.vae_net).__name__} requires a dataset ID but " + "does not expose set_dataset_id()" + ) + x = self._prepare_encoder_input(state) + if self.per_frame: + # 2D net: (B, C, T, H, W) -> encode each frame as (B*T, C, H, W). + B, C, T, H, W = x.shape + frames = x.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W) + enc = self.vae_net.encode(frames) + z = enc[0] if isinstance(enc, tuple) else enc + Cz, Hz, Wz = z.shape[1], z.shape[2], z.shape[3] + latent = z.reshape(B, T, Cz, Hz, Wz).permute(0, 2, 1, 3, 4) + else: + encoded = self.vae_net.encode(x) + latent = encoded[0] if isinstance(encoded, tuple) else encoded + latent = latent.to(self.encoder_dtype) + latent_mean = self.latent_mean.to(self.encoder_dtype) + latent_std = self.latent_std.to(self.encoder_dtype) + return (latent - latent_mean) / latent_std + + @torch.no_grad() + def encode_stream( + self, + state_new: torch.Tensor, + temporal_kv_cache=None, + max_cache_frames: int | None = None, + ): + """Encode newly appended frames with the wrapped causal VAE cache.""" + if self.per_frame or not getattr( + self.vae_net, "supports_encoder_temporal_kv_cache", False + ): + raise NotImplementedError( + f"{type(self.vae_net).__name__} does not support temporal " + "KV-cache encoding" + ) + x_new = self._prepare_encoder_input(state_new) + encoded, new_cache = self.vae_net.encode_stream( + x_new, + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + ) + latent = encoded[0] if isinstance(encoded, tuple) else encoded + latent = latent.to(self.encoder_dtype) + latent_mean = self.latent_mean.to(self.encoder_dtype) + latent_std = self.latent_std.to(self.encoder_dtype) + latent = (latent - latent_mean) / latent_std + return latent, new_cache + + @torch.no_grad() + def decode( + self, + latent: torch.Tensor, + t: float | torch.Tensor | None = None, + return_validity: bool = False, + sensor_dataset_id: torch.Tensor | int | None = None, + ) -> torch.Tensor: + """Decode a normalized latent back to pixels. + + Args: + latent: ``(B, latent_ch, T, H, W)`` in normalized-latent space + (i.e. already divided by ``self.sigma_data`` upstream). + t: optional rectified-flow timestep in ``[0, 1]``. Only + accepted when ``self.is_ltx`` is True (the wrapped VAE + net supports ``decode(z, t=t)``). For non-LTX wrappers + the standard ``decode(z)`` signature is used and + passing ``t`` raises -- prevents silently dropping the + timestep on an unrelated VAE. + return_validity: when True (and the wrapped net has a validity + head), also return the per-pixel validity probability + ``(B, 1, T, H, W)`` in ``[0, 1]``; ``None`` otherwise. + + When the wrapped net has ``predict_validity`` and this wrapper was + built with ``apply_validity_mask=True``, predicted-invalid pixels + (prob < 0.5) are filled with the depth sentinel so the returned range + map carries raydrop directly. + """ + if sensor_dataset_id is not None: + setter = getattr(self.vae_net, "set_dataset_id", None) + if setter is not None: + setter(sensor_dataset_id) + elif getattr(self.vae_net, "uses_dataset_id", False): + raise TypeError( + f"{type(self.vae_net).__name__} requires a dataset ID but " + "does not expose set_dataset_id()" + ) + if t is not None and not self.is_ltx: + raise ValueError( + f"Got t={t!r} but the wrapped VAE net " + f"({type(self.vae_net).__name__}) is not LTX-style " + f"(is_ltx=False). Use a TransformerVAELTX checkpoint " + f"with denoising_t_max > 0 to enable timestep-" + f"conditioned decoding." + ) + latent = latent.to(self.decoder_dtype) + latent_std = self.latent_std.to(self.decoder_dtype) + latent_mean = self.latent_mean.to(self.decoder_dtype) + latent = latent * latent_std + latent_mean + + if self.per_frame: + # 2D net: (B, Cz, T, Hz, Wz) -> decode each frame as (B*T, Cz, Hz, Wz). + # These nets have no validity head, so return_validity yields None. + B, Cz, T, Hz, Wz = latent.shape + z = latent.permute(0, 2, 1, 3, 4).reshape(B * T, Cz, Hz, Wz) + rec = self.vae_net.decode(z) + if isinstance(rec, tuple): + rec = rec[0] + if rec.ndim == 5: # some nets return (B, C, 1, H, W) + rec = rec[:, :, 0] + C, H, W = rec.shape[1], rec.shape[2], rec.shape[3] + out = rec.reshape(B, T, C, H, W).permute(0, 2, 1, 3, 4) + if return_validity: + return out, None + return out + + validity = None + if self.is_ltx: + out = self.vae_net.decode(latent, t=t) + elif self.predict_validity or self.decoder_validity_head: + out, logits = self.vae_net.decode(latent, return_validity=True) + if logits is not None: + validity = torch.sigmoid(logits.to(out.dtype)) + if self.apply_validity_mask: + out = out.masked_fill(validity < 0.5, self.invalid_fill) + else: + out = self.vae_net.decode(latent) + + if return_validity: + return out, validity + return out + + @torch.no_grad() + def decode_stream( + self, + latent_new: torch.Tensor, + temporal_kv_cache=None, + return_validity: bool = False, + max_cache_frames: int | None = None, + ): + """Decode newly appended frames with the wrapped causal VAE cache.""" + if self.per_frame or self.is_ltx or self.decoder_validity_head: + raise NotImplementedError( + "streaming decode currently supports the attention-based " + "TransformerVAE video decoder with its integrated validity head" + ) + if not getattr( + self.vae_net, "supports_temporal_kv_cache", False + ): + raise NotImplementedError( + f"{type(self.vae_net).__name__} does not support temporal " + "KV-cache decoding" + ) + + latent_new = latent_new.to(self.decoder_dtype) + latent_std = self.latent_std.to(self.decoder_dtype) + latent_mean = self.latent_mean.to(self.decoder_dtype) + latent_new = latent_new * latent_std + latent_mean + decode_kwargs = { + "temporal_kv_cache": temporal_kv_cache, + "return_validity": self.predict_validity, + } + if max_cache_frames is not None: + decode_kwargs["max_cache_frames"] = max_cache_frames + decoded, new_cache = self.vae_net.decode_stream( + latent_new, **decode_kwargs + ) + validity = None + if self.predict_validity: + out, logits = decoded + validity = torch.sigmoid(logits.to(out.dtype)) + if self.apply_validity_mask: + out = out.masked_fill(validity < 0.5, self.invalid_fill) + else: + out = decoded + + if return_validity: + return out, validity, new_cache + return out, new_cache + + def reset_dtype(self, *args, **kwargs): + del args, kwargs + self._reset_module_dtypes() + + @property + def spatial_compression_factor(self) -> int: + return self._spatial_compression + + +class SDVAE(BaseVAE): + def __init__(self, batch_size=16, count_std: bool = False, is_downsample: bool = True) -> None: + super().__init__(channel=4, name="sd_vae") + self.dtype = torch.bfloat16 + self.register_buffer( + "scale", + torch.tensor([4.17, 4.62, 3.71, 3.28], dtype=self.dtype).reciprocal().reshape(1, -1, 1, 1), + persistent=False, + ) + self.register_buffer( + "bias", + -1.0 * torch.tensor([5.81, 3.25, 0.12, -2.15], dtype=self.dtype).reshape(1, -1, 1, 1) * self.scale, + persistent=False, + ) + self.batch_size = batch_size + self.count_std = count_std + self.is_downsample = is_downsample + self.load_vae() + self.reset_dtype() + + def reset_dtype(self, *args, **kwargs): + del args, kwargs + self.vae.to(self.dtype) + + @rank0_first + def load_vae(self) -> None: + os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1" + os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1" + import diffusers + + vae_name = "stabilityai/sd-vae-ft-mse" + try: + vae = diffusers.models.AutoencoderKL.from_pretrained(vae_name, local_files_only=True) + except: # noqa: E722 + # Could not load the model from cache; try without local_files_only. + vae = diffusers.models.AutoencoderKL.from_pretrained(vae_name) + self.vae = vae.eval().requires_grad_(False) + + @torch.no_grad() + def encode(self, state: torch.Tensor) -> torch.Tensor: + """ + state : pixel range [-1, 1] + """ + if self.is_downsample: + _h, _w = state.shape[-2:] + state = F.interpolate(state, size=(_h // 2, _w // 2), mode="bilinear", align_corners=False) + in_dtype = state.dtype + state = state.to(self.dtype) + state = (state + 1.0) / 2.0 + latent_dist = self.vae.encode(state)["latent_dist"] + mean, std = latent_dist.mean, latent_dist.std + if self.count_std: + latent = mean + torch.randn_like(mean) * std + else: + latent = mean + latent = latent * self.scale + latent = latent + self.bias + return latent.to(in_dtype) + + @torch.no_grad() + def decode(self, latent: torch.Tensor) -> torch.Tensor: + in_dtype = latent.dtype + latent = latent.to(self.dtype) + latent = latent - self.bias + latent = latent / self.scale + latent = torch.cat([self.vae.decode(batch)["sample"] for batch in latent.split(self.batch_size)]) + if self.is_downsample: + _h, _w = latent.shape[-2:] + latent = F.interpolate(latent, size=(_h * 2, _w * 2), mode="bilinear", align_corners=False) + return latent.to(in_dtype) * 2 - 1.0 + + @property + def spatial_compression_factor(self) -> int: + return 8 diff --git a/diffusion/training/module/vae_utils.py b/diffusion/training/module/vae_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23d9a14862cf35117da0b82c40d45c0d781862e9 --- /dev/null +++ b/diffusion/training/module/vae_utils.py @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build the public tokenizer architecture from its experiment config.""" + +import importlib +from copy import deepcopy + +from omegaconf import DictConfig + +from tokenizer.training.configs.base.nets.lidarverse import ( + LIDARVERSE_TOKENIZER_CONFIG, + PAI_TOKENIZER_NAME, +) +from utils.lazy_config import instantiate + + +def build_vae_from_tokenizer_experiment(experiment_name: str, **overrides): + """Instantiate a tokenizer network without loading checkpoint weights.""" + if experiment_name == PAI_TOKENIZER_NAME: + # The PAI expert has the same GridRoPE architecture, different weights. + network = deepcopy(LIDARVERSE_TOKENIZER_CONFIG) + network.activation_checkpointing = False + network.update(overrides) + return instantiate(network) + + module = importlib.import_module( + f"tokenizer.training.configs.experiments.{experiment_name}" + ) + experiment = getattr(module, "config", None) + if not isinstance(experiment, DictConfig): + experiment = next( + ( + value + for value in vars(module).values() + if isinstance(value, DictConfig) and "defaults" in value + ), + None, + ) + if experiment is None: + raise ValueError( + f"Tokenizer experiment {experiment_name!r} has no config" + ) + + network_name = None + for entry in experiment["defaults"]: + try: + network_name = entry["override /network"] + except (KeyError, TypeError): + continue + break + if network_name != "lidarverse_tokenizer": + raise ValueError( + f"Unsupported public tokenizer network: {network_name!r}" + ) + + network = deepcopy(LIDARVERSE_TOKENIZER_CONFIG) + try: + experiment_overrides = experiment["model"]["config"]["network"] + except (KeyError, TypeError): + experiment_overrides = None + if isinstance(experiment_overrides, DictConfig): + for key in experiment_overrides: + network[key] = experiment_overrides[key] + for key, value in overrides.items(): + network[key] = value + return instantiate(network) diff --git a/diffusion/training/modules/edm_sde.py b/diffusion/training/modules/edm_sde.py new file mode 100644 index 0000000000000000000000000000000000000000..3d08a8229f03c9fdd6a8d905ad4543fe5fe5238a --- /dev/null +++ b/diffusion/training/modules/edm_sde.py @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from statistics import NormalDist + +import numpy as np +import torch + + +class EDMSDE: + def __init__( + self, + p_mean: float = -1.2, + p_std: float = 1.2, + sigma_max: float = 80.0, + sigma_min: float = 0.002, + ): + self.gaussian_dist = NormalDist(mu=p_mean, sigma=p_std) + self.sigma_max = sigma_max + self.sigma_min = sigma_min + + def sample_t(self, batch_size: int) -> torch.Tensor: + cdf_vals = np.random.uniform(size=(batch_size)) + samples_interval_gaussian = [self.gaussian_dist.inv_cdf(cdf_val) for cdf_val in cdf_vals] + + log_sigma = torch.tensor(samples_interval_gaussian, device="cuda") + return torch.exp(log_sigma) + + def marginal_prob(self, x0: torch.Tensor, sigma: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """This is trivial in the base class, but may be used by derived classes in a more interesting way""" + return x0, sigma diff --git a/diffusion/training/networks/a2a_cp.py b/diffusion/training/networks/a2a_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..fd996829574b367ec867ae195fe2361d450e7746 --- /dev/null +++ b/diffusion/training/networks/a2a_cp.py @@ -0,0 +1,225 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +# from neophilia; Author: Qsh (qsh.zh27@gmail.com) +# MIT License + +from typing import Any, Callable, List, Tuple, Union + +import torch +import torch.distributed as dist +from einops import rearrange +from torch import Tensor +from torch.distributed import ProcessGroup +from torch.nn import Module + +from diffusion.training.networks.neighborhood_attn import NeighborhoodAttention +from diffusion.training.networks.cosmos_attention import attention + + +def post_all2all(local_seq_2_local_head, seq_world_size): + def post_func(input): + # b, s, n, h + if local_seq_2_local_head: + output = rearrange(input, "w bs seq h d -> bs (w seq) h d") + else: + output = rearrange(input, "w bs s h d -> bs s (w h) d", w=seq_world_size) + + return output + + return post_func + + +def single_all_to_all(input, local_seq_2_local_head, group, async_op=False): + seq_world_size = dist.get_world_size(group) + + # b, s, n, h + if local_seq_2_local_head: + bs, local_seq_len, num_total_head, head_dim = input.shape + assert num_total_head % seq_world_size == 0, ( + f"Number of heads ({num_total_head}) must be divisible by the sequence parallel size ({seq_world_size})!" + ) + input_t = rearrange( + input, "bs seq_len (w h) d -> w bs seq_len h d", w=seq_world_size, h=num_total_head // seq_world_size + ).contiguous() + post_all2all_fun = post_all2all(local_seq_2_local_head, seq_world_size) + else: + bs, global_seq_len, num_local_head, head_dim = input.shape + input_t = rearrange( + input, "bs (w s) h d -> w bs s h d", w=seq_world_size, s=global_seq_len // seq_world_size + ).contiguous() + post_all2all_fun = post_all2all(local_seq_2_local_head, seq_world_size) + + output = torch.empty_like(input_t) + dist.all_to_all_single(output, input_t, group=group, async_op=async_op) + + res = post_all2all_fun(output) + return res + + +def async_a2a_communicate( + a2a_inputs: Union[torch.Tensor, List[torch.Tensor]], + cp_size: int, + cp_group: ProcessGroup, + cp_stream: torch.cuda.Stream, + local_seq_2_local_head: bool, +) -> Union[torch.Tensor, List[torch.Tensor]]: + """ + A2A communication for context parallelism. best used in communicate qkv + Modified from Nvidia Transformer Engine. + """ + a2a_inputs = [a2a_inputs] if not isinstance(a2a_inputs, list) else a2a_inputs + a2a_outputs, a2a_reqs = [None] * len(a2a_inputs), [None] * len(a2a_inputs) + a2a_post_fns = [None] * len(a2a_inputs) + if local_seq_2_local_head: + for i in range(len(a2a_inputs) + 2): + if 0 < i < len(a2a_inputs) + 1: + a2a_outputs[i - 1] = torch.empty_like(a2a_inputs[i - 1]) + a2a_reqs[i - 1] = torch.distributed.all_to_all_single( + a2a_outputs[i - 1], a2a_inputs[i - 1], group=cp_group, async_op=True + ) + a2a_post_fns[i - 1] = post_all2all(local_seq_2_local_head, cp_size) + if i > 1: + with torch.cuda.stream(cp_stream): + a2a_reqs[i - 2].wait() + a2a_outputs[i - 2] = a2a_post_fns[i - 2](a2a_outputs[i - 2]) + if i < len(a2a_inputs): + a2a_inputs[i] = rearrange( + a2a_inputs[i], "bs seq_len (w h) d -> w bs seq_len h d", w=cp_size + ).contiguous() + else: + for i in range(len(a2a_inputs) + 2): + if 0 < i < len(a2a_inputs) + 1: + a2a_outputs[i - 1] = torch.empty_like(a2a_inputs[i - 1]) + a2a_reqs[i - 1] = torch.distributed.all_to_all_single( + a2a_outputs[i - 1], a2a_inputs[i - 1], group=cp_group, async_op=True + ) + a2a_post_fns[i - 1] = post_all2all(local_seq_2_local_head, cp_size) + if i < len(a2a_inputs): + a2a_inputs[i] = rearrange(a2a_inputs[i], "bs (w s) h d -> w bs s h d", w=cp_size).contiguous() + if i > 1: + with torch.cuda.stream(cp_stream): + a2a_reqs[i - 2].wait() + a2a_outputs[i - 2] = a2a_post_fns[i - 2](a2a_outputs[i - 2]) + torch.cuda.current_stream().wait_stream(cp_stream) + return a2a_outputs[0] if len(a2a_inputs) == 1 else a2a_outputs + + +class _SeqAllToAll(torch.autograd.Function): + @staticmethod + def forward(ctx: Any, group: dist.ProcessGroup, input: Tensor, local_seq_2_local_head: bool) -> Tensor: + ctx.group = group + res = single_all_to_all(input, local_seq_2_local_head, group, False) + ctx.local_seq_2_local_head = local_seq_2_local_head + return res + + @staticmethod + def backward(ctx: Any, *grad_output: Tensor) -> Tuple[None, Tensor, None]: + return (None, _SeqAllToAll.apply(ctx.group, *grad_output, not ctx.local_seq_2_local_head), None) + + +class _SeqAllToAllQKV(torch.autograd.Function): + @staticmethod + def forward( + ctx: Any, + group: dist.ProcessGroup, + q: Tensor, + k: Tensor, + v: Tensor, + cp_size: int, + cp_stream: torch.cuda.Stream, + local_seq_2_local_head: bool, + ) -> Tuple[Tensor, Tensor, Tensor]: + ctx.group = group + ctx.cp_size = cp_size + ctx.cp_stream = cp_stream + ctx.local_seq_2_local_head = local_seq_2_local_head + q, k, v = async_a2a_communicate([q, k, v], cp_size, group, cp_stream, local_seq_2_local_head) + return q, k, v + + @staticmethod + def backward(ctx: Any, *grad_output: Tensor) -> Tuple[None, Tensor, Tensor, Tensor, None, None, None]: + q_grad, k_grad, v_grad = _SeqAllToAllQKV.apply( + ctx.group, *grad_output, ctx.cp_size, ctx.cp_stream, not ctx.local_seq_2_local_head + ) + return (None, q_grad, k_grad, v_grad, None, None, None) + + +class DistributedAttention(torch.nn.Module): + """Initialization. + + Arguments: + local_attention (Module): local attention with q,k,v + sequence_process_group (ProcessGroup): sequence parallel process group + """ + + def __init__( + self, + local_attention: Union[Module, Callable], + ) -> None: + super(DistributedAttention, self).__init__() + self.local_attn = local_attention + self.pg = None + self.stream = None + + def forward(self, query: Tensor, key: Tensor, value: Tensor, *args: Any, **kwargs) -> Tensor: + """forward + + Arguments: + query (Tensor): query input to the layer + key (Tensor): key input to the layer + value (Tensor): value input to the layer + args: other args + + Returns: + * output (Tensor): context output + """ + if self.pg is None: + return self.local_attn(query, key, value, *args, **kwargs) + pg_size = dist.get_world_size(self.pg) + if pg_size < 2: + return self.local_attn(query, key, value, *args, **kwargs) + + query_layer, key_layer, value_layer = _SeqAllToAllQKV.apply( + self.pg, query, key, value, pg_size, self.stream, True + ) + context_layer = self.local_attn(query_layer, key_layer, value_layer, *args, **kwargs) + + output = _SeqAllToAll.apply(self.pg, context_layer, False) + return output + + def set_context_parallel_group(self, group, stream): + self.pg = group + self.stream = stream + + +class MinimalA2AAttnOp(DistributedAttention): + def __init__(self, *args, **kwargs): + del args, kwargs + super(MinimalA2AAttnOp, self).__init__(attention) + + def set_context_parallel_group(self, process_group, ranks, stream, cp_comm_type: str = "p2p"): + del ranks + super().set_context_parallel_group(process_group, stream) + + def forward(self, query: Tensor, key: Tensor, value: Tensor, *args: Any, **kwargs) -> Tensor: + results = super().forward(query, key, value, *args, **kwargs) + return rearrange(results, "b ... h l -> b ... (h l)") + + +class NattenA2AAttnOp(MinimalA2AAttnOp): + def __init__(self, *args, **kwargs): + super(NattenA2AAttnOp, self).__init__(None) + self.natten_op = NeighborhoodAttention(*args, **kwargs, base_attn_op=attention) + self.local_attn = self.natten_op diff --git a/diffusion/training/networks/cosmos_attention.py b/diffusion/training/networks/cosmos_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..05c221a8b2446f1e715be0e98c45645e1dc57bb7 --- /dev/null +++ b/diffusion/training/networks/cosmos_attention.py @@ -0,0 +1,189 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +# From Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. + +# Description: +# Single point of entry for all generic attention ops (self and cross attention), that tries to +# deliver the best performance possible given any use case (GPU and environment). +# +# On Hopper GPUs (i.e. H100, H20, H200), Flash Attention 3 is the best-performing choice, but it +# needs to be installed. When it is not available, the second best choice is cuDNN attention, which +# we get using PyTorch's SDPA API. +# +# For all other use cases, we will just use PyTorch's SDPA, but we need to specify backends and +# priorities. +# Flash Attention 2, which is one of the backends, is the best choice for Ampere GPUs (both RTX and +# datacenter-class). +# +# For anything pre-Ampere, the only choice is "memory-efficient" (xformers) FMHA. +# +# For Ada and Blackwell RTX, it is unclear at the moment, so we defer to Flash Attention 2, and +# fallbacks are cuDNN and xformers. +# +# For Blackwell datacenter-class (B200, GB200), cuDNN is the best choice. +# +# +# Dispatching to the desired backends/paths are done by checking the compute capability (really SM +# number, which is just compute capability * 10) of the GPU device the input tensors are on. +# +# Here's a breakdown of relevant compute capabilities: +# +# | GPU / category | Arch | +# |================|=======| +# | A100 | SM80 | +# | A40 | SM80 | +# | Ampere RTX | SM86 | +# |----------------|-------| +# | Ada Lovelace | SM89 | +# |----------------|-------| +# | H20 | SM90 | +# | H100 | SM90 | +# | H200 | SM90 | +# |----------------|-------| +# | B200 | SM100 | +# | Blackwell RTX | SM103 | +# |----------------|-------| +# + +from functools import partial + +import torch +from torch.nn.attention import SDPBackend, sdpa_kernel + +try: + try: + from flash_attn_interface import flash_attn_func + except (ImportError, OSError): + from flash_attn_3.flash_attn_interface import flash_attn_func + + FLASH_ATTN_3_AVAILABLE = True +except (ImportError, OSError): + FLASH_ATTN_3_AVAILABLE = False + + +def get_device_cc(device) -> int: + """ + Returns the compute capability of a given torch device if it's a CUDA device, otherwise returns 0. + + Args: + device: torch device. + + Returns: + device_cc (int): compute capability in the SmXXX format (i.e. 90 for Hopper). + """ + if torch.cuda.is_available() and torch.version.cuda and device.type == "cuda": + major, minor = torch.cuda.get_device_capability(device) + return major * 10 + minor + return 0 + + +# Force a graph break here under torch.compile: this op does device-capability +# branching + a ``sdpa_kernel(backends=..., set_priority_order=True)`` probe that +# Dynamo cannot trace (raises AssertionError). Attention is a flash/cuDNN leaf +# (not fusible) so running it eager costs nothing; compile still fuses the rest +# of each block. No-op when the caller is not compiled. +@torch._dynamo.disable +def attention( + q, + k, + v, + q_lens=None, + k_lens=None, + dropout_p=0.0, + softmax_scale=None, + q_scale=None, + causal=False, + deterministic=False, + dtype=torch.bfloat16, +): + supported_dtypes = [torch.bfloat16, torch.float16, torch.float32] + is_half = dtype in [torch.bfloat16, torch.float16] + compute_cap = get_device_cc(q.device) + + if dtype not in supported_dtypes: + raise NotImplementedError(f"{dtype=} is not supported.") + + q = q.to(dtype) + k = k.to(dtype) + v = v.to(dtype) + + if q_scale is not None: + q = q * q_scale + + # If Flash Attention 3 is installed, and the user's running on a Hopper GPU (compute capability + # 9.0, or SM90), use Flash Attention 3. + if compute_cap == 90 and FLASH_ATTN_3_AVAILABLE and is_half: + return flash_attn_func( + q=q, + k=k, + v=v, + softmax_scale=softmax_scale, + causal=causal, + deterministic=deterministic, + )[0] + else: + # If Blackwell or Hopper (SM100 or SM90), cuDNN has native FMHA kernels. The Hopper one is + # not always as fast as Flash Attention 3, but when Flash Attention is unavailable, it's + # still a far better choice than Flash Attention 2 (Ampere). + if compute_cap in [90, 100] and is_half: + SDPA_BACKENDS = [ + SDPBackend.CUDNN_ATTENTION, + SDPBackend.FLASH_ATTENTION, + SDPBackend.EFFICIENT_ATTENTION, + ] + BEST_SDPA_BACKEND = SDPBackend.CUDNN_ATTENTION + elif is_half: + SDPA_BACKENDS = [ + SDPBackend.FLASH_ATTENTION, + SDPBackend.CUDNN_ATTENTION, + SDPBackend.EFFICIENT_ATTENTION, + ] + BEST_SDPA_BACKEND = SDPBackend.FLASH_ATTENTION if compute_cap >= 80 else SDPBackend.EFFICIENT_ATTENTION + else: + assert dtype == torch.float32, f"Unrecognized {dtype=}." + SDPA_BACKENDS = [SDPBackend.EFFICIENT_ATTENTION] + BEST_SDPA_BACKEND = SDPBackend.EFFICIENT_ATTENTION + + if deterministic: + raise NotImplementedError( + "Deterministic mode in attention is only supported when Flash Attention 3 is available." + ) + + # Torch 2.6 and later allows priorities for backends, but for older versions + # we can only run with a specific backend. As long as we pick ones we're certain + # will work on that device, it should be fine. + try: + sdpa_kernel(backends=SDPA_BACKENDS, set_priority_order=True) + sdpa_kernel_ = partial(sdpa_kernel, set_priority_order=True) + except TypeError: + sdpa_kernel_ = sdpa_kernel + SDPA_BACKENDS = [BEST_SDPA_BACKEND] + + q = q.transpose(1, 2) + k = k.transpose(1, 2) + v = v.transpose(1, 2) + + with sdpa_kernel_(backends=SDPA_BACKENDS): + out = torch.nn.functional.scaled_dot_product_attention( + q, + k, + v, + is_causal=causal, + dropout_p=dropout_p, + scale=softmax_scale, + ) + + out = out.transpose(1, 2).contiguous() + return out diff --git a/diffusion/training/networks/kv_cache.py b/diffusion/training/networks/kv_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..add7758726301ba80397c7a730eea0745272abc5 --- /dev/null +++ b/diffusion/training/networks/kv_cache.py @@ -0,0 +1,215 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Optional + +import torch +import torch.nn as nn + + +@dataclass +class KVCacheConfig: + run_with_kv: bool = False + store_kv: bool = False + current_idx: int = 0 + recompute_cross_attn_kv: bool = False + # External per-layer cache used by MiniTrainDIT's block-streaming path. + # Attention mutates this field when ``store_kv=True``; keeping the state + # outside the module avoids checkpoint/state-dict changes. + cache: Optional[dict[str, torch.Tensor]] = None + max_cache_tokens: Optional[int] = None + sink_cache_tokens: int = 0 + detach_cache: bool = True + + +def select_kv_cache_tokens( + tensor: torch.Tensor, + *, + max_cache_tokens: Optional[int], + sink_cache_tokens: int = 0, +) -> torch.Tensor: + """Retain a fixed prefix plus the newest suffix of a K/V tensor.""" + if tensor.ndim < 2: + raise ValueError( + f"cached K/V must have a token dimension, got {tensor.shape}" + ) + if max_cache_tokens is None: + if sink_cache_tokens: + raise ValueError( + "sink_cache_tokens requires a finite max_cache_tokens" + ) + return tensor + if max_cache_tokens <= 0: + raise ValueError( + f"max_cache_tokens must be positive, got {max_cache_tokens}" + ) + if not 0 <= sink_cache_tokens < max_cache_tokens: + raise ValueError( + "sink_cache_tokens must satisfy 0 <= sink < max, got " + f"{sink_cache_tokens}/{max_cache_tokens}" + ) + if tensor.shape[1] <= max_cache_tokens: + return tensor + if sink_cache_tokens == 0: + return tensor[:, -max_cache_tokens:] + tail_tokens = max_cache_tokens - sink_cache_tokens + return torch.cat( + [ + tensor[:, :sink_cache_tokens], + tensor[:, -tail_tokens:], + ], + dim=1, + ) + + +class AttentionOpWithKVCache(nn.Module): + """A thin wrapper that adds K/V caching to an existing attention op. + + This wrapper expects the wrapped op to accept (q, k, v, attn_mask=None) + and return attention outputs with heads already flattened on the last dim. + + Cache semantics: + - Cache entries are stored as per-chunk tensors, where each chunk corresponds + to one latent frame composed of HxW tokens (after patchify). + - The `max_cache_size` capacity therefore refers to the number of latent + frames (chunks), NOT the number of individual tokens. + - When `max_cache_size` is None, the cache grows without an automatic + rolling window; otherwise, it acts as a rolling window of at most + `max_cache_size` frames. Upon overflow, the oldest frames are dropped. + """ + + def __init__(self, attn_op: nn.Module | Any, max_cache_size: Optional[int] = None): + """Initialize the KV cache wrapper. + + Args: + attn_op: The underlying attention operation (q, k, v[, attn_mask]) -> out. + max_cache_size: Optional capacity measured in number of latent frames + (chunks). Each chunk is a single frame worth of HxW tokens. If None, + the cache does not enforce a rolling capacity. + """ + super().__init__() + self.attn_op = attn_op + self.reset_kv_cache(max_cache_size=max_cache_size) + self.pg: Optional[Any] = None + self.stream: Optional[Any] = None + + def reset_kv_cache(self, max_cache_size: Optional[int] = None) -> None: + """Reset/initialize the KV caches. + + Args: + max_cache_size: Optional capacity measured in number of latent frames + (chunks). Each chunk is a single frame worth of HxW tokens. If None, + the cache does not enforce a rolling capacity. + """ + # Initialize list-based caches and optionally set capacity in chunks + self.start_idx = 0 + self.k_cache: list[torch.Tensor | None] = [None] * (max_cache_size or 99999) + self.v_cache: list[torch.Tensor | None] = [None] * (max_cache_size or 99999) + self.max_cache_size = max_cache_size + + def forward( + self, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + *, + kv_cache_cfg: KVCacheConfig, + **kwargs, + ) -> torch.Tensor: + assert self.k_cache is not None and self.v_cache is not None, ( + "KV cache is not initialized. Call reset_kv_cache() first." + ) + + # Store into cache at start_idx location (list-based) + if kv_cache_cfg.store_kv: + index = int(kv_cache_cfg.current_idx) + self.k_cache[index] = k.detach() + self.v_cache[index] = v.detach() + + # Prepend cached prefix up to start_idx (list-based) + if kv_cache_cfg.run_with_kv and kv_cache_cfg.current_idx > 0: + history_k = self.k_cache[self.start_idx : kv_cache_cfg.current_idx] + history_v = self.v_cache[self.start_idx : kv_cache_cfg.current_idx] + assert not any(x is None for x in history_k) + assert not any(x is None for x in history_v) + k_out = torch.cat(history_k + [k], dim=1) # type: ignore + v_out = torch.cat(history_v + [v], dim=1) # type: ignore + else: + k_out = k + v_out = v + + # Enforce rolling capacity in number of cached chunks (frames) + if kv_cache_cfg.run_with_kv and self.max_cache_size is not None: + # Instead of deleting, just update start_idx for rolling window + self.start_idx = max(0, int(kv_cache_cfg.current_idx) - self.max_cache_size) + + return self.attn_op(q, k_out, v_out, **kwargs) + + def set_context_parallel_group(self, process_group, ranks, stream, cp_comm_type: str = "p2p"): + self.attn_op.set_context_parallel_group(process_group, ranks, stream, cp_comm_type=cp_comm_type) # type: ignore + + +class VideoSeqPos: + """Flattened 3D grid positions for a video clip. + + Stores flattened t/h/w indices of length L = T*H*W to enable constructing + RoPE frequencies aligned with global positions across sequential chunks. + """ + + def __init__(self, T: int, H: int, W: int, pos_h=None, pos_w=None, pos_t=None) -> None: + self.T = T + self.H = H + self.W = W + + if pos_h is not None and pos_w is not None and pos_t is not None: + self.pos_h = pos_h.to(dtype=torch.long) + self.pos_w = pos_w.to(dtype=torch.long) + self.pos_t = pos_t.to(dtype=torch.long) + return + + device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu") + t = torch.arange(self.T, device=device, dtype=torch.long) + h = torch.arange(self.H, device=device, dtype=torch.long) + w = torch.arange(self.W, device=device, dtype=torch.long) + pos_t, pos_h, pos_w = torch.meshgrid(t, h, w, indexing="ij") + self.pos_t = pos_t.reshape(-1) + self.pos_h = pos_h.reshape(-1) + self.pos_w = pos_w.reshape(-1) + + def size(self) -> int: + return int(self.pos_h.numel()) + + def frame(self, t_idx: int) -> "VideoSeqPos": + """Return a `VideoSeqPos` view for a single frame at absolute index `t_idx`. + + This is useful for streaming / KV-cache inference where the model is run on + one frame at a time but RoPE positions must reflect global video indices. + """ + t_idx = int(t_idx) + if t_idx < 0 or t_idx >= int(self.T): + raise IndexError(f"t_idx out of range: {t_idx} (valid: [0, {self.T}))") + tokens_per_frame = int(self.H) * int(self.W) + start = t_idx * tokens_per_frame + end = start + tokens_per_frame + return VideoSeqPos( + T=1, + H=int(self.H), + W=int(self.W), + pos_h=self.pos_h[start:end], + pos_w=self.pos_w[start:end], + pos_t=self.pos_t[start:end], + ) diff --git a/diffusion/training/networks/lvg_dit.py b/diffusion/training/networks/lvg_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8635edc1d83400c9e1d2824ab2a42aa8942872 --- /dev/null +++ b/diffusion/training/networks/lvg_dit.py @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""LVGDiT wrapper for hdmap-conditioned lidar generation. + +Adapts MinimalV1LVGDiT's forward signature to the interface used by +HdmapToLidarRectifiedFlowModel._rf_network_forward: + + net(x=..., timesteps=..., **condition.to_dict()) + +Also exposes ``fsdp_wrap_block_cls`` for FSDP auto-wrap. +""" + +from typing import List, Optional, Tuple, Union + +import torch + +from diffusion.conditioner import DataType +from diffusion.training.networks.minimal_v1_lvg_dit import MinimalV1LVGDiT +from diffusion.training.networks.minimal_v4_dit import Block + + +class LVGDiTForLidar(MinimalV1LVGDiT): + """MinimalV1LVGDiT with a GeneralDIT-compatible forward interface. + + The hdmap channel-concat is handled externally by ``_rf_network_forward`` + *before* calling the network, so ``x`` already contains (latent + hdmap) + channels. MinimalV1LVGDiT adds +1 to ``in_channels`` for an internal + condition-mask channel; we satisfy that by always passing + ``data_type=IMAGE`` which concatenates a zero-channel. + + Image-conditioned (img2lidar-style) usage instead passes an explicit + ``condition_video_input_mask`` (1 on RGB condition frames, 0 on the + generated lidar frame); when present we route through the native + ``data_type=VIDEO`` path so ``MinimalV1LVGDiT`` concatenates *that* mask + (not a zero) as the +1 channel and the DiT attends jointly over the + RGB + lidar frames. + """ + + fsdp_wrap_block_cls = Block + + def forward( + self, + x: torch.Tensor, + timesteps: torch.Tensor, + crossattn_emb: torch.Tensor, + crossattn_mask: Optional[torch.Tensor] = None, + data_type: Optional[DataType] = None, + padding_mask: Optional[torch.Tensor] = None, + fps: Optional[torch.Tensor] = None, + condition_video_input_mask: Optional[torch.Tensor] = None, + side_condition: Optional[torch.Tensor] = None, + frame_is_rgb: Optional[torch.Tensor] = None, + temporal_positions: Optional[torch.Tensor] = None, + frame_type_ids: Optional[torch.Tensor] = None, + frame_drop_mask: Optional[torch.Tensor] = None, + img_context_emb: Optional[torch.Tensor] = None, + img_context_pos: Optional[torch.Tensor] = None, + ego_pose_B_T_P: Optional[torch.Tensor] = None, + ego_pose_null_mask_B: Optional[torch.Tensor] = None, + dataset_ids_B: Optional[torch.Tensor] = None, + self_attn_kv_cache: Optional[ + List[Optional[dict[str, torch.Tensor]]] + ] = None, + store_self_attn_kv: bool = False, + self_attn_kv_max_frames: Optional[int] = None, + self_attn_kv_sink_frames: int = 0, + detach_self_attn_kv: bool = True, + return_self_attn_kv: bool = False, + teacher_forcing_clean_frames: Optional[int] = None, + **kwargs, + ) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: + if condition_video_input_mask is not None: + return super().forward( + x_B_C_T_H_W=x, + timesteps_B_T=timesteps, + crossattn_emb=crossattn_emb, + condition_video_input_mask_B_C_T_H_W=condition_video_input_mask, + side_condition_B_C_T_H_W=side_condition, + fps=fps, + padding_mask=padding_mask, + data_type=DataType.VIDEO, + frame_is_rgb=frame_is_rgb, + temporal_positions=temporal_positions, + frame_type_ids=frame_type_ids, + frame_drop_mask=frame_drop_mask, + img_context_emb=img_context_emb, + img_context_pos=img_context_pos, + ego_pose_B_T_P=ego_pose_B_T_P, + ego_pose_null_mask_B=ego_pose_null_mask_B, + dataset_ids_B=dataset_ids_B, + self_attn_kv_cache=self_attn_kv_cache, + store_self_attn_kv=store_self_attn_kv, + self_attn_kv_max_frames=self_attn_kv_max_frames, + self_attn_kv_sink_frames=self_attn_kv_sink_frames, + detach_self_attn_kv=detach_self_attn_kv, + return_self_attn_kv=return_self_attn_kv, + teacher_forcing_clean_frames=teacher_forcing_clean_frames, + ) + return super().forward( + x_B_C_T_H_W=x, + timesteps_B_T=timesteps, + crossattn_emb=crossattn_emb, + condition_video_input_mask_B_C_T_H_W=None, + side_condition_B_C_T_H_W=side_condition, + fps=fps, + padding_mask=padding_mask, + data_type=DataType.IMAGE, + temporal_positions=temporal_positions, + frame_type_ids=frame_type_ids, + dataset_ids_B=dataset_ids_B, + self_attn_kv_cache=self_attn_kv_cache, + store_self_attn_kv=store_self_attn_kv, + self_attn_kv_max_frames=self_attn_kv_max_frames, + self_attn_kv_sink_frames=self_attn_kv_sink_frames, + detach_self_attn_kv=detach_self_attn_kv, + return_self_attn_kv=return_self_attn_kv, + teacher_forcing_clean_frames=teacher_forcing_clean_frames, + ) diff --git a/diffusion/training/networks/minimal_v1_lvg_dit.py b/diffusion/training/networks/minimal_v1_lvg_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b0b62201b2b7fe530f4c5b01ef62dd10b45752 --- /dev/null +++ b/diffusion/training/networks/minimal_v1_lvg_dit.py @@ -0,0 +1,124 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +from typing import List, Optional, Tuple + +import torch +from torch import nn + +from diffusion.conditioner import DataType +from diffusion.training.networks.minimal_v4_dit import MiniTrainDIT + + +class MinimalV1LVGDiT(MiniTrainDIT): + def __init__(self, *args, timestep_scale: float = 1.0, rgb_drop_pad: bool = False, **kwargs): + assert "in_channels" in kwargs, "in_channels must be provided" + # Data (latent) channel count BEFORE the internal condition-mask channel + # is appended below; the learnable drop-pad lives in this latent space + # (substituted pre-mask-cat in ``forward``). + data_channels = kwargs["in_channels"] + kwargs["in_channels"] += 1 # Add 1 for the condition mask + self.timestep_scale = timestep_scale + super().__init__(*args, **kwargs) + # Learnable placeholder for DROPPED RGB condition frames. The diffusion + # operates in *normalized* latent space, so plain zeros == the per- + # channel latent mean (an in-distribution value, a poor "absent" + # signal). A ZERO-INIT learnable token starts bit-identical to the + # model's zeroing of dropped frames and drifts to a distinct "this + # frame is intentionally absent" code. Substituted in ``forward`` at the + # frames flagged by ``frame_drop_mask``. Default off => no param built. + self.use_rgb_drop_pad = bool(rgb_drop_pad) + if self.use_rgb_drop_pad: + self.rgb_drop_pad = nn.Parameter(torch.zeros(1, data_channels, 1, 1, 1)) + + def forward( + self, + x_B_C_T_H_W: torch.Tensor, + timesteps_B_T: torch.Tensor, + crossattn_emb: torch.Tensor, + condition_video_input_mask_B_C_T_H_W: Optional[torch.Tensor] = None, + side_condition_B_C_T_H_W: Optional[torch.Tensor] = None, + fps: Optional[torch.Tensor] = None, + padding_mask: Optional[torch.Tensor] = None, + data_type: Optional[DataType] = DataType.VIDEO, + intermediate_feature_ids: Optional[List[int]] = None, + img_context_emb: Optional[torch.Tensor] = None, + frame_is_rgb: Optional[torch.Tensor] = None, + temporal_positions: Optional[torch.Tensor] = None, + frame_type_ids: Optional[torch.Tensor] = None, + frame_drop_mask: Optional[torch.Tensor] = None, + img_context_pos: Optional[torch.Tensor] = None, + ego_pose_B_T_P: Optional[torch.Tensor] = None, + ego_pose_null_mask_B: Optional[torch.Tensor] = None, + dataset_ids_B: Optional[torch.Tensor] = None, + self_attn_kv_cache: Optional[ + List[Optional[dict[str, torch.Tensor]]] + ] = None, + store_self_attn_kv: bool = False, + self_attn_kv_max_frames: Optional[int] = None, + self_attn_kv_sink_frames: int = 0, + detach_self_attn_kv: bool = True, + return_self_attn_kv: bool = False, + teacher_forcing_clean_frames: Optional[int] = None, + **kwargs, + ) -> torch.Tensor | List[torch.Tensor] | Tuple[torch.Tensor, List[torch.Tensor]]: + del kwargs + + # Replace DROPPED RGB condition frames' latent content with the learnable + # placeholder (in normalized latent space, BEFORE the mask channel is + # appended). ``frame_drop_mask`` is (B, T) bool, True on dropped frames. + # Zero-init => no-op at iter 0 (matches the model's frame zeroing). + if ( + frame_drop_mask is not None + and getattr(self, "use_rgb_drop_pad", False) + ): + B, _, T = x_B_C_T_H_W.shape[:3] + assert frame_drop_mask.shape == (B, T), ( + f"frame_drop_mask {tuple(frame_drop_mask.shape)} must be (B={B}, T={T})" + ) + dm = frame_drop_mask.to(device=x_B_C_T_H_W.device, dtype=torch.bool).view(B, 1, T, 1, 1) + x_B_C_T_H_W = torch.where(dm, self.rgb_drop_pad.type_as(x_B_C_T_H_W), x_B_C_T_H_W) + + if data_type == DataType.VIDEO: + x_B_C_T_H_W = torch.cat([x_B_C_T_H_W, condition_video_input_mask_B_C_T_H_W.type_as(x_B_C_T_H_W)], dim=1) + else: + B, _, T, H, W = x_B_C_T_H_W.shape + x_B_C_T_H_W = torch.cat( + [x_B_C_T_H_W, torch.zeros((B, 1, T, H, W), dtype=x_B_C_T_H_W.dtype, device=x_B_C_T_H_W.device)], dim=1 + ) + return super().forward( + x_B_C_T_H_W=x_B_C_T_H_W, + timesteps_B_T=timesteps_B_T * self.timestep_scale, + crossattn_emb=crossattn_emb, + side_condition_B_C_T_H_W=side_condition_B_C_T_H_W, + fps=fps, + padding_mask=padding_mask, + data_type=data_type, + intermediate_feature_ids=intermediate_feature_ids, + img_context_emb=img_context_emb, + frame_is_rgb=frame_is_rgb, + temporal_positions=temporal_positions, + frame_type_ids=frame_type_ids, + img_context_pos=img_context_pos, + ego_pose_B_T_P=ego_pose_B_T_P, + ego_pose_null_mask_B=ego_pose_null_mask_B, + dataset_ids_B=dataset_ids_B, + self_attn_kv_cache=self_attn_kv_cache, + store_self_attn_kv=store_self_attn_kv, + self_attn_kv_max_frames=self_attn_kv_max_frames, + self_attn_kv_sink_frames=self_attn_kv_sink_frames, + detach_self_attn_kv=detach_self_attn_kv, + return_self_attn_kv=return_self_attn_kv, + teacher_forcing_clean_frames=teacher_forcing_clean_frames, + ) diff --git a/diffusion/training/networks/minimal_v4_dit.py b/diffusion/training/networks/minimal_v4_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..369e86ba702be41e7344c4b8bb2f509e1789c212 --- /dev/null +++ b/diffusion/training/networks/minimal_v4_dit.py @@ -0,0 +1,3030 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +import collections +import math +from collections import namedtuple +from collections.abc import Sequence +from dataclasses import dataclass +from enum import Enum +from typing import List, Optional, Tuple, Union + +from diffusion.training.networks.kv_cache import ( + AttentionOpWithKVCache, + KVCacheConfig, + select_kv_cache_tokens, +) + +try: + import megatron.core.parallel_state as parallel_state + + USE_MEGATRON = True +except ImportError: + USE_MEGATRON = False + +import numpy as np +import torch +import torch.amp as amp +import transformer_engine as te +from einops import rearrange, repeat +from einops.layers.torch import Rearrange +from torch import nn +from torch.distributed import ProcessGroup, get_process_group_ranks +from torch.distributed._composable.fsdp import fully_shard +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper as ptd_checkpoint_wrapper + +try: + from torch.utils.checkpoint import CheckpointPolicy, create_selective_checkpoint_contexts +except ImportError: + CheckpointPolicy = None + +from torchvision import transforms + +_FLASH_ATTN_3_IMPORT_ERROR = None +try: + try: + from flash_attn_interface import flash_attn_func as _flash_attn_3_func + except (ImportError, OSError): + from flash_attn_3.flash_attn_interface import ( + flash_attn_func as _flash_attn_3_func, + ) +except (ImportError, OSError) as exc: + _flash_attn_3_func = None + _FLASH_ATTN_3_IMPORT_ERROR = exc + +try: + from transformer_engine.pytorch.attention.rope import apply_rotary_pos_emb +except ImportError: + from transformer_engine.pytorch.attention import apply_rotary_pos_emb +from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention + +from diffusion.training.networks.cosmos_attention import attention as i4_attention_fn +from diffusion.training.context_parallel import split_inputs_cp +from utils import log +from diffusion.conditioner import DataType +from diffusion.training.networks.neighborhood_attn import NeighborhoodAttention +from diffusion.training.networks.a2a_cp import MinimalA2AAttnOp, NattenA2AAttnOp +from diffusion.training.networks.model_weights_stats import WeightTrainingStat +from diffusion.training.networks.selective_activation_checkpoint import SACConfig as _SACConfig +from diffusion.training.utils.diffusion_forcing import ( + teacher_forcing_clean_noisy_allows, + temporal_prefix_block_allows, +) + + +# selective activation checkpoint; only apply to the minimal v4 model. if there are change in the networks, some policy will not work as we expect. +def predict2_2B_720_context_fn(): + op_count = collections.defaultdict(int) + + def policy_fn(ctx, func, *args, **kwargs): + mode = "recompute" if ctx.is_recompute else "forward" + if func == torch.ops.aten.mm.default: + op_count_key = f"{mode}_mm_count" + op_count[op_count_key] = (op_count[op_count_key] + 1) % 16 + if op_count[op_count_key] > 8: # recompute self attn first 3 linear layers + return CheckpointPolicy.MUST_SAVE + if "flash_attn" in str(func): + op_count_key = f"{mode}_flash_attn_count" + op_count[op_count_key] = (op_count[op_count_key] + 1) % 2 + if op_count[op_count_key]: + return CheckpointPolicy.MUST_SAVE + return CheckpointPolicy.PREFER_RECOMPUTE + + return create_selective_checkpoint_contexts(policy_fn) + + +def predict2_2B_720_context_fn_aggressive(): + op_count = collections.defaultdict(int) + + def policy_fn(ctx, func, *args, **kwargs): + # The default policy is to recompute everything. This is the most memory-efficient + # starting point. We then selectively choose what to save. + default_policy = CheckpointPolicy.PREFER_RECOMPUTE + + # Save the output of Flash Attention. This is the most computationally + # expensive part of a transformer block. Saving its output provides a + # good balance between memory savings and computational overhead. + if "flash_attn" in str(func): + return CheckpointPolicy.MUST_SAVE + + # All other operations (e.g., torch.ops.aten.mm.default, layer norms, additions) + # will fall through to the default policy and be recomputed. + return default_policy + + return create_selective_checkpoint_contexts(policy_fn) + + +def predict2_2B_720_context_fn_aggressive_v2(): + """ + The most memory-aggressive checkpointing policy. Recomputes ALL operations. + """ + + def policy_fn(ctx, func, *args, **kwargs): + # The policy is to always recompute everything. + # This saves the maximum amount of memory but incurs the highest + # computational cost during the backward pass. + return CheckpointPolicy.PREFER_RECOMPUTE + + return create_selective_checkpoint_contexts(policy_fn) + + +def predict2_14B_720_context_fn(): + op_count = collections.defaultdict(int) + + def policy_fn(ctx, func, *args, **kwargs): + mode = "recompute" if ctx.is_recompute else "forward" + if func == torch.ops.aten.mm.default: + op_count_key = f"{mode}_mm_count" + op_count[op_count_key] = (op_count[op_count_key] + 1) % 16 + if op_count[op_count_key] > 8: # recompute self attn first 1 linear layers + return CheckpointPolicy.MUST_SAVE + if "flash_attn" in str(func): + op_count_key = f"{mode}_flash_attn_count" + op_count[op_count_key] = (op_count[op_count_key] + 1) % 2 + if op_count[op_count_key]: + return CheckpointPolicy.MUST_SAVE + return CheckpointPolicy.PREFER_RECOMPUTE + + return create_selective_checkpoint_contexts(policy_fn) + + +def predict2_14B_720_context_fn_aggressive(): + op_count = collections.defaultdict(int) + + def policy_fn(ctx, func, *args, **kwargs): + mode = "recompute" if ctx.is_recompute else "forward" + if func == torch.ops.aten.mm.default: + op_count_key = f"{mode}_mm_count" + op_count[op_count_key] = (op_count[op_count_key] + 1) % 16 + if op_count[op_count_key] > 12: # recompute self attn first 1 linear layers + return CheckpointPolicy.MUST_SAVE + return CheckpointPolicy.PREFER_RECOMPUTE + + return create_selective_checkpoint_contexts(policy_fn) + + +def linear_selfattn_context_fn(): + op_count = collections.defaultdict(int) + + def policy_fn(ctx, func, *args, **kwargs): + mode = "recompute" if ctx.is_recompute else "forward" + if func == torch.ops.aten.mm.default: + return CheckpointPolicy.MUST_SAVE + if "flash_attn" in str(func): + op_count_key = f"{mode}_flash_attn_count" + op_count[op_count_key] = (op_count[op_count_key] + 1) % 2 + if op_count[op_count_key]: + return CheckpointPolicy.MUST_SAVE + return CheckpointPolicy.PREFER_RECOMPUTE + + return create_selective_checkpoint_contexts(policy_fn) + + +class CheckpointMode(str, Enum): + NONE = "none" + MM_ONLY = "mm_only" + BLOCK_WISE = "block_wise" + LINEAR_SELFATTN = "linear_selfattn" + PREDICT2_2B_720 = "predict2_2b_720" + PREDICT2_14B_720 = "predict2_14b_720" + PREDICT2_2B_720_AGGRESSIVE = "predict2_2b_720_aggressive" + PREDICT2_2B_720_AGGRESSIVE_V2 = "predict2_2b_720_aggressive_v2" + PREDICT2_14B_720_AGGRESSIVE = "predict2_14b_720_aggressive" + + def __str__(self) -> str: + return self.value + + +@dataclass +class SACConfig(_SACConfig): + def get_context_fn(self): + if self.mode == CheckpointMode.LINEAR_SELFATTN: + return linear_selfattn_context_fn + elif self.mode == CheckpointMode.PREDICT2_2B_720: + return predict2_2B_720_context_fn + elif self.mode == CheckpointMode.PREDICT2_2B_720_AGGRESSIVE: + return predict2_2B_720_context_fn_aggressive + elif self.mode == CheckpointMode.PREDICT2_2B_720_AGGRESSIVE_V2: + return predict2_2B_720_context_fn_aggressive_v2 + elif self.mode == CheckpointMode.PREDICT2_14B_720: + return predict2_14B_720_context_fn + elif self.mode == CheckpointMode.PREDICT2_14B_720_AGGRESSIVE: + return predict2_14B_720_context_fn_aggressive + else: + # Reuse parent class implementation for other modes + return super().get_context_fn() + + +VideoSize = namedtuple("VideoSize", ["T", "H", "W"]) + + +class RMSNorm(torch.nn.Module): + def __init__(self, dim: int, eps: float = 1e-5): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def reset_parameters(self): + torch.nn.init.ones_(self.weight) + + def _norm(self, x): + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + + +# ---------------------- Feed Forward Network ----------------------- +class GPT2FeedForward(nn.Module): + def __init__(self, d_model: int, d_ff: int): + super().__init__() + self.activation = nn.GELU() + self.layer1 = nn.Linear(d_model, d_ff, bias=False) + self.layer2 = nn.Linear(d_ff, d_model, bias=False) + + self._layer_id = None + self._dim = d_model + self._hidden_dim = d_ff + self.init_weights() + + def init_weights(self) -> None: + std = 1.0 / math.sqrt(self._dim) + torch.nn.init.trunc_normal_(self.layer1.weight, std=std, a=-3 * std, b=3 * std) + + # scale init by depth as in https://arxiv.org/abs/1908.11365 -- worked slightly better. + std = 1.0 / math.sqrt(self._hidden_dim) + if self._layer_id is not None: + std = std / math.sqrt(2 * (self._layer_id + 1)) + torch.nn.init.trunc_normal_(self.layer2.weight, std=std, a=-3 * std, b=3 * std) + + def forward(self, x: torch.Tensor): + x = self.layer1(x) + + x = self.activation(x) + x = self.layer2(x) + return x + + +def torch_attention_op( + q_B_S_H_D: torch.Tensor, + k_B_S_H_D: torch.Tensor, + v_B_S_H_D: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + flatten_heads: bool = True, +) -> torch.Tensor: + """Scaled dot-product attention with optional mask. + + Inputs are shaped [B, S, H, D]. If flatten_heads=True, flattens heads to return [B, S, H*D]. + Otherwise returns [B, S, H, D]. + """ + q_B_H_S_D = rearrange(q_B_S_H_D, "b s h d -> b h s d") + k_B_H_S_D = rearrange(k_B_S_H_D, "b s h d -> b h s d") + v_B_H_S_D = rearrange(v_B_S_H_D, "b s h d -> b h s d") + result_B_H_S_D = torch.nn.functional.scaled_dot_product_attention( + q_B_H_S_D, k_B_H_S_D, v_B_H_S_D, attn_mask=attn_mask + ) + if flatten_heads: + return rearrange(result_B_H_S_D, "b h s d -> b s (h d)") + else: + return rearrange(result_B_H_S_D, "b h s d -> b s h d") + + +def torch_flash_attention_op( + q_B_S_H_D: torch.Tensor, + k_B_S_H_D: torch.Tensor, + v_B_S_H_D: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + flatten_heads: bool = True, +) -> torch.Tensor: + """Call PyTorch's fused FlashAttention operator directly. + + This is intended for cached inference, where each call receives only past + K/V plus one complete bidirectional DF block and therefore needs no mask. + Calling the operator directly avoids the process-wide ``sdpa_kernel`` + policy context, which would otherwise leak into concurrently running VAE + attention on the asynchronous clean-commit path. + """ + if attn_mask is not None: + raise ValueError( + "forced SDPA FlashAttention does not support the DF block mask; " + "use it only for cached inference" + ) + q_B_H_S_D = rearrange(q_B_S_H_D, "b s h d -> b h s d") + k_B_H_S_D = rearrange(k_B_S_H_D, "b s h d -> b h s d") + v_B_H_S_D = rearrange(v_B_S_H_D, "b s h d -> b h s d") + # Space port: mask-free SDPA (same math); lets PyTorch pick a kernel that exists on sm_120. + result_B_H_S_D = torch.nn.functional.scaled_dot_product_attention( + q_B_H_S_D, k_B_H_S_D, v_B_H_S_D, dropout_p=0.0, is_causal=False, + ) + if flatten_heads: + return rearrange(result_B_H_S_D, "b h s d -> b s (h d)") + return rearrange(result_B_H_S_D, "b h s d -> b s h d") + + +def flash_attention_3_op( + q_B_S_H_D: torch.Tensor, + k_B_S_H_D: torch.Tensor, + v_B_S_H_D: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + flatten_heads: bool = True, +) -> torch.Tensor: + """Call the external FlashAttention-3 Hopper kernel for cached inference.""" + if _flash_attn_3_func is None: + raise ImportError( + "cached backend 'fa3' requires flash-attn-3; install the Hopper " + "package from Dao-AILab/flash-attention" + ) from _FLASH_ATTN_3_IMPORT_ERROR + if attn_mask is not None: + raise ValueError( + "FlashAttention-3 does not support the DF block mask in this path; " + "use it only for cached inference" + ) + if not q_B_S_H_D.is_cuda or torch.cuda.get_device_capability( + q_B_S_H_D.device + ) != (9, 0): + raise RuntimeError("cached backend 'fa3' requires an SM90 Hopper GPU") + if q_B_S_H_D.dtype not in (torch.float16, torch.bfloat16): + raise TypeError( + "cached backend 'fa3' requires FP16 or BF16 Q/K/V, got " + f"{q_B_S_H_D.dtype}" + ) + result = _flash_attn_3_func( + q=q_B_S_H_D, + k=k_B_S_H_D, + v=v_B_S_H_D, + softmax_scale=None, + causal=False, + deterministic=False, + ) + result_B_S_H_D = result[0] if isinstance(result, tuple) else result + if flatten_heads: + return rearrange(result_B_S_H_D, "b s h d -> b s (h d)") + return result_B_S_H_D + + +def flex_attention_op( + q_B_S_H_D: torch.Tensor, + k_B_S_H_D: torch.Tensor, + v_B_S_H_D: torch.Tensor, + attn_mask: Optional[BlockMask] = None, + flatten_heads: bool = True, +) -> torch.Tensor: + # Rearrange to [B, H, S, D] + q_B_H_Sq_D = rearrange(q_B_S_H_D, "b s h d -> b h s d") + k_B_H_Sk_D = rearrange(k_B_S_H_D, "b s h d -> b h s d") + v_B_H_Sk_D = rearrange(v_B_S_H_D, "b s h d -> b h s d") + + S_q = q_B_H_Sq_D.shape[2] + S_kv = k_B_H_Sk_D.shape[2] + # Right-pad to multiples of 128 for optimal FlexAttention kernels + pad_q = ((S_q + 127) // 128) * 128 - S_q + pad_kv = ((S_kv + 127) // 128) * 128 - S_kv + + if pad_q > 0: + q_pad_tensor = torch.zeros( + (q_B_H_Sq_D.shape[0], q_B_H_Sq_D.shape[1], pad_q, q_B_H_Sq_D.shape[3]), + device=q_B_H_Sq_D.device, + dtype=q_B_H_Sq_D.dtype, + ) + q_cat = torch.cat([q_B_H_Sq_D, q_pad_tensor], dim=2) + else: + q_cat = q_B_H_Sq_D + + if pad_kv > 0: + kv_pad_tensor = torch.zeros( + (k_B_H_Sk_D.shape[0], k_B_H_Sk_D.shape[1], pad_kv, k_B_H_Sk_D.shape[3]), + device=k_B_H_Sk_D.device, + dtype=k_B_H_Sk_D.dtype, + ) + k_cat = torch.cat([k_B_H_Sk_D, kv_pad_tensor], dim=2) + v_cat = torch.cat([v_B_H_Sk_D, kv_pad_tensor], dim=2) + else: + k_cat, v_cat = k_B_H_Sk_D, v_B_H_Sk_D + + block_mask = None + if attn_mask is not None and isinstance(attn_mask, BlockMask): + block_mask = attn_mask + else: + # When padding is introduced without an explicit mask, build a validity mask + if pad_q > 0 or pad_kv > 0: + + def allow_valid(b, h, q_idx, kv_idx): + return (q_idx < S_q) & (kv_idx < S_kv) + + block_mask = create_block_mask( + allow_valid, + B=None, + H=None, + Q_LEN=q_cat.shape[2], + KV_LEN=k_cat.shape[2], + _compile=True, + device=q_cat.device, + ) + + if block_mask is not None: + out_B_H_Sqp_D = torch.compile(flex_attention)(query=q_cat, key=k_cat, value=v_cat, block_mask=block_mask) + else: + out_B_H_Sqp_D = torch.compile(flex_attention)(query=q_cat, key=k_cat, value=v_cat) + + out_B_H_Sq_D = out_B_H_Sqp_D[:, :, :S_q] if pad_q > 0 else out_B_H_Sqp_D + if flatten_heads: + return rearrange(out_B_H_Sq_D, "b h s d -> b s (h d)") + else: + return rearrange(out_B_H_Sq_D, "b h s d -> b s h d") + + +def i4_attention_op( + q_B_S_H_D: torch.Tensor, + k_B_S_H_D: torch.Tensor, + v_B_S_H_D: torch.Tensor, + flatten_heads: bool = True, + **kwargs: dict, +) -> torch.Tensor: + """ + I4 regular (bidirectional) attention. + Matches torch_attention_op's signature but omits attn_mask (full attention assumed). + Ignores any additional kwargs (e.g., video_size). + """ + out_B_S_H_D = i4_attention_fn( + query=q_B_S_H_D, + key=k_B_S_H_D, + value=v_B_S_H_D, + is_causal=False, + ) + if isinstance(out_B_S_H_D, tuple): + out_B_S_H_D = out_B_S_H_D[0] + if flatten_heads: + return rearrange(out_B_S_H_D, "b s h d -> b s (h d)") + else: + return out_B_S_H_D + + +class Attention(nn.Module): + """ + A flexible attention module supporting both self-attention and cross-attention mechanisms. + + This module implements a multi-head attention layer that can operate in either self-attention + or cross-attention mode. The mode is determined by whether a context dimension is provided. + The implementation uses scaled dot-product attention and supports optional bias terms and + dropout regularization. + + Args: + query_dim (int): The dimensionality of the query vectors. + context_dim (int, optional): The dimensionality of the context (key/value) vectors. + If None, the module operates in self-attention mode using query_dim. Default: None + n_heads (int, optional): Number of attention heads for multi-head attention. Default: 8 + head_dim (int, optional): The dimension of each attention head. Default: 64 + dropout (float, optional): Dropout probability applied to the output. Default: 0.0 + qkv_format (str, optional): Format specification for QKV tensors. Default: "bshd" + backend (str, optional): Backend to use for the attention operation. Default: "transformer_engine" + + Examples: + >>> # Self-attention with 512 dimensions and 8 heads + >>> self_attn = Attention(query_dim=512) + >>> x = torch.randn(32, 16, 512) # (batch_size, seq_len, dim) + >>> out = self_attn(x) # (32, 16, 512) + + >>> # Cross-attention + >>> cross_attn = Attention(query_dim=512, context_dim=256) + >>> query = torch.randn(32, 16, 512) + >>> context = torch.randn(32, 8, 256) + >>> out = cross_attn(query, context) # (32, 16, 512) + """ + + def __init__( + self, + query_dim: int, + context_dim=None, + n_heads=8, + head_dim=64, + dropout=0.0, + qkv_format: str = "bshd", + backend: str = "transformer_engine", + use_wan_fp32_strategy: bool = False, + ) -> None: + super().__init__() + log.debug( + f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using " + f"{n_heads} heads with a dimension of {head_dim}." + ) + self.is_selfattn = context_dim is None # self attention + + assert backend in ["transformer_engine", "torch", "torch-flex", "minimal_a2a", "i4"], ( + f"Invalid backend: {backend}" + ) + self.backend = backend + + context_dim = query_dim if context_dim is None else context_dim + inner_dim = head_dim * n_heads + + self.n_heads = n_heads + self.head_dim = head_dim + self.qkv_format = qkv_format + self.query_dim = query_dim + self.context_dim = context_dim + self.use_wan_fp32_strategy = use_wan_fp32_strategy + + self.q_proj = nn.Linear(query_dim, inner_dim, bias=False) + self.q_norm = te.pytorch.RMSNorm(self.head_dim, eps=1e-6) + + self.k_proj = nn.Linear(context_dim, inner_dim, bias=False) + self.k_norm = te.pytorch.RMSNorm(self.head_dim, eps=1e-6) + + self.v_proj = nn.Linear(context_dim, inner_dim, bias=False) + self.v_norm = nn.Identity() + + self.output_proj = nn.Linear(inner_dim, query_dim, bias=False) + self.output_dropout = nn.Dropout(dropout) if dropout > 1e-4 else nn.Identity() + + if self.backend == "transformer_engine": + from transformer_engine.pytorch.attention import DotProductAttention + + self.attn_op = DotProductAttention( + self.n_heads, + self.head_dim, + num_gqa_groups=self.n_heads, + attention_dropout=0, + qkv_format=qkv_format, + attn_mask_type="no_mask", + ) + elif self.backend == "minimal_a2a": + self.attn_op = MinimalA2AAttnOp() + elif self.backend == "torch": + self.attn_op = torch_attention_op + elif self.backend == "torch-flex": + # FlexAttention backend; returns [B, S, H*D] + self.attn_op = flex_attention_op + elif self.backend == "i4": + # I4 spatio-temporal attention; returns [B, S, H*D] + self.attn_op = i4_attention_op + + if not hasattr(self.attn_op, "set_context_parallel_group"): + + def set_context_parallel_group(*args, **kwargs) -> None: + return None + + self.attn_op.set_context_parallel_group = set_context_parallel_group + + self._query_dim = query_dim + self._context_dim = context_dim + self._inner_dim = inner_dim + + def init_weights(self) -> None: + std = 1.0 / math.sqrt(self._query_dim) + torch.nn.init.trunc_normal_(self.q_proj.weight, std=std, a=-3 * std, b=3 * std) + std = 1.0 / math.sqrt(self._context_dim) + torch.nn.init.trunc_normal_(self.k_proj.weight, std=std, a=-3 * std, b=3 * std) + torch.nn.init.trunc_normal_(self.v_proj.weight, std=std, a=-3 * std, b=3 * std) + + std = 1.0 / math.sqrt(self._inner_dim) + torch.nn.init.trunc_normal_(self.output_proj.weight, std=std, a=-3 * std, b=3 * std) + + for layer in self.q_norm, self.k_norm, self.v_norm: + if hasattr(layer, "reset_parameters"): + layer.reset_parameters() + + def compute_qkv(self, x, context=None, rope_emb=None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + q = self.q_proj(x) + context = x if context is None else context + k = self.k_proj(context) + v = self.v_proj(context) + q, k, v = map( + lambda t: rearrange(t, "b ... (h d) -> b ... h d", h=self.n_heads, d=self.head_dim), + (q, k, v), + ) + + def apply_norm_and_rotary_pos_emb(q, k, v, rope_emb): + q = self.q_norm(q) + k = self.k_norm(k) + v = self.v_norm(v) + original_dtype = q.dtype + if self.is_selfattn and rope_emb is not None: # only apply to self-attention! + if self.use_wan_fp32_strategy: # wan will force q and k to fp32 before rotary pos emb + q = q.to(torch.float32) + k = k.to(torch.float32) + q = apply_rotary_pos_emb(q, rope_emb, tensor_format=self.qkv_format, fused=True) + k = apply_rotary_pos_emb(k, rope_emb, tensor_format=self.qkv_format, fused=True) + if self.use_wan_fp32_strategy: + q = q.to(original_dtype) + k = k.to(original_dtype) + return q, k, v + + q, k, v = apply_norm_and_rotary_pos_emb(q, k, v, rope_emb) + + return q, k, v + + def compute_attention( + self, + q, + k, + v, + video_size: Optional[VideoSize] = None, + kv_cache_cfg: Optional[KVCacheConfig] = None, + attn_mask: Optional[torch.Tensor] = None, + ): + additional_args = {} + if ( + kv_cache_cfg is not None + and self.is_selfattn + and not isinstance(self.attn_op, AttentionOpWithKVCache) + ): + if attn_mask is not None: + raise ValueError( + "streaming self-attention receives only cached history " + "plus the current causal block, so no full-sequence mask " + "may be supplied" + ) + cache = kv_cache_cfg.cache + if kv_cache_cfg.run_with_kv and cache is not None: + k_past, v_past = cache["k"], cache["v"] + if ( + k_past.shape[0] != k.shape[0] + or k_past.shape[2:] != k.shape[2:] + or v_past.shape != k_past.shape + ): + raise ValueError( + "DiT KV-cache shape mismatch: " + f"cached={tuple(k_past.shape)}/{tuple(v_past.shape)}, " + f"current={tuple(k.shape)}/{tuple(v.shape)}" + ) + k = torch.cat([k_past, k], dim=1) + v = torch.cat([v_past, v], dim=1) + if kv_cache_cfg.store_kv: + k_store = select_kv_cache_tokens( + k, + max_cache_tokens=kv_cache_cfg.max_cache_tokens, + sink_cache_tokens=kv_cache_cfg.sink_cache_tokens, + ) + v_store = select_kv_cache_tokens( + v, + max_cache_tokens=kv_cache_cfg.max_cache_tokens, + sink_cache_tokens=kv_cache_cfg.sink_cache_tokens, + ) + if kv_cache_cfg.detach_cache: + k_store = k_store.detach() + v_store = v_store.detach() + kv_cache_cfg.cache = { + "k": k_store, + "v": v_store, + } + if isinstance(self.attn_op, (NattenA2AAttnOp, NeighborhoodAttention)) or self.backend == "i4": + additional_args["video_size"] = video_size + if isinstance(self.attn_op, AttentionOpWithKVCache): + additional_args["kv_cache_cfg"] = kv_cache_cfg + if attn_mask is not None: + assert self.backend in ("torch", "torch-flex"), ( + f"attn_mask only supported with the torch / torch-flex backends, got '{self.backend}'" + ) + additional_args["attn_mask"] = attn_mask + + result = self.attn_op(q, k, v, **additional_args) # [B, S, H, D] + return self.output_dropout(self.output_proj(result)) + + def forward( + self, + x, + context: Optional[torch.Tensor] = None, + rope_emb: Optional[torch.Tensor] = None, + video_size: Optional[VideoSize] = None, + kv_cache_cfg: Optional[KVCacheConfig] = None, + attn_mask: Optional[torch.Tensor] = None, + ): + """ + Args: + x (Tensor): The query tensor of shape [B, Mq, K] + context (Optional[Tensor]): The key tensor of shape [B, Mk, K] or use x as context [self attention] if None + rope_emb (Optional[Tensor]): RoPE embedding tensor, or no RoPE embeddings (i.e. in cross attention) + video_size(VideoSize): Shape [T, H, W] + attn_mask (Optional[Tensor]): dense torch mask or sparse FlexAttention + ``BlockMask`` (bool: True = attend). Cross-attention never + passes one. + """ + q, k, v = self.compute_qkv(x, context, rope_emb=rope_emb) + return self.compute_attention( + q, k, v, video_size=video_size, kv_cache_cfg=kv_cache_cfg, attn_mask=attn_mask + ) + + def set_context_parallel_group(self, process_group, ranks, stream, cp_comm_type: str = "p2p"): + # self.attn_op.set_context_parallel_group(process_group, ranks, stream, cp_comm_type="a2a") + self.attn_op.set_context_parallel_group(process_group, ranks, stream, cp_comm_type=cp_comm_type) + + +class I2VCrossAttention(Attention): + def __init__(self, *args, img_latent_dim: int = 1024, **kwargs): + super().__init__(*args, **kwargs) + inner_dim = self.head_dim * self.n_heads + self.k_img = nn.Linear(img_latent_dim, inner_dim, bias=False) + self.v_img = nn.Linear(img_latent_dim, inner_dim, bias=False) + self.k_img_norm = te.pytorch.RMSNorm(self.head_dim, eps=1e-6) + + def init_weights(self) -> None: + super().init_weights() + torch.nn.init.trunc_normal_(self.k_img.weight, std=1.0 / math.sqrt(self._inner_dim)) + torch.nn.init.trunc_normal_(self.v_img.weight, std=1.0 / math.sqrt(self._inner_dim)) + self.k_img_norm.reset_parameters() + + def compute_qkv( + self, x, context, rope_emb=None + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + text_context, img_context = context + q, k, v = super().compute_qkv(x, text_context, rope_emb) + k_img = self.k_img(img_context) + v_img = self.v_img(img_context) + # Rearrange k_img, v_img + k_img, v_img = map( + lambda t: rearrange(t, "b ... (h d) -> b ... h d", h=self.n_heads, d=self.head_dim), + (k_img, v_img), + ) + + return q, k, v, self.k_img_norm(k_img), v_img + + def compute_attention(self, q, k, v, k_img, v_img): + result = self.attn_op(q, k, v) # [B, S, H, D] + result_img = self.attn_op(q, k_img, v_img) + return self.output_dropout(self.output_proj(result + result_img)) + + def forward( + self, + x, + context=None, + rope_emb=None, + ): + q, k, v, k_img, v_img = self.compute_qkv(x, context, rope_emb) + return self.compute_attention(q, k, v, k_img, v_img) + + +class VideoPositionEmb(nn.Module): + def __init__(self): + super().__init__() + self._cp_group = None + + def enable_context_parallel(self, process_group: ProcessGroup): + self._cp_group = process_group + + def disable_context_parallel(self): + self._cp_group = None + + @property + def seq_dim(self): + return 1 + + def forward( + self, + x_B_T_H_W_C: torch.Tensor, + fps=Optional[torch.Tensor], + temporal_positions: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """ + With CP, the function assume that the input tensor is already split. + It delegates the embedding generation to generate_embeddings function. + + ``temporal_positions`` (optional, shape ``(T,)``): explicit per-frame + temporal indices for RoPE. When given, the temporal axis is positioned + at these values instead of ``0..T-1`` -- used to align modalities with + different temporal compression rates (e.g. pixel-time of lidar vs RGB + condition frames). Not supported under context parallel. + """ + B_T_H_W_C = x_B_T_H_W_C.shape + if self._cp_group is not None: + assert temporal_positions is None, "temporal_positions not supported with context parallel" + cp_ranks = get_process_group_ranks(self._cp_group) + cp_size = len(cp_ranks) + cp_size_t = cp_size + if USE_MEGATRON and hasattr(parallel_state, "cp_size_t"): + # We saved cp_size_t in find_split function for combined temporal and spatial splitting. + # We need cp_size_t to find out the split values for T and H dimensions for correct embedding calculations. + cp_size_t = parallel_state.cp_size_t + cp_size_h = max(1, cp_size // cp_size_t) + B, T, H, W, C = B_T_H_W_C + B_T_H_W_C = (B, T * cp_size_t, H * cp_size_h, W, C) + embeddings = self.generate_embeddings(B_T_H_W_C, fps=fps, temporal_positions=temporal_positions) + + return self._split_for_context_parallel(embeddings) + + def generate_embeddings(self, B_T_H_W_C: torch.Size, fps=Optional[torch.Tensor], temporal_positions=None): + raise NotImplementedError + + def _split_for_context_parallel(self, embeddings): + if self._cp_group is not None: + embeddings = split_inputs_cp(x=embeddings, seq_dim=self.seq_dim, cp_group=self._cp_group) + return embeddings + + +class VideoRopePosition3DEmb(VideoPositionEmb): + def __init__( + self, + *, # enforce keyword arguments + head_dim: int, + len_h: int, + len_w: int, + len_t: int, + base_fps: int = 24, + h_extrapolation_ratio: float = 1.0, + w_extrapolation_ratio: float = 1.0, + t_extrapolation_ratio: float = 1.0, + h_position_stride: float = 1.0, + w_position_stride: float = 1.0, + enable_fps_modulation: bool = True, + **kwargs, # used for compatibility with other positional embeddings; unused in this class + ): + del kwargs + super().__init__() + self.register_buffer("seq", torch.arange(max(len_h, len_w, len_t), dtype=torch.float)) + self.base_fps = base_fps + self.max_h = len_h + self.max_w = len_w + self.max_t = len_t + self.h_position_stride = float(h_position_stride) + self.w_position_stride = float(w_position_stride) + if self.h_position_stride <= 0 or self.w_position_stride <= 0: + raise ValueError( + "RoPE spatial position strides must be positive, got " + f"{(self.h_position_stride, self.w_position_stride)}" + ) + self.enable_fps_modulation = enable_fps_modulation + dim = head_dim + dim_h = dim // 6 * 2 + dim_w = dim_h + dim_t = dim - 2 * dim_h + assert dim == dim_h + dim_w + dim_t, f"bad dim: {dim} != {dim_h} + {dim_w} + {dim_t}" + # TODO: (qsh 2025-01-04) this is tricky! https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/llama/model.py#L361 + self.register_buffer( + "dim_spatial_range", + torch.arange(0, dim_h, 2)[: (dim_h // 2)].float() / dim_h, + persistent=True, + ) + self.register_buffer( + "dim_temporal_range", + torch.arange(0, dim_t, 2)[: (dim_t // 2)].float() / dim_t, + persistent=True, + ) + self._dim_h = dim_h + self._dim_t = dim_t + + self.h_ntk_factor = h_extrapolation_ratio ** (dim_h / (dim_h - 2)) + self.w_ntk_factor = w_extrapolation_ratio ** (dim_w / (dim_w - 2)) + self.t_ntk_factor = t_extrapolation_ratio ** (dim_t / (dim_t - 2)) + self.reset_parameters() + + def reset_parameters(self) -> None: + dim_h = self._dim_h + dim_t = self._dim_t + + self.seq = torch.arange(max(self.max_h, self.max_w, self.max_t)).float().to(self.dim_spatial_range.device) + self.dim_spatial_range = ( + torch.arange(0, dim_h, 2)[: (dim_h // 2)].float().to(self.dim_spatial_range.device) / dim_h + ) + self.dim_temporal_range = ( + torch.arange(0, dim_t, 2)[: (dim_t // 2)].float().to(self.dim_spatial_range.device) / dim_t + ) + + def generate_embeddings( + self, + B_T_H_W_C: torch.Size, + fps: Optional[torch.Tensor] = None, + h_ntk_factor: Optional[float] = None, + w_ntk_factor: Optional[float] = None, + t_ntk_factor: Optional[float] = None, + temporal_positions: Optional[torch.Tensor] = None, + ): + """ + Generate embeddings for the given input size. + + Args: + B_T_H_W_C (torch.Size): Input tensor size (Batch, Time, Height, Width, Channels). + fps (Optional[torch.Tensor], optional): Frames per second. Defaults to None. + h_ntk_factor (Optional[float], optional): Height NTK factor. If None, uses self.h_ntk_factor. + w_ntk_factor (Optional[float], optional): Width NTK factor. If None, uses self.w_ntk_factor. + t_ntk_factor (Optional[float], optional): Time NTK factor. If None, uses self.t_ntk_factor. + + Returns: + Not specified in the original code snippet. + """ + h_ntk_factor = h_ntk_factor if h_ntk_factor is not None else self.h_ntk_factor + w_ntk_factor = w_ntk_factor if w_ntk_factor is not None else self.w_ntk_factor + t_ntk_factor = t_ntk_factor if t_ntk_factor is not None else self.t_ntk_factor + + h_theta = 10000.0 * h_ntk_factor + w_theta = 10000.0 * w_ntk_factor + t_theta = 10000.0 * t_ntk_factor + + h_spatial_freqs = 1.0 / (h_theta ** self.dim_spatial_range.float()) + w_spatial_freqs = 1.0 / (w_theta ** self.dim_spatial_range.float()) + temporal_freqs = 1.0 / (t_theta ** self.dim_temporal_range.float()) + + B, T, H, W, _ = B_T_H_W_C + assert H <= self.max_h and W <= self.max_w, ( + f"Input dimensions (H={H}, W={W}) exceed the maximum dimensions (max_h={self.max_h}, max_w={self.max_w})" + ) + half_emb_h = torch.outer( + self.seq[:H] * self.h_position_stride, + h_spatial_freqs, + ) + half_emb_w = torch.outer( + self.seq[:W] * self.w_position_stride, + w_spatial_freqs, + ) + + # Explicit per-frame temporal positions (e.g. pixel-time alignment of + # heterogeneous-compression modalities) override the default 0..T-1. + if temporal_positions is not None: + assert temporal_positions.shape[0] == T, ( + f"temporal_positions {tuple(temporal_positions.shape)} must have length T={T}" + ) + t_seq = temporal_positions.to(device=temporal_freqs.device, dtype=temporal_freqs.dtype) + else: + t_seq = self.seq[:T] + + if self.enable_fps_modulation: + uniform_fps = (fps is None) or (fps.min() == fps.max()) + assert uniform_fps or B == 1 or T == 1, ( + "For video batch, batch size should be 1 for non-uniform fps. For image batch, T should be 1" + ) + + # apply sequence scaling in temporal dimension + if fps is None: # image case + assert T == 1, "T should be 1 for image batch." + half_emb_t = torch.outer(t_seq, temporal_freqs) + else: + half_emb_t = torch.outer(t_seq / fps[:1] * self.base_fps, temporal_freqs) + else: + half_emb_t = torch.outer(t_seq, temporal_freqs) + + em_T_H_W_D = torch.cat( + [ + repeat(half_emb_t, "t d -> t h w d", h=H, w=W), + repeat(half_emb_h, "h d -> t h w d", t=T, w=W), + repeat(half_emb_w, "w d -> t h w d", t=T, h=H), + ] + * 2, + dim=-1, + ) + + return rearrange(em_T_H_W_D, "t h w d -> (t h w) 1 1 d").float() + + @property + def seq_dim(self): + return 0 + + +class LearnablePosEmbAxis(VideoPositionEmb): + def __init__( + self, + *, # enforce keyword arguments + interpolation: str, + model_channels: int, + len_h: int, + len_w: int, + len_t: int, + **kwargs, + ): + """ + Args: + interpolation (str): we curretly only support "crop", ideally when we need extrapolation capacity, we should adjust frequency or other more advanced methods. they are not implemented yet. + """ + del kwargs # unused + super().__init__() + self.interpolation = interpolation + assert self.interpolation in ["crop"], f"Unknown interpolation method {self.interpolation}" + self.model_channels = model_channels + + self.pos_emb_h = nn.Parameter(torch.zeros(len_h, model_channels)) + self.pos_emb_w = nn.Parameter(torch.zeros(len_w, model_channels)) + self.pos_emb_t = nn.Parameter(torch.zeros(len_t, model_channels)) + + self.reset_parameters() + + def reset_parameters(self): + std = 1.0 / math.sqrt(self.model_channels) + torch.nn.init.trunc_normal_(self.pos_emb_h, std=std, a=-3 * std, b=3 * std) + torch.nn.init.trunc_normal_(self.pos_emb_w, std=std, a=-3 * std, b=3 * std) + torch.nn.init.trunc_normal_(self.pos_emb_t, std=std, a=-3 * std, b=3 * std) + + def generate_embeddings( + self, B_T_H_W_C: torch.Size, fps=Optional[torch.Tensor], temporal_positions=None + ) -> torch.Tensor: + del temporal_positions # learnable abs pos-emb indexes by crop, no custom positions + B, T, H, W, _ = B_T_H_W_C + if self.interpolation == "crop": + emb_h_H = self.pos_emb_h[:H] + emb_w_W = self.pos_emb_w[:W] + emb_t_T = self.pos_emb_t[:T] + emb = ( + repeat(emb_t_T, "t d-> b t h w d", b=B, h=H, w=W) + + repeat(emb_h_H, "h d-> b t h w d", b=B, t=T, w=W) + + repeat(emb_w_W, "w d-> b t h w d", b=B, t=T, h=H) + ) + assert list(emb.shape)[:4] == [B, T, H, W], f"bad shape: {list(emb.shape)[:4]} != {B, T, H, W}" + else: + raise ValueError(f"Unknown interpolation method {self.interpolation}") + + norm = torch.linalg.vector_norm(emb, dim=-1, keepdim=True, dtype=torch.float32) + norm = torch.add(1e-6, norm, alpha=np.sqrt(norm.numel() / emb.numel())) + return emb / norm.to(emb.dtype) + + +def modulate(x, shift, scale): + return x * (1 + scale) + shift + + +class Timesteps(nn.Module): + def __init__(self, num_channels): + super().__init__() + self.num_channels = num_channels + + def forward(self, timesteps_B_T): + assert timesteps_B_T.ndim == 2, f"Expected 2D input, got {timesteps_B_T.ndim}" + # wan need emb to be in fp32 + in_dtype = timesteps_B_T.dtype + timesteps = timesteps_B_T.flatten().float() + half_dim = self.num_channels // 2 + exponent = -math.log(10000) * torch.arange(half_dim, dtype=torch.float32, device=timesteps.device) + exponent = exponent / (half_dim - 0.0) + + emb = torch.exp(exponent) + emb = timesteps[:, None].float() * emb[None, :] + + sin_emb = torch.sin(emb) + cos_emb = torch.cos(emb) + emb = torch.cat([cos_emb, sin_emb], dim=-1) + + return rearrange(emb.to(dtype=in_dtype), "(b t) d -> b t d", b=timesteps_B_T.shape[0], t=timesteps_B_T.shape[1]) + + +class TimestepEmbedding(nn.Module): + def __init__(self, in_features: int, out_features: int, use_adaln_lora: bool = False): + super().__init__() + log.debug( + f"Using AdaLN LoRA Flag: {use_adaln_lora}. We enable bias if no AdaLN LoRA for backward compatibility." + ) + self.in_dim = in_features + self.out_dim = out_features + self.linear_1 = nn.Linear(in_features, out_features, bias=not use_adaln_lora) + self.activation = nn.SiLU() + self.use_adaln_lora = use_adaln_lora + if use_adaln_lora: + self.linear_2 = nn.Linear(out_features, 3 * out_features, bias=False) + else: + self.linear_2 = nn.Linear(out_features, out_features, bias=False) + + self.init_weights() + + def init_weights(self) -> None: + std = 1.0 / math.sqrt(self.in_dim) + torch.nn.init.trunc_normal_(self.linear_1.weight, std=std, a=-3 * std, b=3 * std) + + std = 1.0 / math.sqrt(self.out_dim) + torch.nn.init.trunc_normal_(self.linear_2.weight, std=std, a=-3 * std, b=3 * std) + + def forward(self, sample: torch.Tensor) -> torch.Tensor: + emb = self.linear_1(sample) + emb = self.activation(emb) + emb = self.linear_2(emb) + + if self.use_adaln_lora: + adaln_lora_B_T_3D = emb + emb_B_T_D = sample + else: + emb_B_T_D = emb + adaln_lora_B_T_3D = None + + return emb_B_T_D, adaln_lora_B_T_3D + + +class FourierFeatures(nn.Module): + """ + Implements a layer that generates Fourier features from input tensors, based on randomly sampled + frequencies and phases. This can help in learning high-frequency functions in low-dimensional problems. + + [B] -> [B, D] + + Parameters: + num_channels (int): The number of Fourier features to generate. + bandwidth (float, optional): The scaling factor for the frequency of the Fourier features. Defaults to 1. + normalize (bool, optional): If set to True, the outputs are scaled by sqrt(2), usually to normalize + the variance of the features. Defaults to False. + + Example: + >>> layer = FourierFeatures(num_channels=256, bandwidth=0.5, normalize=True) + >>> x = torch.randn(10, 256) # Example input tensor + >>> output = layer(x) + >>> print(output.shape) # Expected shape: (10, 256) + """ + + def __init__(self, num_channels, bandwidth=1, normalize=False): + super().__init__() + self.register_buffer("freqs", 2 * np.pi * bandwidth * torch.randn(num_channels), persistent=True) + self.register_buffer("phases", 2 * np.pi * torch.rand(num_channels), persistent=True) + self.gain = np.sqrt(2) if normalize else 1 + self.bandwidth = bandwidth + self.num_channels = num_channels + + self.reset_parameters() + + def reset_parameters(self) -> None: + generator = torch.Generator() + generator.manual_seed(0) + self.freqs = ( + 2 * np.pi * self.bandwidth * torch.randn(self.num_channels, generator=generator).to(self.freqs.device) + ) + self.phases = 2 * np.pi * torch.rand(self.num_channels, generator=generator).to(self.freqs.device) + + def forward(self, x, gain: float = 1.0): + """ + Apply the Fourier feature transformation to the input tensor. + + Args: + x (torch.Tensor): The input tensor. + gain (float, optional): An additional gain factor applied during the forward pass. Defaults to 1. + + Returns: + torch.Tensor: The transformed tensor, with Fourier features applied. + """ + in_dtype = x.dtype + x = x.to(torch.float32).ger(self.freqs.to(torch.float32)).add(self.phases.to(torch.float32)) + x = x.cos().mul(self.gain * gain).to(in_dtype) + return x + + +def _spatial_pair(value, name: str) -> Tuple[int, int]: + """Normalize a scalar or ``(height, width)`` spatial setting.""" + if isinstance(value, int): + pair = (value, value) + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + if len(value) != 2: + raise ValueError(f"{name} must have two entries, got {value!r}") + pair = (int(value[0]), int(value[1])) + else: + raise TypeError(f"{name} must be an int or length-2 sequence, got {value!r}") + if pair[0] <= 0 or pair[1] <= 0: + raise ValueError(f"{name} entries must be positive, got {pair}") + return pair + + +class PatchEmbed(nn.Module): + """ + PatchEmbed is a module for embedding patches from an input tensor by applying either 3D or 2D convolutional layers, + depending on the . This module can process inputs with temporal (video) and spatial (image) dimensions, + making it suitable for video and image processing tasks. It supports dividing the input into patches + and embedding each patch into a vector of size `out_channels`. + + Parameters: + - spatial_patch_size (int | tuple[int, int]): Spatial patch height/width. + - temporal_patch_size (int): The size of each temporal patch. + - in_channels (int): Number of input channels. Default: 3. + - out_channels (int): The dimension of the embedding vector for each patch. Default: 768. + - bias (bool): If True, adds a learnable bias to the output of the convolutional layers. Default: True. + """ + + def __init__( + self, + spatial_patch_size, + temporal_patch_size, + in_channels=3, + out_channels=768, + ): + super().__init__() + self.spatial_patch_size = spatial_patch_size + self.patch_h, self.patch_w = _spatial_pair( + spatial_patch_size, "spatial_patch_size" + ) + self.temporal_patch_size = temporal_patch_size + + self.proj = nn.Sequential( + Rearrange( + "b c (t r) (h m) (w n) -> b t h w (c r m n)", + r=temporal_patch_size, + m=self.patch_h, + n=self.patch_w, + ), + nn.Linear( + in_channels + * self.patch_h + * self.patch_w + * temporal_patch_size, + out_channels, + bias=False, + ), + ) + self.dim = ( + in_channels * self.patch_h * self.patch_w * temporal_patch_size + ) + + self.init_weights() + + def init_weights(self) -> None: + std = 1.0 / math.sqrt(self.dim) + torch.nn.init.trunc_normal_(self.proj[1].weight, std=std, a=-3 * std, b=3 * std) + + def forward(self, x): + """ + Forward pass of the PatchEmbed module. + + Parameters: + - x (torch.Tensor): The input tensor of shape (B, C, T, H, W) where + B is the batch size, + C is the number of channels, + T is the temporal dimension, + H is the height, and + W is the width of the input. + + Returns: + - torch.Tensor: The embedded patches as a tensor, with shape b t h w c. + """ + assert x.dim() == 5 + _, _, T, H, W = x.shape + assert H % self.patch_h == 0 and W % self.patch_w == 0, ( + f"H,W {(H, W)} should be divisible by spatial patch " + f"{(self.patch_h, self.patch_w)}" + ) + assert T % self.temporal_patch_size == 0 + x = self.proj(x) + return x + + +class FinalLayer(nn.Module): + """ + The final layer of video DiT. + """ + + def __init__( + self, + hidden_size, + spatial_patch_size, + temporal_patch_size, + out_channels, + use_adaln_lora: bool = False, + adaln_lora_dim: int = 256, + use_wan_fp32_strategy: bool = False, + ): + super().__init__() + self.use_wan_fp32_strategy = use_wan_fp32_strategy + self.patch_h, self.patch_w = _spatial_pair( + spatial_patch_size, "spatial_patch_size" + ) + self.layer_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.linear = nn.Linear( + hidden_size, + self.patch_h + * self.patch_w + * temporal_patch_size + * out_channels, + bias=False, + ) + self.hidden_size = hidden_size + self.n_adaln_chunks = 2 + self.use_adaln_lora = use_adaln_lora + self.adaln_lora_dim = adaln_lora_dim + if use_adaln_lora: + self.adaln_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, adaln_lora_dim, bias=False), + nn.Linear(adaln_lora_dim, self.n_adaln_chunks * hidden_size, bias=False), + ) + else: + self.adaln_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(hidden_size, self.n_adaln_chunks * hidden_size, bias=False) + ) + + self.init_weights() + + def init_weights(self) -> None: + std = 1.0 / math.sqrt(self.hidden_size) + torch.nn.init.trunc_normal_(self.linear.weight, std=std, a=-3 * std, b=3 * std) + if self.use_adaln_lora: + torch.nn.init.trunc_normal_(self.adaln_modulation[1].weight, std=std, a=-3 * std, b=3 * std) + torch.nn.init.zeros_(self.adaln_modulation[2].weight) + else: + torch.nn.init.zeros_(self.adaln_modulation[1].weight) + + self.layer_norm.reset_parameters() + + def forward( + self, + # x_BT_HW_D, + x_B_T_H_W_D, + emb_B_T_D, + adaln_lora_B_T_3D: Optional[torch.Tensor] = None, + ): + if self.use_wan_fp32_strategy: + assert emb_B_T_D.dtype == torch.float32 + with amp.autocast("cuda", enabled=self.use_wan_fp32_strategy, dtype=torch.float32): + if self.use_adaln_lora: + assert adaln_lora_B_T_3D is not None + shift_B_T_D, scale_B_T_D = ( + self.adaln_modulation(emb_B_T_D) + adaln_lora_B_T_3D[:, :, : 2 * self.hidden_size] + ).chunk(2, dim=-1) + else: + shift_B_T_D, scale_B_T_D = self.adaln_modulation(emb_B_T_D).chunk(2, dim=-1) + + shift_B_T_1_1_D, scale_B_T_1_1_D = ( + rearrange(shift_B_T_D, "b t d -> b t 1 1 d"), + rearrange(scale_B_T_D, "b t d -> b t 1 1 d"), + ) + + def _fn(_x_B_T_H_W_D, _norm_layer, _scale_B_T_1_1_D, _shift_B_T_1_1_D): + return _norm_layer(_x_B_T_H_W_D) * (1 + _scale_B_T_1_1_D) + _shift_B_T_1_1_D + + x_B_T_H_W_D = _fn(x_B_T_H_W_D, self.layer_norm, scale_B_T_1_1_D, shift_B_T_1_1_D) + x_B_T_H_W_O = self.linear( + x_B_T_H_W_D + ) # O = patch_h * patch_w * temporal_patch_size * out_channels + return x_B_T_H_W_O + + +class Block(nn.Module): + """ + A transformer block that combines self-attention, cross-attention and MLP layers with AdaLN modulation. + Each component (self-attention, cross-attention, MLP) has its own layer normalization and AdaLN modulation. + + Parameters: + x_dim (int): Dimension of input features + context_dim (int): Dimension of context features for cross-attention + num_heads (int): Number of attention heads + mlp_ratio (float): Multiplier for MLP hidden dimension. Default: 4.0 + use_adaln_lora (bool): Whether to use AdaLN-LoRA modulation. Default: False + adaln_lora_dim (int): Hidden dimension for AdaLN-LoRA layers. Default: 256 + use_wan_fp32_strategy (bool): Whether to use Wan's FP32 strategy. Default: False + If True, in Attention layer, if do self-attention, q and k will be forced to fp32 before rotary pos emb + also, in modulation computation, force entire computation in fp32 + + The block applies the following sequence: + 1. Self-attention with AdaLN modulation + 2. Cross-attention with AdaLN modulation + 3. MLP with AdaLN modulation + + Each component uses skip connections and layer normalization. + """ + + def __init__( + self, + x_dim: int, + context_dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + use_adaln_lora: bool = False, + adaln_lora_dim: int = 256, + backend: str = "transformer_engine", + image_context_dim: Optional[int] = None, + use_wan_fp32_strategy: bool = False, + ): + super().__init__() + self.x_dim = x_dim + self.layer_norm_self_attn = nn.LayerNorm(x_dim, elementwise_affine=False, eps=1e-6) + self.self_attn = Attention( + x_dim, + None, + num_heads, + x_dim // num_heads, + qkv_format="bshd", + backend=backend, + use_wan_fp32_strategy=use_wan_fp32_strategy, + ) + + self.layer_norm_cross_attn = nn.LayerNorm(x_dim, elementwise_affine=False, eps=1e-6) + + if image_context_dim is None: + self.cross_attn = Attention( + x_dim, context_dim, num_heads, x_dim // num_heads, qkv_format="bshd", backend=backend + ) + else: + self.cross_attn = I2VCrossAttention( + x_dim, + context_dim, + num_heads, + x_dim // num_heads, + img_latent_dim=image_context_dim, + qkv_format="bshd", + backend=backend, + ) + + self.layer_norm_mlp = nn.LayerNorm(x_dim, elementwise_affine=False, eps=1e-6) + self.mlp = GPT2FeedForward(x_dim, int(x_dim * mlp_ratio)) + + self.use_adaln_lora = use_adaln_lora + if self.use_adaln_lora: + self.adaln_modulation_self_attn = nn.Sequential( + nn.SiLU(), + nn.Linear(x_dim, adaln_lora_dim, bias=False), + nn.Linear(adaln_lora_dim, 3 * x_dim, bias=False), + ) + self.adaln_modulation_cross_attn = nn.Sequential( + nn.SiLU(), + nn.Linear(x_dim, adaln_lora_dim, bias=False), + nn.Linear(adaln_lora_dim, 3 * x_dim, bias=False), + ) + self.adaln_modulation_mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(x_dim, adaln_lora_dim, bias=False), + nn.Linear(adaln_lora_dim, 3 * x_dim, bias=False), + ) + else: + self.adaln_modulation_self_attn = nn.Sequential(nn.SiLU(), nn.Linear(x_dim, 3 * x_dim, bias=False)) + self.adaln_modulation_cross_attn = nn.Sequential(nn.SiLU(), nn.Linear(x_dim, 3 * x_dim, bias=False)) + self.adaln_modulation_mlp = nn.Sequential(nn.SiLU(), nn.Linear(x_dim, 3 * x_dim, bias=False)) + + self.cp_size = None + self.use_wan_fp32_strategy = use_wan_fp32_strategy + # Inference-only optimization enabled by MiniTrainDIT after it verifies + # that the text context is exactly zero. Keep all modules/parameters so + # existing checkpoints remain strictly load-compatible. + self.skip_crossattn = False + + def set_context_parallel_group(self, process_group, ranks, stream, cp_comm_type: str = "p2p"): + self.cp_size = None if ranks is None else len(ranks) + self.self_attn.set_context_parallel_group( + process_group=process_group, + ranks=ranks, + stream=stream, + cp_comm_type=cp_comm_type, + ) + + def reset_parameters(self) -> None: + self.layer_norm_self_attn.reset_parameters() + self.layer_norm_cross_attn.reset_parameters() + self.layer_norm_mlp.reset_parameters() + + if self.use_adaln_lora: + std = 1.0 / math.sqrt(self.x_dim) + torch.nn.init.trunc_normal_(self.adaln_modulation_self_attn[1].weight, std=std, a=-3 * std, b=3 * std) + torch.nn.init.trunc_normal_(self.adaln_modulation_cross_attn[1].weight, std=std, a=-3 * std, b=3 * std) + torch.nn.init.trunc_normal_(self.adaln_modulation_mlp[1].weight, std=std, a=-3 * std, b=3 * std) + torch.nn.init.zeros_(self.adaln_modulation_self_attn[2].weight) + torch.nn.init.zeros_(self.adaln_modulation_cross_attn[2].weight) + torch.nn.init.zeros_(self.adaln_modulation_mlp[2].weight) + else: + torch.nn.init.zeros_(self.adaln_modulation_self_attn[1].weight) + torch.nn.init.zeros_(self.adaln_modulation_cross_attn[1].weight) + torch.nn.init.zeros_(self.adaln_modulation_mlp[1].weight) + + def init_weights(self) -> None: + self.reset_parameters() + self.self_attn.init_weights() + self.cross_attn.init_weights() + self.mlp.init_weights() + + def forward( + self, + x_B_T_H_W_D: torch.Tensor, + emb_B_T_D: torch.Tensor, + crossattn_emb: torch.Tensor, + rope_emb_L_1_1_D: Optional[torch.Tensor] = None, + adaln_lora_B_T_3D: Optional[torch.Tensor] = None, + extra_per_block_pos_emb: Optional[torch.Tensor] = None, + kv_cache_cfg: Optional[KVCacheConfig] = None, + self_attn_mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + if extra_per_block_pos_emb is not None: + x_B_T_H_W_D = x_B_T_H_W_D + extra_per_block_pos_emb + + with amp.autocast("cuda", enabled=self.use_wan_fp32_strategy, dtype=torch.float32): + if self.use_adaln_lora: + shift_self_attn_B_T_D, scale_self_attn_B_T_D, gate_self_attn_B_T_D = ( + self.adaln_modulation_self_attn(emb_B_T_D) + adaln_lora_B_T_3D + ).chunk(3, dim=-1) + shift_cross_attn_B_T_D, scale_cross_attn_B_T_D, gate_cross_attn_B_T_D = ( + self.adaln_modulation_cross_attn(emb_B_T_D) + adaln_lora_B_T_3D + ).chunk(3, dim=-1) + shift_mlp_B_T_D, scale_mlp_B_T_D, gate_mlp_B_T_D = ( + self.adaln_modulation_mlp(emb_B_T_D) + adaln_lora_B_T_3D + ).chunk(3, dim=-1) + else: + shift_self_attn_B_T_D, scale_self_attn_B_T_D, gate_self_attn_B_T_D = self.adaln_modulation_self_attn( + emb_B_T_D + ).chunk(3, dim=-1) + shift_cross_attn_B_T_D, scale_cross_attn_B_T_D, gate_cross_attn_B_T_D = ( + self.adaln_modulation_cross_attn(emb_B_T_D).chunk(3, dim=-1) + ) + shift_mlp_B_T_D, scale_mlp_B_T_D, gate_mlp_B_T_D = self.adaln_modulation_mlp(emb_B_T_D).chunk(3, dim=-1) + + # Reshape tensors from (B, T, D) to (B, T, 1, 1, D) for broadcasting + shift_self_attn_B_T_1_1_D = rearrange(shift_self_attn_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + scale_self_attn_B_T_1_1_D = rearrange(scale_self_attn_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + gate_self_attn_B_T_1_1_D = rearrange(gate_self_attn_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + + shift_cross_attn_B_T_1_1_D = rearrange(shift_cross_attn_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + scale_cross_attn_B_T_1_1_D = rearrange(scale_cross_attn_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + gate_cross_attn_B_T_1_1_D = rearrange(gate_cross_attn_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + + shift_mlp_B_T_1_1_D = rearrange(shift_mlp_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + scale_mlp_B_T_1_1_D = rearrange(scale_mlp_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + gate_mlp_B_T_1_1_D = rearrange(gate_mlp_B_T_D, "b t d -> b t 1 1 d").type_as(x_B_T_H_W_D) + + B, T, H, W, D = x_B_T_H_W_D.shape + + def _fn(_x_B_T_H_W_D, _norm_layer, _scale_B_T_1_1_D, _shift_B_T_1_1_D): + return _norm_layer(_x_B_T_H_W_D) * (1 + _scale_B_T_1_1_D) + _shift_B_T_1_1_D + + normalized_x_B_T_H_W_D = _fn( + x_B_T_H_W_D, + self.layer_norm_self_attn, + scale_self_attn_B_T_1_1_D, + shift_self_attn_B_T_1_1_D, + ) + + video_size = VideoSize(T=T, H=H, W=W) + + # (ahassani): Hack to correct `video_size` when CP is enabled. + # I really don't like this, but there doesn't seem to be any central + # piece of code that's responsible for handling CP/TP that also defines the + # layout of shardings. Other parts of the code (i.e. RoPE) seem to make this + # assumption that CP sharding is always done along T. + if self.cp_size is not None and self.cp_size > 1: + video_size = VideoSize(T=T * self.cp_size, H=H, W=W) + + result_B_T_H_W_D = rearrange( + self.self_attn( + # normalized_x_B_T_HW_D, + rearrange(normalized_x_B_T_H_W_D, "b t h w d -> b (t h w) d"), + None, + rope_emb=rope_emb_L_1_1_D, + video_size=video_size, + kv_cache_cfg=kv_cache_cfg, + attn_mask=self_attn_mask, + ), + "b (t h w) d -> b t h w d", + t=T, + h=H, + w=W, + ) + x_B_T_H_W_D = x_B_T_H_W_D + gate_self_attn_B_T_1_1_D * result_B_T_H_W_D + + def _x_fn( + _x_B_T_H_W_D, + layer_norm_cross_attn, + _scale_cross_attn_B_T_1_1_D, + _shift_cross_attn_B_T_1_1_D, + _gate_cross_attn_B_T_1_1_D, + ): + _normalized_x_B_T_H_W_D = _fn( + _x_B_T_H_W_D, layer_norm_cross_attn, _scale_cross_attn_B_T_1_1_D, _shift_cross_attn_B_T_1_1_D + ) + _result_B_T_H_W_D = rearrange( + self.cross_attn( + rearrange(_normalized_x_B_T_H_W_D, "b t h w d -> b (t h w) d"), + crossattn_emb, + rope_emb=rope_emb_L_1_1_D, + ), + "b (t h w) d -> b t h w d", + t=T, + h=H, + w=W, + ) + # _x_B_T_H_W_D = _x_B_T_H_W_D + _gate_cross_attn_B_T_1_1_D * _result_B_T_H_W_D + return _result_B_T_H_W_D + + if not self.skip_crossattn: + result_B_T_H_W_D = _x_fn( + x_B_T_H_W_D, + self.layer_norm_cross_attn, + scale_cross_attn_B_T_1_1_D, + shift_cross_attn_B_T_1_1_D, + gate_cross_attn_B_T_1_1_D, + ) + x_B_T_H_W_D = ( + result_B_T_H_W_D * gate_cross_attn_B_T_1_1_D + + x_B_T_H_W_D + ) + + normalized_x_B_T_H_W_D = _fn( + x_B_T_H_W_D, + self.layer_norm_mlp, + scale_mlp_B_T_1_1_D, + shift_mlp_B_T_1_1_D, + ) + result_B_T_H_W_D = self.mlp(normalized_x_B_T_H_W_D) + x_B_T_H_W_D = x_B_T_H_W_D + gate_mlp_B_T_1_1_D * result_B_T_H_W_D + return x_B_T_H_W_D + + +class MiniTrainDIT(WeightTrainingStat): + """ + A clean impl of DIT that can load and reproduce the training results of the original DIT model in edify_video/v4~(cosmos 1) + A general implementation of adaln-modulated VIT-like~(DiT) transformer for video processing. + + Args: + max_img_h (int): Maximum height of the input images. + max_img_w (int): Maximum width of the input images. + max_frames (int): Maximum number of frames in the video sequence. + in_channels (int): Number of input channels (e.g., RGB channels for color images). + out_channels (int): Number of output channels. + patch_spatial (int | tuple[int, int]): Spatial patch height/width. + patch_temporal (int): Temporal resolution of patches for input processing. + concat_padding_mask (bool): If True, includes a mask channel in the input to handle padding. + model_channels (int): Base number of channels used throughout the model. + num_blocks (int): Number of transformer blocks. + num_heads (int): Number of heads in the multi-head attention layers. + mlp_ratio (float): Expansion ratio for MLP blocks. + crossattn_emb_channels (int): Number of embedding channels for cross-attention. + extra_image_context_dim (int): Number of embedding channels for extra image context. + pos_emb_cls (str): Type of positional embeddings. + pos_emb_learnable (bool): Whether positional embeddings are learnable. + pos_emb_interpolation (str): Method for interpolating positional embeddings. + min_fps (int): Minimum frames per second. + max_fps (int): Maximum frames per second. + use_adaln_lora (bool): Whether to use AdaLN-LoRA. + adaln_lora_dim (int): Dimension for AdaLN-LoRA. + rope_h_extrapolation_ratio (float): Height extrapolation ratio for RoPE. + rope_w_extrapolation_ratio (float): Width extrapolation ratio for RoPE. + rope_t_extrapolation_ratio (float): Temporal extrapolation ratio for RoPE. + extra_per_block_abs_pos_emb (bool): Whether to use extra per-block absolute positional embeddings. + extra_h_extrapolation_ratio (float): Height extrapolation ratio for extra embeddings. + extra_w_extrapolation_ratio (float): Width extrapolation ratio for extra embeddings. + extra_t_extrapolation_ratio (float): Temporal extrapolation ratio for extra embeddings. + n_dense_blocks (`int`, *optional*, defaults to -1): + Number of blocks that will remain dense (not replaced with sparse attention) + If -1, no blocks are replaced with sparse attention + If 0, all blocks use sparse attention + Otherwise, n_dense_blocks blocks will remain dense, distributed evenly across the network + natten_parameters (`dict`, *optional*, defaults to None): + NATTEN (Sparse attention) parameter list. + The list length must be the same as the number of layers, with each list element + indicating NATTEN parameters for that layer. If None, NATTEN will not be used in that + layer and it would remain a full dense self attention. If not None, it must be a + dictionary/mapping with at least the following key: + - window_size: `tuple` of size 3 indicating neighborhood attention window size. + window size of -1 along any dimension means self attention. + Other optional parameters and their keys: + - stride: `tuple` of size 3 indicating neighborhood attention stride value. + stride = 1 is standard neighborhood attention, stride = window size means + blocked/window self attention (WSA) along that dimension. Any other values are + strided neighborhood attention. Refer to the GNA paper for more information. + + - dilation: `tuple` of size 3 indicating neighborhood attention dilation value. + dilation = 1 is standard neighborhood attention. Refer to the DiNAT paper for more + information. + + - is_causal: `tuple` of 3 booleans indicating whether causal masking is enabled for + any of the T, H, W dimensions. + """ + + def __init__( + self, + max_img_h: int, + max_img_w: int, + max_frames: int, + in_channels: int, + out_channels: int, + patch_spatial: Union[int, Tuple[int, int]], + patch_temporal: int, + concat_padding_mask: bool = True, + # attention settings + model_channels: int = 768, + num_blocks: int = 10, + num_heads: int = 16, + mlp_ratio: float = 4.0, + atten_backend: str = "transformer_engine", + # cross attention settings + crossattn_emb_channels: int = 1024, + use_crossattn_projection: bool = False, + crossattn_proj_in_channels: int = 1024, + extra_image_context_dim: Optional[int] = None, + # Learnable positional embeddings ADDED to the projected image-context + # tokens (only used when ``extra_image_context_dim`` is set AND + # ``img_context_num_views > 0``). They let RGB K/V tokens carry their + # view id, pixel-time (soft temporal alignment) and (h, w) spatial + # location so cross-attention can localize the condition without a + # shared canvas. Sizes = table extents; ``forward`` takes + # ``img_context_pos`` (N, 4) = [view, pixel_time, h, w] per token. + img_context_num_views: int = 0, + img_context_max_temporal: int = 0, + img_context_spatial_h: int = 0, + img_context_spatial_w: int = 0, + # positional embedding settings + pos_emb_cls: str = "sincos", + pos_emb_learnable: bool = False, + pos_emb_interpolation: str = "crop", + min_fps: int = 1, + max_fps: int = 30, + use_adaln_lora: bool = False, + adaln_lora_dim: int = 256, + rope_h_extrapolation_ratio: float = 1.0, + rope_w_extrapolation_ratio: float = 1.0, + rope_t_extrapolation_ratio: float = 1.0, + rope_scale_positions_by_patch: bool = False, + extra_per_block_abs_pos_emb: bool = False, + extra_h_extrapolation_ratio: float = 1.0, + extra_w_extrapolation_ratio: float = 1.0, + extra_t_extrapolation_ratio: float = 1.0, + rope_enable_fps_modulation: bool = True, + sac_config: SACConfig = SACConfig(), + n_dense_blocks: int = -1, + natten_parameters: Union[dict, list] = None, + # if True, will closely match wan's strategy to use fp32 in certain layers/operations + use_wan_fp32_strategy: bool = False, + # Optional independently projected latent condition. Its PatchEmbed has + # the same output shape as x_embedder and is zero-initialized before + # being added, preserving warm-start behavior exactly at iteration 0. + side_condition_channels: int = 0, + # Block-causal temporal self-attention. 0 preserves full bidirectional + # attention. A positive value groups that many latent frames into one + # block: queries attend to their own block and all earlier blocks, never + # later blocks. This is mask-only (no parameters), so bidirectional + # checkpoints remain strictly load-compatible. Requires torch-flex. + temporal_block_size: int = 0, + # Optional clean prefix before temporal blocks. Prefix frames attend + # bidirectionally within the prefix; later frames are partitioned into + # ``temporal_block_size`` blocks and attend to the prefix plus current + # and earlier future blocks. 0 preserves the legacy modulo-T blocks. + temporal_prefix_frames: int = 0, + # Number of learnable, ZERO-INIT per-frame "type" embeddings (e.g. lidar + # vs RGB view-0/1/2). 0 disables the module entirely (bit-identical to + # before). When >0, ``forward`` accepts ``frame_type_ids`` (T,) and adds + # the corresponding embedding to every token of that frame. Zero-init => + # no-op at iter 0, so a warm-start checkpoint loads unchanged. + num_frame_type_embeddings: int = 0, + # Optional global sensor-dataset identity. The selected zero-initialized + # embedding is added to the AdaLN timestep embedding for every frame, + # giving all transformer blocks a categorical sensor-domain signal + # without spending spatial tokens or introducing an ordinal channel. + num_dataset_embeddings: int = 0, + # Copilot4D-style per-frame ego-pose conditioning. 0 disables the module + # entirely (bit-identical to before). When >0 (e.g. 16 = flattened 4x4 + # SE(3)), ``forward`` accepts ``ego_pose_B_T_P`` (B, T, ego_pose_dim) and + # a zero-init MLP head maps it to a per-frame embedding ADDED to the AdaLN + # timestep embedding. Living inside the network (not the model wrapper) + # means it is optimized / EMA'd / checkpointed / FSDP-sharded like every + # other parameter. Zero-init output => no-op at iter 0. + ego_pose_dim: int = 0, + ) -> None: + super().__init__() + self.num_frame_type_embeddings = num_frame_type_embeddings + self.num_dataset_embeddings = int(num_dataset_embeddings) + if self.num_dataset_embeddings < 0: + raise ValueError( + "num_dataset_embeddings must be non-negative, got " + f"{self.num_dataset_embeddings}" + ) + self.ego_pose_dim = ego_pose_dim + self.max_img_h = max_img_h + self.max_img_w = max_img_w + self.max_frames = max_frames + self.in_channels = in_channels + self.out_channels = out_channels + self.patch_spatial = patch_spatial + self.patch_spatial_h, self.patch_spatial_w = _spatial_pair( + patch_spatial, "patch_spatial" + ) + self.patch_temporal = patch_temporal + self.num_heads = num_heads + self.num_blocks = num_blocks + self.model_channels = model_channels + self.concat_padding_mask = concat_padding_mask + self.atten_backend = atten_backend + self.side_condition_channels = int(side_condition_channels) + assert self.side_condition_channels >= 0, ( + "side_condition_channels must be non-negative, got " + f"{self.side_condition_channels}" + ) + self.temporal_block_size = int(temporal_block_size) + assert self.temporal_block_size >= 0, ( + f"temporal_block_size must be >= 0, got {self.temporal_block_size}" + ) + self.temporal_prefix_frames = int(temporal_prefix_frames) + assert self.temporal_prefix_frames >= 0, ( + "temporal_prefix_frames must be >= 0, got " + f"{self.temporal_prefix_frames}" + ) + if self.temporal_prefix_frames > 0 and self.temporal_block_size <= 0: + raise ValueError( + "temporal_prefix_frames requires temporal_block_size > 0" + ) + if self.temporal_block_size > 0: + assert self.atten_backend == "torch-flex", ( + "temporal block-causal attention requires " + f"atten_backend='torch-flex', got {self.atten_backend!r}" + ) + if ( + self.atten_backend == "torch-flex" + and str(sac_config.mode) not in ( + str(CheckpointMode.NONE), + str(CheckpointMode.BLOCK_WISE), + ) + ): + raise ValueError( + "torch-flex is incompatible with selective activation " + "checkpoint caching; use sac_config.mode='block_wise' for " + "ordinary full-block checkpointing, or 'none' to disable it" + ) + # positional embedding settings + self.pos_emb_cls = pos_emb_cls + self.pos_emb_learnable = pos_emb_learnable + self.pos_emb_interpolation = pos_emb_interpolation + self.min_fps = min_fps + self.max_fps = max_fps + self.rope_h_extrapolation_ratio = rope_h_extrapolation_ratio + self.rope_w_extrapolation_ratio = rope_w_extrapolation_ratio + self.rope_t_extrapolation_ratio = rope_t_extrapolation_ratio + self.rope_scale_positions_by_patch = bool( + rope_scale_positions_by_patch + ) + self.extra_per_block_abs_pos_emb = extra_per_block_abs_pos_emb + self.extra_h_extrapolation_ratio = extra_h_extrapolation_ratio + self.extra_w_extrapolation_ratio = extra_w_extrapolation_ratio + self.extra_t_extrapolation_ratio = extra_t_extrapolation_ratio + self.rope_enable_fps_modulation = rope_enable_fps_modulation + self.extra_image_context_dim = extra_image_context_dim + self.build_patch_embed() + self.build_pos_embed() + self.use_adaln_lora = use_adaln_lora + self.adaln_lora_dim = adaln_lora_dim + self.t_embedder = nn.Sequential( + Timesteps(model_channels), + TimestepEmbedding(model_channels, model_channels, use_adaln_lora=use_adaln_lora), + ) + # Copilot4D ego-pose head: flattened SE(3) (ego_pose_dim) -> Linear -> + # LayerNorm -> Linear -> model_channels. Final linear ZERO-INIT so the + # pose embedding is exactly 0 at iter 0 (warm-start-safe additive residual + # on the AdaLN timestep embedding). Only built when ego_pose_dim > 0. + if self.ego_pose_dim > 0: + self.ego_pose_head = nn.Sequential( + nn.Linear(self.ego_pose_dim, model_channels), + nn.LayerNorm(model_channels), + nn.Linear(model_channels, model_channels), + ) + nn.init.zeros_(self.ego_pose_head[-1].weight) + nn.init.zeros_(self.ego_pose_head[-1].bias) + self.use_crossattn_projection = use_crossattn_projection + self.crossattn_proj_in_channels = crossattn_proj_in_channels + self.use_wan_fp32_strategy = use_wan_fp32_strategy + self.skip_crossattn_when_zero = False + self._zero_crossattn_validated = False + self._cached_inference_self_attention_backend = "flex" + + self.blocks = nn.ModuleList( + [ + Block( + x_dim=model_channels, + context_dim=crossattn_emb_channels, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + use_adaln_lora=use_adaln_lora, + adaln_lora_dim=adaln_lora_dim, + backend=atten_backend, + image_context_dim=None if extra_image_context_dim is None else model_channels, + use_wan_fp32_strategy=use_wan_fp32_strategy, + ) + for _ in range(num_blocks) + ] + ) + + self.final_layer = FinalLayer( + hidden_size=self.model_channels, + spatial_patch_size=self.patch_spatial, + temporal_patch_size=self.patch_temporal, + out_channels=self.out_channels, + use_adaln_lora=self.use_adaln_lora, + adaln_lora_dim=self.adaln_lora_dim, + use_wan_fp32_strategy=self.use_wan_fp32_strategy, + ) + + self.t_embedding_norm = te.pytorch.RMSNorm(model_channels, eps=1e-6) + if extra_image_context_dim is not None: + self.img_context_proj = nn.Sequential( + nn.Linear( + extra_image_context_dim, model_channels, bias=True + ), # help distinguish between image and video context + nn.GELU(), + ) + + # Learnable positional embeddings for the image-context tokens. + self.use_img_context_pos_emb = ( + extra_image_context_dim is not None and img_context_num_views > 0 + ) + if self.use_img_context_pos_emb: + self.img_view_embed = nn.Embedding(img_context_num_views, model_channels) + self.img_time_embed = nn.Embedding(img_context_max_temporal, model_channels) + self.img_h_embed = nn.Embedding(img_context_spatial_h, model_channels) + self.img_w_embed = nn.Embedding(img_context_spatial_w, model_channels) + + if use_crossattn_projection: + self.crossattn_proj = nn.Sequential( + nn.Linear(crossattn_proj_in_channels, crossattn_emb_channels, bias=True), + nn.GELU(), + ) + + if self.num_frame_type_embeddings > 0: + self.frame_type_embed = nn.Embedding(self.num_frame_type_embeddings, model_channels) + if self.num_dataset_embeddings > 0: + self.dataset_embed = nn.Embedding( + self.num_dataset_embeddings, model_channels + ) + + self.init_weights() + self.enable_selective_checkpoint(sac_config, self.blocks) + + # Replace self-attention with sparse attention if specified + if n_dense_blocks != -1: + self = replace_selfattn_op_with_sparse_attn_op(self, n_dense_blocks, natten_parameters=natten_parameters) + + self._is_context_parallel_enabled = False + + def init_weights(self): + self.x_embedder.init_weights() + if self.side_condition_channels > 0: + torch.nn.init.zeros_(self.side_condition_embedder.proj[1].weight) + self.pos_embedder.reset_parameters() + if self.extra_per_block_abs_pos_emb: + self.extra_pos_embedder.reset_parameters() + + self.t_embedder[1].init_weights() + for block in self.blocks: + block.init_weights() + + self.final_layer.init_weights() + self.t_embedding_norm.reset_parameters() + + if self.extra_image_context_dim is not None: + self.img_context_proj[0].reset_parameters() + + if getattr(self, "use_img_context_pos_emb", False): + for emb in ( + self.img_view_embed, + self.img_time_embed, + self.img_h_embed, + self.img_w_embed, + ): + torch.nn.init.trunc_normal_(emb.weight, std=0.02) + + # Zero-init the frame-type embeddings so they are a no-op at iter 0 + # (warm-start checkpoints reproduce the pretrained backbone exactly). + if getattr(self, "num_frame_type_embeddings", 0) > 0: + torch.nn.init.zeros_(self.frame_type_embed.weight) + if getattr(self, "num_dataset_embeddings", 0) > 0: + torch.nn.init.zeros_(self.dataset_embed.weight) + + def build_patch_embed(self): + ( + concat_padding_mask, + in_channels, + patch_spatial, + patch_temporal, + model_channels, + ) = ( + self.concat_padding_mask, + self.in_channels, + self.patch_spatial, + self.patch_temporal, + self.model_channels, + ) + in_channels = in_channels + 1 if concat_padding_mask else in_channels + self.x_embedder = PatchEmbed( + spatial_patch_size=patch_spatial, + temporal_patch_size=patch_temporal, + in_channels=in_channels, + out_channels=model_channels, + ) + if self.side_condition_channels > 0: + self.side_condition_embedder = PatchEmbed( + spatial_patch_size=patch_spatial, + temporal_patch_size=patch_temporal, + in_channels=self.side_condition_channels, + out_channels=model_channels, + ) + + def build_pos_embed(self): + if self.pos_emb_cls == "rope3d": + cls_type = VideoRopePosition3DEmb + else: + raise ValueError(f"Unknown pos_emb_cls {self.pos_emb_cls}") + + log.debug(f"Building positional embedding with {self.pos_emb_cls} class, impl {cls_type}") + kwargs = dict( + model_channels=self.model_channels, + len_h=self.max_img_h // self.patch_spatial_h, + len_w=self.max_img_w // self.patch_spatial_w, + len_t=self.max_frames // self.patch_temporal, + max_fps=self.max_fps, + min_fps=self.min_fps, + is_learnable=self.pos_emb_learnable, + interpolation=self.pos_emb_interpolation, + head_dim=self.model_channels // self.num_heads, + h_extrapolation_ratio=self.rope_h_extrapolation_ratio, + w_extrapolation_ratio=self.rope_w_extrapolation_ratio, + t_extrapolation_ratio=self.rope_t_extrapolation_ratio, + h_position_stride=( + self.patch_spatial_h + if self.rope_scale_positions_by_patch + else 1 + ), + w_position_stride=( + self.patch_spatial_w + if self.rope_scale_positions_by_patch + else 1 + ), + enable_fps_modulation=self.rope_enable_fps_modulation, + ) + self.pos_embedder = cls_type( + **kwargs, + ) + + if self.extra_per_block_abs_pos_emb: + kwargs["h_extrapolation_ratio"] = self.extra_h_extrapolation_ratio + kwargs["w_extrapolation_ratio"] = self.extra_w_extrapolation_ratio + kwargs["t_extrapolation_ratio"] = self.extra_t_extrapolation_ratio + self.extra_pos_embedder = LearnablePosEmbAxis( + **kwargs, + ) + + def prepare_embedded_sequence( + self, + x_B_C_T_H_W: torch.Tensor, + side_condition_B_C_T_H_W: Optional[torch.Tensor] = None, + fps: Optional[torch.Tensor] = None, + padding_mask: Optional[torch.Tensor] = None, + temporal_positions: Optional[torch.Tensor] = None, + frame_type_ids: Optional[torch.Tensor] = None, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]: + """ + Prepares an embedded sequence tensor by applying positional embeddings and handling padding masks. + + Args: + x_B_C_T_H_W (torch.Tensor): video + fps (Optional[torch.Tensor]): Frames per second tensor to be used for positional embedding when required. + If None, a default value (`self.base_fps`) will be used. + padding_mask (Optional[torch.Tensor]): current it is not used + + Returns: + Tuple[torch.Tensor, Optional[torch.Tensor]]: + - A tensor of shape (B, T, H, W, D) with the embedded sequence. + - An optional positional embedding tensor, returned only if the positional embedding class + (`self.pos_emb_cls`) includes 'rope'. Otherwise, None. + + Notes: + - If `self.concat_padding_mask` is True, a padding mask channel is concatenated to the input tensor. + - The method of applying positional embeddings depends on the value of `self.pos_emb_cls`. + - If 'rope' is in `self.pos_emb_cls` (case insensitive), the positional embeddings are generated using + the `self.pos_embedder` with the shape [T, H, W]. + - If "fps_aware" is in `self.pos_emb_cls`, the positional embeddings are generated using the + `self.pos_embedder` with the fps tensor. + - Otherwise, the positional embeddings are generated without considering fps. + """ + if self.concat_padding_mask: + padding_mask = transforms.functional.resize( + padding_mask, list(x_B_C_T_H_W.shape[-2:]), interpolation=transforms.InterpolationMode.NEAREST + ) + # A FP32 mask must not promote BF16 latents before patch projection. + padding_mask = padding_mask.to(x_B_C_T_H_W) + x_B_C_T_H_W = torch.cat( + [x_B_C_T_H_W, padding_mask.unsqueeze(1).repeat(1, 1, x_B_C_T_H_W.shape[2], 1, 1)], dim=1 + ) + x_B_T_H_W_D = self.x_embedder(x_B_C_T_H_W) + if self.side_condition_channels > 0: + if side_condition_B_C_T_H_W is None: + raise ValueError( + "side_condition must be provided when " + f"side_condition_channels={self.side_condition_channels}" + ) + if side_condition_B_C_T_H_W.ndim != 5: + raise ValueError( + "side_condition must be (B,C,T,H,W), got " + f"{tuple(side_condition_B_C_T_H_W.shape)}" + ) + expected = ( + x_B_C_T_H_W.shape[0], + self.side_condition_channels, + x_B_C_T_H_W.shape[2], + x_B_C_T_H_W.shape[3], + x_B_C_T_H_W.shape[4], + ) + if tuple(side_condition_B_C_T_H_W.shape) != expected: + raise ValueError( + f"side_condition {tuple(side_condition_B_C_T_H_W.shape)} " + f"must be {expected}" + ) + x_B_T_H_W_D = x_B_T_H_W_D + self.side_condition_embedder( + side_condition_B_C_T_H_W.type_as(x_B_C_T_H_W) + ) + elif side_condition_B_C_T_H_W is not None: + raise ValueError( + "side_condition was provided but side_condition_channels=0" + ) + + # Zero-init per-frame type embedding (lidar vs RGB view); broadcast over + # the H, W token grid. No-op at iter 0 (zero weights). + if frame_type_ids is not None: + assert getattr(self, "num_frame_type_embeddings", 0) > 0, ( + "frame_type_ids given but the model was built without frame-type embeddings" + ) + T_tok = x_B_T_H_W_D.shape[1] + assert frame_type_ids.shape[0] == T_tok, ( + f"frame_type_ids {tuple(frame_type_ids.shape)} must have length T={T_tok}" + ) + ft = self.frame_type_embed(frame_type_ids.to(x_B_T_H_W_D.device)) # (T, D) + x_B_T_H_W_D = x_B_T_H_W_D + ft[None, :, None, None, :].type_as(x_B_T_H_W_D) + + if self.extra_per_block_abs_pos_emb: + extra_pos_emb = self.extra_pos_embedder(x_B_T_H_W_D, fps=fps, temporal_positions=temporal_positions) + else: + extra_pos_emb = None + + if "rope" in self.pos_emb_cls.lower(): + return ( + x_B_T_H_W_D, + self.pos_embedder(x_B_T_H_W_D, fps=fps, temporal_positions=temporal_positions), + extra_pos_emb, + ) + x_B_T_H_W_D = x_B_T_H_W_D + self.pos_embedder(x_B_T_H_W_D) # [B, T, H, W, D] + + return x_B_T_H_W_D, None, extra_pos_emb + + @staticmethod + def _build_block_attn_mask( + frame_is_rgb: torch.Tensor, + T: int, + H: int, + W: int, + device: torch.device, + ) -> torch.Tensor: + """Block self-attention mask over the flattened ``(T H W)`` sequence. + + RGB query tokens attend ONLY to RGB key tokens; lidar query tokens + attend to everything: ``allow[q, k] = is_lidar[t_q] OR is_rgb[t_k]``. + Returns a bool ``(1, 1, S, S)`` mask (True = attend) broadcastable to + ``(B, n_heads, S, S)`` for ``scaled_dot_product_attention``. + """ + assert frame_is_rgb.shape[0] == T, ( + f"frame_is_rgb {tuple(frame_is_rgb.shape)} must have length T={T}" + ) + tpf = H * W + is_rgb = frame_is_rgb.to(device=device, dtype=torch.bool) + token_is_rgb = is_rgb.repeat_interleave(tpf) # (S,) + token_is_lidar = ~token_is_rgb + allow = token_is_lidar[:, None] | token_is_rgb[None, :] # (S, S) + return allow[None, None] + + def _build_block_flex_mask( + self, + frame_is_rgb: torch.Tensor, + T: int, + H: int, + W: int, + device: torch.device, + ) -> BlockMask: + """Block-sparse FlexAttention version of ``_build_block_attn_mask``. + + Same semantics (``allow[q, k] = is_lidar[t_q] OR is_rgb[t_k]``) but as a + ``BlockMask`` so ``flex_attention_op`` runs a fused (flash-like) kernel + and skips fully-masked blocks instead of materializing a dense + ``(S, S)`` score matrix through ``scaled_dot_product_attention``. + + The mask is a pure function of the (constant) frame layout, so it is + built once and cached; ``flex_attention_op`` right-pads Q/KV to a + multiple of 128, so the mask is built at the padded length with a + validity guard that matches that padding. + """ + assert frame_is_rgb.shape[0] == T, ( + f"frame_is_rgb {tuple(frame_is_rgb.shape)} must have length T={T}" + ) + cache = getattr(self, "_flex_block_mask_cache", None) + if cache is None: + cache = {} + self._flex_block_mask_cache = cache + key = (T, H, W, tuple(frame_is_rgb.to(torch.bool).tolist())) + cached = cache.get(key) + if cached is not None: + return cached + + S = T * H * W + S_pad = ((S + 127) // 128) * 128 + tpf = H * W + is_rgb = frame_is_rgb.to(device=device, dtype=torch.bool) + token_is_rgb = is_rgb.repeat_interleave(tpf) # (S,) + if S_pad > S: + token_is_rgb = torch.cat( + [token_is_rgb, token_is_rgb.new_zeros(S_pad - S)] + ) + token_is_lidar = ~token_is_rgb + + def mask_mod(b, h, q_idx, kv_idx): + valid = (q_idx < S) & (kv_idx < S) + return valid & (token_is_lidar[q_idx] | token_is_rgb[kv_idx]) + + block_mask = create_block_mask( + mask_mod, B=None, H=None, Q_LEN=S_pad, KV_LEN=S_pad, + device=device, _compile=True, + ) + cache[key] = block_mask + return block_mask + + def _build_temporal_block_flex_mask( + self, + T: int, + H: int, + W: int, + device: torch.device, + ) -> BlockMask: + """Build a cached block-causal mask over flattened ``(T,H,W)`` tokens. + + An optional prefix attends bidirectionally within itself. All later + tokens attend to that prefix; within the future, a query in block ``i`` + attends to key blocks ``0..i`` only. Padding tokens added by + ``flex_attention_op`` are excluded by the validity guard. + """ + block_size = self.temporal_block_size + assert block_size > 0 + cache = getattr(self, "_flex_block_mask_cache", None) + if cache is None: + cache = {} + self._flex_block_mask_cache = cache + prefix_frames = int(getattr(self, "temporal_prefix_frames", 0)) + if prefix_frames > T: + raise ValueError( + f"temporal_prefix_frames={prefix_frames} exceeds T={T}" + ) + key = ( + "temporal_causal", + T, + H, + W, + block_size, + prefix_frames, + str(device), + ) + cached = cache.get(key) + if cached is not None: + return cached + + S = T * H * W + S_pad = ((S + 127) // 128) * 128 + tokens_per_frame = H * W + + def mask_mod(b, h, q_idx, kv_idx): + valid = (q_idx < S) & (kv_idx < S) + q_frame = q_idx // tokens_per_frame + kv_frame = kv_idx // tokens_per_frame + return valid & temporal_prefix_block_allows( + q_frame, + kv_frame, + block_size, + prefix_frames, + ) + + block_mask = create_block_mask( + mask_mod, + B=None, + H=None, + Q_LEN=S_pad, + KV_LEN=S_pad, + device=device, + _compile=True, + ) + cache[key] = block_mask + return block_mask + + def _build_teacher_forcing_flex_mask( + self, + clean_frames: int, + T: int, + H: int, + W: int, + device: torch.device, + ) -> BlockMask: + """Build the one-pass ``[clean | noisy]`` teacher-forcing mask.""" + if T != 2 * clean_frames: + raise ValueError( + "one-pass teacher forcing requires T=2*clean_frames, got " + f"T={T}, clean_frames={clean_frames}" + ) + block_size = self.temporal_block_size + if block_size <= 0: + raise ValueError( + "one-pass teacher forcing requires temporal_block_size > 0" + ) + prefix_frames = int(self.temporal_prefix_frames) + cache = getattr(self, "_flex_block_mask_cache", None) + if cache is None: + cache = {} + self._flex_block_mask_cache = cache + key = ( + "teacher_forcing_clean_noisy", + clean_frames, + H, + W, + block_size, + prefix_frames, + str(device), + ) + cached = cache.get(key) + if cached is not None: + return cached + + S = T * H * W + S_pad = ((S + 127) // 128) * 128 + tokens_per_frame = H * W + + def mask_mod(b, h, q_idx, kv_idx): + valid = (q_idx < S) & (kv_idx < S) + q_frame = q_idx // tokens_per_frame + kv_frame = kv_idx // tokens_per_frame + return valid & teacher_forcing_clean_noisy_allows( + q_frame, + kv_frame, + clean_frames, + block_size, + prefix_frames, + ) + + block_mask = create_block_mask( + mask_mod, + B=None, + H=None, + Q_LEN=S_pad, + KV_LEN=S_pad, + device=device, + _compile=True, + ) + cache[key] = block_mask + return block_mask + + def enable_zero_crossattn_skip(self) -> int: + """Bypass a provably zero, bias-free text cross-attention residual.""" + if self.use_crossattn_projection: + raise ValueError( + "cannot skip zero cross-attention when a potentially biased " + "cross-attention projection is enabled" + ) + if self.extra_image_context_dim is not None: + raise ValueError( + "cannot skip cross-attention when image-context tokens are enabled" + ) + self.skip_crossattn_when_zero = True + self._zero_crossattn_validated = False + enabled = 0 + # ``sac_config`` can wrap blocks in PyTorch checkpoint wrappers whose + # implementation is not exposed as ``.module``. Walk each wrapper's + # registered submodules so the actual Block receives the runtime flag. + for wrapped_block in self.blocks: + implementations = [ + module + for module in wrapped_block.modules() + if isinstance(module, Block) + ] + if len(implementations) != 1: + raise RuntimeError( + "expected exactly one MiniTrainDIT Block under each " + f"registered block, found {len(implementations)} in " + f"{type(wrapped_block).__name__}" + ) + implementations[0].skip_crossattn = True + enabled += 1 + if enabled != self.num_blocks: + raise RuntimeError( + f"enabled zero cross-attention skip on {enabled} blocks, " + f"expected {self.num_blocks}" + ) + return enabled + + def validate_zero_crossattn_skip( + self, + crossattn_emb: torch.Tensor, + img_context_emb: torch.Tensor | None = None, + ) -> None: + """Validate the zero-context shortcut once, outside compiled forward.""" + if ( + not self.skip_crossattn_when_zero + or self._zero_crossattn_validated + ): + return + if img_context_emb is not None: + raise ValueError( + "zero-cross-attention bypass received image context" + ) + nonzero = int(torch.count_nonzero(crossattn_emb).item()) + if nonzero: + max_abs = float(crossattn_emb.abs().max().item()) + raise ValueError( + "zero-cross-attention bypass requires an exactly zero " + f"text embedding, got {nonzero} nonzero values " + f"(max_abs={max_abs})" + ) + self._zero_crossattn_validated = True + + def disable_selective_checkpoint_for_inference(self) -> int: + """Remove activation-checkpoint wrappers before eval compilation.""" + if self.training: + raise RuntimeError( + "selective checkpoint wrappers may only be removed in eval mode" + ) + + unwrapped = 0 + for block_id, block in self.blocks.named_children(): + implementation = block + while hasattr(implementation, "_checkpoint_wrapped_module"): + implementation = implementation._checkpoint_wrapped_module + unwrapped += 1 + if implementation is not block: + self.blocks.register_module(block_id, implementation) + + final_layer = self.final_layer + while hasattr(final_layer, "_checkpoint_wrapped_module"): + final_layer = final_layer._checkpoint_wrapped_module + unwrapped += 1 + if final_layer is not self.final_layer: + self.register_module("final_layer", final_layer) + return unwrapped + + def set_cached_inference_self_attention_backend( + self, backend: str + ) -> int: + """Select self-attention for a mask-free inference forward. + + Causal video checkpoints use this only with their external KV cache. + Fully bidirectional checkpoints are also mask-free, so their native + ``minimal_a2a`` attention can be replaced directly at inference. + """ + mask_free_native = ( + self.temporal_block_size == 0 + and self.atten_backend == "minimal_a2a" + ) + if self.atten_backend != "torch-flex" and not mask_free_native: + raise ValueError( + "inference backend override expects either a torch-flex " + "causal checkpoint or a mask-free minimal_a2a bidirectional " + f"checkpoint, got backend={self.atten_backend!r}, " + f"temporal_block_size={self.temporal_block_size}" + ) + implementations = { + "flex": ("torch-flex", flex_attention_op), + "sdpa-flash": ("torch", torch_flash_attention_op), + "fa3": ("torch", flash_attention_3_op), + } + if backend not in implementations: + raise ValueError( + f"unsupported cached inference backend {backend!r}; " + f"choose from {sorted(implementations)}" + ) + if backend == "fa3": + if _flash_attn_3_func is None: + raise ImportError( + "cached backend 'fa3' requires flash-attn-3; install the " + "Hopper package from Dao-AILab/flash-attention" + ) from _FLASH_ATTN_3_IMPORT_ERROR + if ( + not torch.cuda.is_available() + or torch.cuda.get_device_capability() != (9, 0) + ): + raise RuntimeError( + "cached backend 'fa3' requires an SM90 Hopper GPU" + ) + backend_name, attention_op = implementations[backend] + enabled = 0 + for wrapped_block in self.blocks: + blocks = [ + module + for module in wrapped_block.modules() + if isinstance(module, Block) + ] + if len(blocks) != 1: + raise RuntimeError( + "expected exactly one MiniTrainDIT Block under each " + f"registered block, found {len(blocks)} in " + f"{type(wrapped_block).__name__}" + ) + self_attn = blocks[0].self_attn + self_attn.backend = backend_name + if "attn_op" in self_attn._modules: + del self_attn._modules["attn_op"] + self_attn.attn_op = attention_op + enabled += 1 + if enabled != self.num_blocks: + raise RuntimeError( + f"set cached self-attention backend on {enabled} blocks, " + f"expected {self.num_blocks}" + ) + self._cached_inference_self_attention_backend = backend + return enabled + + def unpatchify(self, x_B_T_H_W_M): + x_B_C_Tt_Hp_Wp = rearrange( + x_B_T_H_W_M, + "B T H W (p1 p2 t C) -> B C (T t) (H p1) (W p2)", + p1=self.patch_spatial_h, + p2=self.patch_spatial_w, + t=self.patch_temporal, + ) + return x_B_C_Tt_Hp_Wp + + def forward( + self, + x_B_C_T_H_W: torch.Tensor, + timesteps_B_T: torch.Tensor, + crossattn_emb: torch.Tensor, + side_condition_B_C_T_H_W: Optional[torch.Tensor] = None, + fps: Optional[torch.Tensor] = None, + padding_mask: Optional[torch.Tensor] = None, + data_type: Optional[DataType] = DataType.VIDEO, + intermediate_feature_ids: Optional[List[int]] = None, + img_context_emb: Optional[torch.Tensor] = None, + frame_is_rgb: Optional[torch.Tensor] = None, + temporal_positions: Optional[torch.Tensor] = None, + frame_type_ids: Optional[torch.Tensor] = None, + img_context_pos: Optional[torch.Tensor] = None, + ego_pose_B_T_P: Optional[torch.Tensor] = None, + ego_pose_null_mask_B: Optional[torch.Tensor] = None, + dataset_ids_B: Optional[torch.Tensor] = None, + self_attn_kv_cache: Optional[ + List[Optional[dict[str, torch.Tensor]]] + ] = None, + store_self_attn_kv: bool = False, + self_attn_kv_max_frames: Optional[int] = None, + self_attn_kv_sink_frames: int = 0, + detach_self_attn_kv: bool = True, + return_self_attn_kv: bool = False, + teacher_forcing_clean_frames: Optional[int] = None, + ) -> torch.Tensor | List[torch.Tensor] | Tuple[torch.Tensor, List[torch.Tensor]]: + """ + Args: + x: (B, C, T, H, W) tensor of spatial-temp inputs + timesteps: (B,) shared or (B,T) per-frame tensor of timesteps + crossattn_emb: (B, N, D) tensor of cross-attention embeddings + ego_pose_B_T_P: optional (B, T, ego_pose_dim) raw per-frame ego pose + (flattened SE(3)). The in-network zero-init ``ego_pose_head`` + (built iff ``ego_pose_dim > 0``) maps it to a per-frame embedding + ADDED to the timestep embedding that drives every block's AdaLN + (Copilot4D-style). ``T`` must equal the tokenized temporal length. + ego_pose_null_mask_B: optional (B,) bool -- True on samples whose ego + pose should be DROPPED (embedding forced to 0). Used for pose + dropout during training and the unconditional pass of pose CFG. + dataset_ids_B: optional (B,) long sensor-dataset identity. Required + when ``num_dataset_embeddings > 0`` and added globally to the + AdaLN timestep embedding. + img_context_pos: optional (N, 4) long -- per image-context-token + [view, pixel_time, h, w] indices into the learnable image-context + positional embedding tables (view / time / spatial). Added to the + projected image-context tokens so RGB K/V carry their location. + frame_is_rgb: optional (T,) bool -- True on RGB *condition* frames. + When given, a block self-attention mask is built so RGB query + tokens attend ONLY to RGB key tokens (their KV is then + noise-independent => cacheable), while lidar query tokens attend + to everything. Requires the ``torch`` self-attn backend. + temporal_positions: optional (T,) -- explicit per-frame RoPE temporal + positions (pixel-time alignment of heterogeneous modalities). + frame_type_ids: optional (T,) long -- per-frame type id for the + zero-init frame-type embedding (lidar vs RGB view). + return_self_attn_kv: return the updated external cache alongside + the prediction. This is needed when an FSDP boundary rebuilds + nested input containers instead of mutating the caller's list. + """ + assert isinstance(data_type, DataType), ( + f"Expected DataType, got {type(data_type)}. We need discuss this flag later." + ) + if ( + self.skip_crossattn_when_zero + and not self._zero_crossattn_validated + ): + self.validate_zero_crossattn_skip( + crossattn_emb, + img_context_emb, + ) + x_B_T_H_W_D, rope_emb_L_1_1_D, extra_pos_emb_B_T_H_W_D_or_T_H_W_B_D = self.prepare_embedded_sequence( + x_B_C_T_H_W, + side_condition_B_C_T_H_W=side_condition_B_C_T_H_W, + fps=fps, + padding_mask=padding_mask, + temporal_positions=temporal_positions, + frame_type_ids=frame_type_ids, + ) + + # Build one optional self-attention mask. Diffusion-Forcing temporal + # causality and heterogeneous RGB/LiDAR modality masking are separate + # modes for now; combining both is deliberately rejected rather than + # silently weakening either constraint. + self_attn_mask = None + T_tok, H_tok, W_tok = x_B_T_H_W_D.shape[1:4] + if teacher_forcing_clean_frames is not None: + if self_attn_kv_cache is not None: + raise ValueError( + "one-pass teacher forcing is incompatible with a KV cache" + ) + if frame_is_rgb is not None: + raise ValueError( + "one-pass teacher forcing does not support the RGB/LiDAR " + "modality mask" + ) + if self.is_context_parallel_enabled: + raise ValueError( + "one-pass teacher forcing does not support context parallelism" + ) + if self._cached_inference_self_attention_backend != "flex": + raise RuntimeError( + "one-pass teacher forcing requires the torch-flex backend" + ) + self_attn_mask = self._build_teacher_forcing_flex_mask( + int(teacher_forcing_clean_frames), + T_tok, + H_tok, + W_tok, + device=x_B_T_H_W_D.device, + ) + elif self_attn_kv_cache is not None: + if self.temporal_block_size <= 0: + raise ValueError( + "DiT KV caching requires temporal_block_size > 0" + ) + if frame_is_rgb is not None: + raise ValueError( + "DiT KV caching does not support the RGB/LiDAR modality mask" + ) + if self.is_context_parallel_enabled: + raise ValueError( + "DiT KV caching does not support context parallelism" + ) + if len(self_attn_kv_cache) != len(self.blocks): + raise ValueError( + f"expected {len(self.blocks)} per-layer KV caches, got " + f"{len(self_attn_kv_cache)}" + ) + valid_stream_chunk_sizes = {self.temporal_block_size} + if self.temporal_prefix_frames > 0: + valid_stream_chunk_sizes.add(self.temporal_prefix_frames) + if T_tok not in valid_stream_chunk_sizes: + raise ValueError( + "streaming calls must contain the temporal prefix or one " + "complete causal block: " + f"T={T_tok}, prefix={self.temporal_prefix_frames}, " + f"block_size={self.temporal_block_size}" + ) + if temporal_positions is None: + raise ValueError( + "streaming calls require explicit global temporal_positions" + ) + if self_attn_kv_sink_frames < 0: + raise ValueError( + "self_attn_kv_sink_frames must be non-negative, got " + f"{self_attn_kv_sink_frames}" + ) + if self_attn_kv_max_frames is None: + if self_attn_kv_sink_frames: + raise ValueError( + "self-attention sink frames require a finite cache" + ) + elif self_attn_kv_sink_frames >= self_attn_kv_max_frames: + raise ValueError( + "self-attention sink frames must be smaller than the " + "persistent cache: " + f"{self_attn_kv_sink_frames}/" + f"{self_attn_kv_max_frames}" + ) + # No mask is needed: each query sees only cached earlier blocks and + # its complete current block (which is bidirectional by definition). + elif self.temporal_block_size > 0: + if self._cached_inference_self_attention_backend != "flex": + raise RuntimeError( + "the cached inference self-attention backend override " + "cannot run a full block-causal forward; restore backend " + "'flex' or supply self_attn_kv_cache" + ) + assert frame_is_rgb is None, ( + "temporal block-causal and RGB/LiDAR modality masks cannot be " + "combined in the current implementation" + ) + self_attn_mask = self._build_temporal_block_flex_mask( + T_tok, H_tok, W_tok, device=x_B_T_H_W_D.device + ) + elif frame_is_rgb is not None: + if getattr(self, "atten_backend", "torch") == "torch-flex": + # Block-sparse fused kernel -- no dense (S, S) mask. + self_attn_mask = self._build_block_flex_mask( + frame_is_rgb, T_tok, H_tok, W_tok, device=x_B_T_H_W_D.device + ) + else: + self_attn_mask = self._build_block_attn_mask( + frame_is_rgb, T_tok, H_tok, W_tok, device=x_B_T_H_W_D.device + ) + + # Training batches may keep conditioning tensors in FP32. + crossattn_emb = crossattn_emb.to(x_B_T_H_W_D) + if self.use_crossattn_projection: + crossattn_emb = self.crossattn_proj(crossattn_emb) + + if img_context_emb is not None: + assert self.extra_image_context_dim is not None, ( + "extra_image_context_dim must be set if img_context_emb is provided" + ) + img_context_emb = self.img_context_proj(img_context_emb) + if img_context_pos is not None and getattr(self, "use_img_context_pos_emb", False): + pos = img_context_pos.to(device=img_context_emb.device, dtype=torch.long) + pos_emb = ( + self.img_view_embed(pos[:, 0]) + + self.img_time_embed(pos[:, 1]) + + self.img_h_embed(pos[:, 2]) + + self.img_w_embed(pos[:, 3]) + ) # (N, D) + img_context_emb = img_context_emb + pos_emb.unsqueeze(0).type_as(img_context_emb) + context_input = (crossattn_emb, img_context_emb) + else: + context_input = crossattn_emb + + with amp.autocast("cuda", enabled=self.use_wan_fp32_strategy, dtype=torch.float32): + if timesteps_B_T.ndim == 1: + timesteps_B_T = timesteps_B_T.unsqueeze(1) + t_embedding_B_T_D, adaln_lora_B_T_3D = self.t_embedder(timesteps_B_T) + t_embedding_B_T_D = self.t_embedding_norm(t_embedding_B_T_D) + + # Copilot4D-style additive per-frame ego-pose conditioning: run the raw + # per-frame pose through the in-network zero-init head, then fold the + # (B, T, D) pose embedding into the timestep embedding that drives every + # block's AdaLN. The timestep embedding is usually (B, 1, D) (one sigma + # per sample, broadcast over frames); adding a per-frame pose embedding + # makes the whole network's AdaLN per-frame -> expand T first. Zero-init + # head => iter-0 no-op / warm-start-safe. ``ego_pose_null_mask_B`` (True = + # drop) zeroes the embedding per sample for pose dropout / CFG uncond. + if ego_pose_B_T_P is not None and self.ego_pose_dim > 0: + assert ego_pose_B_T_P.shape[-1] == self.ego_pose_dim, ( + f"ego_pose_B_T_P last dim {ego_pose_B_T_P.shape[-1]} != " + f"ego_pose_dim {self.ego_pose_dim}" + ) + # Feed the head in the network's COMPUTE dtype (bf16 under FSDP mixed + # precision), not t_embedding's dtype -- t_embedding is built in an + # fp32 autocast block above, so casting the input to it would feed + # fp32 into bf16 weights ("mat1 and mat2 must have the same dtype"). + # ``x_B_T_H_W_D`` (the embedded hidden state) carries that compute + # dtype and is always present; the head's own ``.parameters()`` is + # empty here because FSDP flattens submodule params. Output is cast + # back to t_embedding's dtype at the add below. + ego_pose_emb_B_T_D = self.ego_pose_head( + ego_pose_B_T_P.to(x_B_T_H_W_D.dtype) + ) # (B, T, D) + if ego_pose_null_mask_B is not None: + keep = (~ego_pose_null_mask_B.to(torch.bool)).to(ego_pose_emb_B_T_D.dtype) + ego_pose_emb_B_T_D = ego_pose_emb_B_T_D * keep.view(-1, 1, 1) + T_pose = ego_pose_emb_B_T_D.shape[1] + if t_embedding_B_T_D.shape[1] == 1 and T_pose != 1: + t_embedding_B_T_D = t_embedding_B_T_D.expand(-1, T_pose, -1) + assert ego_pose_emb_B_T_D.shape == t_embedding_B_T_D.shape, ( + f"ego_pose_emb {tuple(ego_pose_emb_B_T_D.shape)} must match " + f"t_embedding {tuple(t_embedding_B_T_D.shape)} (after T-expand)" + ) + t_embedding_B_T_D = t_embedding_B_T_D + ego_pose_emb_B_T_D.to(t_embedding_B_T_D.dtype) + + if self.num_dataset_embeddings > 0: + if dataset_ids_B is None: + raise ValueError( + "dataset_ids_B is required when dataset conditioning is enabled" + ) + dataset_ids_B = dataset_ids_B.to( + device=x_B_T_H_W_D.device, dtype=torch.long + ).reshape(-1) + if dataset_ids_B.shape != (x_B_T_H_W_D.shape[0],): + raise ValueError( + "dataset_ids_B must have one id per sample, got " + f"{tuple(dataset_ids_B.shape)} for " + f"B={x_B_T_H_W_D.shape[0]}" + ) + if bool( + ((dataset_ids_B < 0) | ( + dataset_ids_B >= self.num_dataset_embeddings + )).any() + ): + raise ValueError( + "dataset_ids_B contains an id outside [0, " + f"{self.num_dataset_embeddings})" + ) + dataset_embedding = self.dataset_embed(dataset_ids_B) + t_embedding_B_T_D = ( + t_embedding_B_T_D + + dataset_embedding[:, None].to(t_embedding_B_T_D.dtype) + ) + elif dataset_ids_B is not None: + raise ValueError( + "dataset_ids_B was provided but dataset conditioning is disabled" + ) + + # for logging purpose + affline_scale_log_info = {} + affline_scale_log_info["t_embedding_B_T_D"] = t_embedding_B_T_D.detach() + self.affline_scale_log_info = affline_scale_log_info + self.affline_emb = t_embedding_B_T_D + self.crossattn_emb = crossattn_emb + + if extra_pos_emb_B_T_H_W_D_or_T_H_W_B_D is not None: + assert x_B_T_H_W_D.shape == extra_pos_emb_B_T_H_W_D_or_T_H_W_B_D.shape, ( + f"{x_B_T_H_W_D.shape} != {extra_pos_emb_B_T_H_W_D_or_T_H_W_B_D.shape}" + ) + + B, T, H, W, D = x_B_T_H_W_D.shape + # x_B_THW_D = rearrange(x_B_T_H_W_D, "b t h w d -> b (t h w) d") + + intermediate_features_outputs = [] + for i, block in enumerate(self.blocks): + kv_cache_cfg = None + if self_attn_kv_cache is not None: + max_cache_tokens = None + if self_attn_kv_max_frames is not None: + max_cache_tokens = ( + int(self_attn_kv_max_frames) * H * W + ) + sink_cache_tokens = int(self_attn_kv_sink_frames) * H * W + kv_cache_cfg = KVCacheConfig( + run_with_kv=True, + store_kv=store_self_attn_kv, + cache=self_attn_kv_cache[i], + max_cache_tokens=max_cache_tokens, + sink_cache_tokens=sink_cache_tokens, + detach_cache=detach_self_attn_kv, + ) + x_B_T_H_W_D = block( + x_B_T_H_W_D, + t_embedding_B_T_D, + context_input, + rope_emb_L_1_1_D=rope_emb_L_1_1_D, + adaln_lora_B_T_3D=adaln_lora_B_T_3D, + extra_per_block_pos_emb=extra_pos_emb_B_T_H_W_D_or_T_H_W_B_D, + kv_cache_cfg=kv_cache_cfg, + self_attn_mask=self_attn_mask, + ) + if kv_cache_cfg is not None: + self_attn_kv_cache[i] = kv_cache_cfg.cache + if intermediate_feature_ids and i in intermediate_feature_ids: + x_reshaped_for_disc = rearrange(x_B_T_H_W_D, "b tp hp wp d -> b (tp hp wp) d") + intermediate_features_outputs.append(x_reshaped_for_disc) + + # x_B_T_H_W_D = rearrange(x_B_THW_D, "b (t h w) d -> b t h w d", t=T, h=H, w=W) + # O = out_channels * patch_h * patch_w * temporal_patch_size + x_B_T_H_W_O = self.final_layer(x_B_T_H_W_D, t_embedding_B_T_D, adaln_lora_B_T_3D=adaln_lora_B_T_3D) + x_B_C_Tt_Hp_Wp = self.unpatchify(x_B_T_H_W_O) + if intermediate_feature_ids: + if return_self_attn_kv: + raise ValueError( + "return_self_attn_kv is incompatible with intermediate " + "feature collection" + ) + if len(intermediate_features_outputs) != len(intermediate_feature_ids): + log.warning( + f"Collected {len(intermediate_features_outputs)} intermediate features, " + f"but expected {len(intermediate_feature_ids)}. " + f"Requested IDs: {intermediate_feature_ids}" + ) + return x_B_C_Tt_Hp_Wp, intermediate_features_outputs + + if return_self_attn_kv: + if self_attn_kv_cache is None: + raise ValueError( + "return_self_attn_kv requires self_attn_kv_cache" + ) + return x_B_C_Tt_Hp_Wp, self_attn_kv_cache + return x_B_C_Tt_Hp_Wp + + def enable_selective_checkpoint(self, sac_config: SACConfig, blocks: nn.ModuleList): + if sac_config.mode == CheckpointMode.NONE: + return self + + log.info( + f"Enable selective checkpoint with {sac_config.mode}, for every {sac_config.every_n_blocks} blocks. Total blocks: {len(blocks)}" + ) + _context_fn = sac_config.get_context_fn() + for block_id, block in blocks.named_children(): + if int(block_id) % sac_config.every_n_blocks == 0: + log.info(f"Enable selective checkpoint for block {block_id}") + block = ptd_checkpoint_wrapper( + block, + context_fn=_context_fn, + preserve_rng_state=False, + ) + blocks.register_module(block_id, block) + self.register_module( + "final_layer", + ptd_checkpoint_wrapper( + self.final_layer, + context_fn=_context_fn, + preserve_rng_state=False, + ), + ) + + return self + + def fully_shard(self, mesh, **fsdp_kwargs): + for i, block in enumerate(self.blocks): + reshard_after_forward = i < len(self.blocks) - 1 + fully_shard(block, mesh=mesh, reshard_after_forward=reshard_after_forward, **fsdp_kwargs) + + # TODO: (qsh 2025-01-13) shall we do it? + fully_shard(self.final_layer, mesh=mesh, reshard_after_forward=True, **fsdp_kwargs) + if self.extra_per_block_abs_pos_emb: + fully_shard(self.extra_pos_embedder, mesh=mesh, reshard_after_forward=True, **fsdp_kwargs) + fully_shard(self.t_embedder, mesh=mesh, reshard_after_forward=False, **fsdp_kwargs) + if self.extra_image_context_dim is not None: + fully_shard(self.img_context_proj, mesh=mesh, reshard_after_forward=False, **fsdp_kwargs) + + def disable_context_parallel(self): + # pos_embedder + self.pos_embedder.disable_context_parallel() + if self.extra_per_block_abs_pos_emb: + self.extra_pos_embedder.disable_context_parallel() + + # attention + for block in self.blocks: + block.set_context_parallel_group( + process_group=None, + ranks=None, + stream=torch.cuda.Stream(), + ) + + self._is_context_parallel_enabled = False + + def enable_context_parallel(self, process_group: Optional[ProcessGroup] = None): + # pos_embedder + self.pos_embedder.enable_context_parallel(process_group=process_group) + if self.extra_per_block_abs_pos_emb: + self.extra_pos_embedder.enable_context_parallel(process_group=process_group) + + # attention + cp_ranks = get_process_group_ranks(process_group) + for block in self.blocks: + block.set_context_parallel_group( + process_group=process_group, + ranks=cp_ranks, + stream=torch.cuda.Stream(), + ) + + self._is_context_parallel_enabled = True + + @property + def is_context_parallel_enabled(self): + return self._is_context_parallel_enabled + + +def replace_selfattn_op_with_sparse_attn_op( + model: MiniTrainDIT, n_dense_blocks: int = 0, natten_parameters: Union[dict, list] = None +) -> MiniTrainDIT: + """ + Replace the self-attention operator with a sparse self-attention operator. + + Args: + model: MiniTrainDIT instance + n_dense_blocks: Number of blocks that will remain dense (not replaced with NeighborhoodAttention) + If 0, all blocks use NeighborhoodAttention. + If -1, return model directly without any modifications. + Otherwise, n_dense_blocks blocks will remain dense, distributed evenly across the network. + + Returns: + Modified instance + """ + # Special case: return model directly without modifications + if n_dense_blocks == -1: + return model + + num_blocks = len(model.blocks) + + if natten_parameters is None: + raise ValueError("Please specify natten_parameters when n_dense_blocks > -1.") + + if isinstance(natten_parameters, Sequence) and len(natten_parameters) != num_blocks: + raise ValueError( + "List of NATTEN parameters must be the same length as the number of blocks, " + f"got {len(natten_parameters)=} != {num_blocks=}." + ) + + if isinstance(natten_parameters, Sequence) and n_dense_blocks > 0: + log.warning(f"NATTEN parameters was a list; ignoring {n_dense_blocks=}.") + + if isinstance(natten_parameters, Sequence): + natten_parameters_list = natten_parameters + else: + if n_dense_blocks >= num_blocks: + raise ValueError(f"n_dense_blocks ({n_dense_blocks}) must be less than the number of blocks ({num_blocks})") + + # Determine which blocks should remain dense + dense_indices = set() + + if n_dense_blocks > 0: + # General rule: distribute n_dense_blocks blocks evenly across the network + if n_dense_blocks == 1: + # Special case: just the middle block + dense_indices.add(num_blocks // 2) + else: + # For multiple blocks, distribute them evenly from start to end + indices = np.linspace(0, num_blocks - 1, n_dense_blocks, dtype=int) + dense_indices.update(indices.tolist()) + + natten_parameters_list = [None if i in dense_indices else natten_parameters for i in range(num_blocks)] + + # Replace self-attention with NeighborhoodAttention for non-dense blocks + for i, block in enumerate(model.blocks): + natten_params = natten_parameters_list[i] + if natten_params is not None: + natten_parameters_layer = {k: v for k, v in natten_params.items()} + natten_parameters_layer["layer_id"] = i + if block.self_attn.backend == "minimal_a2a": + sparse_attn_op = NattenA2AAttnOp(natten_parameters=natten_parameters_layer) + else: + raise NotImplementedError( + f"Using sparsity with attention backend {block.self_attn.backend} is not supported." + ) + + block.self_attn.register_module("attn_op", sparse_attn_op) + + return model diff --git a/diffusion/training/networks/model_weights_stats.py b/diffusion/training/networks/model_weights_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..42fbf1facd0a5f5364113abe24ff0a1dc52d0a77 --- /dev/null +++ b/diffusion/training/networks/model_weights_stats.py @@ -0,0 +1,63 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Any + +import torch +from torch import nn + + +@dataclass +class TrainingStats: + """Data class to hold training statistics.""" + + video_samples: int = 0 + image_samples: int = 0 + iterations: int = 0 + training_hours: float = 0.0 + + +class WeightTrainingStat(nn.Module, ABC): + """Abstract base class for tracking training statistics.""" + + def __init__(self) -> None: + super().__init__() + self._initialize_tracking_buffers() + + def _initialize_tracking_buffers(self) -> None: + """Initialize tracking buffers with default values.""" + tracking_buffers = { + "accum_video_sample_counter": torch.tensor(0, dtype=torch.int64), + "accum_image_sample_counter": torch.tensor(0, dtype=torch.int64), + "accum_iteration": torch.tensor(0, dtype=torch.int64), + "accum_train_in_hours": torch.tensor(0.0, dtype=torch.float32), + } + + for name, tensor in tracking_buffers.items(): + self.register_buffer(name, tensor) + + def get_training_stats(self) -> TrainingStats: + """Return current training statistics.""" + return TrainingStats( + video_samples=self.accum_video_sample_counter.item(), + image_samples=self.accum_image_sample_counter.item(), + iterations=self.accum_iteration.item(), + training_hours=self.accum_train_in_hours.item(), + ) + + @abstractmethod + def forward(self, *args, **kwargs) -> Any: + pass diff --git a/diffusion/training/networks/neighborhood_attn.py b/diffusion/training/networks/neighborhood_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a2c4666ba876d8f02ad9506a6556105aafb8f3 --- /dev/null +++ b/diffusion/training/networks/neighborhood_attn.py @@ -0,0 +1,249 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +from collections import namedtuple +from collections.abc import Mapping, Sequence +from typing import Optional + +import torch +from torch import nn + +from utils import log + +try: + import natten + from natten.functional import neighborhood_attention_generic + + natten.use_kv_parallelism_in_fused_na(True) + natten.set_memory_usage_preference("unrestricted") + + HAS_NATTEN = True + +except ImportError: + HAS_NATTEN = False + + def neighborhood_attention_generic(*args, **kwargs): + raise RuntimeError( + "You attempted to run Cosmos-Predict2 + NATTEN, but NATTEN is not installed. " + "Refer to natten.org/install for install instructions, or use " + "the cosmos-predict2 container image." + ) + + +from diffusion.training.networks.cosmos_attention import get_device_cc + +# TODO (ahassani): should we move VideoSize definitions to a common place? +VideoSize = namedtuple("VideoSize", ["T", "H", "W"]) + + +# TODO (ahassani) in I4, we're allowing SM80 as well in case we want to train with Ampere. +# Only allowing on Hopper and Blackwell for now, since Hopper FNA and +# Blackwell FNA can deliver excellent speedup over SOL baselines. +# Other architectures will be enabled as soon as good kernels for them +# land in NATTEN. +ALLOWED_COMPUTE_CAPS = [80, 90, 100] + + +class NeighborhoodAttention(nn.Module): + def __init__(self, natten_parameters, base_attn_op): + super(NeighborhoodAttention, self).__init__() + + self.base_attn_op = base_attn_op + + self.natten_parameters = natten_parameters + if ( + not isinstance(natten_parameters, Mapping) + or "window_size" not in natten_parameters + or "layer_id" not in natten_parameters + ): + raise ValueError( + f"Expected `natten_parameters` to be a dict with at least keys `window_size` and `layer_id`, got {natten_parameters=}." + ) + + self.layer_id = natten_parameters["layer_id"] + self.window_size = natten_parameters["window_size"] + self.stride = 1 if "stride" not in natten_parameters else natten_parameters["stride"] + self.dilation = 1 if "dilation" not in natten_parameters else natten_parameters["dilation"] + self.is_causal = False if "is_causal" not in natten_parameters else natten_parameters["is_causal"] + + if not isinstance(self.window_size, Sequence) or len(self.window_size) != 3: + raise ValueError(f"Invalid window_size value. Expected an iterable of length 3, got {self.window_size}.") + + if (not isinstance(self.stride, Sequence) or len(self.stride) != 3) and not isinstance(self.stride, int): + raise ValueError(f"Invalid stride value. Expected an iterable of length 3, or integer, got {self.stride}.") + + if (not isinstance(self.dilation, Sequence) or len(self.dilation) != 3) and not isinstance(self.dilation, int): + raise ValueError( + f"Invalid dilation value. Expected an iterable of length 3, or integer, got {self.dilation}." + ) + + if (not isinstance(self.is_causal, Sequence) or len(self.is_causal) != 3) and not isinstance( + self.is_causal, bool + ): + raise ValueError( + f"Invalid is_causal value. Expected an iterable of length 3, or boolean, got {self.is_causal}." + ) + + log.info( + f"NeighborhoodAttention op registered for layer {self.layer_id}, with " + f"window_size={self.window_size}, stride={self.stride}, dilation={self.dilation}." + ) + + self.base_size = None if "base_size" not in natten_parameters else natten_parameters["base_size"] + if self.base_size is not None and (not isinstance(self.base_size, Sequence) or len(self.base_size) != 3): + raise ValueError( + f"Invalid base feature map size. Expected an iterable of length 3, or None, got {self.base_size}." + ) + + # Configurations + # Tuned for 720p and window sizes (24, 12, 24), (16, 12, 24), and stride (1, 4, 8). + # They also assume head dim = 128. + self.performance_configs = { + # Ampere (SM80). Also serves as the default option for RTX cards (Ampere RTX, Ada, Blackwell RTX.) + 80: { + "backend": "cutlass-fna", + "q_tile_shape": (4, 4, 4), + "kv_tile_shape": (4, 4, 8), + "backward_q_tile_shape": (4, 4, 8), + "backward_kv_tile_shape": (4, 4, 8), + "backward_use_pt_reduction": False, + }, + # Hopper (SM90) + 90: { + "backend": "hopper-fna", + "q_tile_shape": (4, 4, 8), + "kv_tile_shape": (4, 4, 8), + "backward_q_tile_shape": (4, 4, 4), + "backward_kv_tile_shape": (4, 4, 8), + }, + # Blackwell (SM100) + 100: { + "backend": "blackwell-fna", + "q_tile_shape": (8, 4, 8), + "kv_tile_shape": (4, 4, 8), + "backward_q_tile_shape": (4, 4, 8), + "backward_kv_tile_shape": (4, 4, 8), + "run_persistent_kernel": True, + }, + } + + def get_adaptive_parameters(self, window_size, stride, dilation, is_causal, input_shape, base_size=None): + window_size = tuple(w if w > 1 else x for x, w in zip(input_shape, window_size)) + stride = tuple(stride for _ in range(3)) if isinstance(stride, int) else tuple(x for x in stride) + dilation = tuple(dilation for _ in range(3)) if isinstance(dilation, int) else tuple(x for x in dilation) + is_causal = tuple(is_causal for _ in range(3)) if isinstance(is_causal, bool) else tuple(x for x in is_causal) + + # Scale window size and stride according to some base input size + # For example, if window size is (8, 8, 8), stride is (1, 2, 2), for a base + # input/feature map size of (16, 16, 16); then if the input feat map in this iteration + # has shape (8, 8, 8), we should use window size (4, 4, 4), and stride (1, 1, 1). + if base_size is not None: + base_shape = tuple(b if b > 0 else x for x, b in zip(input_shape, base_size)) + + scale = tuple(x / b for x, b in zip(input_shape, base_shape)) + + scaled_window_size = tuple(min(max(2, round(w * s)), x) for w, s, x in zip(window_size, scale, input_shape)) + scaled_stride = tuple(min(max(1, round(st * s)), w) for w, s, st in zip(scaled_window_size, scale, stride)) + + max_dilation = tuple(x // w for x, w in zip(input_shape, scaled_window_size)) + scaled_dilation = tuple( + min(max(1, round(d * s)), max_d) for d, s, max_d in zip(dilation, scale, max_dilation) + ) + + window_size = scaled_window_size + stride = scaled_stride + dilation = scaled_dilation + + assert all(x >= w * d for x, w, d in zip(input_shape, window_size, dilation)) + assert all(w >= s for w, s in zip(window_size, stride)) + assert all(isinstance(c, bool) for c in is_causal) + + return window_size, stride, dilation, is_causal + + def forward( + self, + q_B_L_H_D: torch.Tensor, + k_B_L_H_D: torch.Tensor, + v_B_L_H_D: torch.Tensor, + video_size: Optional[VideoSize] = None, + ): + if not (q_B_L_H_D.shape == k_B_L_H_D.shape == v_B_L_H_D.shape): + raise ValueError( + f"NATTEN requires QKV shapes to match, got {q_B_L_H_D.shape=}, {k_B_L_H_D.shape=}, {v_B_L_H_D.shape=}." + ) + + device = q_B_L_H_D.device + compute_cap = get_device_cc(device) + requires_grad = q_B_L_H_D.requires_grad or k_B_L_H_D.requires_grad or v_B_L_H_D.requires_grad + is_cuda = torch.cuda.is_available() and torch.version.cuda and device.type == "cuda" + + if not is_cuda: + raise NotImplementedError(f"Cosmos-Predict2 + NATTEN requires CUDA, tensors were on {device=}.") + + if compute_cap not in ALLOWED_COMPUTE_CAPS: + raise NotImplementedError( + "Cosmos-Predict2 + NATTEN is only allowed on devices with the following " + f"compute capabilities: {ALLOWED_COMPUTE_CAPS}, got {compute_cap}." + ) + + natten_configuration = None + assert 80 in self.performance_configs.keys() + if is_cuda and compute_cap in self.performance_configs.keys(): + natten_configuration = self.performance_configs[compute_cap] + elif is_cuda and compute_cap >= 80: + natten_configuration = self.performance_configs[80] + else: + raise ValueError(f"No NATTEN config found for this use case: {requires_grad=}, {is_cuda=}, {compute_cap=}.") + + batch, seqlen, heads, head_dim = q_B_L_H_D.shape + T, H, W = video_size + + if seqlen != T * H * W: + raise ValueError(f"Mismatch between seqlen and video_size dimensions; got {video_size=}, {seqlen=}.") + + if T > 1: + input_shape = (T, H, W) + + window_size, stride, dilation, is_causal = self.get_adaptive_parameters( + window_size=self.window_size, + stride=self.stride, + dilation=self.dilation, + is_causal=self.is_causal, + input_shape=input_shape, + base_size=self.base_size, + ) + + elif T == 1: + # Do self attention for image model; skip natten + return self.base_attn_op(q_B_L_H_D, k_B_L_H_D, v_B_L_H_D) + + else: + raise ValueError(f"Invalid dimension {T=}.") + + q = q_B_L_H_D.view(batch, *input_shape, heads, head_dim) + k = k_B_L_H_D.view(batch, *input_shape, heads, head_dim) + v = v_B_L_H_D.view(batch, *input_shape, heads, head_dim) + + out = neighborhood_attention_generic( + query=q, + key=k, + value=v, + kernel_size=window_size, + stride=stride, + dilation=dilation, + is_causal=is_causal, + **natten_configuration, + ) + + return out.view(batch, seqlen, heads, head_dim) diff --git a/diffusion/training/networks/selective_activation_checkpoint.py b/diffusion/training/networks/selective_activation_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..a3345f73c650920eaa37b42f787bea4fa9826d64 --- /dev/null +++ b/diffusion/training/networks/selective_activation_checkpoint.py @@ -0,0 +1,72 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +from dataclasses import dataclass +from enum import Enum + +import torch + +try: + from torch.utils.checkpoint import CheckpointPolicy, create_selective_checkpoint_contexts, noop_context_fn +except ImportError: + CheckpointPolicy = None + +mm_only_save_list = { + torch.ops.aten.mm.default, + torch.ops.aten._scaled_dot_product_efficient_attention.default, + torch.ops.aten._scaled_dot_product_flash_attention.default, + torch.ops.aten.addmm.default, +} + + +class CheckpointMode(str, Enum): + """ + Enum for the different checkpoint modes. + """ + + NONE = "none" + MM_ONLY = "mm_only" + BLOCK_WISE = "block_wise" + + def __str__(self) -> str: + # Optional: makes print() show just the value + return self.value + + +def mm_only_policy(ctx, func, *args, **kwargs): + """ + In newer flash-attn and TE versions, FA2 shows up in the list of ops with the name of 'flash_attn._flash_attn_forward'. + However, FA2 is much slower (2-3x) than FA3 or cuDNN kernel. Registering cuDNN kernel would require heavy changes in TE code. + That's why the best option is to use FA3 with small modifications to flash_attn_interface.py to register FA3 as PyTorch op. + """ + to_save = func in mm_only_save_list or "flash_attn" in str(func) + return CheckpointPolicy.MUST_SAVE if to_save else CheckpointPolicy.PREFER_RECOMPUTE + + +def mm_only_context_fn(): + return create_selective_checkpoint_contexts(mm_only_policy) + + +@dataclass +class SACConfig: + mode: str = "mm_only" + every_n_blocks: int = 1 + + def get_context_fn(self): + if self.mode == CheckpointMode.MM_ONLY: + return mm_only_context_fn + elif self.mode == CheckpointMode.BLOCK_WISE: + return noop_context_fn + else: + raise ValueError(f"Invalid mode: {self.mode}") diff --git a/diffusion/training/schedulers/__init__.py b/diffusion/training/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/diffusion/training/schedulers/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/diffusion/training/schedulers/rectified_flow.py b/diffusion/training/schedulers/rectified_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..5410c268306f3ec91c583522c28767db84d3964c --- /dev/null +++ b/diffusion/training/schedulers/rectified_flow.py @@ -0,0 +1,204 @@ +# ----------------------------------------------------------------------------- +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# +# This codebase constitutes NVIDIA proprietary technology and is strictly +# confidential. Any unauthorized reproduction, distribution, or disclosure +# of this code, in whole or in part, outside NVIDIA is strictly prohibited +# without prior written consent. +# +# For inquiries regarding the use of this code in other NVIDIA proprietary +# projects, please contact the Deep Imagination Research Team at +# dir@exchange.nvidia.com. +# ----------------------------------------------------------------------------- + +from typing import Callable, Optional, Tuple + +import numpy as np +import torch + +from diffusion.training.schedulers.shift_schedule import ( + sample_stretched_shifted_u, + stretch_shifted_t_to_unit, + stretch_shifts_to_terminal, +) + + +class TrainTimeWeight: + def __init__( + self, + noise_scheduler, + weight: str = "uniform", + ): + # Map reweighting -> uniform to support inference for existing checkpoints. + if weight == "reweighting": + weight = "uniform" + + self.weight = weight + self.noise_scheduler = noise_scheduler + + assert self.weight == "uniform", "Only uniform loss weight is supported in RF" + + def __call__(self, t, tensor_kwargs) -> torch.Tensor: + if self.weight == "uniform": + wts = torch.ones_like(t) + else: + raise NotImplementedError(f"Time weight '{self.weight}' is not implemented.") + + return wts + + +class TrainTimeSampler: + def __init__( + self, + distribution: str = "uniform", + ): + self.distribution = distribution + + @torch.no_grad() + def __call__( + self, + batch_size: int, + device: torch.device = torch.device("cpu"), + dtype: torch.dtype = torch.float32, + ) -> torch.Tensor: + """ + Sample time tensor for training + + Returns: + torch.Tensor: Time tensor, shape (batch_size,) + """ + if self.distribution == "uniform": + t = torch.rand((batch_size,)).to(device=device, dtype=dtype) + elif self.distribution == "logitnormal": + t = torch.sigmoid(torch.randn((batch_size,))).to(device=device, dtype=dtype) + elif self.distribution.startswith("waver_mode_"): + s = float(self.distribution.split("_")[-1]) + assert s - 1.29 < 1e-4, "Waver's mode distribution is only supported with s = 1.29" + u = torch.rand((batch_size,), dtype=torch.float32) + t = 1.0 - u - s * (torch.cos(torch.pi / 2.0 * u) ** 2 - 1 + u) + t = t.to(device=device, dtype=dtype) + else: + raise NotImplementedError(f"Time distribution '{self.distribution}' is not implemented.") + + return t + + +class RectifiedFlow: + def __init__( + self, + velocity_field: Callable, + train_time_distribution: TrainTimeSampler | str = "uniform", + train_time_weight_method: str = "uniform", + use_dynamic_shift: bool = False, + shift: int = 3, + shift_clamp_percentiles: Optional[Tuple[float, float]] = None, + shift_stretch_terminal: Optional[float] = None, + device: torch.device = torch.device("cpu"), + dtype: torch.dtype = torch.float32, + ): + r"""Initialize the RectifiedFlow class. + + Args: + velocity_field (`Callable`): + A function that predicts the velocity given the current state and time. + train_time_distribution (`TrainTimeSampler` or `str`, *optional*, defaults to `"uniform"`): + Distribution for sampling training times. + Can be an instance of `TrainTimeSampler` or a string specifying the distribution type. + train_time_weight (`TrainTimeWeight` or `str`, *optional*, defaults to `"uniform"`): + Weight applied to training times. + Can be an instance of `TrainTimeWeight` or a string specifying the weight type. + """ + self.velocity_field = velocity_field + self.train_time_sampler: TrainTimeSampler = ( + train_time_distribution + if isinstance(train_time_distribution, TrainTimeSampler) + else TrainTimeSampler(train_time_distribution) + ) + + assert use_dynamic_shift is False, "Dynamic shift is not supported in RectifiedFlow" + self.shift = shift + self.shift_clamp_percentiles = shift_clamp_percentiles + self.shift_stretch_terminal = shift_stretch_terminal + self.num_train_timesteps = 1000 + self.train_time_weight = TrainTimeWeight(None, train_time_weight_method) + + self.device = torch.device(device) if isinstance(device, str) else device + self.dtype = torch.dtype(dtype) if isinstance(dtype, str) else dtype + + def sample_train_time(self, batch_size: int): + r"""This method calls the `TrainTimeSampler` to sample training times. + + Returns: + t (`torch.Tensor`): + A tensor of sampled training times with shape `(batch_size,)`, + matching the class specified `device` and `dtype`. + """ + if self.shift_clamp_percentiles is not None: + return sample_stretched_shifted_u( + batch_size, + float(self.shift), + tuple(self.shift_clamp_percentiles), + device=self.device, + dtype=self.dtype, + ) + return self.train_time_sampler(batch_size, device=self.device, dtype=self.dtype) + + def apply_shift_reparam(self, u: torch.Tensor) -> torch.Tensor: + """Map ``u ∈ [0, 1]`` through shift (+ optional LTX stretch affine to ``[0, 1]``).""" + t = self.shift * u / (1 + (self.shift - 1) * u) + if self.shift_clamp_percentiles is not None: + t = stretch_shifted_t_to_unit( + t, float(self.shift), tuple(self.shift_clamp_percentiles), + ) + return t + + def stretch_inference_sigmas(self, sigmas: np.ndarray) -> np.ndarray: + """LTX stretch on a noise→clean sigma schedule (``sigmas[-1]`` → terminal).""" + if self.shift_stretch_terminal is None: + return sigmas + return stretch_shifts_to_terminal(sigmas, self.shift_stretch_terminal) + + def get_discrete_timestamp(self, u, tensor_kwargs): + r"""This method map time from 0,1 to discrete steps""" + u = u.squeeze() + timesteps = self.apply_shift_reparam(u) + timesteps = timesteps * self.num_train_timesteps # [0, 1] to [0, 1000] + return timesteps.unsqueeze(0) if timesteps.ndim == 0 else timesteps + + def get_sigmas(self, timesteps, tensor_kwargs): + sigmas = (timesteps.to(**tensor_kwargs)) / self.num_train_timesteps + return sigmas + + def get_interpolation( + self, + x_0: torch.Tensor, + x_1: torch.Tensor, + t: torch.Tensor, + ): + r""" + This method computes interpolation `X_t` and their time derivatives `dotX_t` at the specified time points `t`. + Note that `x_0` is the noise, and `x_1` is the clean data. This is aligned with the notation in the recified flow community, + but different from the notation in the diffusion community. + + Args: + x_0 (`torch.Tensor`): + noise, shape `(B, D1, D2, ..., Dn)`, where `B` is the batch size, and `D1, D2, ..., Dn` are the data dimensions. + x_1 (`torch.Tensor`): + clean data, with the same shape as `x_0` + t (`torch.Tensor`): + A tensor of time steps, with shape `(B,)`, where each value is in `[0, 1]`. + + Returns: + (x_t, dot_x_t) (`Tuple[torch.Tensor, torch.Tensor]`): + - x_t (`torch.Tensor`): The interpolated state, with shape `(B, D1, D2, ..., Dn)`. + - dot_x_t (torch.Tensor): The time derivative of the interpolated state, with the same shape as `x_t`. + """ + assert x_0.shape == x_1.shape, "x_0 and x_1 must have the same shape." + assert x_0.shape[0] == x_1.shape[0], "Batch size of x_0 and x_1 must match." + assert t.shape[0] == x_1.shape[0], "Batch size of t must match x_1." + # Reshape t to match dimensions of x_1 + t = t.view(t.shape[0], *([1] * (len(x_1.shape) - 1))) + x_t = x_0 * t + x_1 * (1 - t) + dot_x_t = x_0 - x_1 + return x_t, dot_x_t diff --git a/diffusion/training/schedulers/shift_schedule.py b/diffusion/training/schedulers/shift_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..87f098fa899840c1721b11f14072bac0ec290a19 --- /dev/null +++ b/diffusion/training/schedulers/shift_schedule.py @@ -0,0 +1,197 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Rectified-flow shift reparam, LTX training stretch, inference terminal stretch. + +LTX-Video arXiv:2501.00103 §2.5.2 / Fig. 10 (training): + After shift, support is limited to the shifted-t ``(p_lo, p_hi)`` percentiles and + affine-mapped to ``[0, 1]``. Use **truncated logitnormal** draws (not clip-then-map): + clip piles ~0.5% of mass at exactly ``t=0``; truncation keeps a smooth left tail like + the paper's blue curve. + +Inference: ``stretch_shifts_to_terminal`` remaps the discrete sigma ladder (separate). +""" + +from __future__ import annotations + +import math +from typing import Optional, Tuple, Union + +import numpy as np +import torch + +DEFAULT_SHIFT_CLAMP_PERCENTILES: Tuple[float, float] = (0.5, 99.9) + +_SHIFT_T_QUANTILE_CACHE: dict[tuple, tuple[float, float]] = {} +_STRETCH_U_BOUNDS_CACHE: dict[tuple, tuple[float, float, float, float, float, float]] = {} + + +def shifted_t(t, shift: float): + """``t' = shift*t / (1 + (shift-1)*t)``; monotone on ``[0, 1]``.""" + return shift * t / (1.0 + (shift - 1.0) * t) + + +def inv_shifted_t(t, shift: float): + """Inverse of :func:`shifted_t` on ``[0, 1]``.""" + t = np.asarray(t, dtype=np.float64) if not isinstance(t, torch.Tensor) else t + return t / (shift - (shift - 1.0) * t) + + +def stretch_shifts_to_terminal( + shifts: np.ndarray, + terminal: float = 0.1, +) -> np.ndarray: + """Stretch a monotone inference schedule so ``shifts[-1] == terminal`` (LTX rf.py).""" + shifts = np.asarray(shifts, dtype=np.float64) + if shifts.size == 0: + raise ValueError("shifts must not be empty") + if not (0.0 < terminal < 1.0): + raise ValueError(f"terminal must be in (0, 1), got {terminal}") + one_minus_z = 1.0 - shifts + scale_factor = one_minus_z[-1] / (1.0 - terminal) + return 1.0 - (one_minus_z / scale_factor) + + +def shift_t_quantile_bounds( + shift: float, + p_lo: float = DEFAULT_SHIFT_CLAMP_PERCENTILES[0], + p_hi: float = DEFAULT_SHIFT_CLAMP_PERCENTILES[1], + n_mc: int = 200_000, + seed: int = 0, +) -> tuple[float, float]: + """``(p_lo, p_hi)`` percentiles of ``logitnormal(0,1) ∘ shifted_t`` (no stretch).""" + key = (float(shift), float(p_lo), float(p_hi), int(n_mc), int(seed)) + if key not in _SHIFT_T_QUANTILE_CACHE: + rng = np.random.default_rng(seed) + t = sample_shifted_t_density(shift, n=n_mc, rng=rng, stretch_percentiles=None) + _SHIFT_T_QUANTILE_CACHE[key] = ( + float(np.percentile(t, p_lo)), + float(np.percentile(t, p_hi)), + ) + return _SHIFT_T_QUANTILE_CACHE[key] + + +def shift_stretch_bounds( + shift: float, + percentiles: Tuple[float, float] = DEFAULT_SHIFT_CLAMP_PERCENTILES, +) -> tuple[float, float, float, float, float, float]: + """``(lo, hi, u_lo, u_hi, z_lo, z_hi)`` for truncated logitnormal stretch.""" + key = (float(shift), float(percentiles[0]), float(percentiles[1])) + if key not in _STRETCH_U_BOUNDS_CACHE: + lo, hi = shift_t_quantile_bounds(shift, percentiles[0], percentiles[1]) + eps = 1e-6 + u_lo = float(np.clip(inv_shifted_t(lo, shift), eps, 1.0 - eps)) + u_hi = float(np.clip(inv_shifted_t(hi, shift), u_lo, 1.0 - eps)) + z_lo = math.log(u_lo / (1.0 - u_lo)) + z_hi = math.log(u_hi / (1.0 - u_hi)) + _STRETCH_U_BOUNDS_CACHE[key] = (lo, hi, u_lo, u_hi, z_lo, z_hi) + return _STRETCH_U_BOUNDS_CACHE[key] + + +def _affine_stretch_to_unit(t, lo: float, hi: float): + span = max(float(hi) - float(lo), 1e-12) + if isinstance(t, torch.Tensor): + return (t - lo) / span + return (np.asarray(t, dtype=np.float64) - lo) / span + + +def _sample_truncated_standard_normal_np( + n: int, + low: float, + high: float, + rng: np.random.Generator, +) -> np.ndarray: + """``z ~ N(0,1)`` conditioned on ``z in [low, high]`` (rejection).""" + out: list[np.ndarray] = [] + need = n + for _ in range(32): + if need <= 0: + break + z = rng.normal(0.0, 1.0, size=need * 2) + ok = (z >= low) & (z <= high) + if ok.any(): + out.append(z[ok]) + need -= int(ok.sum()) + if need > 0: + out.append(rng.uniform(low, high, size=need)) + return np.concatenate(out)[:n] + + +def _sample_truncated_standard_normal_torch( + size: int, + low: float, + high: float, + device: torch.device, + dtype: torch.dtype, +) -> torch.Tensor: + low_t = torch.tensor(low, device=device, dtype=dtype) + high_t = torch.tensor(high, device=device, dtype=dtype) + buf: list[torch.Tensor] = [] + need = size + for _ in range(32): + if need <= 0: + break + z = torch.randn(need * 2, device=device, dtype=dtype) + m = (z >= low_t) & (z <= high_t) + if m.any(): + buf.append(z[m]) + need -= int(m.sum().item()) + if need > 0: + buf.append(low_t + (high_t - low_t) * torch.rand(need, device=device, dtype=dtype)) + return torch.cat(buf)[:size] + + +def sample_stretched_shifted_u( + n: int, + shift: float, + percentiles: Tuple[float, float] = DEFAULT_SHIFT_CLAMP_PERCENTILES, + *, + rng: Optional[np.random.Generator] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, +) -> Union[np.ndarray, torch.Tensor]: + """``u = sigmoid(z)`` with ``z ~ N(0,1)`` truncated so ``shifted_t(u) in [lo, hi]``.""" + lo, hi, _u_lo, _u_hi, z_lo, z_hi = shift_stretch_bounds(shift, percentiles) + if device is not None: + dtype = dtype or torch.float32 + z = _sample_truncated_standard_normal_torch(n, z_lo, z_hi, device, dtype) + return torch.sigmoid(z) + rng = rng if rng is not None else np.random.default_rng(0) + z = _sample_truncated_standard_normal_np(n, z_lo, z_hi, rng) + return (1.0 / (1.0 + np.exp(-z))).astype(np.float64) + + +def stretch_shifted_t_to_unit( + t, + shift: float, + percentiles: Tuple[float, float] = DEFAULT_SHIFT_CLAMP_PERCENTILES, +): + """Affine map assuming ``t`` already lies in ``[lo, hi]`` (no clip).""" + lo, hi, _, _, _, _ = shift_stretch_bounds(shift, percentiles) + return _affine_stretch_to_unit(t, lo, hi) + + +def clamp_shifted_t_pdf(t, shift: float, clamp_percentiles: Tuple[float, float] = DEFAULT_SHIFT_CLAMP_PERCENTILES): + """Deprecated alias — prefer truncated sampling via :func:`sample_shifted_t_density`.""" + return stretch_shifted_t_to_unit(t, shift, clamp_percentiles) + + +def sample_shifted_t_density( + shift: float, + n: int = 10_000, + rng: Optional[np.random.Generator] = None, + stretch_percentiles: Optional[Tuple[float, float]] = None, + *, + clamp_percentiles: Optional[Tuple[float, float]] = None, +) -> np.ndarray: + """MC samples: logitnormal ∘ shift, optionally LTX stretch (truncated, smooth tails).""" + if clamp_percentiles is not None and stretch_percentiles is None: + stretch_percentiles = clamp_percentiles + if stretch_percentiles is not None: + u = sample_stretched_shifted_u(n, shift, stretch_percentiles, rng=rng) + t = np.asarray(shifted_t(u, shift), dtype=np.float64) + lo, hi, _, _, _, _ = shift_stretch_bounds(shift, stretch_percentiles) + return _affine_stretch_to_unit(t, lo, hi) + rng = rng if rng is not None else np.random.default_rng(0) + u_logit = rng.normal(0.0, 1.0, size=n) + u = 1.0 / (1.0 + np.exp(-u_logit)) + return np.asarray(shifted_t(u, shift), dtype=np.float64) diff --git a/diffusion/training/train.py b/diffusion/training/train.py new file mode 100644 index 0000000000000000000000000000000000000000..242b740bf227257f4134e36120f685425255564a --- /dev/null +++ b/diffusion/training/train.py @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import importlib +import os + +import torch.distributed as dist +from loguru import logger as logging +from omegaconf import OmegaConf + +from utils import log, misc +from utils.config import Config +from utils.config_helper import get_config_module, override +from utils.lazy_config import instantiate +from utils.lazy_config.lazy import LazyConfig +from utils.parallel_state_helper import is_tp_cp_pp_rank0 + + +@misc.timer("instantiate model") +def instantiate_model(config: Config, trainer) -> None: + misc.set_random_seed(seed=config.trainer.seed, by_rank=False) + config.model_obj.config = config.model + if getattr(config.model, "fsdp_enabled", False): + assert config.trainer.distributed_parallelism == "fsdp", "FSDP model is only supported with FSDP trainer" + log.critical("FSDP enabled") + config.model_obj.fsdp_checkpointer = trainer.checkpointer + model = instantiate(config.model_obj) + config.model_obj.fsdp_checkpointer = None + else: + model = instantiate(config.model_obj) + config.model_obj.config = None + misc.set_random_seed(seed=config.trainer.seed, by_rank=True) + return model + + +def destroy_distributed(): + log.info("Destroying distributed environment...") + if dist.is_available() and dist.is_initialized(): + try: + dist.destroy_process_group() + except ValueError as e: + print(f"Error destroying default process group: {e}") + + +@logging.catch(reraise=True) +def launch(config: Config, args: argparse.Namespace) -> None: + # Check that the config is valid + config.validate() + # Freeze the config so developers don't change it during training. + config.freeze() # type: ignore + trainer = config.trainer.type(config) + # # Setup the miscellaneous stuff for reproducibility. + # log_reproducible_setup(config, args) + # Create the model + model = instantiate_model(config, trainer) + model.on_model_init_end() + # Create the dataloaders. + if args.mp0_only_dl: + log.critical( + "Using only tp_cp_pp_rank0 dataloader for faster dataloading! Make sure val dl is mock and mock data has same keys as real data." + ) + raise NotImplementedError( + "mp0_only_dl is not implemented correctly! Please revisit this code and propose a more robust impl that raise error timely! It does not do necessary check before training to confirm it can work with image / video data. Current impl is problematic for image training." + ) + if is_tp_cp_pp_rank0() or not args.mp0_only_dl: + dataloader_train = instantiate(config.dataloader_train) + else: + dataloader_train = instantiate(config.dataloader_val) + dataloader_val = instantiate(config.dataloader_val) + # Start training + trainer.train( + model, + dataloader_train, + dataloader_val, + ) + destroy_distributed() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Training") + parser.add_argument( + "--config", + default="cosmos_predict1/diffusion/posttrain/config/config.py", + help="Path to the config file", + ) + parser.add_argument( + "opts", + help=""" +Modify config options at the end of the command. For Yacs configs, use +space-separated "PATH.KEY VALUE" pairs. +For python-based LazyConfig, use "path.key=value". + """.strip(), + default=None, + nargs=argparse.REMAINDER, + ) + parser.add_argument( + "--dryrun", + action="store_true", + help="Do a dry run without training. Useful for debugging the config.", + ) + parser.add_argument( + "--mp0_only_dl", + action="store_true", + help="Use only model parallel rank 0 dataloader for faster dataloading! Make sure mock data has same keys as real data.", + ) + args = parser.parse_args() + config_module = get_config_module(args.config) + config = importlib.import_module(config_module).make_config() + config = override(config, args.opts) + if args.dryrun: + os.makedirs(config.job.path_local, exist_ok=True) + LazyConfig.save_yaml(config, f"{config.job.path_local}/config.yaml") + print(OmegaConf.to_yaml(OmegaConf.load(f"{config.job.path_local}/config.yaml"))) + print(f"{config.job.path_local}/config.yaml") + else: + # Launch the training job. + launch(config, args) diff --git a/diffusion/training/trainer.py b/diffusion/training/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c31dcd6e077e3dacc1277b80ac998938f57ee048 --- /dev/null +++ b/diffusion/training/trainer.py @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.utils.data + +from diffusion.training.utils.checkpointer import MultiRankCheckpointer +from utils import misc +from utils.fsdp_checkpointer import FSDPCheckpointer +from utils.model import Model +from utils.trainer import Trainer as BaseTrainer + + +class Trainer(BaseTrainer): + def __init__(self, config): + super(Trainer, self).__init__(config) + if config.trainer.distributed_parallelism == "ddp": + self.checkpointer = MultiRankCheckpointer(config.checkpoint, config.job, callbacks=self.callbacks) + elif config.trainer.distributed_parallelism == "fsdp": + self.checkpointer = FSDPCheckpointer(config.checkpoint, config.job, callbacks=self.callbacks) + else: + raise ValueError(f"Unsupported distributed parallelism: {config.trainer.distributed_parallelism}") + + @torch.no_grad() + def validate( + self, + model: Model, + dataloader_val: torch.utils.data.DataLoader, + iteration: int = 0, + ) -> None: + """Validation without ema_scope — FSDP models manage EMA internally.""" + self.callbacks.on_validation_start(model, dataloader_val, iteration=iteration) + model.eval() + for val_iter, data_batch in enumerate(dataloader_val): + if self.config.trainer.max_val_iter is not None and val_iter >= self.config.trainer.max_val_iter: + break + data_batch = misc.to(data_batch, device="cuda") + self.callbacks.on_validation_step_start(model, data_batch, iteration=iteration) + output_batch, loss = model.validation_step(data_batch, iteration) + self.callbacks.on_validation_step_end( + model, data_batch, output_batch, loss, iteration=iteration + ) + self.callbacks.on_validation_end(model, iteration=iteration) diff --git a/diffusion/training/trainer_sf_dmd.py b/diffusion/training/trainer_sf_dmd.py new file mode 100644 index 0000000000000000000000000000000000000000..8af08121d427b1d88e0f686bd52d9c31616c60e3 --- /dev/null +++ b/diffusion/training/trainer_sf_dmd.py @@ -0,0 +1,1024 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Cycle-based trainer and checkpointing for LiDAR Self-Forcing DMD.""" + +from __future__ import annotations + +import gc +import os +import re +import time +from contextlib import nullcontext +from typing import Any + +import torch +from torch.distributed.fsdp import FullStateDictConfig, StateDictType +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + +from diffusion.checkpointers.ema_fsdp_checkpointer import ( + FSDPCheckpointer as EMAFSDPCheckpointer, +) +from diffusion.training.trainer import Trainer +from diffusion.training.utils.optim_instantiate import get_base_scheduler +from diffusion.training.utils.sf_dmd import normalized_frame_weights +from utils import distributed, log, misc +from utils.atomic_save import atomic_torch_save +from utils.fsdp_checkpointer import FSDPCheckpointer as BaseFSDPCheckpointer +from utils.fsdp_optim_fix import scatter_full_optim_state_dict +from utils.lazy_config import instantiate as lazy_instantiate + + +class SFDMDCheckpointer(EMAFSDPCheckpointer): + """Add fake-score model/optimizer state beside the normal student files.""" + + _GENERATION_MARKER_RE = re.compile(r"^iter_(\d{9})\.pt$") + _GENERATION_FILE_RE = re.compile(r"^iter_(\d{9}).*\.pt$") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._resolved_external_checkpoint: str | None = None + self.keep_last_checkpoints = int( + getattr(self.config_checkpoint, "keep_last_checkpoints", 0) + ) + self.save_at_iters = frozenset( + int(iteration) + for iteration in getattr( + self.config_checkpoint, "save_at_iters", [] + ) + ) + if self.keep_last_checkpoints < 0: + raise ValueError( + "checkpoint.keep_last_checkpoints must be non-negative, " + f"got {self.keep_last_checkpoints}" + ) + if any(iteration <= 0 for iteration in self.save_at_iters): + raise ValueError( + "checkpoint.save_at_iters must contain positive iterations, " + f"got {sorted(self.save_at_iters)}" + ) + + def should_save(self, cycle: int) -> bool: + save_iter = int(self.config_checkpoint.save_iter) + if save_iter <= 0: + raise ValueError( + f"checkpoint.save_iter must be positive, got {save_iter}" + ) + return cycle % save_iter == 0 or cycle in self.save_at_iters + + def _load_ckpt_file_during_init(self): + checkpoint_path, resume = super()._load_ckpt_file_during_init() + if checkpoint_path is None or not os.path.isdir(checkpoint_path): + return checkpoint_path, resume + if self._resolved_external_checkpoint is None: + latest_path = os.path.join( + checkpoint_path, "latest_checkpoint.txt" + ) + self._check_checkpoint_exists(latest_path) + with open(latest_path) as file: + latest = file.read().strip() + if not latest: + raise RuntimeError( + f"empty external latest checkpoint marker: {latest_path}" + ) + resolved = os.path.join(checkpoint_path, latest) + self._check_checkpoint_exists(resolved) + self._resolved_external_checkpoint = resolved + log.critical( + "[Checkpoint] Resolved external SF-DMD directory " + f"{checkpoint_path} to {resolved}" + ) + return self._resolved_external_checkpoint, resume + + @staticmethod + def _extra_path(checkpoint_path: str, suffix: str) -> str: + return checkpoint_path.replace(".pt", suffix) + + def _prune_old_generations(self, current_cycle: int) -> None: + """Delete complete SF-DMD generations older than the configured limit.""" + if self.keep_last_checkpoints == 0: + return + + filenames = os.listdir(self.checkpoint_dir_local) + completed_cycles = [] + for filename in filenames: + match = self._GENERATION_MARKER_RE.fullmatch(filename) + if match is not None: + cycle = int(match.group(1)) + if cycle <= current_cycle: + completed_cycles.append(cycle) + completed_cycles.sort() + ordinary_cycles = [ + cycle + for cycle in completed_cycles + if cycle not in self.save_at_iters + ] + stale_cycles = set( + ordinary_cycles[: -self.keep_last_checkpoints] + ) + if not stale_cycles: + return + + removed_files = 0 + for filename in filenames: + match = self._GENERATION_FILE_RE.fullmatch(filename) + if match is None or int(match.group(1)) not in stale_cycles: + continue + os.remove(os.path.join(self.checkpoint_dir_local, filename)) + removed_files += 1 + log.info( + "Pruned SF-DMD checkpoint generations " + f"{sorted(stale_cycles)} ({removed_files} files); retained the " + f"latest {self.keep_last_checkpoints} non-target generations and " + f"target iterations {sorted(self.save_at_iters)}" + ) + + def get_fake_score_load_path(self) -> str | None: + latest = self._read_latest_checkpoint_file() + if latest is not None: + checkpoint_path = os.path.join( + self.checkpoint_dir_local, latest + ) + else: + checkpoint_path, resume = self._load_ckpt_file_during_init() + if checkpoint_path is None or not resume: + return None + fake_path = self._extra_path(checkpoint_path, "_fake_score_model.pt") + self._check_checkpoint_exists(fake_path) + return fake_path + + def load_model_during_init( + self, model, is_ema: bool = False, ema_id: int = 0 + ): + # EMA->regular applies only to the external Stage-2 warm-start. A local + # SF-DMD resume must restore its independently evolved regular student. + checkpoint_path, resume = self._load_ckpt_file_during_init() + if resume: + return BaseFSDPCheckpointer.load_model_during_init( + self, model, is_ema=is_ema, ema_id=ema_id + ) + if ( + is_ema + and not self.load_ema_to_reg + and checkpoint_path is not None + ): + ema_path = checkpoint_path.replace(".pt", "_ema_model.pt") + regular_path = checkpoint_path.replace(".pt", "_reg_model.pt") + if not os.path.exists(ema_path) and os.path.exists(regular_path): + log.critical( + "External warm-start has no EMA payload; initializing " + f"Stage-3 EMA from regular student {regular_path}." + ) + return BaseFSDPCheckpointer.load_model_during_init( + self, model, is_ema=False, ema_id=0 + ) + return super().load_model_during_init( + model, is_ema=is_ema, ema_id=ema_id + ) + + @staticmethod + def _full_model_state(model: torch.nn.Module) -> dict[str, Any]: + if isinstance(model, FSDP): + with FSDP.state_dict_type( + model, + StateDictType.FULL_STATE_DICT, + FullStateDictConfig(offload_to_cpu=True, rank0_only=True), + ): + return model.state_dict() + return { + key: value.detach().cpu() + for key, value in model.state_dict().items() + } + + @staticmethod + def _expose_master_weights(optimizer: torch.optim.Optimizer) -> None: + groups_master = getattr(optimizer, "param_groups_master", None) + if groups_master is None: + return + for group, master_group in zip( + optimizer.param_groups, groups_master + ): + for parameter, master in zip( + group["params"], master_group["params"] + ): + if master is not None: + optimizer.state[parameter][ + "_sfdmd_master_param" + ] = master + + @staticmethod + def _restore_master_weights(optimizer: torch.optim.Optimizer) -> None: + if not getattr(optimizer, "master_weights", False): + return + groups_master = [] + for group in optimizer.param_groups: + masters = [] + for parameter in group["params"]: + master = optimizer.state[parameter].get( + "_sfdmd_master_param" + ) + if master is None: + # External warm-starts have no optimizer state. + optimizer.param_groups_master = None + return + masters.append( + master.to( + device=parameter.device, + dtype=torch.float32, + ) + ) + groups_master.append({"params": masters}) + optimizer.param_groups_master = groups_master + + def get_optim_scheduler_state(self, optim, fsdp_model, scheduler): + self._expose_master_weights(optim) + return super().get_optim_scheduler_state( + optim, fsdp_model, scheduler + ) + + def _load_optimizer_file( + self, + path: str, + fsdp_model: FSDP, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + ) -> None: + error = None + if distributed.get_rank() == 0: + try: + state = torch.load( + path, + map_location=lambda storage, loc: storage, + weights_only=False, + ) + full_optim_state = state["optimizer"] + scheduler_state = state["scheduler"] + except Exception as exc: # noqa: BLE001 + full_optim_state = None + scheduler_state = None + error = repr(exc) + else: + full_optim_state = None + scheduler_state = None + errors = [error] + torch.distributed.broadcast_object_list(errors, src=0) + if errors[0] is not None: + raise RuntimeError(f"optimizer load failed: {errors[0]}") + scatter_error = None + try: + sharded = scatter_full_optim_state_dict( + full_optim_state, + fsdp_model, + ) + except Exception as exc: # noqa: BLE001 + sharded = None + scatter_error = f"rank {distributed.get_rank()}: {exc!r}" + scatter_errors = [None] * distributed.get_world_size() + torch.distributed.all_gather_object( + scatter_errors, scatter_error + ) + failures = [item for item in scatter_errors if item is not None] + if failures: + raise RuntimeError( + f"optimizer-state scatter failed: {failures}" + ) + + local_error = None + try: + optimizer.load_state_dict(sharded) + except Exception as exc: # noqa: BLE001 + local_error = f"rank {distributed.get_rank()}: {exc!r}" + load_errors = [None] * distributed.get_world_size() + torch.distributed.all_gather_object(load_errors, local_error) + failures = [item for item in load_errors if item is not None] + if failures: + raise RuntimeError( + f"optimizer.load_state_dict failed: {failures}" + ) + + objects = [scheduler_state] + torch.distributed.broadcast_object_list(objects, src=0) + local_error = None + try: + scheduler.load_state_dict(objects[0]) + self._restore_master_weights(optimizer) + except Exception as exc: # noqa: BLE001 + local_error = f"rank {distributed.get_rank()}: {exc!r}" + load_errors = [None] * distributed.get_world_size() + torch.distributed.all_gather_object(load_errors, local_error) + failures = [item for item in load_errors if item is not None] + if failures: + raise RuntimeError( + f"scheduler/master restore failed: {failures}" + ) + + def load_optim_scheduler_during_init( + self, + fsdp_model, + optimizer, + scheduler, + ): + checkpoint_path, resume = self._load_ckpt_file_during_init() + if not resume or checkpoint_path is None: + return + path = checkpoint_path.replace(".pt", "_optim.pt") + self._check_checkpoint_exists(path) + self._load_optimizer_file( + path, fsdp_model, optimizer, scheduler + ) + log.info(f"Loaded SF-DMD student optimizer from {path}") + + def load_fake_optimizer( + self, + fake_model: FSDP, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + ) -> None: + checkpoint_path, resume = self._load_ckpt_file_during_init() + if not resume or checkpoint_path is None: + return + path = self._extra_path(checkpoint_path, "_fake_optim.pt") + self._check_checkpoint_exists(path) + self._load_optimizer_file( + path, fake_model, optimizer, scheduler + ) + log.info(f"Loaded SF-DMD fake-score optimizer from {path}") + + def save_sfdmd( + self, + model, + student_optimizer: torch.optim.Optimizer, + student_scheduler: torch.optim.lr_scheduler.LRScheduler, + fake_optimizer: torch.optim.Optimizer, + fake_scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + cycle: int, + ) -> None: + """Write a versioned multi-file generation, then publish one marker.""" + del grad_scaler + self.callbacks.on_save_checkpoint_start(model, cycle) + collection_error = None + try: + student_state = model.state_dict_model() + student_optim_state = self.get_optim_scheduler_state( + student_optimizer, + model.model, + student_scheduler, + ) + fake_state = self._full_model_state(model.fake_score) + fake_optim_state = self.get_optim_scheduler_state( + fake_optimizer, + model.fake_score, + fake_scheduler, + ) + except Exception as exc: # noqa: BLE001 + student_state = None + student_optim_state = None + fake_state = None + fake_optim_state = None + collection_error = ( + f"rank {distributed.get_rank()}: {exc!r}" + ) + collection_errors = [None] * distributed.get_world_size() + torch.distributed.all_gather_object( + collection_errors, collection_error + ) + failures = [ + item for item in collection_errors if item is not None + ] + if failures: + raise RuntimeError( + f"SF-DMD state collection failed: {failures}" + ) + callback_state = {"iteration": cycle} + self.callbacks.on_save_checkpoint( + model, state_dict=callback_state + ) + postfix, replicate_idx, shard_idx, total_ema_num = ( + model.get_ckpt_postfix() + ) + checkpoint_file = f"iter_{cycle:09d}{postfix}.pt" + checkpoint_path = os.path.join( + self.checkpoint_dir_local, checkpoint_file + ) + local_error = None + try: + os.makedirs(self.checkpoint_dir_local, exist_ok=True) + if replicate_idx == 0 and shard_idx == 0: + atomic_torch_save( + student_state["model"], + self._extra_path(checkpoint_path, "_reg_model.pt"), + ) + atomic_torch_save( + student_state["ema"], + self._extra_path(checkpoint_path, "_ema_model.pt"), + ) + atomic_torch_save( + student_optim_state, + self._extra_path(checkpoint_path, "_optim.pt"), + ) + atomic_torch_save(fake_state, self._extra_path( + checkpoint_path, "_fake_score_model.pt" + )) + atomic_torch_save(fake_optim_state, self._extra_path( + checkpoint_path, "_fake_optim.pt" + )) + atomic_torch_save(callback_state, checkpoint_path) + elif ( + replicate_idx < total_ema_num + and shard_idx == 0 + and student_state["ema"] is not None + ): + atomic_torch_save( + student_state["ema"], + self._extra_path(checkpoint_path, "_ema_model.pt"), + ) + except Exception as exc: # noqa: BLE001 + local_error = f"rank {distributed.get_rank()}: {exc!r}" + + errors = [None] * distributed.get_world_size() + torch.distributed.all_gather_object(errors, local_error) + failures = [error for error in errors if error is not None] + if failures: + raise RuntimeError( + "SF-DMD checkpoint generation failed; latest pointer was not " + f"updated: {failures}" + ) + marker_error = None + if distributed.get_rank() == 0: + try: + self._write_latest_checkpoint_file( + f"iter_{cycle:09d}.pt" + ) + except Exception as exc: # noqa: BLE001 + marker_error = repr(exc) + marker_errors = [marker_error] + torch.distributed.broadcast_object_list(marker_errors, src=0) + if marker_errors[0] is not None: + raise RuntimeError( + "SF-DMD checkpoint files are complete but latest marker " + f"publication failed: {marker_errors[0]}" + ) + if distributed.get_rank() == 0: + try: + # Prune only after the new generation is complete and its + # atomic latest pointer has been published. A crash during + # cleanup can therefore leave extras, never break resume. + self._prune_old_generations(cycle) + except Exception as exc: # noqa: BLE001 + log.warning( + "SF-DMD checkpoint retention cleanup failed; keeping " + f"older generations: {exc!r}" + ) + self.callbacks.on_save_checkpoint_success(iteration=cycle) + self.callbacks.on_save_checkpoint_end(model=model, iteration=cycle) + + +class SFDMDTrainer(Trainer): + """Train legacy SF-DMD or the ArtiFixer-aligned update schedule.""" + + def __init__(self, config): + super().__init__(config) + self.checkpointer = SFDMDCheckpointer( + config.checkpoint, + config.job, + callbacks=self.callbacks, + ) + + def _init_optimizers(self, model): + student_optimizer, student_scheduler = ( + model.init_optimizer_scheduler( + self.config.optimizer, + self.config.scheduler, + ) + ) + fake_optimizer = lazy_instantiate( + self.config.optimizer_fake, + model=model.fake_score, + ) + fake_scheduler = get_base_scheduler( + fake_optimizer, + model, + self.config.scheduler_fake, + ) + self.checkpointer.load_fake_optimizer( + model.fake_score, + fake_optimizer, + fake_scheduler, + ) + return ( + student_optimizer, + student_scheduler, + fake_optimizer, + fake_scheduler, + ) + + @staticmethod + def _mean_metrics( + metric_rows: list[dict[str, torch.Tensor]], + ) -> dict[str, torch.Tensor]: + if not metric_rows: + return {} + output = {} + for key in metric_rows[0]: + values = [row[key].detach().float() for row in metric_rows] + output[key] = torch.stack(values).mean() + return output + + def _fake_updates( + self, + model, + rollout, + optimizer, + scheduler, + grad_scaler, + cycle: int, + ) -> list[dict[str, torch.Tensor]]: + rows = [] + model.fake_score.train() + if ( + model.sfdmd_artifixer_matching + or model.sfdmd_imaginaire_matching + ): + optimizer.zero_grad(set_to_none=True) + num_records = ( + 1 + if model.sfdmd_imaginaire_matching + else len(rollout.records) + ) + record_weights = ( + [1.0] + if model.sfdmd_imaginaire_matching + else normalized_frame_weights( + [ + record.score_active_end + - record.score_active_start + for record in rollout.records + ] + ) + ) + score_batch = model.new_score_batch(rollout) + for record_idx in range(num_records): + sync_context = ( + nullcontext() + if record_idx == num_records - 1 + else model.fake_score.no_sync() + ) + with sync_context: + loss, metrics = model.fake_score_loss( + rollout, + record_idx, + score_batch=score_batch, + ) + weighted_loss = loss * record_weights[record_idx] + self.callbacks.on_before_backward( + model, weighted_loss, iteration=cycle + ) + grad_scaler.scale(weighted_loss).backward() + model.on_after_backward(iteration=cycle) + self.callbacks.on_after_backward( + model, iteration=cycle + ) + rows.append(metrics) + grads = [ + parameter.grad + for parameter in model.fake_score.parameters() + if parameter.grad is not None + ] + for grad in grads: + torch.nan_to_num_( + grad, nan=0.0, posinf=0.0, neginf=0.0 + ) + if isinstance(model.fake_score, FSDP): + model.fake_score.clip_grad_norm_( + model.sfdmd_max_grad_norm + ) + else: + torch.nn.utils.clip_grad_norm_( + model.fake_score.parameters(), + model.sfdmd_max_grad_norm, + ) + grad_scaler.step(optimizer) + grad_scaler.update() + scheduler.step() + # The student phase follows immediately and does not use fake-score + # gradients. Release their FSDP flat buffers before student replay. + optimizer.zero_grad(set_to_none=True) + return rows + + for update_idx in range(model.sfdmd_fake_updates): + optimizer.zero_grad(set_to_none=True) + loss, metrics = model.fake_score_loss( + rollout, + cycle * model.sfdmd_fake_updates + update_idx, + ) + self.callbacks.on_before_backward( + model, loss, iteration=cycle + ) + grad_scaler.scale(loss).backward() + model.on_after_backward(iteration=cycle) + self.callbacks.on_after_backward(model, iteration=cycle) + # The standard grad-clip callback targets model.model (student). + # Apply the same finite+norm policy explicitly to fake_score. + grads = [ + parameter.grad + for parameter in model.fake_score.parameters() + if parameter.grad is not None + ] + for grad in grads: + torch.nan_to_num_( + grad, nan=0.0, posinf=0.0, neginf=0.0 + ) + if isinstance(model.fake_score, FSDP): + model.fake_score.clip_grad_norm_( + model.sfdmd_max_grad_norm + ) + else: + torch.nn.utils.clip_grad_norm_( + model.fake_score.parameters(), + model.sfdmd_max_grad_norm, + ) + grad_scaler.step(optimizer) + grad_scaler.update() + scheduler.step() + optimizer.zero_grad(set_to_none=True) + rows.append(metrics) + return rows + + def _student_update( + self, + model, + rollout, + optimizer, + scheduler, + grad_scaler, + cycle: int, + target_map=None, + ) -> list[dict[str, torch.Tensor]]: + rows = [] + optimizer.zero_grad(set_to_none=True) + num_records = len(rollout.records) + record_weights = ( + None + if model.sfdmd_imaginaire_matching + else normalized_frame_weights( + [ + record.score_active_end - record.score_active_start + for record in rollout.records + ] + ) + ) + kv_cache = model.new_student_kv_cache() + if rollout.conditioned_prefix_frames > 0: + model.seed_student_conditioned_prefix(rollout, kv_cache) + tbptt_blocks = model.sfdmd_tbptt_blocks + # FSDP no_sync retains full gradients, defeating memory-bounded TBPTT. + sync_each_segment = model.sfdmd_allow_truncated_bptt + for segment_start in range(0, num_records, tbptt_blocks): + segment_end = min(segment_start + tbptt_blocks, num_records) + sync_context = ( + nullcontext() + if sync_each_segment or segment_end == num_records + else model.model.no_sync() + ) + with sync_context: + segment_loss = None + for record_idx in range(segment_start, segment_end): + record = rollout.records[record_idx] + if cycle == 1 and distributed.get_rank() == 0: + gib = 1024**3 + log.info( + "Student replay memory before block " + f"{record.block_index}: allocated=" + f"{torch.cuda.memory_allocated() / gib:.2f} GiB, " + f"reserved={torch.cuda.memory_reserved() / gib:.2f} GiB" + ) + loss, metrics = model.student_replay_loss( + record, + kv_cache, + None + if target_map is None + else target_map[record.block_index], + ) + scaled_loss = ( + loss + if model.sfdmd_imaginaire_matching + else loss * record_weights[record_idx] + ) + segment_loss = ( + scaled_loss + if segment_loss is None + else segment_loss + scaled_loss + ) + rows.append(metrics) + assert segment_loss is not None + self.callbacks.on_before_backward( + model, segment_loss, iteration=cycle + ) + grad_scaler.scale(segment_loss).backward() + model.on_after_backward(iteration=cycle) + self.callbacks.on_after_backward(model, iteration=cycle) + # Preserve sink/recent contents while cutting the graph only at the + # configured replay-segment boundary. Canonical ArtiFixer uses one + # full-rollout segment; explicit memory-bounded handoffs detach at + # their configured truncated-BPTT boundary. + model.detach_student_kv_cache(kv_cache) + self.callbacks.on_before_optimizer_step( + model, + optimizer, + scheduler, + grad_scaler, + iteration=cycle, + ) + grad_scaler.step(optimizer) + grad_scaler.update() + scheduler.step() + self.callbacks.on_before_zero_grad( + model, + optimizer, + scheduler, + iteration=cycle, + ) + if model.sfdmd_artifixer_matching and model.config.ema.enabled: + beta = ( + 0.0 + if cycle < model.sfdmd_ema_start_cycle + else float(model.config.ema.beta) + ) + ema_worker = getattr(model, "model_ema_worker", None) + ema_model = getattr(model, "model_ema", None) + if ema_worker is None or ema_model is None: + raise RuntimeError( + "ArtiFixer-aligned SF-DMD requires an initialized EMA " + "worker and model" + ) + ema_worker.update_average( + model.model, + ema_model, + beta=beta, + ) + else: + ema_iteration = ( + cycle // model.sfdmd_student_update_freq + if model.sfdmd_imaginaire_matching + else cycle + ) + model.on_before_zero_grad( + optimizer, + scheduler, + iteration=ema_iteration, + ) + optimizer.zero_grad(set_to_none=True) + return rows + + def train( + self, + model, + dataloader_train: torch.utils.data.DataLoader, + dataloader_val: torch.utils.data.DataLoader, + ) -> None: + del dataloader_val + model = model.to( + "cuda", memory_format=self.config.trainer.memory_format + ) + model.on_train_start(self.config.trainer.memory_format) + self._log_param_count(model) + + self.callbacks.on_optimizer_init_start() + ( + student_optimizer, + student_scheduler, + fake_optimizer, + fake_scheduler, + ) = self._init_optimizers(model) + grad_scaler = torch.amp.GradScaler( + "cuda", **self.config.trainer.grad_scaler_args + ) + self.callbacks.on_optimizer_init_end() + cycle = self.checkpointer.load( + model, + student_optimizer, + student_scheduler, + grad_scaler, + ) + self.callbacks.on_train_start(model, iteration=cycle) + dataloader_iter = iter(dataloader_train) + run_kv_gate = bool(model.sfdmd_run_kv_equivalence_gate) + kv_gate_metrics = None if cycle == 0 and run_kv_gate else {} + if not run_kv_gate: + log.info( + "Skipping the DiT KV-cache equivalence gate because " + "model.sfdmd_run_kv_equivalence_gate=False." + ) + elif cycle > 0: + log.info( + "Skipping the DiT KV-cache equivalence gate when resuming " + f"from cycle {cycle}; the gate runs only before cycle 0." + ) + + while cycle < self.config.trainer.max_iter: + self.callbacks.on_before_dataloading(cycle) + try: + data_batch = next(dataloader_iter) + except StopIteration: + dataloader_iter = iter(dataloader_train) + data_batch = next(dataloader_iter) + self.callbacks.on_after_dataloading(cycle) + data_batch = misc.to(data_batch, device="cuda") + self.callbacks.on_training_step_start( + model, data_batch, iteration=cycle + ) + model.train() + if kv_gate_metrics is None: + kv_gate_metrics = model.verify_student_kv_equivalence( + data_batch + ) + + cycle_start = time.perf_counter() + rollout_start = cycle_start + rollout = model.rollout_sfdmd(data_batch, cycle) + rollout_seconds = time.perf_counter() - rollout_start + + if model.sfdmd_imaginaire_matching: + student_due = ( + cycle % model.sfdmd_student_update_freq == 0 + ) + else: + student_due = ( + not model.sfdmd_artifixer_matching + or ( + (cycle - 1) + % model.sfdmd_student_update_freq + == 0 + ) + ) + target_start = time.perf_counter() + student_targets = ( + model.artifixer_student_targets(rollout) + if ( + ( + model.sfdmd_artifixer_matching + or model.sfdmd_imaginaire_matching + ) + and student_due + ) + else None + ) + target_seconds = time.perf_counter() - target_start + + fake_start = time.perf_counter() + fake_rows = ( + [] + if model.sfdmd_imaginaire_matching and student_due + else self._fake_updates( + model, + rollout, + fake_optimizer, + fake_scheduler, + grad_scaler, + cycle, + ) + ) + fake_seconds = time.perf_counter() - fake_start + + student_start = time.perf_counter() + student_rows = ( + self._student_update( + model, + rollout, + student_optimizer, + student_scheduler, + grad_scaler, + cycle, + target_map=student_targets, + ) + if student_due + else [] + ) + student_seconds = time.perf_counter() - student_start + + cycle += 1 + device = rollout.generated_real_latents.device + output_batch = { + **kv_gate_metrics, + **self._mean_metrics(fake_rows), + **self._mean_metrics(student_rows), + "sfdmd/cycle": torch.tensor( + float(cycle), device=device + ), + "sfdmd/num_blocks": torch.tensor( + float(len(rollout.records)), device=device + ), + "sfdmd/rollout_seconds": torch.tensor( + rollout_seconds, device=device + ), + "sfdmd/target_seconds": torch.tensor( + target_seconds, device=device + ), + "sfdmd/fake_seconds": torch.tensor( + fake_seconds, device=device + ), + "sfdmd/student_seconds": torch.tensor( + student_seconds, device=device + ), + "sfdmd/cycle_seconds": torch.tensor( + time.perf_counter() - cycle_start, device=device + ), + "sfdmd/generated_abs": ( + rollout.generated_real_latents.abs().mean() + ), + "sfdmd/exit_step": torch.tensor( + float(rollout.exit_step), device=device + ), + "sfdmd/student_updated": torch.tensor( + float(student_due), device=device + ), + } + if model.sfdmd_factorized_conditioning: + output_batch["sfdmd/factorized_prefix_k"] = torch.tensor( + float(rollout.conditioned_prefix_frames), device=device + ) + output_batch["sfdmd/factorized_geometry_g"] = torch.tensor( + float(rollout.factorized_geometry_observations), + device=device, + ) + for mode in model.sfdmd_factorized_hdmap_modes: + output_batch[ + f"sfdmd/factorized_hdmap_{mode}" + ] = torch.tensor( + float(mode == rollout.factorized_hdmap_mode), + device=device, + ) + for mode in model.sfdmd_factorized_geometry_modes: + output_batch[ + f"sfdmd/factorized_geometry_{mode}" + ] = torch.tensor( + float(mode == rollout.factorized_geometry_mode), + device=device, + ) + if fake_rows: + output_batch["loss/sfdmd_fake_score"] = output_batch[ + "fake_score_loss" + ] + if student_rows: + output_batch["loss/sfdmd_student"] = output_batch[ + "student_vsd_loss" + ] + for row in fake_rows: + block = int(row["critic_block"].item()) + output_batch[ + f"loss/sfdmd_fake_score_block_{block:02d}" + ] = row["fake_score_loss"] + for row in student_rows: + block = int(row["student_block"].item()) + output_batch[ + f"loss/sfdmd_student_block_{block:02d}" + ] = row["student_vsd_loss"] + output_batch[ + f"metric/sfdmd_teacher_fake_x0_l1_block_{block:02d}" + ] = row["teacher_fake_x0_l1"] + output_batch[ + f"metric/sfdmd_teacher_gen_x0_l1_block_{block:02d}" + ] = row["teacher_gen_x0_l1"] + loss_for_callbacks = output_batch[ + "student_vsd_loss" + if student_rows + else "fake_score_loss" + ] + self.callbacks.on_training_step_end( + model, + data_batch, + output_batch, + loss_for_callbacks, + iteration=cycle, + ) + del rollout, data_batch + gc.collect() + torch.cuda.empty_cache() + + if self.checkpointer.should_save(cycle): + self.checkpointer.save_sfdmd( + model, + student_optimizer, + student_scheduler, + fake_optimizer, + fake_scheduler, + grad_scaler, + cycle, + ) + + if not self.checkpointer.should_save(cycle): + self.checkpointer.save_sfdmd( + model, + student_optimizer, + student_scheduler, + fake_optimizer, + fake_scheduler, + grad_scaler, + cycle, + ) + self.callbacks.on_train_end(model, iteration=cycle) + self.checkpointer.finalize() + distributed.barrier() + self.callbacks.on_app_end() + log.success(f"Done with SF-DMD training at cycle {cycle}.") diff --git a/diffusion/training/utils/checkpointer.py b/diffusion/training/utils/checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..09048e5530b6e770babff923d6030d379c32c362 --- /dev/null +++ b/diffusion/training/utils/checkpointer.py @@ -0,0 +1,359 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import threading +from typing import List, NamedTuple, Tuple + +import torch + +from utils import distributed, log, misc +from utils.checkpointer import Checkpointer as BaseCheckpointer +from utils.model import Model + +TORCH_VERSION: Tuple[int, ...] = tuple(int(x) for x in torch.__version__.split(".")[:2]) +if TORCH_VERSION >= (1, 11): + from torch.ao import quantization + from torch.ao.quantization import FakeQuantizeBase, ObserverBase +elif ( + TORCH_VERSION >= (1, 8) + and hasattr(torch.quantization, "FakeQuantizeBase") + and hasattr(torch.quantization, "ObserverBase") +): + from torch import quantization + from torch.quantization import FakeQuantizeBase, ObserverBase + + +class _IncompatibleKeys( + NamedTuple( + "IncompatibleKeys", + [ + ("missing_keys", List[str]), + ("unexpected_keys", List[str]), + ("incorrect_shapes", List[Tuple[str, Tuple[int], Tuple[int]]]), + ], + ) +): + pass + + +def _get_module_for_key( + model: torch.nn.Module, + key: str, +) -> torch.nn.Module: + """Resolve the module owning one state-dict parameter or buffer.""" + current = model + for key_part in key.split(".")[:-1]: + current = getattr(current, key_part) + return current + + +def _adapt_zero_init_input_expansion( + target_module: torch.nn.Module, + checkpoint_tensor: torch.Tensor, + model_tensor: torch.Tensor, +) -> torch.Tensor | None: + """Preserve prefix/suffix inputs around zero-initialized inserted slots.""" + layout = getattr( + target_module, + "_checkpoint_zero_init_input_expansion", + None, + ) + if layout is None: + return None + if checkpoint_tensor.ndim != 2 or model_tensor.ndim != 2: + return None + prefix_channels, old_channels, new_channels = map(int, layout) + if ( + prefix_channels <= 0 + or old_channels < prefix_channels + or new_channels <= old_channels + or checkpoint_tensor.shape[0] != model_tensor.shape[0] + or checkpoint_tensor.shape[1] % old_channels != 0 + ): + return None + patch_volume = checkpoint_tensor.shape[1] // old_channels + if model_tensor.shape[1] != new_channels * patch_volume: + return None + prefix_features = prefix_channels * patch_volume + suffix_features = (old_channels - prefix_channels) * patch_volume + expanded = checkpoint_tensor.new_zeros(model_tensor.shape) + expanded[:, :prefix_features] = checkpoint_tensor[ + :, :prefix_features + ] + if suffix_features > 0: + expanded[:, -suffix_features:] = checkpoint_tensor[ + :, -suffix_features: + ] + return expanded + + +def _adapt_channel_remap( + target_module: torch.nn.Module, + checkpoint_tensor: torch.Tensor, + model_tensor: torch.Tensor, +) -> torch.Tensor | None: + """Remap selected channel spans while zero-initializing new channels.""" + layout = getattr(target_module, "_checkpoint_channel_remap", None) + if layout is None or checkpoint_tensor.ndim != 2 or model_tensor.ndim != 2: + return None + kind, old_channels, new_channels, spans = layout + old_channels = int(old_channels) + new_channels = int(new_channels) + spans = tuple(tuple(map(int, span)) for span in spans) + if old_channels <= 0 or new_channels <= 0: + return None + expanded = checkpoint_tensor.new_zeros(model_tensor.shape) + if kind == "input": + if ( + checkpoint_tensor.shape[0] != model_tensor.shape[0] + or checkpoint_tensor.shape[1] % old_channels != 0 + ): + return None + patch_volume = checkpoint_tensor.shape[1] // old_channels + if model_tensor.shape[1] != new_channels * patch_volume: + return None + source = checkpoint_tensor.reshape( + checkpoint_tensor.shape[0], old_channels, patch_volume + ) + target = expanded.reshape( + model_tensor.shape[0], new_channels, patch_volume + ) + for old_start, old_stop, new_start, new_stop in spans: + if old_stop - old_start != new_stop - new_start: + return None + target[:, new_start:new_stop] = source[:, old_start:old_stop] + return expanded + if kind == "output": + if ( + checkpoint_tensor.shape[1] != model_tensor.shape[1] + or checkpoint_tensor.shape[0] % old_channels != 0 + ): + return None + patch_volume = checkpoint_tensor.shape[0] // old_channels + if model_tensor.shape[0] != new_channels * patch_volume: + return None + source = checkpoint_tensor.reshape( + patch_volume, old_channels, checkpoint_tensor.shape[1] + ) + target = expanded.reshape( + patch_volume, new_channels, model_tensor.shape[1] + ) + for old_start, old_stop, new_start, new_stop in spans: + if old_stop - old_start != new_stop - new_start: + return None + target[:, new_start:new_stop] = source[:, old_start:old_stop] + return expanded + return None + + +class MultiRankCheckpointer(BaseCheckpointer): + def save( + self, + model: Model, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int, + ) -> None: + """Save network weights, optimizer parameters, scheduler parameters to a checkpoint. + + Args: + model (Model): The PyTorch model. + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + grad_scaler (torch.amp.GradScaler): The gradient scaler (for mixed precision training). + iteration (int): Current iteration number. + """ + postfix, _, total_ema_num = model.get_ckpt_postfix() + checkpoint_file = f"ckpt_{postfix}.pt" + save_ranks = list(range(total_ema_num)) + for _rank in save_ranks: + if distributed.get_rank() == _rank: + state_dict = dict( + model=model.state_dict(), + optimizer=optimizer.state_dict(), + scheduler=scheduler.state_dict(), + grad_scaler=grad_scaler.state_dict(), + iteration=iteration, + ) + state_dict = misc.to(state_dict, device="cpu") + self.callbacks.on_save_checkpoint(model, state_dict=state_dict) + # Wait for previous saver thread to end. + if self.save_thread: + self.save_thread.join() + # Run the checkpoint saver in a separate thread. + self.save_thread = threading.Thread( + target=self._save_worker_local, + daemon=False, + args=(state_dict, checkpoint_file, distributed.get_rank()), + ) + self.save_thread.start() + + @misc.timer("checkpoint loading") + def load( + self, + model: Model, + optimizer: torch.optim.Optimizer | None = None, + scheduler: torch.optim.lr_scheduler.LRScheduler | None = None, + grad_scaler: torch.amp.GradScaler | None = None, + ) -> int: + """Load network weights and optimizer states from a checkpoint in a single process. + + The priority of the checkpoint loading logic is: + 1. Attempt to resume training if possible by looking for latest_checkpoint.txt under the same name. + 2. If no latest checkpoint were found, it loads the model weights specified by config_checkpoint.path. + - This is typically used for inference mode. + - If config_checkpoint.load_optimizer_state is True, then also load the optimizer and scheduler states. + 3. If none of the above, randomly initialize the model parameters and train from scratch. + + Args: + model (Model): The PyTorch model. + optimizer (torch.optim.Optimizer | None): The model optimizer (default: None). + scheduler (torch.optim.lr_scheduler.LRScheduler | None): The optimization scheduler (default: None). + grad_scaler (torch.amp.GradScaler | None): The gradient scaler (for mixed precision training). + + Returns: + iteration (int): the iteration number to start/resume from. + """ + latest_checkpoint_file = self._read_latest_checkpoint_file() + if latest_checkpoint_file is not None: + # different from base checkpointer, this support multi-EMA + postfix, _, total_ema_num = model.get_ckpt_postfix() + latest_checkpoint_file = latest_checkpoint_file.replace(".pt", f"{postfix}.pt") + # 1. Resume training from latest_checkpoint.txt under the same name. + checkpoint_dir = self.checkpoint_dir_local + checkpoint_path = os.path.join(checkpoint_dir, latest_checkpoint_file) + resume = True + else: + if self.load_path: + # 2. Load the module weights specified by config_checkpoint.path. + checkpoint_path = self.load_path + # different from base checkpointer, this support multi-EMA + postfix, _, total_ema_num = model.get_ckpt_postfix() + checkpoint_path = checkpoint_path.replace(".pt", f"{postfix}.pt") + resume = self.load_training_state + else: + # 3. Randomly initialize the model parameters and train from scratch. + checkpoint_path = None + resume = False + # Load checkpoint. + if checkpoint_path is not None: + self._check_checkpoint_exists(checkpoint_path) + log.info(f"Loading checkpoint (local): {checkpoint_path}") + state_dict = torch.load(checkpoint_path, map_location=lambda storage, loc: storage) + log.success(f"Complete loading checkpoint (local): {checkpoint_path}") + self.callbacks.on_load_checkpoint(model, state_dict=state_dict) + # Load the state dicts. + log.info("- Loading the model...") + log.critical(model.load_state_dict(state_dict["model"], strict=self.strict_resume)) + if resume: + iteration = state_dict["iteration"] + assert optimizer and scheduler + log.info("- Loading the optimizer...") + optimizer.load_state_dict(state_dict["optimizer"]) + log.info("- Loading the scheduler...") + scheduler.load_state_dict(state_dict["scheduler"]) + scheduler.last_epoch = iteration + log.info("- Loading the gradient scaler...") + grad_scaler.load_state_dict(state_dict["grad_scaler"]) + log.success(f"Done with loading the checkpoint (iteration {iteration}).") + else: + iteration = 0 + log.success("Done with loading the checkpoint.") + else: + # Checkpoint not found and not specified. We will train everything from scratch. + iteration = 0 + log.info("Training from scratch.") + torch.cuda.empty_cache() + return iteration + + +# https://github.com/facebookresearch/fvcore/blob/9d683aae73fb899dd35d6cf6720e5ef567761c57/fvcore/common/checkpoint.py +def non_strict_load_model(model: torch.nn.Module, checkpoint_state_dict: dict) -> _IncompatibleKeys: + # workaround https://github.com/pytorch/pytorch/issues/24139 + model_state_dict = model.state_dict() + incorrect_shapes = [] + for k in list(checkpoint_state_dict.keys()): + if k in model_state_dict: + if "_extra_state" in k: # Key introduced by TransformerEngine for FP8 + log.warning(f"Skipping key {k} introduced by TransformerEngine for FP8 in the checkpoint.") + continue + model_param = model_state_dict[k] + # Allow mismatch for uninitialized parameters + if TORCH_VERSION >= (1, 8) and isinstance(model_param, torch.nn.parameter.UninitializedParameter): + continue + if not isinstance(model_param, torch.Tensor): + raise ValueError( + f"Find non-tensor parameter {k} in the model. type: {type(model_param)} {type(checkpoint_state_dict[k])}, please check if this key is safe to skip or not." + ) + + shape_model = tuple(model_param.shape) + shape_checkpoint = tuple(checkpoint_state_dict[k].shape) + if shape_model != shape_checkpoint: + original_shape_checkpoint = shape_checkpoint + target_module = _get_module_for_key(model, k) + adapted = _adapt_channel_remap( + target_module, + checkpoint_state_dict[k], + model_param, + ) + if adapted is None: + adapted = _adapt_zero_init_input_expansion( + target_module, + checkpoint_state_dict[k], + model_param, + ) + if adapted is not None: + checkpoint_state_dict[k] = adapted + shape_checkpoint = tuple(adapted.shape) + log.info( + "Adapted checkpoint channel layout " + f"{k}: {original_shape_checkpoint} -> " + f"{shape_checkpoint}" + ) + if shape_model != shape_checkpoint: + has_observer_base_classes = ( + TORCH_VERSION >= (1, 8) + and hasattr(quantization, "ObserverBase") + and hasattr(quantization, "FakeQuantizeBase") + ) + if has_observer_base_classes: + # Handle the special case of quantization per channel observers, + # where buffer shape mismatches are expected. + cls_to_skip = ( + ObserverBase, + FakeQuantizeBase, + ) + target_module = _get_module_for_key(model, k) + if isinstance(target_module, cls_to_skip): + # Do not remove modules with expected shape mismatches + # them from the state_dict loading. They have special logic + # in _load_from_state_dict to handle the mismatches. + continue + + incorrect_shapes.append((k, shape_checkpoint, shape_model)) + checkpoint_state_dict.pop(k) + incompatible = model.load_state_dict(checkpoint_state_dict, strict=False) + # Remove keys with "_extra_state" suffix, which are non-parameter items introduced by TransformerEngine for FP8 handling + missing_keys = [k for k in incompatible.missing_keys if "_extra_state" not in k] + unexpected_keys = [k for k in incompatible.unexpected_keys if "_extra_state" not in k] + return _IncompatibleKeys( + missing_keys=missing_keys, + unexpected_keys=unexpected_keys, + incorrect_shapes=incorrect_shapes, + ) diff --git a/diffusion/training/utils/diffusion_forcing.py b/diffusion/training/utils/diffusion_forcing.py new file mode 100644 index 0000000000000000000000000000000000000000..7b614633e3adf08883d5cb87993c3979008cb3c3 --- /dev/null +++ b/diffusion/training/utils/diffusion_forcing.py @@ -0,0 +1,417 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Small dependency-free helpers for blockwise Diffusion Forcing.""" + +import torch +from torch import Tensor + + +def temporal_chunk_slices( + num_frames: int, + block_size: int, + prefix_frames: int = 0, +) -> list[tuple[int, int]]: + """Partition time into an optional prefix and complete causal blocks.""" + if num_frames <= 0: + raise ValueError(f"num_frames must be positive, got {num_frames}") + if block_size <= 0: + raise ValueError(f"block_size must be positive, got {block_size}") + if prefix_frames < 0 or prefix_frames > num_frames: + raise ValueError( + "prefix_frames must be in [0, num_frames], got " + f"{prefix_frames}/{num_frames}" + ) + body_frames = num_frames - prefix_frames + if body_frames % block_size != 0: + raise ValueError( + "temporal body must contain complete causal blocks: " + f"({num_frames}-{prefix_frames}) % {block_size} != 0" + ) + chunks = [] + if prefix_frames: + chunks.append((0, prefix_frames)) + chunks.extend( + (start, start + block_size) + for start in range(prefix_frames, num_frames, block_size) + ) + return chunks + + +def temporal_stream_chunk_bounds( + chunk_index: int, + block_size: int, + prefix_frames: int = 0, +) -> tuple[int, int]: + """Return one cached-call interval for a prefix-plus-block stream.""" + if chunk_index < 0: + raise ValueError("chunk_index must be non-negative") + if block_size <= 0: + raise ValueError("block_size must be positive") + if prefix_frames < 0: + raise ValueError("prefix_frames must be non-negative") + if prefix_frames and chunk_index == 0: + return 0, prefix_frames + body_index = chunk_index - int(prefix_frames > 0) + start = prefix_frames + body_index * block_size + return start, start + block_size + + +def pad_temporal_stream_tokens( + num_tokens: int, + block_size: int, + prefix_frames: int = 0, +) -> int: + """Pad a stream to a complete prefix-plus-block boundary.""" + if num_tokens < prefix_frames: + raise ValueError( + f"num_tokens={num_tokens} is smaller than prefix={prefix_frames}" + ) + if block_size <= 0: + raise ValueError("block_size must be positive") + body_tokens = num_tokens - prefix_frames + padded_body = ( + (body_tokens + block_size - 1) // block_size + ) * block_size + return prefix_frames + padded_body + + +def is_temporal_stream_boundary( + num_tokens: int, + block_size: int, + prefix_frames: int = 0, +) -> bool: + """Whether ``num_tokens`` ends after the prefix or a complete block.""" + if block_size <= 0 or prefix_frames < 0 or num_tokens < prefix_frames: + return False + return (num_tokens - prefix_frames) % block_size == 0 + + +def temporal_block_allows( + query_frame: Tensor | int, + key_frame: Tensor | int, + block_size: int, +): + """Whether a query block may attend to a key block.""" + if block_size <= 0: + raise ValueError(f"block_size must be positive, got {block_size}") + return (key_frame // block_size) <= (query_frame // block_size) + + +def temporal_prefix_block_allows( + query_frame: Tensor | int, + key_frame: Tensor | int, + block_size: int, + prefix_frames: int, +): + """Prefix-bidirectional, then block-causal temporal attention. + + Prefix queries see only the complete prefix. Future queries see the prefix, + their own future block, and earlier future blocks. ``prefix_frames=0`` is + exactly ``temporal_block_allows``. + """ + if block_size <= 0: + raise ValueError(f"block_size must be positive, got {block_size}") + if prefix_frames < 0: + raise ValueError( + f"prefix_frames must be non-negative, got {prefix_frames}" + ) + query_is_prefix = query_frame < prefix_frames + key_is_prefix = key_frame < prefix_frames + query_is_future = query_frame >= prefix_frames + key_is_future = key_frame >= prefix_frames + query_block = (query_frame - prefix_frames) // block_size + key_block = (key_frame - prefix_frames) // block_size + future_allows = key_is_prefix | ( + key_is_future & (key_block <= query_block) + ) + return (query_is_prefix & key_is_prefix) | ( + query_is_future & future_allows + ) + + +def teacher_forcing_clean_noisy_allows( + query_frame: Tensor | int, + key_frame: Tensor | int, + clean_frames: int, + block_size: int, + prefix_frames: int, +): + """Visibility for a packed ``[clean | noisy]`` teacher-forcing pass. + + Clean queries use frame-causal inclusive visibility. A noisy query sees + clean chunks strictly before its own chunk and noisy keys from its own + chunk. This matches Imaginaire's frame-causal clean-history pass while + preserving its chunkwise noisy-query layout; text remains cross-attention + in the LiDAR DiT and is therefore not part of this packed mask. + """ + if clean_frames <= 0: + raise ValueError( + f"clean_frames must be positive, got {clean_frames}" + ) + if block_size <= 0: + raise ValueError(f"block_size must be positive, got {block_size}") + if prefix_frames < 0 or prefix_frames > clean_frames: + raise ValueError( + "prefix_frames must be in [0, clean_frames], got " + f"{prefix_frames}/{clean_frames}" + ) + + query_is_clean = query_frame < clean_frames + key_is_clean = key_frame < clean_frames + query_is_noisy = query_frame >= clean_frames + key_is_noisy = key_frame >= clean_frames + query_local = query_frame - query_is_noisy * clean_frames + key_local = key_frame - key_is_noisy * clean_frames + + clean_query_allows = ( + query_is_clean & key_is_clean & (key_local <= query_local) + ) + + query_is_prefix = query_local < prefix_frames + key_is_prefix = key_local < prefix_frames + query_is_future = query_local >= prefix_frames + key_is_future = key_local >= prefix_frames + query_block = (query_local - prefix_frames) // block_size + key_block = (key_local - prefix_frames) // block_size + clean_strictly_precedes = query_is_future & ( + key_is_prefix + | (key_is_future & (key_block < query_block)) + ) + same_chunk = (query_is_prefix & key_is_prefix) | ( + query_is_future + & key_is_future + & (query_block == key_block) + ) + noisy_query_allows = query_is_noisy & ( + (key_is_clean & clean_strictly_precedes) + | (key_is_noisy & same_chunk) + ) + return clean_query_allows | noisy_query_allows + + +def expand_blockwise( + block_values_B_K: Tensor, + num_frames: int, + block_size: int, +) -> Tensor: + """Broadcast ``(B,K)`` values onto ``(B,T)`` consecutive frame blocks.""" + if block_values_B_K.ndim != 2: + raise ValueError( + f"block_values must be (B,K), got {tuple(block_values_B_K.shape)}" + ) + if num_frames <= 0 or block_size <= 0: + raise ValueError( + f"num_frames and block_size must be positive, got " + f"{num_frames}, {block_size}" + ) + num_blocks = (num_frames + block_size - 1) // block_size + if block_values_B_K.shape[1] != num_blocks: + raise ValueError( + f"need K={num_blocks} blocks for T={num_frames}, " + f"block_size={block_size}; got K={block_values_B_K.shape[1]}" + ) + block_ids = ( + torch.arange(num_frames, device=block_values_B_K.device) + // block_size + ) + return block_values_B_K[:, block_ids] + + +def expand_chunkwise( + chunk_values_B_K: Tensor, + num_frames: int, + block_size: int, + prefix_frames: int = 0, +) -> Tensor: + """Broadcast values over an optional prefix and complete causal blocks.""" + if chunk_values_B_K.ndim != 2: + raise ValueError( + f"chunk values must be (B,K), got {tuple(chunk_values_B_K.shape)}" + ) + chunks = temporal_chunk_slices( + num_frames, + block_size, + prefix_frames, + ) + if chunk_values_B_K.shape[1] != len(chunks): + raise ValueError( + f"need K={len(chunks)} chunks for T={num_frames}, " + f"prefix={prefix_frames}, block_size={block_size}; got " + f"K={chunk_values_B_K.shape[1]}" + ) + return torch.cat( + [ + chunk_values_B_K[:, index : index + 1].expand(-1, end - start) + for index, (start, end) in enumerate(chunks) + ], + dim=1, + ) + + +def artifixer_flow_schedule( + timestep_ids: Tensor, + *, + num_train_timesteps: int = 1000, + shift: float = 5.0, +) -> tuple[Tensor, Tensor, Tensor]: + """Map discrete ArtiFixer IDs to timestep, sigma, and training weight.""" + if num_train_timesteps <= 0: + raise ValueError( + "num_train_timesteps must be positive, got " + f"{num_train_timesteps}" + ) + if shift <= 0.0: + raise ValueError(f"shift must be positive, got {shift}") + if timestep_ids.dtype not in ( + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint8, + ): + raise TypeError( + f"timestep_ids must be integer, got {timestep_ids.dtype}" + ) + # IDs are sampled in-range on the training hot path. Keep validation for + # CPU callers without introducing a device synchronization every update. + if timestep_ids.device.type == "cpu" and bool( + ((timestep_ids < 0) | (timestep_ids >= num_train_timesteps)).any() + ): + raise ValueError( + f"timestep_ids must be in [0,{num_train_timesteps})" + ) + + base_ladder = torch.linspace( + 1.0, + 0.0, + num_train_timesteps + 1, + device=timestep_ids.device, + dtype=torch.float32, + )[:-1] + sigma_ladder = ( + shift + * base_ladder + / (1.0 + (shift - 1.0) * base_ladder) + ) + timestep_ladder = sigma_ladder * num_train_timesteps + bell = torch.exp( + -2.0 + * ( + ( + timestep_ladder - num_train_timesteps / 2.0 + ) + / num_train_timesteps + ) + ** 2 + ) + bell = bell - bell.min() + weight_ladder = bell * num_train_timesteps / bell.sum() + return ( + timestep_ladder[timestep_ids], + sigma_ladder[timestep_ids], + weight_ladder[timestep_ids], + ) + + +def expand_after_prefix( + block_values_B_K: Tensor, + num_frames: int, + block_size: int, + prefix_frames: int, + prefix_value: float = 0.0, +) -> Tensor: + """Broadcast block values after a fixed prefix. + + Returns ``(B,T)`` with ``prefix_value`` in ``[:prefix_frames]`` and + consecutive ``block_size`` groups thereafter. + """ + if not 0 <= prefix_frames < num_frames: + raise ValueError( + f"prefix_frames={prefix_frames} must be in [0,{num_frames})" + ) + future_frames = num_frames - prefix_frames + future = expand_blockwise( + block_values_B_K, + num_frames=future_frames, + block_size=block_size, + ) + prefix = future.new_full( + (future.shape[0], prefix_frames), + float(prefix_value), + ) + return torch.cat([prefix, future], dim=1) + + +def mean_after_prefix(values_B_T: Tensor, prefix_frames: int) -> Tensor: + """Per-sample mean over future frames only.""" + if values_B_T.ndim != 2: + raise ValueError( + f"values must be (B,T), got {tuple(values_B_T.shape)}" + ) + if not 0 <= prefix_frames < values_B_T.shape[1]: + raise ValueError( + f"prefix_frames={prefix_frames} must be in " + f"[0,{values_B_T.shape[1]})" + ) + return values_B_T[:, prefix_frames:].mean(dim=1) + + +def build_clean_context_timesteps( + active_timesteps_B: Tensor, + known_mask_B_T: Tensor, +) -> Tensor: + """Set committed prefix frames to t=0 and active frames to the sampler t.""" + if active_timesteps_B.ndim != 1: + raise ValueError( + f"active timesteps must be (B,), got {tuple(active_timesteps_B.shape)}" + ) + if known_mask_B_T.ndim != 2: + raise ValueError( + f"known mask must be (B,T), got {tuple(known_mask_B_T.shape)}" + ) + if active_timesteps_B.shape[0] != known_mask_B_T.shape[0]: + raise ValueError( + f"timestep batch {active_timesteps_B.shape[0]} does not match " + f"mask batch {known_mask_B_T.shape[0]}" + ) + active_B_T = active_timesteps_B[:, None].expand_as(known_mask_B_T) + return torch.where( + known_mask_B_T.to(torch.bool), + torch.zeros_like(active_B_T), + active_B_T, + ) + + +def validate_prefix_mask( + known_mask_B_T: Tensor, + block_size: int, +) -> tuple[Tensor, Tensor]: + """Validate block-aligned known-prefix masks and return known/active counts.""" + if known_mask_B_T.ndim != 2: + raise ValueError( + f"known mask must be (B,T), got {tuple(known_mask_B_T.shape)}" + ) + mask = known_mask_B_T.to(torch.bool) + _, num_frames = mask.shape + n_known = mask.sum(dim=1) + expected = ( + torch.arange(num_frames, device=mask.device)[None, :] + < n_known[:, None] + ) + if not torch.equal(mask, expected): + raise ValueError( + "known mask must be a contiguous prefix followed by active frames" + ) + if bool((n_known % block_size != 0).any()): + raise ValueError( + f"known prefix lengths {n_known.tolist()} must align to " + f"block_size={block_size}" + ) + n_active = num_frames - n_known + if bool((n_active <= 0).any()) or bool((n_active > block_size).any()): + raise ValueError( + f"active lengths must be in [1,{block_size}], got " + f"{n_active.tolist()}" + ) + return n_known, n_active diff --git a/diffusion/training/utils/fsdp_helper.py b/diffusion/training/utils/fsdp_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..34b3b2594f4f9e73e89ed4f072ba7b116007e803 --- /dev/null +++ b/diffusion/training/utils/fsdp_helper.py @@ -0,0 +1,159 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from contextlib import contextmanager +from functools import partial + +import torch +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + apply_activation_checkpointing, + checkpoint_wrapper, +) +from torch.distributed.device_mesh import init_device_mesh +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp._runtime_utils import ( + _post_forward, + _post_forward_reshard, + _pre_forward, + _pre_forward_unshard, + _root_pre_forward, +) +from torch.distributed.utils import _p_assert + +from utils import distributed, log + + +def apply_fsdp_checkpointing(model, list_block_cls): + """apply activation checkpointing to model + returns None as model is updated directly + """ + log.critical("--> applying fdsp activation checkpointing...") + non_reentrant_wrapper = partial( + checkpoint_wrapper, + # offload_to_cpu=False, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + ) + + def check_fn(submodule): + result = False + for block_cls in list_block_cls: + if isinstance(submodule, block_cls): + result = True + break + return result + + apply_activation_checkpointing(model, checkpoint_wrapper_fn=non_reentrant_wrapper, check_fn=check_fn) + + +@contextmanager +def possible_fsdp_scope( + model: torch.nn.Module, +): + enabled = isinstance(model, FSDP) + if enabled: + assert not torch.is_grad_enabled(), "FSDP context should be entered with grad disabled" + handle = model._handle + args, kwargs = [0], dict(dummy=0) + with torch.autograd.profiler.record_function("FullyShardedDataParallel.possible_fsdp_scope"): + args, kwargs = _root_pre_forward(model, model, args, kwargs) + unused = None + args, kwargs = _pre_forward( + model, + handle, + _pre_forward_unshard, + model._fsdp_wrapped_module, + args, + kwargs, + ) + if handle: + _p_assert( + handle.flat_param.device == model.compute_device, + "Expected `FlatParameter` to be on the compute device " + f"{model.compute_device} but got {handle.flat_param.device}", + ) + try: + yield None + finally: + if enabled: + output = {"output": 1} + _post_forward(model, handle, _post_forward_reshard, model, unused, output) + + +def hsdp_device_mesh(replica_group_size=None, sharding_group_size=None, device=None): + """ + Initializes a device mesh for use with Hybrid Sharding strategy in FSDP (HSDP) training. + + This function requires explicit sizes for replica and sharding groups to accommodate models + whose GPU fit is unknown, providing flexibility in distributed training setups. + + Args: + replica_group_size (int): The size of each replica group. Must be provided to ensure + the model fits within the available resources. + sharding_group_size (int): The size of each sharding group that the model can fit. Must be provided to + ensure the correct distribution of model parameters. + device (str, optional): The device to use (e.g., "cuda:0"). If None, defaults to "cuda" + with the local rank as the device index. + + Returns: + A device mesh object compatible with FSDP. + + Raises: + ValueError: If replica_group_size or sharding_group_size are not provided, or if the + world size is not evenly divisible by the sharding group size. + RuntimeError: If a valid device mesh cannot be created. + + Usage: + If your model fits on 4 GPUS, and you have 3 nodes of 8 GPUs, then: + Sharding_Group_Size = 4 + Replica_Groups_Size = (24 total gpus, 4 per sharding group) = 6 Replica Groups + >>> device_mesh = initialize_device_mesh(replica_group_size, sharding_group_size) + >>> sharded_model = FSDP(model, device_mesh=device_mesh, ...) + """ + + # world_size = int(os.getenv("WORLD_SIZE", "1")) + world_size = distributed.get_world_size() + if sharding_group_size is None: + sharding_group_size = min(world_size, 8) + sharding_group_size = min(sharding_group_size, world_size) + if replica_group_size is None: + replica_group_size = world_size // sharding_group_size + + device = device or "cuda" + + if world_size % sharding_group_size != 0: + raise ValueError( + f"World size {world_size} is not evenly divisible by " f"sharding group size {sharding_group_size}." + ) + + if (world_size // sharding_group_size) % replica_group_size != 0: + raise ValueError( + f"The calculated number of replica groups is not evenly divisible by " + f"replica_group_size {replica_group_size}." + ) + + device_mesh = init_device_mesh( + device, (replica_group_size, sharding_group_size), mesh_dim_names=("replicate", "shard") + ) + if device_mesh is None: + raise RuntimeError("Failed to create a valid device mesh.") + + log.critical( + f"Device mesh initialized with replica group size {replica_group_size} and sharding group size {sharding_group_size}" + ) + + return device_mesh diff --git a/diffusion/training/utils/optim_instantiate.py b/diffusion/training/utils/optim_instantiate.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f5d2cb3fb351976af6d3750544bb59b1d4d82a --- /dev/null +++ b/diffusion/training/utils/optim_instantiate.py @@ -0,0 +1,83 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import hydra +import torch +from torch import nn + +from utils import log +from utils.fused_adam import FusedAdam + + +def get_regular_param_group(net: nn.Module): + """ + seperate the parameters of the network into two groups: decay and no_decay. + based on nano_gpt codebase. + """ + param_dict = {pn: p for pn, p in net.named_parameters()} + param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad} + + decay_params = [p for n, p in param_dict.items() if p.dim() >= 2] + nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2] + return decay_params, nodecay_params + + +def get_base_optimizer( + model: nn.Module, + lr: float, + weight_decay: float, + optim_type: str = "adamw", + sharding: bool = False, + **kwargs, +) -> torch.optim.Optimizer: + net_decay_param, net_nodecay_param = get_regular_param_group(model) + + num_decay_params = sum(p.numel() for p in net_decay_param) + num_nodecay_params = sum(p.numel() for p in net_nodecay_param) + net_param_total = num_decay_params + num_nodecay_params + log.critical(f"total num parameters : {net_param_total:,}") + + param_group = [ + { + "params": net_decay_param + net_nodecay_param, + "lr": lr, + "weight_decay": weight_decay, + }, + ] + + if optim_type == "adamw": + opt_cls = torch.optim.AdamW + elif optim_type == "fusedadam": + opt_cls = FusedAdam + else: + raise ValueError(f"Unknown optimizer type: {optim_type}") + + return opt_cls(param_group, **kwargs) + + +def get_base_scheduler( + optimizer: torch.optim.Optimizer, + model: nn.Module, + scheduler_config: dict, +): + net_scheduler = hydra.utils.instantiate(scheduler_config) + net_scheduler.model = model + + return torch.optim.lr_scheduler.LambdaLR( + optimizer, + lr_lambda=[ + net_scheduler.schedule, + ], + ) diff --git a/diffusion/training/utils/sf_dmd.py b/diffusion/training/utils/sf_dmd.py new file mode 100644 index 0000000000000000000000000000000000000000..4c3b19975bd2b38ef9e60ca8937fd62554aae94e --- /dev/null +++ b/diffusion/training/utils/sf_dmd.py @@ -0,0 +1,328 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Lightweight mathematical helpers for Self-Forcing RF-DMD.""" + +from __future__ import annotations + +import torch +from torch import Tensor + + +def fixed_sde_sigmas( + *, + num_steps: int = 4, + shift: float = 5.0, + device: torch.device | str | None = None, + dtype: torch.dtype = torch.float32, +) -> Tensor: + """Return a fixed uniform-base RF-SDE ladder after timestep shifting.""" + if num_steps <= 0: + raise ValueError(f"num_steps must be positive, got {num_steps}") + if shift <= 0.0: + raise ValueError(f"shift must be positive, got {shift}") + # Preserve the original four-step schedule exactly for existing runs. + if num_steps == 4 and shift == 5.0: + return torch.tensor( + [1.0, 15.0 / 16.0, 5.0 / 6.0, 5.0 / 8.0, 0.0], + device=device, + dtype=dtype, + ) + base = torch.linspace( + 1.0, + 0.0, + num_steps + 1, + device=device, + dtype=dtype, + ) + return shift * base / (1.0 + (shift - 1.0) * base) + + +def confidence_weighted_geometry_source( + noise: Tensor, + geometry: Tensor, + confidence: Tensor, + noise_floor: float, +) -> Tensor: + """Match the Stage-2 geometry-source RF endpoint distribution.""" + if geometry.shape != noise.shape: + raise ValueError( + "geometry source must match noise: " + f"geometry={tuple(geometry.shape)}, noise={tuple(noise.shape)}" + ) + expected_confidence = (noise.shape[0], 1, *noise.shape[2:]) + if confidence.shape != expected_confidence: + raise ValueError( + "geometry confidence must be (B,1,T,H,W): " + f"confidence={tuple(confidence.shape)}, " + f"expected={expected_confidence}" + ) + if not 0.0 <= noise_floor <= 1.0: + raise ValueError(f"noise_floor must be in [0,1], got {noise_floor}") + source_weight = (1.0 - noise_floor) * confidence.float() + return ( + source_weight * geometry.float() + + (1.0 - source_weight) * noise.float() + ) + + +def confidence_composite_geometry( + geometry: Tensor, + confidence: Tensor, + empty_value: float, +) -> Tensor: + """Composite projected range geometry against the empty-range value.""" + if confidence.shape != geometry.shape: + raise ValueError( + "geometry confidence must match projected geometry: " + f"confidence={tuple(confidence.shape)}, " + f"geometry={tuple(geometry.shape)}" + ) + confidence = confidence.to( + device=geometry.device, + dtype=geometry.dtype, + ).clamp(0.0, 1.0) + empty = geometry.new_full((), float(empty_value)) + return confidence * geometry + (1.0 - confidence) * empty + + +def complete_score_state_dict( + loaded: dict[str, Tensor], + target: dict[str, Tensor], + fallback: dict[str, Tensor] | None = None, +) -> tuple[dict[str, Tensor], list[str]]: + """Select compatible critic weights and fill newly added parameters.""" + completed = {} + dropped = [] + mismatched = [] + for key, value in loaded.items(): + if key not in target: + dropped.append(key) + elif value.shape != target[key].shape: + mismatched.append( + f"{key}: checkpoint={tuple(value.shape)} " + f"target={tuple(target[key].shape)}" + ) + else: + completed[key] = value + if mismatched: + raise ValueError( + "score checkpoint shape mismatch: " + "; ".join(mismatched) + ) + missing = [key for key in target if key not in completed] + if fallback is not None: + for key in list(missing): + value = fallback.get(key) + if value is not None and value.shape == target[key].shape: + completed[key] = value + missing.remove(key) + if missing: + raise KeyError( + "score checkpoint is missing tensors: " + ", ".join(missing) + ) + return completed, dropped + + +def rf_velocity_to_x0( + x_t: Tensor, velocity: Tensor, sigma: Tensor | float +) -> Tensor: + """Convert the repository's RF velocity ``noise-clean`` to clean x0.""" + sigma_tensor = torch.as_tensor( + sigma, device=x_t.device, dtype=x_t.dtype + ) + return x_t - sigma_tensor * velocity + + +def sde_renoise( + x0: Tensor, + eps_implied: Tensor, + eps_fresh: Tensor, + sigma_next: Tensor | float, + eta: float, +) -> Tensor: + """Advance one RF-SDE step with the repository's eta noise blend.""" + if not 0.0 <= eta <= 1.0: + raise ValueError(f"eta must be in [0,1], got {eta}") + if not (x0.shape == eps_implied.shape == eps_fresh.shape): + raise ValueError( + "x0/eps_implied/eps_fresh must have equal shapes, got " + f"{x0.shape}/{eps_implied.shape}/{eps_fresh.shape}" + ) + sigma = torch.as_tensor( + sigma_next, device=x0.device, dtype=x0.dtype + ) + eps_used = (1.0 - eta) * eps_implied + eta * eps_fresh + return (1.0 - sigma) * x0 + sigma * eps_used + + +def dmd_pseudo_target( + generated: Tensor, + teacher_x0: Tensor, + fake_x0: Tensor, + *, + eps: float = 1.0e-6, +) -> tuple[Tensor, Tensor]: + """Build the detached adaptive x0-space VSD pseudo target.""" + if not (generated.shape == teacher_x0.shape == fake_x0.shape): + raise ValueError( + "generated/teacher_x0/fake_x0 must have equal shapes, got " + f"{generated.shape}/{teacher_x0.shape}/{fake_x0.shape}" + ) + reduce_dims = tuple(range(1, generated.ndim)) + weight = 1.0 / ( + (generated.detach() - teacher_x0.detach()).abs().mean( + dim=reduce_dims, keepdim=True + ) + + eps + ) + vsd_grad = fake_x0.detach() - teacher_x0.detach() + target = generated.detach() - weight * vsd_grad + return target.detach(), weight.detach() + + +def active_slice_loss( + prediction: Tensor, + target: Tensor, + active_start: int, + active_end: int, + *, + half: bool = False, +) -> Tensor: + """Mean squared error over one active temporal block only.""" + if prediction.shape != target.shape: + raise ValueError( + f"prediction/target shape mismatch: {prediction.shape}/{target.shape}" + ) + if not 0 <= active_start < active_end <= prediction.shape[2]: + raise ValueError( + f"invalid active slice [{active_start}:{active_end}] for " + f"T={prediction.shape[2]}" + ) + loss = ( + prediction[:, :, active_start:active_end] + - target[:, :, active_start:active_end] + ).square().mean() + return 0.5 * loss if half else loss + + +def normalized_frame_weights(frame_counts: list[int]) -> list[float]: + """Weight per-record mean losses like one mean over all frames.""" + if not frame_counts or any(count <= 0 for count in frame_counts): + raise ValueError( + f"frame_counts must be non-empty and positive, got {frame_counts}" + ) + total_frames = sum(frame_counts) + return [count / total_frames for count in frame_counts] + + +def sfdmd_update_counts( + num_cycles: int, fake_updates_per_cycle: int +) -> dict[str, int]: + """Return optimizer-step counts for a cycle-based SF-DMD run.""" + if num_cycles < 0 or fake_updates_per_cycle <= 0: + raise ValueError( + "num_cycles must be non-negative and fake_updates_per_cycle positive" + ) + return { + "cycles": num_cycles, + "student": num_cycles, + "fake_score": num_cycles * fake_updates_per_cycle, + "total": num_cycles * (fake_updates_per_cycle + 1), + } + + +def sfdmd_nonoverlap_layout( + block_index: int, + *, + block_size: int = 3, + score_window_tokens: int = 9, + prefix_frames: int = 0, +) -> tuple[int, int, int, int]: + """Map one global AR block to its local bidirectional score window. + + Returns ``(global_start, real_window_start, active_start, active_end)``. + The first score window covers every seed chunk. Later windows score the + newly generated final block. With a temporal prefix, chunk zero is the + singleton prefix and subsequent chunks have ``block_size`` frames. + """ + if ( + block_index < 0 + or block_size <= 0 + or score_window_tokens <= 0 + or prefix_frames < 0 + or prefix_frames >= score_window_tokens + or (score_window_tokens - prefix_frames) % block_size != 0 + ): + raise ValueError( + "invalid block/prefix/window layout: " + f"index={block_index}, prefix={prefix_frames}, " + f"block={block_size}, window={score_window_tokens}" + ) + seed_blocks = ( + (1 if prefix_frames else 0) + + (score_window_tokens - prefix_frames) // block_size + ) + if prefix_frames and block_index == 0: + global_start = 0 + active_frames = prefix_frames + else: + body_index = block_index - int(bool(prefix_frames)) + global_start = prefix_frames + body_index * block_size + active_frames = block_size + if block_index < seed_blocks: + return global_start, 0, global_start, global_start + active_frames + real_window_start = global_start - (score_window_tokens - block_size) + active_start = score_window_tokens - block_size + return ( + global_start, + real_window_start, + active_start, + score_window_tokens, + ) + + +def build_sfdmd_block_timesteps( + batch_size: int, + num_frames: int, + active_start: int, + block_size: int, + active_timestep: Tensor | float, + *, + max_timestep: float = 1000.0, + device: torch.device | str | None = None, +) -> tuple[Tensor, Tensor, Tensor]: + """Build clean-prefix / active / pure-noise-future block schedules.""" + active_end = active_start + block_size + if ( + batch_size <= 0 + or block_size <= 0 + or not 0 <= active_start < active_end <= num_frames + ): + raise ValueError( + f"invalid B/T/active/block: {batch_size}/{num_frames}/" + f"{active_start}/{block_size}" + ) + timesteps = torch.full( + (batch_size, num_frames), + max_timestep, + device=device, + dtype=torch.float32, + ) + active = torch.zeros_like(timesteps, dtype=torch.bool) + active[:, active_start:active_end] = True + active_value = torch.as_tensor( + active_timestep, device=timesteps.device, dtype=timesteps.dtype + ) + if active_value.ndim == 0: + timesteps[active] = active_value + elif tuple(active_value.shape) == (batch_size,): + timesteps[:, active_start:active_end] = active_value[:, None] + else: + raise ValueError( + "active_timestep must be scalar or (B,), got " + f"{tuple(active_value.shape)}" + ) + known = torch.zeros_like(active) + known[:, :active_start] = True + timesteps[known] = 0.0 + return timesteps, known, active diff --git a/diffusion/types.py b/diffusion/types.py new file mode 100644 index 0000000000000000000000000000000000000000..0459d88d423794a97fb62ee3275c57c9d1c2007a --- /dev/null +++ b/diffusion/types.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +import torch + + +@dataclass +class LabelImageCondition: + label: torch.Tensor + + def get_classifier_free_guidance_condition(self) -> LabelImageCondition: + return LabelImageCondition(torch.zeros_like(self.label)) + + +@dataclass +class DenoisePrediction: + x0: torch.Tensor # clean data prediction + eps: Optional[torch.Tensor] = None # noise prediction + logvar: Optional[torch.Tensor] = None # log variance of noise prediction, can be used a confidence / uncertainty diff --git a/packages.txt b/packages.txt new file mode 100644 index 0000000000000000000000000000000000000000..20645e641240cb419f5fc66c14c1447e91daf669 --- /dev/null +++ b/packages.txt @@ -0,0 +1 @@ +ffmpeg diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dcf582e9d823cc5c6ad30a66b9d42d1ca124f36c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,22 @@ +torch==2.11.0 +torchvision +numpy +einops +hydra-core +omegaconf +attrs +iopath +loguru +lru-dict +termcolor +boto3 +diffusers +matplotlib +mediapy +opencv-python-headless +scipy +pyyaml +tqdm +imageio +nvidia-ml-py +plotly diff --git a/scene.py b/scene.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b59069c9b0cb70a6b56ad68f70c0ca37a86fbd --- /dev/null +++ b/scene.py @@ -0,0 +1,259 @@ +"""Procedural HD-map scenes in the prepared NVIDIA PAI sample format. + +Builds the same fields that ``scripts/data/prepare_pai_bidir.py`` writes for an +official clip (raw vector map polylines, actor boxes, sensor-to-world rolling +shutter poses, calibrated Pandar128 rays), so LidarVerse's world-generation +path (raw HDMap rasterization -> Stage-3 causal sampling) runs unchanged. +""" + +from __future__ import annotations + +import numpy as np +import yaml +from pathlib import Path + +from utils.visualize.hdmap import MAP_KINDS + +FRAMES = 21 +FPS = 10.0 +SENSOR_HEIGHT_M = 1.9 # roof-mounted Pandar128, sensor origin above the road surface +LANE_WIDTH = 3.6 +LAYOUTS = ("Straight road", "Four-way intersection", "Curved road") +KIND = {name: i for i, name in enumerate(MAP_KINDS)} +CAR = (4.6, 1.9, 1.6) +TRUCK = (9.5, 2.5, 3.4) + + +def sensor_rays(): + """Calibrated Pandar128 elevations x uniform 1024 azimuths (identical to the official preparer).""" + path = Path(__file__).resolve().parent / "assets/lidar/lidar_model.yaml" + config = yaml.safe_load(path.read_text()) + elevations = config["lidar_models"]["spinning"]["HESAI-Pandar128"]["inclinations_deg"] + phi, theta = np.meshgrid(np.radians(elevations), np.linspace(np.pi, -np.pi, 1024, endpoint=False), + indexing="ij") + return np.stack([np.cos(phi) * np.cos(theta), np.cos(phi) * np.sin(theta), np.sin(phi)], + axis=-1).astype(np.float32) + + +# --------------------------------------------------------------------------- paths +class Path2D: + """Arc-length parameterized reference path: straight (curvature 0) or constant-curvature arc.""" + + def __init__(self, curvature=0.0, start=-120.0, end=160.0): + self.k, self.s0, self.s1 = curvature, start, end + + def pose(self, s, lateral=0.0): + s = np.asarray(s, dtype=np.float64) + if abs(self.k) < 1e-9: + x, y, yaw = s, np.zeros_like(s), np.zeros_like(s) + else: + yaw = self.k * s + x = np.sin(yaw) / self.k + y = (1 - np.cos(yaw)) / self.k + # Lateral offset to the left of the direction of travel. + return x - lateral * np.sin(yaw), y + lateral * np.cos(yaw), yaw + + def polyline(self, lateral, s_from=None, s_to=None, step=2.0, z=0.0): + s_from = self.s0 if s_from is None else s_from + s_to = self.s1 if s_to is None else s_to + s = np.arange(s_from, s_to + 1e-6, step) + x, y, _ = self.pose(s, lateral) + return np.stack([x, y, np.full_like(x, z)], -1).astype(np.float32) + + +def _dashes(path, lateral, s_from, s_to, dash=3.0, gap=9.0): + out, s = [], s_from + while s + dash <= s_to: + out.append(path.polyline(lateral, s, s + dash, step=dash)) + s += dash + gap + return out + + +def _rect(cx, cy, yaw, length, width, z=0.0): + c, s = np.cos(yaw), np.sin(yaw) + pts = np.array([[length / 2, width / 2], [length / 2, -width / 2], [-length / 2, -width / 2], + [-length / 2, width / 2]]) + rot = pts @ np.array([[c, s], [-s, c]]) + poly = np.concatenate([rot + [cx, cy], np.full((4, 1), z)], -1) + return np.concatenate([poly, poly[:1]]).astype(np.float32) + + +def _box_pose(x, y, yaw, height): + pose = np.eye(4, dtype=np.float32) + c, s = np.cos(yaw), np.sin(yaw) + pose[:3, :3] = [[c, -s, 0], [s, c, 0], [0, 0, 1]] + pose[:3, 3] = [x, y, height / 2] + return pose + + +# --------------------------------------------------------------------------- scene +def build_scene(layout="Straight road", lanes_per_direction=2, ego_speed_kmh=30.0, num_vehicles=8, + parked_cars=True, seed=0): + """Return a dict in the prepared PAI NPZ format (no real LiDAR: world generation only).""" + rng = np.random.default_rng(int(seed)) + n = int(np.clip(lanes_per_direction, 1, 3)) + v_ego = max(0.0, float(ego_speed_kmh)) / 3.6 + curvature = {"Curved road": 1 / 70.0}.get(layout, 0.0) * (1 if rng.random() < 0.5 else -1) + if layout != "Curved road": + curvature = 0.0 + road = Path2D(curvature, -120.0, 160.0 if curvature == 0 else 150.0) + half = n * LANE_WIDTH + sidewalk = 3.0 + shoulder = 2.4 + curb = half + shoulder + ego_lat = LANE_WIDTH * (0.5 + (n - 1 if n > 1 and rng.random() < 0.5 else 0)) # rightmost or a left lane + ego_lat = -ego_lat # drive on the right: own lanes are at negative lateral offset + + polylines, kinds = [], [] + + def add(poly, kind): + if len(poly) >= 2: + polylines.append(np.asarray(poly, np.float32)) + kinds.append(KIND[kind]) + + # Intersection gap along the main road. + X0 = 38.0 + rng.uniform(-4, 6) + cross_half = 2 * LANE_WIDTH + segments = [(road.s0, road.s1)] + if layout == "Four-way intersection": + segments = [(road.s0, X0 - cross_half - sidewalk), (X0 + cross_half + sidewalk, road.s1)] + + for a, b in segments: + # Solid edge lines, curbs (after a parking shoulder) and sidewalk edges. + add(road.polyline(half, a, b), "lanelines") + add(road.polyline(-half, a, b), "lanelines") + add(road.polyline(curb, a, b), "road_boundaries") + add(road.polyline(-curb, a, b), "road_boundaries") + add(road.polyline(curb + sidewalk, a, b), "road_boundaries") + add(road.polyline(-curb - sidewalk, a, b), "road_boundaries") + # Center double line and dashed lane separators. + add(road.polyline(0.12, a, b), "lanelines") + add(road.polyline(-0.12, a, b), "lanelines") + for i in range(1, n): + for d in _dashes(road, i * LANE_WIDTH, a, b): + add(d, "lanelines") + for d in _dashes(road, -i * LANE_WIDTH, a, b): + add(d, "lanelines") + # Street poles along the sidewalk. + for s in np.arange(a + 6, b - 6, 25.0): + for side in (1, -1): + x, y, _ = road.pose(s, side * (curb + 1.0)) + add(np.array([[x, y, 0.0], [x, y, 7.0]], np.float32), "poles") + + if layout == "Four-way intersection": + cross = [] + for side in (1, -1): # cross street boundaries + for off in (cross_half, cross_half + sidewalk): + xs = X0 + side * off + add(np.array([[xs, curb + (sidewalk if off > cross_half else 0), 0], + [xs, 90, 0]], np.float32), "road_boundaries") + add(np.array([[xs, -curb - (sidewalk if off > cross_half else 0), 0], + [xs, -90, 0]], np.float32), "road_boundaries") + for y_from, y_to in ((curb + sidewalk, 90), (-90, -curb - sidewalk)): + add(np.array([[X0, y_from, 0], [X0, y_to, 0]], np.float32), "lanelines") + # Crosswalks and stop lines on the main road. + for side in (-1, 1): + cx = X0 + side * (cross_half + 2.0) + add(_rect(cx, 0.0, 0.0, 3.0, 2 * curb), "crosswalks") + stop_x = X0 + side * (cross_half + 4.2) + if side < 0: + add(np.array([[stop_x, -half, 0], [stop_x, 0, 0]], np.float32), "wait_lines") + else: + add(np.array([[stop_x, 0, 0], [stop_x, half, 0]], np.float32), "wait_lines") + # Crosswalks on the cross street. + for side in (-1, 1): + add(_rect(X0, side * (curb + sidewalk + 2.0), np.pi / 2, 3.0, 2 * cross_half), "crosswalks") + # Traffic-light poles at the corners. + for sx in (-1, 1): + for sy in (-1, 1): + x, y = X0 + sx * (cross_half + 1.0), sy * (curb + 1.0) + add(np.array([[x, y, 0.0], [x, y, 5.5]], np.float32), "poles") + del cross + + # ---------------------------------------------------------------- ego trajectory + t = np.arange(FRAMES + 1) / FPS + s_ego = -2.0 + v_ego * t + ex, ey, eyaw = road.pose(s_ego, ego_lat) + poses = np.zeros((FRAMES, 2, 4, 4), np.float32) + for i in range(FRAMES): + for j, (x, y, yaw) in enumerate(((ex[i], ey[i], eyaw[i]), + (ex[i + 1], ey[i + 1], eyaw[i + 1]))): + c, s = np.cos(yaw), np.sin(yaw) + pose = np.eye(4, dtype=np.float32) + pose[:3, :3] = [[c, -s, 0], [s, c, 0], [0, 0, 1]] + pose[:3, 3] = [x, y, SENSOR_HEIGHT_M] + poses[i, j] = pose + + # ---------------------------------------------------------------- actors + actors = [] # (lateral, s0, speed, size, class) + lanes = [-(i + 0.5) * LANE_WIDTH for i in range(n)] + [(i + 0.5) * LANE_WIDTH for i in range(n)] + occupied = [] + tries = 0 + while len(actors) < int(num_vehicles) and tries < 400: + tries += 1 + lat = lanes[rng.integers(len(lanes))] + s0 = rng.uniform(-40, 95) + same_dir = lat < 0 + speed = (v_ego + rng.uniform(-3, 3)) if same_dir else rng.uniform(6, 14) + speed = max(0.0, speed) + if layout == "Four-way intersection" and abs(s0 - X0) < cross_half + 5: + continue + if any(abs(lat - l2) < 1 and abs(s0 - s2) < 12 for l2, s2 in occupied): + continue + if abs(lat - ego_lat) < 1 and abs(s0 - s_ego[0]) < 14: + continue + occupied.append((lat, s0)) + truck = rng.random() < 0.15 + actors.append((lat, s0, speed if same_dir else -speed, TRUCK if truck else CAR, 1 if truck else 0)) + if parked_cars: + for s0 in np.arange(-30, 110, 9.0): + if rng.random() < 0.45: + if layout == "Four-way intersection" and abs(s0 - X0) < cross_half + sidewalk + 6: + continue + side = -1 if rng.random() < 0.6 else 1 + actors.append((side * (half + shoulder / 2), s0 + rng.uniform(-1, 1), 0.0, CAR, 0)) + if layout == "Four-way intersection": + # Cross traffic waiting at the cross-street stop lines. + for sy in (-1, 1): + if rng.random() < 0.8: + actors.append(("cross", sy * (curb + sidewalk + 6.0 + rng.uniform(0, 4)), 0.0, CAR, 0)) + + M = max(1, len(actors)) + box_pose = np.zeros((FRAMES, M, 4, 4), np.float32) + box_lwh = np.zeros((FRAMES, M, 3), np.float32) + box_valid = np.zeros((FRAMES, M), bool) + box_moving = np.zeros((FRAMES, M), bool) + box_track = np.full((FRAMES, M), -1, np.int64) + box_class = np.full((FRAMES, M), 4, np.int64) + for k, (lat, s0, speed, size, cls) in enumerate(actors): + for i in range(FRAMES): + if lat == "cross": + x, y, yaw = X0 + (LANE_WIDTH / 2 if s0 > 0 else -LANE_WIDTH / 2), s0, (-np.pi / 2 if s0 > 0 else np.pi / 2) + else: + s = s0 + speed * t[i] + x, y, yaw = road.pose(s, lat) + if speed < 0 or (speed == 0 and lat > 0): + yaw = yaw + np.pi + box_pose[i, k] = _box_pose(x, y, yaw, size[2]) + box_lwh[i, k] = size + box_valid[i, k] = True + box_moving[i, k] = abs(speed) > 0.3 + box_track[i, k] = k + box_class[i, k] = cls + + offsets = np.cumsum([0] + [len(p) for p in polylines]).astype(np.int64) + times = (t[:FRAMES] * 1e6).astype(np.int64) + return dict( + range_m=np.zeros((FRAMES, 128, 1024), np.float32), # no observed LiDAR: pure generation + valid_mask=np.zeros((FRAMES, 128, 1024), bool), + hdmap=np.full((FRAMES, 128, 1024), -1.0, np.float32), # replaced by raw rasterization + ray_directions=sensor_rays(), pose_sensor_start_end=poses, + frame_indices=np.asarray([str(i) for i in range(FRAMES)]), timestamp_us=times, + dataset=np.asarray("pandar"), sensor_dataset_id=np.int64(0), fps=np.float32(FPS), + min_range_m=np.float32(2.5), max_range_m=np.float32(100), has_prepend=np.bool_(False), + clip_name=np.asarray(f"procedural_{layout.split()[0].lower()}_{int(seed)}"), + box_object_to_world=box_pose, box_lwh=box_lwh, box_valid=box_valid, box_is_moving=box_moving, + box_track_id=box_track, box_class=box_class, + map_vertices=np.concatenate(polylines).astype(np.float32), map_offsets=offsets, + map_kinds=np.asarray(kinds, np.int64), + ) diff --git a/scripts/prepare_pai_example.py b/scripts/prepare_pai_example.py new file mode 100644 index 0000000000000000000000000000000000000000..33df66dad7fc799962a76c49cf7fb4265cfa4ad8 --- /dev/null +++ b/scripts/prepare_pai_example.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Download and prepare one official NVIDIA PAI example for the 40k tokenizer.""" + +import argparse +from io import BytesIO +import json +from pathlib import Path +import tarfile + +import numpy as np +import torch +import torch.nn.functional as F +import yaml + +REPO_ROOT = Path(__file__).resolve().parents[2] +DATA_REPO = "nvidia/Cosmos-Transfer-LidarGen-Example" +CLIP = "061dbb50-f392-11ee-8e3c-00044baf7cbc_1712352201101085_1712352221101085" + + +def load_ranges(path, frame_ids): + clip = path.stem + frames = [] + with tarfile.open(path, "r") as archive: + members = {Path(member.name).name: member for member in archive.getmembers() if member.isfile()} + for frame in frame_ids: + arrays = [] + for field in ("row", "col", "range"): + name = f"{clip}.{frame}.lidar_{field}.npz" + with archive.extractfile(members[name]) as handle: + with np.load(BytesIO(handle.read()), allow_pickle=False) as data: + arrays.append(data["arr_0"]) + row, col, values = arrays + dense = np.zeros((128, 3600), dtype=np.float32) + dense[row.astype(np.int64), col.astype(np.int64)] = values + # Training: scatter-min over triplets, then nearest-exact 1200 -> 1024. + groups = dense.reshape(128, 1200, 3) + reduced = np.where(groups == 0, 1e3, groups).min(axis=-1) + reduced[reduced == 1e3] = 0 + valid = np.isfinite(reduced) & (reduced >= 2.5) & (reduced <= 100) + reduced = np.where(valid, reduced, 0).astype(np.float32) + resized = F.interpolate( + torch.from_numpy(reduced)[None, None], size=(128, 1024), mode="nearest-exact" + )[0, 0].numpy() + frames.append(resized) + return np.stack(frames) + + +def sensor_rays(): + with (REPO_ROOT / "assets/lidar/lidar_model.yaml").open() as handle: + config = yaml.safe_load(handle) + elevations = config["lidar_models"]["spinning"]["HESAI-Pandar128"]["inclinations_deg"] + phi, theta = np.meshgrid( + np.radians(elevations), np.linspace(np.pi, -np.pi, 1024, endpoint=False), indexing="ij" + ) + return np.stack([ + np.cos(phi) * np.cos(theta), np.cos(phi) * np.sin(theta), np.sin(phi) + ], axis=-1).astype(np.float32) + + +def save_sample(path, payload, provenance): + path.parent.mkdir(parents=True, exist_ok=True) + with path.with_suffix(".npz.tmp").open("wb") as handle: + np.savez_compressed(handle, **payload) + path.with_suffix(".npz.tmp").replace(path) + path.with_suffix(".json").write_text(json.dumps(provenance, indent=2) + "\n") + print(f"Prepared {path} ({len(payload['range_m'])} frames)", flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--source-root", type=Path, help="Existing lidar_dataset_release directory; skips downloads.") + parser.add_argument("--hdmap-root", type=Path, help="Optional projected HDMap TAR directory.") + parser.add_argument("--revision", default="main", help="Dataset revision (default: main).") + args = parser.parse_args() + torch.set_num_threads(4) + if args.source_root is None: + from huggingface_hub import hf_hub_download + download_root = args.output_root / "source" + for filename in ( + "LICENSE", "README.md", + f"lidar_dataset_release/lidar/{CLIP}.tar", + f"lidar_dataset_release/metadata/{CLIP}.npz", + ): + hf_hub_download(DATA_REPO, filename, repo_type="dataset", revision=args.revision, local_dir=download_root) + source = download_root / "lidar_dataset_release" + else: + source = args.source_root + + with np.load(source / "metadata" / f"{CLIP}.npz", allow_pickle=False) as metadata: + frame_ids = metadata["frame_indices"].astype(str) + timestamps = metadata["timestamps_list"].copy() + poses = metadata["pose_list"].copy() + if timestamps.shape != (len(frame_ids), 2) or poses.shape != (len(frame_ids), 2, 4, 4): + raise ValueError("PAI frame IDs, timestamps, and start/end poses must align") + if np.any(np.diff(timestamps[:, 0]) <= 0): + raise ValueError("PAI timestamps must be strictly increasing") + ranges = load_ranges(source / "lidar" / f"{CLIP}.tar", frame_ids) + payload = dict( + range_m=ranges, valid_mask=ranges > 0, ray_directions=sensor_rays(), + dataset=np.asarray("pandar"), sensor_name=np.asarray("NVIDIA PAI"), + sensor_dataset_id=np.int64(0), fps=np.float32(10), + timestamp_us=timestamps[:, 0] - timestamps[0, 0], frame_indices=frame_ids, + clip_name=np.asarray(CLIP), has_prepend=np.bool_(False), + min_range_m=np.float32(2.5), max_range_m=np.float32(100), + ) + provenance = dict( + source_repo=DATA_REPO, clip=CLIP, visualization_yaw_deg=0, + processing="scatter_min: 128x3600 -> 128x1200; nearest-exact -> 128x1024; valid range [2.5,100] m", + rays="Calibrated Pandar128 elevations and uniform final-grid azimuths, matching training", + motion_compensation=False, source_revision=args.revision, + ) + save_sample(args.output_root / "examples/nvidia_pai/sample_000.npz", payload, provenance) + if args.hdmap_root is not None: + hdmap_path = args.hdmap_root / f"{CLIP}.tar" + hdmap = load_ranges(hdmap_path, frame_ids) + condition = np.where(hdmap > 0, 2 * (hdmap - 2.5) / 97.5 - 1, -1).astype(np.float32) + save_sample( + args.output_root / "hdmap_examples/nvidia_pai/sample_000.npz", + {**payload, "hdmap": condition, "pose_sensor_start_end": poses}, + {**provenance, "hdmap_source": str(hdmap_path.resolve())}, + ) + + +if __name__ == "__main__": + main() diff --git a/shims/amp_C.py b/shims/amp_C.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e8764cbaf443559313f9a3e9c4db277b59f764 --- /dev/null +++ b/shims/amp_C.py @@ -0,0 +1,2 @@ +multi_tensor_l2norm = None +multi_tensor_scale = None diff --git a/shims/apex/__init__.py b/shims/apex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/shims/apex/multi_tensor_apply.py b/shims/apex/multi_tensor_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..06331a8203ec976f035282623fede3e5fffe83b6 --- /dev/null +++ b/shims/apex/multi_tensor_apply.py @@ -0,0 +1,2 @@ +def multi_tensor_applier(*args, **kwargs): + raise NotImplementedError("apex fused ops are training-only") diff --git a/shims/megatron/__init__.py b/shims/megatron/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/shims/megatron/core/__init__.py b/shims/megatron/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed0a186f0161c6562304838071b7be2f668e6eb --- /dev/null +++ b/shims/megatron/core/__init__.py @@ -0,0 +1,8 @@ +from . import parallel_state # noqa: F401 + + +class ModelParallelConfig: + """Attrs-factory placeholder; parallelism is unused for single-GPU inference.""" + + def __init__(self, *args, **kwargs): + self.__dict__.update(kwargs) diff --git a/shims/megatron/core/parallel_state.py b/shims/megatron/core/parallel_state.py new file mode 100644 index 0000000000000000000000000000000000000000..dbafe47ce0f89ff9a4a52ea91d4dae1bb50bbfd6 --- /dev/null +++ b/shims/megatron/core/parallel_state.py @@ -0,0 +1,28 @@ +"""Single-process stand-in: model parallelism is never initialized in this Space.""" + + +def is_initialized(): + return False + + +def model_parallel_is_initialized(): + return False + + +def _one(*a, **k): + return 1 + + +def _zero(*a, **k): + return 0 + + +def _none(*a, **k): + return None + + +get_data_parallel_world_size = get_tensor_model_parallel_world_size = get_context_parallel_world_size = _one +get_pipeline_model_parallel_world_size = _one +get_data_parallel_rank = get_tensor_model_parallel_rank = get_context_parallel_rank = _zero +get_tensor_model_parallel_group = get_context_parallel_group = get_model_parallel_group = _none +get_data_parallel_group = _none diff --git a/shims/natten/__init__.py b/shims/natten/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..458d9e04c7d55d99ed160920b4bf369850734985 --- /dev/null +++ b/shims/natten/__init__.py @@ -0,0 +1,14 @@ +"""Pure-PyTorch NATTEN stand-in (exact neighborhood attention, NATTEN window clamping).""" +from . import functional # noqa: F401 + + +def use_fused_na(*a, **k): + pass + + +def use_kv_parallelism_in_fused_na(*a, **k): + pass + + +def set_memory_usage_preference(*a, **k): + pass diff --git a/shims/natten/functional.py b/shims/natten/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5971733a8f48774e7b50ba34d77be50d27c8ee --- /dev/null +++ b/shims/natten/functional.py @@ -0,0 +1,42 @@ +import torch + + +def _window_index(length, kernel, dilation, device): + """NATTEN neighborhood indices: windows are shifted (clamped) to stay inside the axis.""" + if dilation != 1: + raise NotImplementedError("dilation > 1 not needed for LidarVerse") + if length < kernel: + raise ValueError(f"axis length {length} smaller than kernel {kernel}") + pos = torch.arange(length, device=device) + start = (pos - kernel // 2).clamp(0, length - kernel) + return start[:, None] + torch.arange(kernel, device=device)[None] # (L, k) + + +def na2d(query, key, value, kernel_size, dilation=1, scale=None, is_causal=False, **kwargs): + """query/key/value: [B, H, W, heads, D] -> [B, H, W, heads, D].""" + kh, kw = (kernel_size, kernel_size) if isinstance(kernel_size, int) else tuple(kernel_size) + dh, dw = (dilation, dilation) if isinstance(dilation, int) else tuple(dilation) + B, H, W, N, D = query.shape + if scale is None: + scale = D ** -0.5 + ih = _window_index(H, kh, dh, query.device) # (H, kh) + iw = _window_index(W, kw, dw, query.device) # (W, kw) + q = query.float() * scale + kf, vf = key.float(), value.float() + logits = torch.empty(B, H, W, N, kh * kw, device=query.device, dtype=torch.float32) + for a in range(kh): + k_rows = kf[:, ih[:, a]] # (B, H, W, N, D) rows shifted per query row + for b in range(kw): + k_ab = k_rows[:, :, iw[:, b]] + logits[..., a * kw + b] = (q * k_ab).sum(-1) + attn = logits.softmax(-1) + out = torch.zeros(B, H, W, N, D, device=query.device, dtype=torch.float32) + for a in range(kh): + v_rows = vf[:, ih[:, a]] + for b in range(kw): + out += attn[..., a * kw + b, None] * v_rows[:, :, iw[:, b]] + return out.to(query.dtype) + + +def neighborhood_attention_generic(*args, **kwargs): + raise NotImplementedError("NATTEN generic op not available; LidarVerse PAI inference does not use it") diff --git a/shims/transformer_engine/__init__.py b/shims/transformer_engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e2f9be1455fa7944d3f8402ff78530d6631a93b --- /dev/null +++ b/shims/transformer_engine/__init__.py @@ -0,0 +1,2 @@ +"""Minimal pure-PyTorch stand-in for the few Transformer Engine symbols LidarVerse inference uses.""" +from . import pytorch # noqa: F401 diff --git a/shims/transformer_engine/pytorch/__init__.py b/shims/transformer_engine/pytorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a2c47c2fca9dd14dcab84f5cef63699fcc87ae --- /dev/null +++ b/shims/transformer_engine/pytorch/__init__.py @@ -0,0 +1,21 @@ +import torch +from torch import nn + +from . import attention # noqa: F401 + + +class RMSNorm(nn.Module): + """TE-compatible RMSNorm (fp32 compute, weight named `weight`, zero_centered_gamma=False).""" + + def __init__(self, hidden_size, eps=1e-5, **kwargs): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(hidden_size)) + + def reset_parameters(self): + nn.init.ones_(self.weight) + + def forward(self, x): + xf = x.float() + y = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) + return (y * self.weight.float()).to(x.dtype) diff --git a/shims/transformer_engine/pytorch/attention/__init__.py b/shims/transformer_engine/pytorch/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f529635fe169f9d9b878bf9d10d21b2398501307 --- /dev/null +++ b/shims/transformer_engine/pytorch/attention/__init__.py @@ -0,0 +1,27 @@ +import torch + + +def _rotate_half(x): + x1, x2 = x.chunk(2, dim=-1) + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(t, freqs, tensor_format="sbhd", fused=False, interleaved=False, **kwargs): + """Unfused TE rotary embedding (non-interleaved), freqs given as [S, 1, 1, D].""" + if interleaved: + raise NotImplementedError("interleaved RoPE not needed for LidarVerse") + cur = t.shape[1] if tensor_format == "bshd" else t.shape[0] + freqs = freqs[:cur] + if tensor_format == "bshd": + freqs = freqs.transpose(0, 1) + rot = freqs.shape[-1] + t_rot, t_pass = t[..., :rot], t[..., rot:] + cos = torch.cos(freqs).to(t.dtype) + sin = torch.sin(freqs).to(t.dtype) + out = t_rot * cos + _rotate_half(t_rot) * sin + return torch.cat((out, t_pass), dim=-1) if t_pass.shape[-1] else out + + +class DotProductAttention(torch.nn.Module): + def __init__(self, *args, **kwargs): + raise NotImplementedError("transformer_engine attention backend is not available in this Space") diff --git a/shims/transformer_engine/pytorch/attention/rope.py b/shims/transformer_engine/pytorch/attention/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..4c3f457f78e838b87d004b84210dad95161a8d7a --- /dev/null +++ b/shims/transformer_engine/pytorch/attention/rope.py @@ -0,0 +1 @@ +from . import apply_rotary_pos_emb # noqa: F401 diff --git a/tokenizer/__init__.py b/tokenizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/tokenizer/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tokenizer/networks/__init__.py b/tokenizer/networks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9ba0e6db9545bc663066692fa99262844c4925 --- /dev/null +++ b/tokenizer/networks/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +"""Tokenizer network components used by LidarVerse.""" diff --git a/tokenizer/networks/common/__init__.py b/tokenizer/networks/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63d7bcb87c4caba2617bcd6c7966bdac5ecb8d35 --- /dev/null +++ b/tokenizer/networks/common/__init__.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from tokenizer.networks.common.distributions import GaussianDistribution, IdentityDistribution +from tokenizer.networks.common.quantizers import FSQuantizer, LFQuantizer, ResidualFSQuantizer, VectorQuantizer, InvQuantizerJit +from tokenizer.networks.common.patching import Patcher, UnPatcher, Patcher3D, UnPatcher3D + +class ContinuousFormulation(Enum): + VAE = GaussianDistribution + AE = IdentityDistribution + + +class DiscreteQuantizer(Enum): + VQ = VectorQuantizer + LFQ = LFQuantizer + FSQ = FSQuantizer + RESFSQ = ResidualFSQuantizer + diff --git a/tokenizer/networks/common/distributions.py b/tokenizer/networks/common/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..2342fa8246b5fb08428f6c9237a9b935261bf43d --- /dev/null +++ b/tokenizer/networks/common/distributions.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The distribution modes to use for continuous image tokenizers.""" + +import torch + + +class IdentityDistribution(torch.nn.Module): + def __init__(self): + super().__init__() + + def forward(self, parameters, split=False): + if not split: + return parameters, (torch.tensor([0.0]), torch.tensor([0.0])) + mean, logvar = parameters.chunk(2, dim=1) + mean, logvar = mean.contiguous(), logvar.contiguous() + return mean, (torch.tensor([0.0]), torch.tensor([0.0])) + + +class GaussianDistribution(torch.nn.Module): + def __init__(self, min_logvar: float = -30.0, max_logvar: float = 20.0): + super().__init__() + self.min_logvar = min_logvar + self.max_logvar = max_logvar + + def sample(self, mean, logvar): + std = torch.exp(0.5 * logvar) + return mean + std * torch.randn_like(mean) + + def forward(self, parameters, split=False): + mean, logvar = torch.chunk(parameters, 2, dim=1) + mean, logvar = mean.contiguous(), logvar.contiguous() + logvar = torch.clamp(logvar, self.min_logvar, self.max_logvar) + return self.sample(mean, logvar), (mean, logvar) diff --git a/tokenizer/networks/common/patching.py b/tokenizer/networks/common/patching.py new file mode 100644 index 0000000000000000000000000000000000000000..028df019cdf9bf1126682e144f09c107da834908 --- /dev/null +++ b/tokenizer/networks/common/patching.py @@ -0,0 +1,311 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The patcher and unpatcher implementation for 2D and 3D data. + +The idea of Haar wavelet is to compute LL, LH, HL, HH component as two 1D convolutions. +One on the rows and one on the columns. +For example, in 1D signal, we have [a, b], then the low-freq compoenent is [a + b] / 2 and high-freq is [a - b] / 2. +We can use a 1D convolution with kernel [1, 1] and stride 2 to represent the L component. +For H component, we can use a 1D convolution with kernel [1, -1] and stride 2. +Although in principle, we typically only do additional Haar wavelet over the LL component. But here we do it for all + as we need to support downsampling for more than 2x. +For example, 4x downsampling can be done by 2x Haar and additional 2x Haar, and the shape would be. + [3, 256, 256] -> [12, 128, 128] -> [48, 64, 64] +""" + +import torch +import torch.nn.functional as F +from einops import rearrange + +_WAVELETS = { + "haar": torch.tensor([0.7071067811865476, 0.7071067811865476]), + "rearrange": torch.tensor([1.0, 1.0]), +} +_PERSISTENT = True + + +class Patcher(torch.nn.Module): + """A module to convert image tensors into patches using torch operations. + + The main difference from `class Patching` is that this module implements + all operations using torch, rather than python or numpy, for efficiency purpose. + + It's bit-wise identical to the Patching module outputs, with the added + benefit of being torch.jit scriptable. + """ + + def __init__(self, patch_size=1, patch_method="haar"): + super().__init__() + self.patch_size = patch_size + self.patch_method = patch_method + self.register_buffer("wavelets", _WAVELETS[patch_method], persistent=_PERSISTENT) + self.range = range(int(torch.log2(torch.tensor(self.patch_size)).item())) + self.register_buffer( + "_arange", + torch.arange(_WAVELETS[patch_method].shape[0]), + persistent=_PERSISTENT, + ) + for param in self.parameters(): + param.requires_grad = False + + def forward(self, x): + if self.patch_method == "haar": + return self._haar(x) + elif self.patch_method == "rearrange": + return self._arrange(x) + else: + raise ValueError("Unknown patch method: " + self.patch_method) + + def _dwt(self, x, mode="reflect", rescale=False): + dtype = x.dtype + h = self.wavelets + + n = h.shape[0] + g = x.shape[1] + hl = h.flip(0).reshape(1, 1, -1).repeat(g, 1, 1) + hh = (h * ((-1) ** self._arange)).reshape(1, 1, -1).repeat(g, 1, 1) + hh = hh.to(dtype=dtype) + hl = hl.to(dtype=dtype) + + x = F.pad(x, pad=(n - 2, n - 1, n - 2, n - 1), mode=mode).to(dtype) + xl = F.conv2d(x, hl.unsqueeze(2), groups=g, stride=(1, 2)) + xh = F.conv2d(x, hh.unsqueeze(2), groups=g, stride=(1, 2)) + xll = F.conv2d(xl, hl.unsqueeze(3), groups=g, stride=(2, 1)) + xlh = F.conv2d(xl, hh.unsqueeze(3), groups=g, stride=(2, 1)) + xhl = F.conv2d(xh, hl.unsqueeze(3), groups=g, stride=(2, 1)) + xhh = F.conv2d(xh, hh.unsqueeze(3), groups=g, stride=(2, 1)) + + out = torch.cat([xll, xlh, xhl, xhh], dim=1) + if rescale: + out = out / 2 + return out + + def _haar(self, x): + for _ in self.range: + x = self._dwt(x, rescale=True) + return x + + def _arrange(self, x): + x = rearrange( + x, + "b c (h p1) (w p2) -> b (c p1 p2) h w", + p1=self.patch_size, + p2=self.patch_size, + ).contiguous() + return x + + +class Patcher3D(Patcher): + """A 3D discrete wavelet transform for video data, expects 5D tensor, i.e. a batch of videos.""" + + def __init__(self, patch_size=1, patch_method="haar"): + super().__init__(patch_method=patch_method, patch_size=patch_size) + self.register_buffer( + "patch_size_buffer", + patch_size * torch.ones([1], dtype=torch.int32), + persistent=_PERSISTENT, + ) + + def _dwt(self, x, wavelet, mode="reflect", rescale=False): + dtype = x.dtype + h = self.wavelets + + n = h.shape[0] + g = x.shape[1] + hl = h.flip(0).reshape(1, 1, -1).repeat(g, 1, 1) + hh = (h * ((-1) ** self._arange)).reshape(1, 1, -1).repeat(g, 1, 1) + hh = hh.to(dtype=dtype) + hl = hl.to(dtype=dtype) + + # Handles temporal axis. + x = F.pad(x, pad=(max(0, n - 2), n - 1, n - 2, n - 1, n - 2, n - 1), mode=mode).to(dtype) + xl = F.conv3d(x, hl.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1)) + xh = F.conv3d(x, hh.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1)) + + # Handles spatial axes. + xll = F.conv3d(xl, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xlh = F.conv3d(xl, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xhl = F.conv3d(xh, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xhh = F.conv3d(xh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + + xlll = F.conv3d(xll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xllh = F.conv3d(xll, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xlhl = F.conv3d(xlh, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xlhh = F.conv3d(xlh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhll = F.conv3d(xhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhlh = F.conv3d(xhl, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhhl = F.conv3d(xhh, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhhh = F.conv3d(xhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + + out = torch.cat([xlll, xllh, xlhl, xlhh, xhll, xhlh, xhhl, xhhh], dim=1) + if rescale: + out = out / (2 * torch.sqrt(torch.tensor(2.0))) + return out + + def _haar(self, x): + xi, xv = torch.split(x, [1, x.shape[2] - 1], dim=2) + x = torch.cat([xi.repeat_interleave(self.patch_size, dim=2), xv], dim=2) + for _ in self.range: + x = self._dwt(x, "haar", rescale=True) + return x + + def _arrange(self, x): + xi, xv = torch.split(x, [1, x.shape[2] - 1], dim=2) + x = torch.cat([xi.repeat_interleave(self.patch_size, dim=2), xv], dim=2) + x = rearrange( + x, + "b c (t p1) (h p2) (w p3) -> b (c p1 p2 p3) t h w", + p1=self.patch_size, + p2=self.patch_size, + p3=self.patch_size, + ).contiguous() + return x + + +class UnPatcher(torch.nn.Module): + """A module to convert patches into image tensorsusing torch operations. + + The main difference from `class Unpatching` is that this module implements + all operations using torch, rather than python or numpy, for efficiency purpose. + + It's bit-wise identical to the Unpatching module outputs, with the added + benefit of being torch.jit scriptable. + """ + + def __init__(self, patch_size=1, patch_method="haar"): + super().__init__() + self.patch_size = patch_size + self.patch_method = patch_method + self.register_buffer("wavelets", _WAVELETS[patch_method], persistent=_PERSISTENT) + self.range = range(int(torch.log2(torch.tensor(self.patch_size)).item())) + self.register_buffer( + "_arange", + torch.arange(_WAVELETS[patch_method].shape[0]), + persistent=_PERSISTENT, + ) + for param in self.parameters(): + param.requires_grad = False + + def forward(self, x): + if self.patch_method == "haar": + return self._ihaar(x) + elif self.patch_method == "rearrange": + return self._iarrange(x) + else: + raise ValueError("Unknown patch method: " + self.patch_method) + + def _idwt(self, x, wavelet="haar", mode="reflect", rescale=False): + dtype = x.dtype + h = self.wavelets + n = h.shape[0] + + g = x.shape[1] // 4 + hl = h.flip([0]).reshape(1, 1, -1).repeat([g, 1, 1]) + hh = (h * ((-1) ** self._arange)).reshape(1, 1, -1).repeat(g, 1, 1) + hh = hh.to(dtype=dtype) + hl = hl.to(dtype=dtype) + + xll, xlh, xhl, xhh = torch.chunk(x.to(dtype), 4, dim=1) + + # Inverse transform. + yl = torch.nn.functional.conv_transpose2d(xll, hl.unsqueeze(3), groups=g, stride=(2, 1), padding=(n - 2, 0)) + yl += torch.nn.functional.conv_transpose2d(xlh, hh.unsqueeze(3), groups=g, stride=(2, 1), padding=(n - 2, 0)) + yh = torch.nn.functional.conv_transpose2d(xhl, hl.unsqueeze(3), groups=g, stride=(2, 1), padding=(n - 2, 0)) + yh += torch.nn.functional.conv_transpose2d(xhh, hh.unsqueeze(3), groups=g, stride=(2, 1), padding=(n - 2, 0)) + y = torch.nn.functional.conv_transpose2d(yl, hl.unsqueeze(2), groups=g, stride=(1, 2), padding=(0, n - 2)) + y += torch.nn.functional.conv_transpose2d(yh, hh.unsqueeze(2), groups=g, stride=(1, 2), padding=(0, n - 2)) + + if rescale: + y = y * 2 + return y + + def _ihaar(self, x): + for _ in self.range: + x = self._idwt(x, "haar", rescale=True) + return x + + def _iarrange(self, x): + x = rearrange( + x, + "b (c p1 p2) h w -> b c (h p1) (w p2)", + p1=self.patch_size, + p2=self.patch_size, + ) + return x + + +class UnPatcher3D(UnPatcher): + """A 3D inverse discrete wavelet transform for video wavelet decompositions.""" + + def __init__(self, patch_size=1, patch_method="haar"): + super().__init__(patch_method=patch_method, patch_size=patch_size) + + def _idwt(self, x, wavelet="haar", mode="reflect", rescale=False): + dtype = x.dtype + h = self.wavelets + n = h.shape[0] + + g = x.shape[1] // 8 # split into 8 spatio-temporal filtered tesnors. + hl = h.flip([0]).reshape(1, 1, -1).repeat([g, 1, 1]) + hh = (h * ((-1) ** self._arange)).reshape(1, 1, -1).repeat(g, 1, 1) + hl = hl.to(dtype=dtype) + hh = hh.to(dtype=dtype) + + xlll, xllh, xlhl, xlhh, xhll, xhlh, xhhl, xhhh = torch.chunk(x, 8, dim=1) + + # Height height transposed convolutions. + xll = F.conv_transpose3d(xlll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xll += F.conv_transpose3d(xllh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + + xlh = F.conv_transpose3d(xlhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xlh += F.conv_transpose3d(xlhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + + xhl = F.conv_transpose3d(xhll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhl += F.conv_transpose3d(xhlh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + + xhh = F.conv_transpose3d(xhhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhh += F.conv_transpose3d(xhhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + + # Handles width transposed convolutions. + xl = F.conv_transpose3d(xll, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xl += F.conv_transpose3d(xlh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xh = F.conv_transpose3d(xhl, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xh += F.conv_transpose3d(xhh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + + # Handles time axis transposed convolutions. + x = F.conv_transpose3d(xl, hl.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1)) + x += F.conv_transpose3d(xh, hh.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1)) + + if rescale: + x = x * (2 * torch.sqrt(torch.tensor(2.0))) + return x + + def _ihaar(self, x): + for _ in self.range: + x = self._idwt(x, "haar", rescale=True) + x = x[:, :, self.patch_size - 1 :, ...] + return x + + def _iarrange(self, x): + x = rearrange( + x, + "b (c p1 p2 p3) t h w -> b c (t p1) (h p2) (w p3)", + p1=self.patch_size, + p2=self.patch_size, + p3=self.patch_size, + ) + x = x[:, :, self.patch_size - 1 :, ...] + return x diff --git a/tokenizer/networks/common/quantizers.py b/tokenizer/networks/common/quantizers.py new file mode 100644 index 0000000000000000000000000000000000000000..cf07b26a9ccddae5d6d12051231995b894fa34dd --- /dev/null +++ b/tokenizer/networks/common/quantizers.py @@ -0,0 +1,507 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Quantizers for discrete image and video tokenization.""" + +from typing import Optional + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import reduce +from loguru import logger as logging + +from tokenizer.networks.utils import default, entropy, pack_one, rearrange, round_ste, unpack_one + +_PERSISTENT = True + + +class ResidualFSQuantizer(nn.Module): + """Residual Finite Scalar Quantization + + Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf + """ + + def __init__(self, levels: list[int], num_quantizers: int, **ignore_kwargs): + super().__init__() + self.dtype = ignore_kwargs.get("dtype", torch.float32) + self.layers = nn.ModuleList([FSQuantizer(levels=levels) for _ in range(num_quantizers)]) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + indices_stack = [] + residual = x + quantized_out = 0 + loss_out = 0 + for i, layer in enumerate(self.layers): + quant_indices, z, loss = layer(residual) + indices_stack.append(quant_indices) + residual = residual - z.detach() + quantized_out = quantized_out + z + loss_out = loss_out + loss + self.residual = residual + indices = torch.stack(indices_stack, dim=1) + return indices, quantized_out.to(self.dtype), loss_out.to(self.dtype) + + def indices_to_codes(self, indices_stack: torch.Tensor) -> torch.Tensor: + quantized_out = 0 + for layer, indices in zip(self.layers, indices_stack.transpose(0, 1)): + quantized_out += layer.indices_to_codes(indices) + return quantized_out + + +class FSQuantizer(nn.Module): + """Finite Scalar Quantization: VQ-VAE Made Simple - https://arxiv.org/abs/2309.15505 + + Code adapted from Jax version in Appendix A.1. + + Adapted from: https://github.com/lucidrains/vector-quantize-pytorch/blob/9502a1f447876d53fd37685b226bf28f250dc4a3/ + vector_quantize_pytorch/finite_scalar_quantization.py + [Copyright (c) 2020 Phil Wang] + https://github.com/lucidrains/vector-quantize-pytorch/blob/9502a1f447876d53fd37685b226bf28f250dc4a3/LICENSE + """ + + def __init__( + self, + levels: list[int], + dim: Optional[int] = None, + num_codebooks=1, + keep_num_codebooks_dim: Optional[bool] = None, + scale: Optional[float] = None, + **ignore_kwargs, + ): + super().__init__() + self.dtype = ignore_kwargs.get("dtype", torch.bfloat16) + self.persistent = ignore_kwargs.get("persistent_quantizer", _PERSISTENT) + _levels = torch.tensor(levels, dtype=torch.int32) + self.register_buffer("_levels", _levels, persistent=self.persistent) + + _basis = torch.cumprod(torch.tensor([1] + levels[:-1]), dim=0, dtype=torch.int32) + self.register_buffer("_basis", _basis, persistent=self.persistent) + + self.scale = scale + + codebook_dim = len(levels) + self.codebook_dim = codebook_dim + + effective_codebook_dim = codebook_dim * num_codebooks + self.num_codebooks = num_codebooks + self.effective_codebook_dim = effective_codebook_dim + + keep_num_codebooks_dim = default(keep_num_codebooks_dim, num_codebooks > 1) + assert not (num_codebooks > 1 and not keep_num_codebooks_dim) + self.keep_num_codebooks_dim = keep_num_codebooks_dim + + self.dim = default(dim, len(_levels) * num_codebooks) + + has_projections = self.dim != effective_codebook_dim + self.project_in = nn.Linear(self.dim, effective_codebook_dim) if has_projections else nn.Identity() + self.project_out = nn.Linear(effective_codebook_dim, self.dim) if has_projections else nn.Identity() + self.has_projections = has_projections + + self.codebook_size = self._levels.prod().item() + + implicit_codebook = self.indices_to_codes(torch.arange(self.codebook_size), project_out=False) + self.register_buffer("implicit_codebook", implicit_codebook, persistent=self.persistent) + + def bound(self, z: torch.Tensor, eps: float = 1e-3) -> torch.Tensor: + """Bound `z`, an array of shape (..., d).""" + half_l = (self._levels - 1) * (1 + eps) / 2 + offset = torch.where(self._levels % 2 == 0, 0.5, 0.0) + shift = (offset / half_l).atanh() + return (z + shift).tanh() * half_l - offset + + def quantize(self, z: torch.Tensor) -> torch.Tensor: + """Quantizes z, returns quantized zhat, same shape as z.""" + quantized = round_ste(self.bound(z)) + half_width = self._levels // 2 # Renormalize to [-1, 1]. + return quantized / half_width + + def _scale_and_shift(self, zhat_normalized: torch.Tensor) -> torch.Tensor: + half_width = self._levels // 2 + return (zhat_normalized * half_width) + half_width + + def _scale_and_shift_inverse(self, zhat: torch.Tensor) -> torch.Tensor: + half_width = self._levels // 2 + return (zhat - half_width) / half_width + + def codes_to_indices(self, zhat: torch.Tensor) -> torch.Tensor: + """Converts a `code` to an index in the codebook.""" + assert zhat.shape[-1] == self.codebook_dim + zhat = self._scale_and_shift(zhat).float() + return (zhat * self._basis).sum(dim=-1).to(torch.int32) + + def indices_to_codes(self, indices: torch.Tensor, project_out=True) -> torch.Tensor: + """Inverse of `codes_to_indices`.""" + is_img_or_video = indices.ndim >= (3 + int(self.keep_num_codebooks_dim)) + indices = rearrange(indices, "... -> ... 1") + codes_non_centered = (indices // self._basis) % self._levels + codes = self._scale_and_shift_inverse(codes_non_centered) + + if self.keep_num_codebooks_dim: + codes = rearrange(codes, "... c d -> ... (c d)") + + if project_out: + codes = self.project_out(codes) + + if is_img_or_video: + codes = rearrange(codes, "b ... d -> b d ...") + + return codes.to(self.dtype) + + def forward(self, z: torch.Tensor) -> torch.Tensor: + """ + einstein notation + b - batch + n - sequence (or flattened spatial dimensions) + d - feature dimension, which is also log2(codebook size) + c - number of codebook dim + """ + is_img_or_video = z.ndim >= 4 + + # standardize image or video into (batch, seq, dimension) + + if is_img_or_video: + z = rearrange(z, "b d ... -> b ... d") + z, ps = pack_one(z, "b * d") + + assert z.shape[-1] == self.dim, f"expected dimension of {self.dim} but found dimension of {z.shape[-1]}" + + z = self.project_in(z) + + z = rearrange(z, "b n (c d) -> b n c d", c=self.num_codebooks) + + codes = self.quantize(z) + indices = self.codes_to_indices(codes) + + codes = rearrange(codes, "b n c d -> b n (c d)") + + out = self.project_out(codes) + + # reconstitute image or video dimensions + + if is_img_or_video: + out = unpack_one(out, ps, "b * d") + out = rearrange(out, "b ... d -> b d ...") + indices = unpack_one(indices, ps, "b * c") + dummy_loss = torch.zeros_like(out.mean(dim=[1, 2, 3], keepdim=True)) + else: + dummy_loss = torch.zeros_like(out.mean(dim=[1, 2], keepdim=True)).unsqueeze(1) + + if not self.keep_num_codebooks_dim: + indices = rearrange(indices, "... 1 -> ...") + + return (indices, out.to(self.dtype), dummy_loss) + + +class VectorQuantizer(nn.Module): + """Improved version over VectorQuantizer. Mostly + avoids costly matrix multiplications and allows for post-hoc remapping of indices. + + Adapted from: https://github.com/CompVis/taming-transformers/blob/3ba01b241669f5ade541ce990f7650a3b8f65318/ + taming/modules/vqvae/quantize.py + + [Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer] + https://github.com/CompVis/taming-transformers/blob/3ba01b241669f5ade541ce990f7650a3b8f65318/License.txt + """ + + def __init__( + self, + num_embeddings: int, + embedding_dim: int, + beta: float = 0.25, + remap: str = None, + unknown_index: str = "random", + sane_index_shape: bool = False, + legacy: bool = True, + use_norm=False, + **ignore_kwargs, + ): + super().__init__() + self.n_e = num_embeddings + self.e_dim = embedding_dim + self.beta = beta + self.legacy = legacy + self.norm = lambda x: F.normalize(x, dim=-1) if use_norm else x + + self.embedding = nn.Embedding(self.n_e, self.e_dim) + self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e) + + self.remap = remap + if self.remap is not None: + self.register_buffer("used", torch.tensor(np.load(self.remap))) + self.re_embed = self.used.shape[0] + self.unknown_index = unknown_index + if self.unknown_index == "extra": + self.unknown_index = self.re_embed + self.re_embed = self.re_embed + 1 + print( + f"Remapping {self.n_e} indices to {self.re_embed} indices. " + f"Using {self.unknown_index} for unknown indices." + ) + else: + self.re_embed = num_embeddings + + self.sane_index_shape = sane_index_shape + self.dtype = ignore_kwargs.get("dtype", torch.float32) + + def remap_to_used(self, inds): + ishape = inds.shape + assert len(ishape) > 1 + inds = inds.reshape(ishape[0], -1) + used = self.used.to(inds) + match = (inds[:, :, None] == used[None, None, ...]).long() + new = match.argmax(-1) + unknown = match.sum(2) < 1 + if self.unknown_index == "random": + new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device) + else: + new[unknown] = self.unknown_index + return new.reshape(ishape) + + def unmap_to_all(self, inds): + ishape = inds.shape + assert len(ishape) > 1 + inds = inds.reshape(ishape[0], -1) + used = self.used.to(inds) + if self.re_embed > self.used.shape[0]: # extra token + inds[inds >= self.used.shape[0]] = 0 # simply set to zero + back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds) + return back.reshape(ishape) + + def forward(self, z, temp=None, rescale_logits=False, return_logits=False): + assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel" + assert rescale_logits is False, "Only for interface compatible with Gumbel" + assert return_logits is False, "Only for interface compatible with Gumbel" + z = rearrange(z, "b c h w -> b h w c").contiguous() + z_flattened = z.view(-1, self.e_dim) + + d = ( + torch.sum(z_flattened**2, dim=1, keepdim=True) + + torch.sum(self.embedding.weight**2, dim=1) + - 2 + * torch.einsum( + "bd,dn->bn", + z_flattened, + rearrange(self.embedding.weight, "n d -> d n"), + ) + ) + + encoding_indices = torch.argmin(d, dim=1).unsqueeze(1) + encodings = torch.zeros(encoding_indices.shape[0], self.n_e, device=z.device) + encodings.scatter_(1, encoding_indices, 1) + z_q = torch.matmul(encodings, self.embedding.weight).view(z.shape) + min_encodings = None + + z_q, z = self.norm(z_q), self.norm(z) + + # compute loss for embedding + commit_loss = torch.mean((z_q - z.detach()) ** 2, dim=[1, 2, 3], keepdim=True) + emb_loss = torch.mean((z_q.detach() - z) ** 2, dim=[1, 2, 3], keepdim=True) + if not self.legacy: + loss = self.beta * emb_loss + commit_loss + else: + loss = emb_loss + self.beta * commit_loss + + # preserve gradients + z_q = z + (z_q - z).detach() + avg_probs = torch.mean(encodings, dim=0) + perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10))) + + # reshape back to match original input shape + z_q = rearrange(z_q, "b h w c -> b c h w").contiguous() + + if self.remap is not None: + min_encoding_indices = encoding_indices.squeeze(1).reshape(z.shape[0], -1) # add batch axis + min_encoding_indices = self.remap_to_used(encoding_indices.squeeze(1)) + min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten + + if self.sane_index_shape: + min_encoding_indices = min_encoding_indices.reshape(z_q.shape[0], z_q.shape[2], z_q.shape[3]) + + return ( + z_q, + loss, + ( + encoding_indices.squeeze(1), + min_encodings, + commit_loss.mean().detach(), + self.beta * emb_loss.mean().detach(), + perplexity.mean().detach(), + ), + ) + + def get_codebook_entry(self, indices, shape): + # shape specifying (batch, height, width, channel) + if self.remap is not None: + indices = indices.reshape(shape[0], -1) # add batch axis + indices = self.unmap_to_all(indices) + indices = indices.reshape(-1) # flatten again + + # get quantized latent vectors + z_q = self.embedding(indices) + + if shape is not None: + z_q = z_q.view(shape) + # reshape back to match original input shape + z_q = z_q.permute(0, 3, 1, 2).contiguous() + + return z_q + + +class LFQuantizer(nn.Module): + """Lookup-Free Quantization + + Adapted from: https://github.com/lucidrains/vector-quantize-pytorch/blob/9502a1f447876d53fd37685b226bf28f250dc4a3/ + vector_quantize_pytorch/lookup_free_quantization.py + [Copyright (c) 2020 Phil Wang] + https://github.com/lucidrains/vector-quantize-pytorch/blob/9502a1f447876d53fd37685b226bf28f250dc4a3/LICENSE + """ + + def __init__( + self, + *, + codebook_size: int, + codebook_dim: int, + embed_dim: Optional[int] = None, # if None, use codebook_dim + entropy_loss_weight=0.1, + commitment_loss_weight=0.25, + default_temp: float = 0.01, + entropy_loss: bool = False, + **ignore_kwargs, + ): + """Lookup-Free Quantization + + Args: + codebook_size (int): The number of entries in the codebook. + codebook_dim (int): The number of bits in each code. + embed_dim (Optional[int], optional): The dimension of the input embedding. Defaults to None. + entropy_loss_weight (float, optional): Whether to use entropy loss. Defaults to 0.1. + commitment_loss_weight (float, optional): Weight for commitment loss. Defaults to 0.25. + default_temp (float, optional): The temprature to use. Defaults to 0.01. + entropy_loss (bool, optional): Flag for entropy loss. Defaults to False. + """ + super().__init__() + self.entropy_loss = entropy_loss + self.codebook_dim = codebook_dim + self.default_temp = default_temp + self.entrop_loss_weight = entropy_loss_weight + self.commitment_loss_weight = commitment_loss_weight + embed_dim = embed_dim or codebook_dim + + has_projections = embed_dim != codebook_dim + self.project_in = nn.Linear(embed_dim, codebook_dim) if has_projections else nn.Identity() + self.project_out = nn.Linear(codebook_dim, embed_dim) if has_projections else nn.Identity() + logging.info(f"LFQ: has_projections={has_projections}, dim_in={embed_dim}, codebook_dim={codebook_dim}") + + self.dtype = ignore_kwargs.get("dtype", torch.float32) + + if entropy_loss: + assert 2**codebook_dim == codebook_size, "codebook size must be 2 ** codebook_dim" + self.codebook_size = codebook_size + + self.register_buffer( + "mask", + 2 ** torch.arange(codebook_dim - 1, -1, -1), + persistent=_PERSISTENT, + ) + self.register_buffer("zero", torch.tensor(0.0), persistent=_PERSISTENT) + + all_codes = torch.arange(codebook_size) + bits = ((all_codes[..., None].int() & self.mask) != 0).float() + codebook = 2 * bits - 1.0 + + self.register_buffer("codebook", codebook, persistent=_PERSISTENT) # [codebook_size, codebook_dim] + + def forward(self, z: torch.Tensor, temp: float = None) -> torch.Tensor: + temp = temp or self.default_temp + + z = rearrange(z, "b d ... -> b ... d") + z, ps = pack_one(z, "b * d") + z = self.project_in(z) + + # split out number of codebooks + z = rearrange(z, "b n (c d) -> b n c d", c=self.num_codebooks) + + # quantization + original_input = z + + codebook_value = torch.ones_like(z) + z_q = torch.where(z > 0, codebook_value, -codebook_value) + + # preserve gradients + z_q = z + (z_q - z).detach() + + # commit loss + commit_loss = ((original_input - z_q.detach()) ** 2).mean(dim=[1, 2, 3]) + + z_q = rearrange(z_q, "b n c d -> b n (c d)") + z_q = self.project_out(z_q) + + # reshape + z_q = unpack_one(z_q, ps, "b * d") + z_q = rearrange(z_q, "b ... d -> b d ...") + + loss = self.commitment_loss_weight * commit_loss + + # entropy loss (eq-5) + if self.entropy_loss: + # indices + indices = reduce((z > 0).int() * self.mask.int(), "b n c d -> b n c", "sum") + indices = unpack_one(indices, ps, "b * c") + indices = rearrange(indices, "... 1 -> ...") + + distance = -2 * torch.einsum( + "... i d, j d -> ... i j", + original_input, + self.codebook.to(original_input.dtype), + ) + prob = (-distance / temp).softmax(dim=-1) + per_sample_entropy = entropy(prob).mean(dim=[1, 2]) + avg_prob = reduce(prob, "... c d -> c d", "mean") + codebook_entropy = entropy(avg_prob).mean() + entropy_aux_loss = per_sample_entropy - codebook_entropy + + loss += self.entrop_loss_weight * entropy_aux_loss + + return ( + z_q, + loss.unsqueeze(1).unsqueeze(1).unsqueeze(1), + ( + indices, + self.commitment_loss_weight * commit_loss.mean().detach(), + self.entrop_loss_weight * entropy_aux_loss.mean().detach(), + self.entrop_loss_weight * per_sample_entropy.mean().detach(), + self.entrop_loss_weight * codebook_entropy.mean().detach(), + ), + ) + else: + return ( + z_q, + loss.unsqueeze(1).unsqueeze(1).unsqueeze(1), + self.commitment_loss_weight * commit_loss.mean().detach(), + ) + + +class InvQuantizerJit(nn.Module): + """Use for decoder_jit to trace quantizer in discrete tokenizer""" + + def __init__(self, quantizer): + super().__init__() + self.quantizer = quantizer + + def forward(self, indices: torch.Tensor): + codes = self.quantizer.indices_to_codes(indices) + return codes.to(self.quantizer.dtype) diff --git a/tokenizer/networks/transformers/__init__.py b/tokenizer/networks/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb9468c65d295564a72ae1daf807c6e16f50ca3 --- /dev/null +++ b/tokenizer/networks/transformers/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Transformer tokenizer architectures used by LidarVerse.""" + +from .transformer_vae import TransformerVAE +from .transformer_vae_cross_dataset import CrossDatasetTransformerVAE + +__all__ = ["CrossDatasetTransformerVAE", "TransformerVAE"] diff --git a/tokenizer/networks/transformers/encoding.py b/tokenizer/networks/transformers/encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..db65f7e326bd47a8a731de1632ed644b3a135044 --- /dev/null +++ b/tokenizer/networks/transformers/encoding.py @@ -0,0 +1,143 @@ +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +# components_from_spherical_harmonics() is from nerfstudio +# https://github.com/nerfstudio-project/nerfstudio/blob/main/nerfstudio/utils/math.py + + +def components_from_spherical_harmonics(levels: int, directions): + """ + Returns value for each component of spherical harmonics. + + Args: + levels: Number of spherical harmonic levels to compute. + directions: Spherical harmonic coefficients + """ + num_components = levels**2 + components = torch.zeros( + (*directions.shape[:-1], num_components), device=directions.device + ) + + # assert 1 <= levels <= 5, f"SH levels must be in [1,4], got {levels}" + assert ( + directions.shape[-1] == 3 + ), f"Direction input should have three dimensions. Got {directions.shape[-1]}" + + x = directions[..., 0] + y = directions[..., 1] + z = directions[..., 2] + + xx = x**2 + yy = y**2 + zz = z**2 + + # l0 + components[..., 0] = 0.28209479177387814 + + # l1 + if levels > 1: + components[..., 1] = 0.4886025119029199 * y + components[..., 2] = 0.4886025119029199 * z + components[..., 3] = 0.4886025119029199 * x + + # l2 + if levels > 2: + components[..., 4] = 1.0925484305920792 * x * y + components[..., 5] = 1.0925484305920792 * y * z + components[..., 6] = 0.9461746957575601 * zz - 0.31539156525251999 + components[..., 7] = 1.0925484305920792 * x * z + components[..., 8] = 0.5462742152960396 * (xx - yy) + + # l3 + if levels > 3: + components[..., 9] = 0.5900435899266435 * y * (3 * xx - yy) + components[..., 10] = 2.890611442640554 * x * y * z + components[..., 11] = 0.4570457994644658 * y * (5 * zz - 1) + components[..., 12] = 0.3731763325901154 * z * (5 * zz - 3) + components[..., 13] = 0.4570457994644658 * x * (5 * zz - 1) + components[..., 14] = 1.445305721320277 * z * (xx - yy) + components[..., 15] = 0.5900435899266435 * x * (xx - 3 * yy) + + # l4 + if levels > 4: + components[..., 16] = 2.5033429417967046 * x * y * (xx - yy) + components[..., 17] = 1.7701307697799304 * y * z * (3 * xx - yy) + components[..., 18] = 0.9461746957575601 * x * y * (7 * zz - 1) + components[..., 19] = 0.6690465435572892 * y * z * (7 * zz - 3) + components[..., 20] = 0.10578554691520431 * (35 * zz * zz - 30 * zz + 3) + components[..., 21] = 0.6690465435572892 * x * z * (7 * zz - 3) + components[..., 22] = 0.47308734787878004 * (xx - yy) * (7 * zz - 1) + components[..., 23] = 1.7701307697799304 * x * z * (xx - 3 * yy) + components[..., 24] = 0.6258357354491761 * ( + xx * (xx - 3 * yy) - yy * (3 * xx - yy) + ) + + return components + + +def generate_polar_coords(H: int, W: int, device: torch.device = "cpu") -> torch.Tensor: + """ + theta: azimuthal angle in [-pi, pi] + phi: polar angle in [0, pi] + """ + phi = (0.5 - torch.arange(H, device=device) / H) * torch.pi + theta = (1 - torch.arange(W, device=device) / W) * 2 * torch.pi - torch.pi + [phi, theta] = torch.meshgrid([phi, theta], indexing="ij") + angles = torch.stack([phi, theta]) + return angles[None] + + +class SphericalHarmonics(nn.Module): + def __init__(self, levels: int = 4) -> None: + super().__init__() + self.levels = levels + self.extra_ch = levels**2 + + def forward(self, coords: torch.Tensor) -> torch.Tensor: + _, _, H, W = coords.shape + phi, theta = coords[:, 0], coords[:, 1] + directions = torch.stack( + [ + torch.cos(theta) * torch.cos(phi), + -torch.sin(theta) * torch.cos(phi), + torch.sin(phi), + ], + dim=-1, + ) + basis = components_from_spherical_harmonics( + levels=self.levels, directions=directions + ) + basis = basis.permute(0, 3, 1, 2) + return basis + + def extra_repr(self): + return f"levels={self.levels}" + + +class FourierFeatures(nn.Module): + def __init__(self, resolution): + super().__init__() + self.resolution = resolution + + self.L_h = int(np.ceil(np.log2(self.resolution[0]))) + self.L_w = int(np.ceil(np.log2(self.resolution[1]))) + + freqs_h = torch.arange(self.L_h).exp2() + freqs_h = torch.cat([freqs_h, torch.zeros(self.L_w)]) + freqs_w = torch.arange(self.L_w).exp2() + freqs_w = torch.cat([torch.zeros(self.L_h), freqs_w]) + freqs = torch.stack([freqs_h, freqs_w], dim=-1) + phase = torch.zeros(len(freqs_h)) + self.register_buffer("freqs", freqs[..., None, None]) + self.register_buffer("phase", phase) + self.extra_ch = int(len(freqs_h) * 2) + + def forward(self, coords: torch.Tensor) -> torch.Tensor: + coords = F.conv2d(coords, weight=self.freqs, bias=self.phase) + encoded = torch.cat([coords.sin(), coords.cos()], dim=1) + return encoded + + def extra_repr(self): + return f"shape={self.resolution}, num_freqs={self.extra_ch}, L=({self.L_h}, {self.L_w})" diff --git a/tokenizer/networks/transformers/ops.py b/tokenizer/networks/transformers/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c1780029a3890dbe7c14eee7fabfb4d6671aa471 --- /dev/null +++ b/tokenizer/networks/transformers/ops.py @@ -0,0 +1,205 @@ +import numpy as np +import torch +import torch.nn.functional as F +from einops.layers.torch import Rearrange +from torch import nn +from torch.nn.modules.utils import _pair, _quadruple + + +def zero_out(m: nn.Module): + for p in m.parameters(): + p.data.zero_() + + +class SinusoidalPositionalEmbedding(nn.Module): + def __init__(self, channels: int, max_period: int = 10_000): + super().__init__() + self.channels = channels + self.max_period = max_period + + def forward(self, x: torch.Tensor) -> torch.Tensor: + assert len(x.shape) == 1 + h = -np.log(self.max_period) / (self.channels // 2 - 1) + h = torch.exp(h * torch.arange(self.channels // 2, device=x.device)) + h = x[:, None] * h[None, :] + h = torch.cat([h.sin(), h.cos()], dim=-1) + return h.to(x) + + def extra_repr(self): + return f"dim={self.channels} max_period={self.max_period}" + + +class Pad(nn.Module): + def __init__(self, padding, ring=False, mode="constant"): + super().__init__() + self.padding = _quadruple(padding) + self.horizontal = "circular" if ring else mode + self.vertical = mode + + def forward(self, h: torch.Tensor) -> torch.Tensor: + left, right, top, bottom = self.padding + h = F.pad(h, (left, right, 0, 0), mode=self.horizontal) + h = F.pad(h, (0, 0, top, bottom), mode=self.vertical) + return h + + def extra_repr(self): + return ( + f"padding={self.padding}, " + + f"horizontal={self.horizontal}, vertical={self.vertical}" + ) + + +class Resample(nn.Module): + def __init__( + self, + up=1, + down=1, + window=[1, 3, 3, 1], # bilinear + ring=True, + normalize=True, + direction="hw", + mode="constant", + ): + super().__init__() + self.up = np.asarray(_pair(up)) + self.down = np.asarray(_pair(down)) + self.window = window + self.n_taps = len(window) + self.ring = ring + self.pad_mode_w = "circular" if ring else mode + self.pad_mode_h = mode + self.normalize = normalize + self.direction = direction + assert self.direction in ("h", "w", "hw") + + # setup sizes + if "h" in self.direction: + self.k_h = self.n_taps + self.up_h = self.up[0] + self.down_h = self.down[0] + else: + self.k_h = self.up_h = self.down_h = 1 + + if "w" in self.direction: + self.k_w = self.n_taps + self.up_w = self.up[1] + self.down_w = self.down[1] + else: + self.k_w = self.up_w = self.down_w = 1 + + # setup filter + kernel = torch.tensor(self.window, dtype=torch.float32) + if self.normalize: + kernel /= kernel.sum() + kernel *= (self.up_h * self.up_w) ** (kernel.ndim / 2) + self.register_buffer("kernel", kernel) + + # setup padding + if self.up[0] > 1: + self.ph0 = (self.k_h - self.up_h + 1) // 2 + self.up_h - 1 + self.ph1 = (self.k_h - self.up_h) // 2 + elif self.down[0] >= 1: + self.ph0 = (self.k_h - self.down_h + 1) // 2 + self.ph1 = (self.k_h - self.down_h) // 2 + if self.up[1] > 1: + self.pw0 = (self.k_w - self.up_w + 1) // 2 + self.up_w - 1 + self.pw1 = (self.k_w - self.up_w) // 2 + elif self.down[1] >= 1: + self.pw0 = (self.k_w - self.down_w + 1) // 2 + self.pw1 = (self.k_w - self.down_w) // 2 + + self.margin = int(max(self.ph0, self.ph1, self.pw0, self.pw1)) + + def forward(self, h: torch.Tensor) -> torch.Tensor: + # margin + h = F.pad(h, (self.margin, self.margin, 0, 0), mode=self.pad_mode_w) + h = F.pad(h, (0, 0, self.margin, self.margin), mode=self.pad_mode_h) + # up by zero-insertion + B, C, H, W = h.shape + h = h.view(B, C, H, 1, W, 1) + h = F.pad(h, [0, self.up_w - 1, 0, 0, 0, self.up_h - 1]) + h = h.view(B, C, H * self.up_h, W * self.up_w) + # crop + h = h[ + ..., + self.margin * self.up_h - self.ph0 : (H - self.margin) * self.up_h + + self.ph1, + self.margin * self.up_w - self.pw0 : (W - self.margin) * self.up_w + + self.pw1, + ] + # fir + kernel = self.kernel[None, None].repeat(C, 1, 1).to(dtype=h.dtype) + if self.direction == "hw": + h = F.conv2d(h, kernel[..., None, :], groups=C) + h = F.conv2d(h, kernel[..., :, None], groups=C) + elif self.direction == "h": + h = F.conv2d(h, kernel[..., :, None], groups=C) + elif self.direction == "w": + h = F.conv2d(h, kernel[..., None, :], groups=C) + # down + h = h[:, :, :: self.down_h, :: self.down_w] + return h + + def extra_repr(self): + return f"up={tuple(self.up)}, down={tuple(self.down)}, ring={self.ring}" + + +class Conv2d(nn.Conv2d): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + bias=True, + ring=False, + ): + super().__init__( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=0, + bias=bias, + ) + self.pad = Pad(padding=padding, ring=ring) if padding != 0 else None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.pad is not None: + x = self.pad(x) + return super().forward(x) + + +class AdaGN(nn.GroupNorm): + def __init__( + self, + emb_channels, + out_channels, + num_groups, + eps=1e-5, + ): + super().__init__( + num_groups=num_groups, + num_channels=out_channels, + eps=eps, + affine=False, + ) + self.proj = nn.Sequential( + nn.SiLU(), + nn.Linear(emb_channels, out_channels * 2), + Rearrange("B C -> B C 1 1"), + ) + + def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor: + h = super().forward(x) + scale, shift = self.proj(emb).chunk(2, dim=1) + h = h * (1 + scale) + shift + return h + + +class ConditionalSequential(nn.Sequential): + def forward(self, x: torch.Tensor, condition: torch.Tensor) -> torch.Tensor: + for module in self: + x = module(x, condition) + return x diff --git a/tokenizer/networks/transformers/rope3d.py b/tokenizer/networks/transformers/rope3d.py new file mode 100644 index 0000000000000000000000000000000000000000..503e5826c1936e5bf6ae8327f7547f8791844c9c --- /dev/null +++ b/tokenizer/networks/transformers/rope3d.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""3D rotary positional embedding for ``(T, H, W)`` token grids. + +Adapted (PyTorch-only, no TransformerEngine) from +``imaginaire.networks.video_backbone.VideoRopePosition3DEmb``: the head dim +is split into three chunks ``(dim_t, dim_h, dim_w)``, each axis contributes +its own rotary frequency band, and the resulting angles are duplicated +across the two rotation halves (GPT-NeoX style) so that +:func:`apply_rotary_emb` can rotate Q/K with a single tensor. + +For a query at position ``p_q = (t_q, h_q, w_q)`` and a key at +``p_k = (t_k, h_k, w_k)``, the dot product after rotation depends only on +``p_q - p_k``. If the query and key share the same value along some axis +(e.g. a factored *spatial* attention block where both are on the same +frame), the rotation along that axis cancels out -- so this single 3D +RoPE specializes correctly to 2D RoPE for spatial-only blocks and 1D RoPE +for temporal-only blocks. +""" + +from __future__ import annotations + +from typing import Optional + +import torch +from torch import nn + + +class VideoRopePosition3DEmb(nn.Module): + """3D RoPE producing angles for a ``(T, H, W)`` token grid. + + Args: + head_dim: Per-head channel count. Must satisfy + ``head_dim - 2 * (head_dim // 6 * 2) > 0``. + len_t, len_h, len_w: Maximum supported grid sizes (frequencies are + cached for these). ``forward`` accepts any smaller ``(T, H, W)``. + base_theta: RoPE base (``10000.0`` matches LLaMA/Cosmos). + t_extrapolation_ratio, h_extrapolation_ratio, w_extrapolation_ratio: + NTK-aware extrapolation factors, applied as + ``theta *= ratio ** (dim_axis / (dim_axis - 2))``. + """ + + def __init__( + self, + *, + head_dim: int, + len_t: int, + len_h: int, + len_w: int, + base_theta: float = 10000.0, + t_extrapolation_ratio: float = 1.0, + h_extrapolation_ratio: float = 1.0, + w_extrapolation_ratio: float = 1.0, + ) -> None: + super().__init__() + dim = head_dim + dim_h = (dim // 6) * 2 + dim_w = dim_h + dim_t = dim - dim_h - dim_w + assert dim_t >= 2, ( + f"head_dim={dim} too small for 3D RoPE " + f"(dim_t={dim_t}, dim_h={dim_h}, dim_w={dim_w})" + ) + self.head_dim = dim + self.dim_t = dim_t + self.dim_h = dim_h + self.dim_w = dim_w + self.max_t = len_t + self.max_h = len_h + self.max_w = len_w + + # NTK-aware extrapolation exponent ``dim_axis / (dim_axis - 2)`` is + # only well-defined for ``dim_axis > 2``. Smaller axes are degenerate + # (only one frequency bucket) and would also raise ZeroDivisionError + # below regardless of the ratio. Fall back to base_theta in that + # case -- when the ratio is 1.0 (the default) the expression is a + # no-op anyway, so we lose nothing. + def _theta(ratio: float, dim: int) -> float: + if ratio == 1.0 or dim <= 2: + return base_theta + return base_theta * (ratio ** (dim / (dim - 2))) + + h_theta = _theta(h_extrapolation_ratio, dim_h) + w_theta = _theta(w_extrapolation_ratio, dim_w) + t_theta = _theta(t_extrapolation_ratio, dim_t) + + idx_h = torch.arange(0, dim_h, 2, dtype=torch.float32) / dim_h + idx_w = torch.arange(0, dim_w, 2, dtype=torch.float32) / dim_w + idx_t = torch.arange(0, dim_t, 2, dtype=torch.float32) / dim_t + self.register_buffer("freqs_h", 1.0 / (h_theta**idx_h), persistent=False) + self.register_buffer("freqs_w", 1.0 / (w_theta**idx_w), persistent=False) + self.register_buffer("freqs_t", 1.0 / (t_theta**idx_t), persistent=False) + self.register_buffer( + "seq_h", torch.arange(len_h, dtype=torch.float32), persistent=False + ) + self.register_buffer( + "seq_w", torch.arange(len_w, dtype=torch.float32), persistent=False + ) + self.register_buffer( + "seq_t", torch.arange(len_t, dtype=torch.float32), persistent=False + ) + + def forward(self, T: int, H: int, W: int) -> torch.Tensor: + """Returns rope angles of shape ``(T*H*W, head_dim)``. + + Each half of the last dim duplicates the per-axis angles + ``[t_half | h_half | w_half | t_half | h_half | w_half]`` so that + :func:`apply_rotary_emb` (GPT-NeoX style) can rotate Q/K via + ``[x_lo, x_hi] @ rot``. + """ + assert T <= self.max_t and H <= self.max_h and W <= self.max_w, ( + f"Requested ({T},{H},{W}) exceeds cached " + f"({self.max_t},{self.max_h},{self.max_w})" + ) + ang_t = torch.outer(self.seq_t[:T], self.freqs_t) # (T, dim_t/2) + ang_h = torch.outer(self.seq_h[:H], self.freqs_h) # (H, dim_h/2) + ang_w = torch.outer(self.seq_w[:W], self.freqs_w) # (W, dim_w/2) + ang_t_b = ang_t.view(T, 1, 1, -1).expand(T, H, W, -1) + ang_h_b = ang_h.view(1, H, 1, -1).expand(T, H, W, -1) + ang_w_b = ang_w.view(1, 1, W, -1).expand(T, H, W, -1) + half = torch.cat([ang_t_b, ang_h_b, ang_w_b], dim=-1) # (T, H, W, dim/2) + full = torch.cat([half, half], dim=-1) # (T, H, W, dim) + return full.reshape(T * H * W, -1) + + +def apply_rotary_emb(x: torch.Tensor, rope_emb: torch.Tensor) -> torch.Tensor: + """Rotate the last dim of ``x`` via GPT-NeoX rotary embeddings. + + Args: + x: ``(..., S, num_heads, head_dim)`` (any leading shape). + rope_emb: ``(S, head_dim)`` angles tensor produced by + :class:`VideoRopePosition3DEmb`. + + Notes: + Standard GPT-NeoX rotation pairs channel ``i`` with channel + ``i + head_dim/2`` (not adjacent channels). With ``rope_emb``'s + ``[half | half]`` duplication, ``cos(rope_emb[:half]) == + cos(rope_emb[half:])`` so both halves of a pair rotate by the same + angle. + """ + rope_emb = rope_emb.to(x.dtype).unsqueeze(-2) # (S, 1, head_dim) + cos = rope_emb.cos() + sin = rope_emb.sin() + half = x.shape[-1] // 2 + x_lo, x_hi = x[..., :half], x[..., half:] + cos_lo, cos_hi = cos[..., :half], cos[..., half:] + sin_lo, sin_hi = sin[..., :half], sin[..., half:] + out_lo = x_lo * cos_lo - x_hi * sin_lo + out_hi = x_hi * cos_hi + x_lo * sin_hi + return torch.cat([out_lo, out_hi], dim=-1) diff --git a/tokenizer/networks/transformers/transformer_vae.py b/tokenizer/networks/transformers/transformer_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..4a304c27bf80c2db90dff6fb6222d54fd79c87da --- /dev/null +++ b/tokenizer/networks/transformers/transformer_vae.py @@ -0,0 +1,3560 @@ +# ============================================================================= +# Transformer VAE with hierarchical hourglass architecture, +# neighborhood attention (natten) for spatial processing, and +# causal temporal attention for video. +# +# Architecture: +# Encoder: Tokenizer → [spatial blocks + PatchMerging] (level 0, no temporal) +# → [spatial→temporal blocks + PatchMerging (+ TemporalMerging)] × (N-1) +# → global spatial+temporal → z +# Decoder: z → global temporal+spatial +# → [TemporalExpanding + PatchExpanding + temporal→spatial blocks] × (N-1) +# → [PatchExpanding + spatial blocks] (level 0, no temporal) → Detokenizer +# +# No skip connections between encoder and decoder. +# +# Based on: https://github.com/crowsonkb/k-diffusion/blob/master/ +# k_diffusion/models/image_transformer_v2.py +# Call `natten.use_fused_na(True)` for acceleration on GPUs. +# ============================================================================= + +import contextlib +import functools +import math +from collections import namedtuple +from typing import List, Literal + +import einops +import natten +import torch +import torch.distributed as dist +import torch.nn.functional as F +from einops.layers.torch import Rearrange +from loguru import logger +from torch import nn +from torch.nn.modules.utils import _pair +from torch.utils.checkpoint import checkpoint + +from tokenizer.networks.common import ContinuousFormulation +from tokenizer.networks.transformers.rope3d import ( + VideoRopePosition3DEmb, + apply_rotary_emb, +) +from . import encoding, ops + +__all__ = ["TransformerVAE"] + +NetworkEval = namedtuple( + "NetworkEval", ["reconstructions", "posteriors", "latent", "validity_logits"] +) +# Default ``validity_logits`` to None so non-validity networks/call sites that +# construct NetworkEval without it keep working unchanged. +NetworkEval.__new__.__defaults__ = (None,) + + +def _run_block(module: nn.Module, *args, activation_checkpointing: bool): + if activation_checkpointing and torch.is_grad_enabled(): + return checkpoint(module, *args, use_reentrant=False) + return module(*args) + + +# ============================================================================= +# Normalization +# ============================================================================= + + +class RMSNorm(torch.nn.Module): + def __init__(self, in_dim: int, scale: bool = True, eps: float = 1e-6): + super().__init__() + self.in_dim = in_dim + self.eps = eps + self.scale = nn.Parameter(torch.ones(in_dim)) if scale else 1.0 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_fp32 = x.float() + x_normed = x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps) + return (x_normed * self.scale).to(x) + + def extra_repr(self) -> str: + return f"in_dim={self.in_dim}" + + +# ============================================================================= +# Rotary positional encoding (spatial) +# ============================================================================= + + +class AxialRoPE(nn.Module): + def __init__(self, dim: int, num_heads: int, max_harmonics: List[int]): + super().__init__() + freqs_h = self.setup_freqs(num_heads * dim // 4, max_harmonics[0]) + freqs_w = self.setup_freqs(num_heads * dim // 4, max_harmonics[1]) + self.register_buffer("freqs_h", freqs_h.view(dim // 4, num_heads).T) + self.register_buffer("freqs_w", freqs_w.view(dim // 4, num_heads).T) + + def setup_freqs(self, dim: int, max_harmonics: int): + return torch.linspace(math.log(1), math.log(max_harmonics), dim).exp().round() + + def forward(self, coords: torch.Tensor) -> torch.Tensor: + coords = einops.rearrange(coords, "b c h w -> b h w c") + radian_h = coords[..., None, [0]] * self.freqs_h + radian_w = coords[..., None, [1]] * self.freqs_w + return torch.cat((radian_h, radian_w), dim=-1) + + @staticmethod + def rotate(x: torch.Tensor, theta: torch.Tensor) -> torch.Tensor: + x1, x2 = x.chunk(2, dim=-1) + y1 = x1 * theta.cos() - x2 * theta.sin() + y2 = x1 * theta.sin() + x2 * theta.cos() + return torch.cat((y1, y2), dim=-1) + + def extra_repr(self) -> str: + return ( + f"freqs_h={tuple(self.freqs_h.shape)}, freqs_w={tuple(self.freqs_w.shape)}" + ) + + +# ============================================================================= +# Spatial self-attention blocks +# ============================================================================= + + +class GlobalSelfAttentionBlock(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + dropout: float = 0.0, + rope_max_harmonics: List[int] = (1, 1), + bias=False, + eps=1e-6, + ): + super().__init__() + self.num_heads = num_heads + self.head_dim = dim // self.num_heads + self.eps = eps + + self.norm = RMSNorm(dim) + self.scale = nn.Parameter(torch.full([self.num_heads, 1], math.log(10.0))) + self.qkv_proj = nn.Linear(dim, dim * 3, bias=bias) + self.rope = AxialRoPE(self.head_dim, num_heads, rope_max_harmonics) + self.dropout = nn.Dropout(dropout) + self.out_proj = nn.Linear(dim, dim, bias=bias).apply(ops.zero_out) + + def scale_qk(self, q: torch.Tensor, k: torch.Tensor) -> torch.Tensor: + scale = self.scale.clamp(max=math.log(100)).exp().sqrt() + q = (F.normalize(q, p=2, dim=-1, eps=self.eps) * scale).to(q.dtype) + k = (F.normalize(k, p=2, dim=-1, eps=self.eps) * scale).to(k.dtype) + return q, k + + def apply_rope_qk(self, q: torch.Tensor, k: torch.Tensor, coords: torch.Tensor): + theta = self.rope(coords) + d = theta.shape[-1] * 2 + assert (q.shape[-1] >= d) and (k.shape[-1] >= d) + q[..., :d] = self.rope.rotate(q[..., :d], theta).to(q.dtype) + k[..., :d] = self.rope.rotate(k[..., :d], theta).to(k.dtype) + return q, k + + def residual(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + B, H, W, C = x.shape + h = self.norm(x) + qkv = self.qkv_proj(h) + q, k, v = einops.rearrange( + qkv, "B H W (T N D) -> T B H W N D", T=3, D=self.head_dim + ) + q, k = self.scale_qk(q, k) + q, k = self.apply_rope_qk(q, k, coords) + q = einops.rearrange(q, "B H W N D -> B N (H W) D") + k = einops.rearrange(k, "B H W N D -> B N (H W) D") + v = einops.rearrange(v, "B H W N D -> B N (H W) D") + h = F.scaled_dot_product_attention(q, k, v, scale=1.0) + h = einops.rearrange(h, "B N (H W) D -> B H W (N D)", H=H, W=W) + h = self.dropout(h) + h = self.out_proj(h) + return h + + def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + return x + self.residual(x, coords) + + def extra_repr(self) -> str: + return f"head_dim={self.head_dim}, num_heads={self.num_heads}" + + +class CircularNeighborhoodSelfAttentionBlock(GlobalSelfAttentionBlock): + def __init__( + self, + dim: int, + num_heads: int, + kernel_size: List[int], + dilation: List[int] = 1, + dropout: float = 0.0, + rope_max_harmonics: List[int] = (1, 1), + # When True (default), the W (last spatial) axis is treated as + # periodic: it is circularly padded before the neighborhood attention + # so the seam wraps (range-image azimuth, column 0 ~ column W-1). When + # False, no wrap -- ``natten`` clamps the neighborhood at the W edges + # (the same boundary handling it already uses for H). Set False for a + # Cartesian grid (e.g. BEV x-axis) where the two W edges are unrelated. + circular: bool = True, + ): + super().__init__( + dim=dim, + num_heads=num_heads, + dropout=dropout, + rope_max_harmonics=rope_max_harmonics, + ) + self.kernel_size = _pair(kernel_size) + self.dilation = _pair(dilation) + self.circular = circular + self._inference_natten_kwargs = {} + + def set_inference_natten_config( + self, + *, + backend: str, + q_tile_shape: tuple[int, int], + kv_tile_shape: tuple[int, int], + ) -> None: + self._inference_natten_kwargs = { + "backend": backend, + "q_tile_shape": q_tile_shape, + "kv_tile_shape": kv_tile_shape, + } + + def before_attn(self, q, k, v): + if not self.circular: + return q, k, v + padding = self.kernel_size[1] // 2 + q = F.pad(q, (0, 0, 0, 0, padding, padding), mode="circular") + k = F.pad(k, (0, 0, 0, 0, padding, padding), mode="circular") + v = F.pad(v, (0, 0, 0, 0, padding, padding), mode="circular") + return q, k, v + + def after_attn(self, x): + if not self.circular: + return x + padding = self.kernel_size[1] // 2 + x = x[:, :, padding:-padding] + return x + + def residual(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + h = self.norm(x) + qkv = self.qkv_proj(h) + q, k, v = einops.rearrange( + qkv, "B H W (T N D) -> T B H W N D", T=3, D=self.head_dim + ) + q, k = self.scale_qk(q, k) + q, k = self.apply_rope_qk(q, k, coords) + q, k, v = self.before_attn(q, k, v) + h = natten.functional.na2d( + query=q, + key=k, + value=v, + kernel_size=self.kernel_size, + dilation=self.dilation, + scale=1.0, + **self._inference_natten_kwargs, + ) + h = einops.rearrange(h, "B H W N D -> B H W (N D)") + h = self.after_attn(h) + h = self.dropout(h) + h = self.out_proj(h) + return h + + def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + return x + self.residual(x, coords) + + def extra_repr(self) -> str: + return ( + f"head_dim={self.head_dim}, num_heads={self.num_heads}, " + f"kernel_size={self.kernel_size}, dilation={self.dilation}" + ) + + +# ============================================================================= +# Causal temporal self-attention +# ============================================================================= + + +class CausalTemporalAttention(nn.Module): + """Causal self-attention along the temporal dimension. + + Input/output shape: (N, T, C) where N = B*H*W. + Each position attends only to itself and earlier positions. + """ + + def __init__(self, dim: int, num_heads: int, dropout: float = 0.0, bias=False): + super().__init__() + self.num_heads = num_heads + self.head_dim = dim // num_heads + + self.norm = RMSNorm(dim) + self.qkv_proj = nn.Linear(dim, dim * 3, bias=bias) + self.out_proj = nn.Linear(dim, dim, bias=bias).apply(ops.zero_out) + self.dropout = nn.Dropout(dropout) + self._SDPA_MAX_BATCH = 65535 + + def _project_qkv(self, x: torch.Tensor): + h = self.norm(x) + qkv = self.qkv_proj(h) + return einops.rearrange( + qkv, "N T (three heads D) -> three N heads T D", + three=3, D=self.head_dim, + ) + + def _sdpa(self, q, k, v, *, attn_mask=None, is_causal=False): + N = q.shape[0] + if N <= self._SDPA_MAX_BATCH: + return F.scaled_dot_product_attention( + q, k, v, attn_mask=attn_mask, is_causal=is_causal + ) + chunks = [] + for i in range(0, N, self._SDPA_MAX_BATCH): + j = min(i + self._SDPA_MAX_BATCH, N) + chunks.append(F.scaled_dot_product_attention( + q[i:j], k[i:j], v[i:j], + attn_mask=attn_mask, is_causal=is_causal, + )) + return torch.cat(chunks, dim=0) + + def _finish(self, x, h): + h = einops.rearrange(h, "N heads T D -> N T (heads D)") + h = self.dropout(h) + h = self.out_proj(h) + return x + h + + def forward(self, x: torch.Tensor) -> torch.Tensor: + q, k, v = self._project_qkv(x) + return self._finish( + x, self._sdpa(q, k, v, is_causal=True) + ) + + def forward_stream( + self, + x: torch.Tensor, + kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None, + ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: + """Attend new temporal tokens to cached history and this causal block.""" + q, k_new, v_new = self._project_qkv(x) + past = 0 + if kv_cache is not None: + k_past, v_past = kv_cache + if ( + k_past.shape[:2] != k_new.shape[:2] + or k_past.shape[3:] != k_new.shape[3:] + or v_past.shape != k_past.shape + ): + raise ValueError( + "temporal KV cache shape mismatch: " + f"cached k/v={tuple(k_past.shape)}/{tuple(v_past.shape)}, " + f"new k={tuple(k_new.shape)}" + ) + past = k_past.shape[2] + k = torch.cat([k_past, k_new], dim=2) + v = torch.cat([v_past, v_new], dim=2) + else: + k, v = k_new, v_new + + T_new = q.shape[2] + q_index = past + torch.arange(T_new, device=q.device)[:, None] + k_index = torch.arange(past + T_new, device=q.device)[None, :] + causal_offset_mask = k_index <= q_index + out = self._finish( + x, + self._sdpa( + q, k, v, + attn_mask=causal_offset_mask, + is_causal=False, + ), + ) + return out, (k.detach(), v.detach()) + + def extra_repr(self) -> str: + return f"head_dim={self.head_dim}, num_heads={self.num_heads}" + + +# ============================================================================= +# Feed-forward +# ============================================================================= + + +class GEGLU(nn.Linear): + def __init__(self, in_features, out_features, bias): + super().__init__(in_features, out_features * 2, bias=bias) + + def forward(self, x): + h = super().forward(x) + h, gate = h.chunk(2, dim=-1) + return h * F.gelu(gate) + + +class FeedForwardNetwork(nn.Module): + def __init__(self, dim, mid_dim, dropout=0.0): + super().__init__() + self.norm = RMSNorm(dim) + self.gegelu = GEGLU(dim, mid_dim, bias=False) + self.dropout = nn.Dropout(dropout) + self.linear = nn.Linear(mid_dim, dim, bias=False).apply(ops.zero_out) + + def residual(self, x: torch.Tensor) -> torch.Tensor: + x = self.norm(x) + x = self.gegelu(x) + x = self.dropout(x) + x = self.linear(x) + return x + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + self.residual(x) + + +# ============================================================================= +# Spatial block (spatial attention + FFN) +# ============================================================================= + + +class SpatialBlock(nn.Module): + """Spatial attention + FFN. Operates on (BT, H, W, C) per-frame.""" + + def __init__( + self, + in_dim: int, + num_heads: int, + attn_type: Literal["local", "global"] = "global", + kernel_size: List[int] = None, + dilation: List[int] = 1, + rope_max_harmonics: List[int] = (1, 1), + mlp_ratio: float = 3.0, + dropout: float = 0.0, + # Forwarded to the local (neighborhood) attention: whether the W axis + # wraps (periodic azimuth) or clamps (Cartesian). No effect for global. + circular: bool = True, + ): + super().__init__() + + if attn_type == "global": + self.residual_attn = GlobalSelfAttentionBlock( + dim=in_dim, + num_heads=num_heads, + dropout=dropout, + rope_max_harmonics=rope_max_harmonics, + ) + elif attn_type == "local": + self.residual_attn = CircularNeighborhoodSelfAttentionBlock( + dim=in_dim, + num_heads=num_heads, + kernel_size=kernel_size, + dilation=dilation, + dropout=dropout, + rope_max_harmonics=rope_max_harmonics, + circular=circular, + ) + + self.residual_ffn = FeedForwardNetwork( + dim=in_dim, + mid_dim=int(in_dim * mlp_ratio), + dropout=dropout, + ) + + def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + x = self.residual_attn(x, coords) + x = self.residual_ffn(x) + return x + + +class TemporalBlock(nn.Module): + """Causal temporal attention + FFN. Operates on (BHW, T, C).""" + + def __init__( + self, + in_dim: int, + num_heads: int, + mlp_ratio: float = 3.0, + dropout: float = 0.0, + ): + super().__init__() + self.temporal_attn = CausalTemporalAttention(in_dim, num_heads, dropout) + self.ffn = FeedForwardNetwork(in_dim, int(in_dim * mlp_ratio), dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.temporal_attn(x) + x = self.ffn(x) + return x + + def forward_stream( + self, + x: torch.Tensor, + kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None, + ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: + x, kv_cache = self.temporal_attn.forward_stream(x, kv_cache) + x = self.ffn(x) + return x, kv_cache + + +class CausalTemporalConv(nn.Module): + """Causal temporal convolution along T (WAN-style). + + The conv analog of :class:`CausalTemporalAttention` -- same + (N, T, C) interface (N = B*H*W), same zero-init residual so the + block is a residual add at init. Implemented as a depth-preserving + ``Conv1d`` over the T axis with left-only causal padding (kernel-1), + so each output only depends on the current and past frames -- the + ``kernel_size x 1 x 1`` case of WanVAE's ``CausalConv3d`` (spatial + mixing is left to the surrounding neighborhood-attention blocks, so + swapping only the temporal mixer stays a clean ablation). + """ + + def __init__(self, dim: int, kernel_size: int = 3, dropout: float = 0.0): + super().__init__() + self.norm = RMSNorm(dim) + self.conv = nn.Conv1d(dim, dim, kernel_size=kernel_size, bias=False) + self.out_proj = nn.Linear(dim, dim, bias=False).apply(ops.zero_out) + self.dropout = nn.Dropout(dropout) + self.causal_pad = kernel_size - 1 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # x: (N, T, C) + h = self.norm(x) + h = einops.rearrange(h, "N T C -> N C T") + h = F.pad(h, (self.causal_pad, 0)) + h = self.conv(h) + h = einops.rearrange(h, "N C T -> N T C") + h = self.dropout(h) + h = self.out_proj(h) + return x + h + + +class TemporalConvBlock(nn.Module): + """Causal temporal conv + FFN. Operates on (BHW, T, C). + + Drop-in replacement for :class:`TemporalBlock` (identical constructor + signature and (N, T, C) forward) that swaps the temporal *attention* + for a WAN-style causal temporal *convolution*. ``num_heads`` is + accepted only for signature parity (unused). + """ + + def __init__( + self, + in_dim: int, + num_heads: int, + mlp_ratio: float = 3.0, + dropout: float = 0.0, + kernel_size: int = 3, + ): + super().__init__() + self.temporal_conv = CausalTemporalConv(in_dim, kernel_size, dropout) + self.ffn = FeedForwardNetwork(in_dim, int(in_dim * mlp_ratio), dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.temporal_conv(x) + x = self.ffn(x) + return x + + +# ============================================================================= +# Joint 3D self-attention block +# ============================================================================= + + +class Joint3DSelfAttention(nn.Module): + """Joint self-attention over flattened (T*H*W) tokens. + + Mirrors :class:`GlobalSelfAttentionBlock` but operates jointly over time + and space instead of per-frame. + + Two positional-encoding modes are supported via ``use_3d_rope``: + + * **Default (``use_3d_rope=False``)** -- spatial position via the + existing :class:`AxialRoPE` on ``(h, w)`` (broadcast across time, since + polar coords don't vary with time), and time position via a *learnable* + 1D embedding added to the pre-attention features. This is what + original training runs used; kept as the default for backward compat. + Caveat: the learnable temporal slots past the largest ``T`` seen in + training are uninitialized noise, so this mode does *not* extrapolate + cleanly to longer-than-trained sequence lengths at inference. + * **``use_3d_rope=True``** -- replace both the spatial :class:`AxialRoPE` + and the learnable temporal PE with a single 3D RoPE + (:class:`VideoRopePosition3DEmb`) over ``(t, h, w)``. RoPE is a + rotation (length-preserving), and is fully parameter-free, so the + angles extrapolate to longer sequences with no untrained parameters. + The spatial axes of the 3D RoPE play the same role :class:`AxialRoPE` + did, but without coupling to polar coords -- the bottleneck operates + on a regular (H_z, W_z) grid so a Cartesian RoPE is well-defined and + consistent with how the rest of the literature does video VAEs. + + Causality is *orthogonal* to the PE choice: ``causal_time=True`` masks + the joint attention so each ``(t, h, w)`` token only attends to + ``(t', h', w')`` with ``t' <= t``. The causal mask is materialized as + a ``(T*H*W, T*H*W)`` bool tensor so memory scales with ``(T*H*W)^2``. + """ + + def __init__( + self, + dim: int, + num_heads: int, + max_t: int, + rope_max_harmonics: List[int] = (1, 1), + dropout: float = 0.0, + causal_time: bool = False, + bias: bool = False, + eps: float = 1e-6, + # If True, encode both spatial and temporal position with a single + # 3D RoPE (length-preserving rotation, no learnable PE buffer) and + # skip the original 2D AxialRoPE + learnable `temporal_pe` path. + # ``len_h``/``len_w`` set the spatial cap of the 3D RoPE cache. + use_3d_rope: bool = False, + len_h: int = 1, + len_w: int = 1, + ): + super().__init__() + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.eps = eps + self.causal_time = causal_time + self.use_3d_rope = use_3d_rope + self.max_t = max_t + self.max_h = len_h if use_3d_rope else 0 + self.max_w = len_w if use_3d_rope else 0 + + self.norm = RMSNorm(dim) + self.scale = nn.Parameter(torch.full([num_heads, 1], math.log(10.0))) + self.qkv_proj = nn.Linear(dim, dim * 3, bias=bias) + if use_3d_rope: + self.rope = None + self.temporal_pe = None + self.rope3d = VideoRopePosition3DEmb( + head_dim=self.head_dim, + len_t=max_t, + len_h=len_h, + len_w=len_w, + ) + else: + self.rope = AxialRoPE(self.head_dim, num_heads, rope_max_harmonics) + self.temporal_pe = nn.Parameter(torch.zeros(max_t, dim)) + nn.init.trunc_normal_(self.temporal_pe, std=0.02) + self.rope3d = None + self.dropout = nn.Dropout(dropout) + self.out_proj = nn.Linear(dim, dim, bias=bias).apply(ops.zero_out) + + def _scale_qk(self, q: torch.Tensor, k: torch.Tensor): + scale = self.scale.clamp(max=math.log(100)).exp().sqrt() + q = (F.normalize(q, p=2, dim=-1, eps=self.eps) * scale).to(q.dtype) + k = (F.normalize(k, p=2, dim=-1, eps=self.eps) * scale).to(k.dtype) + return q, k + + def _apply_spatial_rope(self, q: torch.Tensor, k: torch.Tensor, coords: torch.Tensor): + theta = self.rope(coords) # (B_c, H, W, N, D//2) + d = theta.shape[-1] * 2 + assert (q.shape[-1] >= d) and (k.shape[-1] >= d) + theta = theta.unsqueeze(1) # broadcast over T → (B_c, 1, H, W, N, D//2) + q[..., :d] = self.rope.rotate(q[..., :d], theta).to(q.dtype) + k[..., :d] = self.rope.rotate(k[..., :d], theta).to(k.dtype) + return q, k + + def residual(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + B, T, H, W, C = x.shape + if T > self.max_t: + raise ValueError( + f"Joint3DSelfAttention received T={T} but was constructed with " + f"max_t={self.max_t}. Increase bottleneck_3d_max_t." + ) + if self.use_3d_rope and (H > self.max_h or W > self.max_w): + raise ValueError( + f"Joint3DSelfAttention received (H, W)=({H}, {W}) but the 3D " + f"RoPE was sized for (len_h, len_w)=({self.max_h}, {self.max_w}). " + f"This usually means the bottleneck spatial shape changed -- " + f"rebuild the decoder with larger len_h/len_w." + ) + h = self.norm(x) + + if self.use_3d_rope: + # 3D RoPE path. We flatten (T, H, W) to a single sequence axis + # so `apply_rotary_emb` can broadcast its (S, head_dim) rope + # tensor over batch + num_heads in one shot. + qkv = self.qkv_proj(h) + qkv = einops.rearrange( + qkv, "B T H W (three N D) -> three B (T H W) N D", + three=3, D=self.head_dim, + ) + q, k, v = qkv[0], qkv[1], qkv[2] + q, k = self._scale_qk(q, k) # rotation preserves L2 norm + rope_emb = self.rope3d(T, H, W) # (T*H*W, head_dim) + q = apply_rotary_emb(q, rope_emb) + k = apply_rotary_emb(k, rope_emb) + q = einops.rearrange(q, "B S N D -> B N S D") + k = einops.rearrange(k, "B S N D -> B N S D") + v = einops.rearrange(v, "B S N D -> B N S D") + else: + # Original: learnable temporal PE + 2D AxialRoPE over (h, w). + h = h + self.temporal_pe[:T].view(1, T, 1, 1, C) + qkv = self.qkv_proj(h) + q, k, v = einops.rearrange( + qkv, "B T H W (three N D) -> three B T H W N D", + three=3, D=self.head_dim, + ) + q, k = self._scale_qk(q, k) + q, k = self._apply_spatial_rope(q, k, coords) + q = einops.rearrange(q, "B T H W N D -> B N (T H W) D") + k = einops.rearrange(k, "B T H W N D -> B N (T H W) D") + v = einops.rearrange(v, "B T H W N D -> B N (T H W) D") + + if self.causal_time: + S = H * W + t_idx = torch.arange(T, device=q.device).repeat_interleave(S) + # mask[i, j] = True iff query t_i can attend to key t_j (t_j <= t_i) + mask = t_idx.unsqueeze(0) <= t_idx.unsqueeze(1) # (T*S, T*S) + out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=1.0) + else: + out = F.scaled_dot_product_attention(q, k, v, scale=1.0) + + out = einops.rearrange(out, "B N (T H W) D -> B T H W (N D)", T=T, H=H, W=W) + out = self.dropout(out) + out = self.out_proj(out) + return out + + def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + return x + self.residual(x, coords) + + def extra_repr(self) -> str: + pe = ( + f"rope3d(len_t={self.max_t}, len_h={self.max_h}, len_w={self.max_w})" + if self.use_3d_rope + else f"max_t={self.max_t}, axial_rope_2d" + ) + return ( + f"head_dim={self.head_dim}, num_heads={self.num_heads}, " + f"{pe}, causal_time={self.causal_time}" + ) + + +class Bottleneck3DBlock(nn.Module): + """Joint 3D self-attention + FFN. Operates on (B, T, H, W, C). + + Set ``use_3d_rope=True`` (with ``len_h`` / ``len_w`` set to the + bottleneck's spatial shape) to swap the default learnable temporal PE + + 2D AxialRoPE for a single 3D RoPE over ``(t, h, w)`` -- see + :class:`Joint3DSelfAttention` for the tradeoffs. Backward-compatible: + leaving ``use_3d_rope`` at its default keeps the original behavior. + """ + + def __init__( + self, + in_dim: int, + num_heads: int, + max_t: int, + rope_max_harmonics: List[int] = (1, 1), + mlp_ratio: float = 3.0, + dropout: float = 0.0, + causal_time: bool = False, + use_3d_rope: bool = False, + len_h: int = 1, + len_w: int = 1, + ): + super().__init__() + self.attn = Joint3DSelfAttention( + dim=in_dim, + num_heads=num_heads, + max_t=max_t, + rope_max_harmonics=rope_max_harmonics, + dropout=dropout, + causal_time=causal_time, + use_3d_rope=use_3d_rope, + len_h=len_h, + len_w=len_w, + ) + self.ffn = FeedForwardNetwork(in_dim, int(in_dim * mlp_ratio), dropout) + + def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + x = self.attn(x, coords) + x = self.ffn(x) + return x + + +# ============================================================================= +# Patch / temporal resampling +# ============================================================================= + + +class PatchMerging(nn.Sequential): + """2x2 spatial downsample: (B, 2H, 2W, C) -> (B, H, W, 2C)""" + + def __init__(self, dim: int): + super().__init__( + Rearrange("B (H P1) (W P2) C -> B H W (P1 P2 C)", P1=2, P2=2), + nn.Linear(4 * dim, 2 * dim, bias=False), + ) + + +class PatchExpanding(nn.Module): + """2x2 spatial upsample: (B, H, W, C) -> (B, 2H, 2W, C//2)""" + + def __init__(self, dim: int): + super().__init__() + self.linear = nn.Linear(dim, dim * 2, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.linear(x) + x = einops.rearrange(x, "B H W (P1 P2 C) -> B (H P1) (W P2) C", P1=2, P2=2) + return x + + +class TemporalMerging(nn.Module): + """Causal 2x temporal downsample (mimics WanVAE downsample3d). + + Uses Conv1d(kernel=3, stride=2) with left-only causal padding. + Each output only depends on the current and past frames. + Input: (B, T, H, W, C) + Output: (B, ceil(T/2), H, W, C) + """ + + def __init__(self, dim: int): + super().__init__() + self.conv = nn.Conv1d(dim, dim, kernel_size=3, stride=2, padding=0, bias=False) + self.causal_pad = 2 # kernel_size - 1 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, T, H, W, C = x.shape + x = einops.rearrange(x, "B T H W C -> (B H W) C T") + x = F.pad(x, (self.causal_pad, 0)) + x = self.conv(x) + x = einops.rearrange(x, "(B H W) C T -> B T H W C", B=B, H=H, W=W) + return x + + +class TemporalMergingFirstFrameSpecial(nn.Module): + """First-frame-special causal 2x temporal downsample (WAN-style). + + Mirrors :class:`WanVAE2P1`'s singleton-first-frame behavior at the + transformer-VAE merge stage: the first input slot becomes ``z[0]`` + via a per-frame ``Linear`` (no temporal mixing), and the remaining + ``T_in - 1`` frames are merged in *disjoint* 2-frame chunks via a + stride-2 ``Conv1d`` with ``kernel=2`` and **no** causal padding -- + each pair stays inside its own chunk: + + ``in[0:1]`` -> z[0] per-frame Linear + ``in[2i-1:2i+1]`` -> z[i>=1] stride-2 kernel-2 conv + + Pair this with :class:`TemporalExpandingWanStyle` in the decoder so + ``T_decoded = 2*T_z - 1`` exactly matches ``T_in = 1 + 2*(T_z - 1)``. + No front-crop needed, no boundary information loss. + + Compared to plain :class:`TemporalMerging` (kernel=3, stride=2, + causal-pad-2): + * z[0] genuinely depends on in[0] alone (not "in[0] + 2 pad" + activations); the Linear is the cleanest analog of WAN's CausalConv + with a fully zero-cached history. + * z[i>=1] sees both frames of its 2-frame chunk (vs. only the first + frame + 2 history frames in plain merging) -- so each latent has + *full* info on the chunk it represents, eliminating the + "z[i] never sees in[2i+1]" information loss. + + Requires ``T_in`` to be ODD (i.e. ``T_in - 1`` divisible by 2). + + Input: (B, T_in, H, W, C), T_in = 2*T_z - 1 + Output: (B, T_z, H, W, C) + """ + + def __init__(self, dim: int): + super().__init__() + # First-frame projection: like WAN's CausalConv3d on a length-1 + # input with zero-padded kernel history -- a linear function of + # the single frame's features. + self.first_frame_proj = nn.Linear(dim, dim, bias=False) + # Disjoint pair merger: kernel=2, stride=2, no padding. Each + # output index i corresponds to ``rest[2i, 2i+1]`` exclusively + # (no kernel overlap across chunks, no causal-pad zero leakage). + self.conv = nn.Conv1d(dim, dim, kernel_size=2, stride=2, padding=0, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, T_in, H, W, C = x.shape + if T_in == 1: + return self.first_frame_proj(x) + first = self.first_frame_proj(x[:, :1]) # (B, 1, H, W, C) + rest = x[:, 1:] + if rest.shape[1] % 2 != 0: + raise ValueError( + f"TemporalMergingFirstFrameSpecial requires (T_in - 1) " + f"divisible by 2 at this level, got T_in={T_in}. With " + f"``temporal_first_frame_special=True`` and N levels of " + f"temporal merge, the input T must satisfy " + f"T = 1 + (2 ** N) * (T_z - 1) -- e.g. T=9 for N=1, T_z=5." + ) + rest = einops.rearrange(rest, "B T H W C -> (B H W) C T") + rest = self.conv(rest) # (N, C, (T_in - 1) // 2) + rest = einops.rearrange(rest, "(B H W) C T -> B T H W C", B=B, H=H, W=W) + return torch.cat([first, rest], dim=1) + + +class TemporalExpanding(nn.Module): + """Causal 2x temporal upsample (mimics WanVAE upsample3d). + + Uses a causal Conv1d that doubles channels, then interleaves the two + channel halves along time to achieve 2x upsampling. No future leakage + because the underlying conv is causal (left-pad only, stride=1). + Input: (B, T//2, H, W, C) + Output: (B, T, H, W, C) + """ + + def __init__(self, dim: int): + super().__init__() + self.conv = nn.Conv1d(dim, dim * 2, kernel_size=3, stride=1, padding=0, bias=False) + self.causal_pad = 2 # kernel_size - 1 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, T_in, H, W, C = x.shape + x = einops.rearrange(x, "B T H W C -> (B H W) C T") + x = F.pad(x, (self.causal_pad, 0)) + x = self.conv(x) # (N, 2C, T_in) + x = einops.rearrange( + x, "N (two C) T -> N C (T two)", two=2, + ) # interleave: [t0_a, t0_b, t1_a, t1_b, ...] → 2*T_in frames + x = einops.rearrange(x, "(B H W) C T -> B T H W C", B=B, H=H, W=W) + return x + + +class TemporalExpandingWanStyle(nn.Module): + """Causal 2x temporal upsample with WAN-style first-frame handling. + + Mirrors :class:`WanVAE2P1.decode`: the first input frame produces a + single output frame (just the "a" half of the causal conv's doubled + output -- i.e. no temporal duplication), while every subsequent input + frame produces 2 output frames. Composed twice (matching the WAN + encoder's 4x temporal compression with its special first-frame chunk), + a latent of length ``T_z`` decodes to ``4*T_z - 3`` output frames -- the + same length as the original input when ``T_in = 1 + 4*(T_z - 1)``, so + no leading-frame crop is needed. + + Input: (B, T_in, H, W, C) + Output: (B, 2*T_in - 1, H, W, C) (or 1 frame if T_in == 1) + """ + + def __init__(self, dim: int): + super().__init__() + self.conv = nn.Conv1d(dim, dim * 2, kernel_size=3, stride=1, padding=0, bias=False) + self.causal_pad = 2 # kernel_size - 1 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, T_in, H, W, C = x.shape + h = einops.rearrange(x, "B T H W C -> (B H W) C T") + h = F.pad(h, (self.causal_pad, 0)) + h = self.conv(h) # (N, 2C, T_in) + h = einops.rearrange( + h, "N (two C) T -> N C (T two)", two=2, + ) # interleave: [t0_a, t0_b, t1_a, t1_b, ...] → 2*T_in frames along T + h = einops.rearrange(h, "(B H W) C T -> B T H W C", B=B, H=H, W=W) + # Keep t0_a as the single "first frame" output; drop t0_b. Keep both + # halves for every other input frame. + if T_in == 1: + return h[:, :1] + return torch.cat([h[:, :1], h[:, 2:]], dim=1) + + +class Tokenizer(nn.Sequential): + def __init__( + self, + in_channels: int, + out_channels: int, + patch_size: List[int], + ): + patch_size = _pair(patch_size) + super().__init__( + nn.Conv2d( + in_channels, + out_channels, + kernel_size=patch_size, + stride=patch_size, + padding=0, + bias=False, + ), + Rearrange("B C H W -> B H W C"), + ) + + +class Detokenizer(nn.Sequential): + def __init__( + self, + in_channels: int, + out_channels: int, + patch_size: List[int], + ): + patch_size = _pair(patch_size) + super().__init__( + RMSNorm(in_channels), + nn.Linear( + in_channels, + out_channels * patch_size[0] * patch_size[1], + bias=False, + ), + Rearrange( + "B H W (P1 P2 C) -> B C (H P1) (W P2)", + P1=patch_size[0], + P2=patch_size[1], + ), + ) + + +# ============================================================================= +# Positional embedding +# ============================================================================= + + +class LearnablePositionalEmbedding(nn.Module): + def __init__(self, out_dim: int, resolution: List[int]): + super().__init__() + self.embedding = nn.Parameter(torch.zeros(1, *resolution, out_dim)) + nn.init.trunc_normal_(self.embedding, std=0.02) + + def forward(self, coords=None): + return self.embedding + + def extra_repr(self): + return f"resolution={tuple(self.embedding.shape[1:3])}, out_dim={self.embedding.shape[3]}" + + +class ZeroPositionalEmbedding(nn.Module): + """No additive PE; attention blocks still apply coordinate-based RoPE.""" + + def __init__(self, out_dim: int): + super().__init__() + self.out_dim = out_dim + + def forward(self, coords: torch.Tensor): + return coords.new_zeros( + coords.shape[0], coords.shape[2], coords.shape[3], self.out_dim + ) + + def extra_repr(self): + return f"out_dim={self.out_dim}" + + +class AbsolutePositionalEmbedding(nn.Module): + def __init__(self, method: str, out_dim: int, resolution: List[int]): + super().__init__() + self.resolution = resolution + if method == "spherical_harmonics": + self.embedding = encoding.SphericalHarmonics(levels=5) + emb_dim = self.embedding.extra_ch + elif method == "fourier_features": + self.embedding = encoding.FourierFeatures(self.resolution) + emb_dim = self.embedding.extra_ch + elif method == "polar_coordinates": + self.embedding = nn.Identity() + emb_dim = 2 + else: + raise ValueError(f"Unknown positional embedding method: {method}") + self.linear = nn.Linear(emb_dim, out_dim, bias=False) + + def forward(self, coords: torch.Tensor): + h = self.embedding(coords) + h = einops.rearrange(h, "B C H W -> B H W C") + h = self.linear(h) + return h + + +class MappingFeedForwardNetwork(nn.Module): + def __init__(self, dim, mid_dim, dropout=0.0): + super().__init__() + self.norm = RMSNorm(dim) + self.gegelu = GEGLU(dim, mid_dim, bias=False) + self.dropout = nn.Dropout(dropout) + self.linear = nn.Linear(mid_dim, dim, bias=False).apply(ops.zero_out) + + def residual(self, x: torch.Tensor) -> torch.Tensor: + x = self.norm(x) + x = self.gegelu(x) + x = self.dropout(x) + x = self.linear(x) + return x + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + self.residual(x) + + +class MappingNetwork(nn.Sequential): + def __init__(self, dim, mid_dim, depth=1, dropout=0.0): + super().__init__( + RMSNorm(dim), + *[MappingFeedForwardNetwork(dim, mid_dim, dropout) for _ in range(depth)], + RMSNorm(dim), + ) + + +# ============================================================================= +# Encoder +# ============================================================================= + + +class Encoder(nn.Module): + def __init__( + self, + resolution: List[int], + in_channels: int, + z_dim: int, + base_channels: int = 128, + patch_size: List[int] = (1, 4), + window_size: List[int] = (3, 9), + depths: List[int] = (3, 3, 3, 3), + num_heads: List[int] = (2, 4, 8, 16), + dilation: List[int] = (1, 1, 1, 1), + temporal_downsample: List[bool] = (True, False, False), + mlp_ratio: float = 3.0, + dropout: float = 0.0, + mapping_depth: int = 2, + positional_embedding: str = "learnable_embedding", + # If True, every level with ``temporal_downsample[i]=True`` uses + # :class:`TemporalMergingFirstFrameSpecial` instead of the plain + # :class:`TemporalMerging`. Yields clean WAN-style chunk + # boundaries (z[0]=enc(in[0]), z[i>=1]=enc(disjoint 2-frame + # chunk)) at the cost of requiring T_in - 1 to be divisible + # by ``2 ** sum(temporal_downsample)``. + temporal_first_frame_special: bool = False, + # ---- Bottleneck options (mirror Decoder) ---- + # If True, replace the encoder bottleneck's factorized (global spatial + # + temporal) attention with a single joint 3D self-attention over + # (T*H*W) tokens. Down-levels are unchanged. Default False keeps the + # original factorized bottleneck (bit-identical to existing configs). + bottleneck_3d: bool = False, + bottleneck_3d_max_t: int = 32, + bottleneck_3d_causal_time: bool = False, + bottleneck_3d_rope: bool = False, + # If False, the local (neighborhood) attention does NOT wrap the W + # axis (clamps at the edges instead). Default True preserves the + # range-image azimuth-periodic behavior. Set False for a Cartesian + # BEV grid where the left/right W edges are unrelated. + circular_padding: bool = True, + # Temporal-mixing mechanism for the down/mid temporal blocks: + # "attention" (:class:`CausalTemporalAttention`, default) or "conv" + # (WAN-style :class:`CausalTemporalConv`, kernel ``temporal_conv_kernel``). + temporal_mixer: Literal["attention", "conv"] = "attention", + temporal_conv_kernel: int = 3, + activation_checkpointing: bool = False, + ): + super().__init__() + self.resolution = _pair(resolution) + self.patch_size = _pair(patch_size) + self.depths = depths + self.temporal_downsample = temporal_downsample + self.bottleneck_3d = bottleneck_3d + self.temporal_mixer = temporal_mixer + self.activation_checkpointing = bool(activation_checkpointing) + self._temporal_cls = ( + functools.partial(TemporalConvBlock, kernel_size=temporal_conv_kernel) + if temporal_mixer == "conv" + else TemporalBlock + ) + + token_size = torch.tensor(self.resolution) // torch.tensor(self.patch_size) + max_harmonics = (token_size / 2).int() + + self.tokenizer = Tokenizer(in_channels, base_channels, patch_size) + + if positional_embedding == "rope_only": + self.spatial_pe = ZeroPositionalEmbedding(out_dim=base_channels) + elif positional_embedding == "learnable_embedding": + self.spatial_pe = LearnablePositionalEmbedding( + out_dim=base_channels, + resolution=token_size.tolist(), + ) + else: + self.spatial_pe = nn.Sequential( + AbsolutePositionalEmbedding( + method=positional_embedding, + out_dim=base_channels, + resolution=token_size.tolist(), + ), + MappingNetwork( + base_channels, + int(base_channels * mlp_ratio), + depth=mapping_depth, + ), + ) + + # Down levels: spatial blocks + temporal blocks + merging + # Skip temporal attention at level 0 (highest resolution) for efficiency. + self.down_levels = nn.ModuleDict() + for i, num_blocks in enumerate(depths[:-1]): + dim_i = base_channels << i + spatial_blocks = nn.ModuleList() + for j in range(num_blocks): + spatial_blocks.append( + SpatialBlock( + in_dim=dim_i, + num_heads=num_heads[i], + attn_type="local", + kernel_size=window_size, + dilation=1 if j % 2 == 0 else dilation[i], + mlp_ratio=mlp_ratio, + dropout=dropout, + rope_max_harmonics=(max_harmonics >> i).clamp(min=1), + circular=circular_padding, + ) + ) + self.down_levels[f"spatial_{i}"] = spatial_blocks + if i > 0: + temporal_blocks = nn.ModuleList() + for j in range(num_blocks): + temporal_blocks.append( + self._temporal_cls( + in_dim=dim_i, + num_heads=num_heads[i], + mlp_ratio=mlp_ratio, + dropout=dropout, + ) + ) + self.down_levels[f"temporal_{i}"] = temporal_blocks + self.down_levels[f"merge_{i}"] = PatchMerging(dim_i) + if temporal_downsample[i]: + merge_cls = ( + TemporalMergingFirstFrameSpecial + if temporal_first_frame_special + else TemporalMerging + ) + self.down_levels[f"temporal_merge_{i}"] = merge_cls(dim_i * 2) + + # Bottleneck: either factorized (global spatial + temporal), or a + # single joint 3D self-attention over (T*H*W) tokens. + i = len(depths) - 1 + bottleneck_dim = base_channels << i + bottleneck_size = (token_size >> i).tolist() + if bottleneck_3d: + self.mid_3d = nn.ModuleList() + for _ in range(depths[-1]): + self.mid_3d.append( + Bottleneck3DBlock( + in_dim=bottleneck_dim, + num_heads=num_heads[-1], + max_t=bottleneck_3d_max_t, + rope_max_harmonics=(max_harmonics >> i).clamp(min=1), + mlp_ratio=mlp_ratio, + dropout=dropout, + causal_time=bottleneck_3d_causal_time, + use_3d_rope=bottleneck_3d_rope, + len_h=bottleneck_size[0], + len_w=bottleneck_size[1], + ) + ) + else: + self.mid_spatial = nn.ModuleList() + self.mid_temporal = nn.ModuleList() + for j in range(depths[-1]): + self.mid_spatial.append( + SpatialBlock( + in_dim=bottleneck_dim, + num_heads=num_heads[-1], + attn_type="global", + mlp_ratio=mlp_ratio, + dropout=dropout, + rope_max_harmonics=(max_harmonics >> i).clamp(min=1), + ) + ) + self.mid_temporal.append( + self._temporal_cls( + in_dim=bottleneck_dim, + num_heads=num_heads[-1], + mlp_ratio=mlp_ratio, + dropout=dropout, + ) + ) + + # Project to z_dim * 2 (mean + logvar) + self.head = nn.Sequential( + RMSNorm(bottleneck_dim), + nn.Linear(bottleneck_dim, z_dim * 2, bias=False), + Rearrange("B H W C -> B C H W"), + ) + + def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: + """ + Args: + x: (B, C, T, H, W) video tensor + coords: (1, 2, H, W) polar coordinates + Returns: + (B, z_dim*2, T', H_z, W_z) latent parameters + """ + B, C, T, H, W = x.shape + coords = coords.to(device=x.device, dtype=x.dtype) + if coords.shape[0] not in (1, B): + raise ValueError( + f"Coordinate batch {coords.shape[0]} must be 1 or input batch {B}" + ) + c = F.avg_pool2d(coords, kernel_size=self.patch_size, stride=self.patch_size) + + # Tokenize per-frame + x = einops.rearrange(x, "B C T H W -> (B T) C H W") + c_frames = ( + einops.repeat(c, "B C H W -> (B T) C H W", T=T) + if c.shape[0] == B + else c + ) + h = self.tokenizer(x) + self.spatial_pe(c_frames) # (BT, H', W', C0) + h = einops.rearrange(h, "(B T) H W C -> B T H W C", B=B, T=T) + + T_cur = T + for i in range(len(self.depths) - 1): + _, _, Hc, Wc, _ = h.shape + has_temporal = f"temporal_{i}" in self.down_levels + t_blocks = self.down_levels[f"temporal_{i}"] if has_temporal else [None] * len(self.down_levels[f"spatial_{i}"]) + for s_block, t_block in zip(self.down_levels[f"spatial_{i}"], t_blocks): + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + c_frames = ( + einops.repeat(c, "B C H W -> (B T) C H W", T=T_cur) + if c.shape[0] == B + else c + ) + h = _run_block( + s_block, + h, + c_frames, + activation_checkpointing=self.activation_checkpointing, + ) + if t_block is not None: + h = einops.rearrange( + h, "(B T) H W C -> (B H W) T C", B=B, T=T_cur + ) + h = _run_block( + t_block, + h, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange( + h, "(B H W) T C -> B T H W C", B=B, H=Hc, W=Wc + ) + else: + h = einops.rearrange( + h, "(B T) H W C -> B T H W C", B=B, T=T_cur + ) + + # Spatial downsample per-frame + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + h = self.down_levels[f"merge_{i}"](h) + h = einops.rearrange(h, "(B T) H W C -> B T H W C", B=B, T=T_cur) + c = F.avg_pool2d(c, kernel_size=2, stride=2) + + # Temporal downsample + if self.temporal_downsample[i]: + h = self.down_levels[f"temporal_merge_{i}"](h) + T_cur = h.shape[1] + + # Bottleneck: joint 3D attention, or factorized spatial-then-temporal. + _, _, Hc, Wc, _ = h.shape + if self.bottleneck_3d: + for block in self.mid_3d: + h = _run_block( + block, + h, + c, + activation_checkpointing=self.activation_checkpointing, + ) + else: + for s_block, t_block in zip(self.mid_spatial, self.mid_temporal): + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + c_frames = ( + einops.repeat(c, "B C H W -> (B T) C H W", T=T_cur) + if c.shape[0] == B + else c + ) + h = _run_block( + s_block, + h, + c_frames, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange(h, "(B T) H W C -> (B H W) T C", B=B, T=T_cur) + h = _run_block( + t_block, + h, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange(h, "(B H W) T C -> B T H W C", B=B, H=Hc, W=Wc) + + # Head per-frame + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + h = self.head(h) # (BT, z_dim*2, H_z, W_z) + h = einops.rearrange(h, "(B T) C H W -> B C T H W", B=B, T=T_cur) + return h + + @staticmethod + def _trim_temporal_kv( + kv: tuple[torch.Tensor, torch.Tensor], + max_cache_frames: int | None, + ) -> tuple[torch.Tensor, torch.Tensor]: + if max_cache_frames is None: + return kv + if max_cache_frames <= 0: + raise ValueError("max_cache_frames must be positive or None") + k, v = kv + return ( + k[:, :, -max_cache_frames:].contiguous(), + v[:, :, -max_cache_frames:].contiguous(), + ) + + def forward_stream( + self, + x_new: torch.Tensor, + coords: torch.Tensor, + temporal_kv_cache: dict[ + str, tuple[torch.Tensor, torch.Tensor] + ] | None = None, + max_cache_frames: int | None = None, + ) -> tuple[ + torch.Tensor, + dict[str, tuple[torch.Tensor, torch.Tensor]], + ]: + """Encode only newly appended frames with causal temporal KV caches.""" + if self.bottleneck_3d: + raise NotImplementedError( + "streaming encode does not support a joint 3D bottleneck" + ) + if any(self.temporal_downsample): + raise NotImplementedError( + "streaming encode currently requires 1x temporal compression" + ) + if self.temporal_mixer != "attention": + raise NotImplementedError( + "streaming encode currently requires temporal attention" + ) + + B, _, T_new, _, _ = x_new.shape + coords = coords.to(device=x_new.device, dtype=x_new.dtype) + c = F.avg_pool2d( + coords, kernel_size=self.patch_size, stride=self.patch_size + ) + x_new = einops.rearrange( + x_new, "B C T H W -> (B T) C H W" + ) + h = self.tokenizer(x_new) + self.spatial_pe(c) + h = einops.rearrange( + h, "(B T) H W C -> B T H W C", B=B, T=T_new + ) + old_cache = temporal_kv_cache or {} + new_cache: dict[str, tuple[torch.Tensor, torch.Tensor]] = {} + + for i in range(len(self.depths) - 1): + _, _, Hc, Wc, _ = h.shape + has_temporal = f"temporal_{i}" in self.down_levels + t_blocks = ( + self.down_levels[f"temporal_{i}"] + if has_temporal + else [None] * len(self.down_levels[f"spatial_{i}"]) + ) + for j, (s_block, t_block) in enumerate( + zip(self.down_levels[f"spatial_{i}"], t_blocks) + ): + h = einops.rearrange( + h, "B T H W C -> (B T) H W C" + ) + h = s_block(h, c) + if t_block is not None: + h = einops.rearrange( + h, + "(B T) H W C -> (B H W) T C", + B=B, + T=T_new, + ) + cache_key = f"down_{i}_{j}" + h, kv = t_block.forward_stream( + h, old_cache.get(cache_key) + ) + new_cache[cache_key] = self._trim_temporal_kv( + kv, max_cache_frames + ) + h = einops.rearrange( + h, + "(B H W) T C -> B T H W C", + B=B, + H=Hc, + W=Wc, + ) + else: + h = einops.rearrange( + h, + "(B T) H W C -> B T H W C", + B=B, + T=T_new, + ) + + h = einops.rearrange( + h, "B T H W C -> (B T) H W C" + ) + h = self.down_levels[f"merge_{i}"](h) + h = einops.rearrange( + h, + "(B T) H W C -> B T H W C", + B=B, + T=T_new, + ) + c = F.avg_pool2d(c, kernel_size=2, stride=2) + + _, _, Hc, Wc, _ = h.shape + for j, (s_block, t_block) in enumerate( + zip(self.mid_spatial, self.mid_temporal) + ): + h = einops.rearrange( + h, "B T H W C -> (B T) H W C" + ) + h = s_block(h, c) + h = einops.rearrange( + h, + "(B T) H W C -> (B H W) T C", + B=B, + T=T_new, + ) + cache_key = f"mid_{j}" + h, kv = t_block.forward_stream(h, old_cache.get(cache_key)) + new_cache[cache_key] = self._trim_temporal_kv( + kv, max_cache_frames + ) + h = einops.rearrange( + h, + "(B H W) T C -> B T H W C", + B=B, + H=Hc, + W=Wc, + ) + + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + h = self.head(h) + h = einops.rearrange( + h, "(B T) C H W -> B C T H W", B=B, T=T_new + ) + return h, new_cache + + +# ============================================================================= +# Decoder +# ============================================================================= + + +class Decoder(nn.Module): + def __init__( + self, + resolution: List[int], + out_channels: int, + z_dim: int, + base_channels: int = 128, + patch_size: List[int] = (1, 4), + window_size: List[int] = (3, 9), + depths: List[int] = (3, 3, 3, 3), + num_heads: List[int] = (2, 4, 8, 16), + dilation: List[int] = (1, 1, 1, 1), + temporal_downsample: List[bool] = (True, False, False), + temporal_upsample: List[bool] | None = None, + mlp_ratio: float = 3.0, + dropout: float = 0.0, + mapping_depth: int = 2, + positional_embedding: str = "learnable_embedding", + stem_patchify: bool = False, + # ---- Bottleneck options ---- + # If True, replace the bottleneck's factorized (temporal + global + # spatial) attention with a single joint 3D self-attention over + # (T*H*W) tokens. The up-levels are unchanged (still skip temporal + # attn at the highest resolution as before). + bottleneck_3d: bool = False, + # Max T accepted by the bottleneck-3D's learnable temporal PE. Only + # used when bottleneck_3d=True. Set this >= the largest T_z (encoder + # latent frames) you'll ever feed the decoder. + bottleneck_3d_max_t: int = 32, + # If True, the joint 3D attention is causal in time (token (t, h, w) + # only attends to (t', h', w') with t' <= t). The causal mask is + # materialized as a (T*H*W, T*H*W) bool tensor, so memory scales as + # O((T*H*W)^2). Bidirectional is the default for non-streaming use. + bottleneck_3d_causal_time: bool = False, + # If True (and bottleneck_3d=True), encode position in the joint 3D + # attention with a parameter-free 3D RoPE (`VideoRopePosition3DEmb`) + # over (t, h, w) instead of the default (learnable temporal PE + 2D + # spatial AxialRoPE). Recommended for length-extrapolation: the + # learnable temporal PE has uninitialized slots past the largest T + # seen in training (= noise at inference); 3D RoPE has none. The + # spatial axes of the 3D RoPE replace AxialRoPE -- the bottleneck + # operates on a regular (H_z, W_z) grid so Cartesian RoPE is fine + # and decouples positional encoding from polar `coords`. + # Orthogonal to `bottleneck_3d_causal_time` -- both can be combined. + bottleneck_3d_rope: bool = False, + # If True, replace each TemporalExpanding with TemporalExpandingWanStyle, + # which mirrors the WAN decoder's first-frame-special behavior: + # T_in -> 2*T_in - 1 per level. Composed twice this maps T_z latents + # to 4*T_z - 3 frames, so when paired with the WAN encoder there's no + # over-production and no leading-frame crop needed downstream. + temporal_expand_wan_style: bool = False, + # ---- Detokenizer (output) options ---- + # Patch size for the final unpatchify (pixel-shuffle) layer. Defaults + # to `patch_size` (symmetric with the stem, the original behavior). + # Setting this larger than `patch_size` lets the decoder run the top + # (highest-resolution) up-levels at a coarser feature grid and rely + # on the final per-pixel Linear + rearrange to upsample to the output + # resolution -- substantially cheaper since the top level dominates + # the activation memory. The user is responsible for making sure + # `bottleneck_size = resolution // out_patch_size >> n_down` matches + # the encoder's latent spatial shape (i.e. reduce `depths` by + # `log2(out_patch_size / patch_size)` to compensate). + out_patch_size: List[int] | None = None, + # ---- HDmap injection (V1 / V3) ---- + # When True, build a sibling ``stem_hdmap`` projection of the same + # shape as ``stem`` but zero-init. At forward time, if ``hdmap_z`` + # is supplied, the decoder computes + # h = stem(z) + stem_hdmap(hdmap_z) + spatial_pe(...) + # which is mathematically equivalent to channel-concating + # [z; hdmap_z] and using a doubled-input Linear -- but keeps the + # original ``stem`` weights loadable strictly from the warm-start + # ckpt and makes the iter-0 forward bit-identical (zero-init + # ``stem_hdmap`` contributes nothing). See + # ``..._mixclean005_hdmap_v1*`` configs for the design notes. + hdmap_inject_stem: bool = False, + # When not None, build per-up-level injection convs that add + # raw-hdmap features (per-frame ``avg_pool2d`` to the matching + # spatial grid, then 1x1 conv) at the entry of each enabled + # up-level (post-``expand_i``, pre-blocks). List length must + # equal ``n_down = len(depths) - 1``; indexed by up-level i + # (i=0 is the top up-level). Each enabled entry adds a zero-init + # ``Conv2d(hdmap_in_channels, dim_i, kernel_size=1, bias=False)``. + # See ``..._mixclean005_hdmap_v1v3`` for the multi-injection-point + # design. + hdmap_inject_raw_at_up_levels: list[bool] | None = None, + # Channel count of the *raw* hdmap tensor passed to forward + # (the per-up-level V3 injections need this to size the 1x1 + # conv input). Defaults to 3 (matches ``process_input="repeat"`` + # which produces a 3-channel hdmap). Ignored when + # ``hdmap_inject_raw_at_up_levels`` is None or all-False. + hdmap_in_channels: int = 3, + # If False, the local (neighborhood) attention does NOT wrap the W + # axis (clamps at the edges). Default True keeps the range-image + # azimuth-periodic behavior. Set False for a Cartesian BEV grid. + circular_padding: bool = True, + # Temporal-mixing mechanism for the mid/up temporal blocks: + # "attention" (:class:`CausalTemporalAttention`, default) or "conv" + # (WAN-style :class:`CausalTemporalConv`, kernel ``temporal_conv_kernel``). + temporal_mixer: Literal["attention", "conv"] = "attention", + temporal_conv_kernel: int = 3, + activation_checkpointing: bool = False, + ): + super().__init__() + self.resolution = _pair(resolution) + self.patch_size = _pair(patch_size) + self.out_patch_size = ( + _pair(out_patch_size) if out_patch_size is not None else self.patch_size + ) + self.depths = depths + self.temporal_upsample = temporal_upsample if temporal_upsample is not None else temporal_downsample + self.stem_patchify = stem_patchify + self.bottleneck_3d = bottleneck_3d + self.activation_checkpointing = bool(activation_checkpointing) + self._temporal_cls = ( + functools.partial(TemporalConvBlock, kernel_size=temporal_conv_kernel) + if temporal_mixer == "conv" + else TemporalBlock + ) + self.temporal_expand_wan_style = temporal_expand_wan_style + self.hdmap_inject_stem = bool(hdmap_inject_stem) + if hdmap_inject_raw_at_up_levels is not None: + if len(hdmap_inject_raw_at_up_levels) != len(depths) - 1: + raise ValueError( + f"hdmap_inject_raw_at_up_levels must have length " + f"n_down = len(depths) - 1 = {len(depths) - 1}, " + f"got length {len(hdmap_inject_raw_at_up_levels)}." + ) + self.hdmap_inject_raw_at_up_levels = list( + bool(b) for b in hdmap_inject_raw_at_up_levels + ) + else: + self.hdmap_inject_raw_at_up_levels = None + self.hdmap_in_channels = int(hdmap_in_channels) + temporal_expand_cls = ( + TemporalExpandingWanStyle if temporal_expand_wan_style else TemporalExpanding + ) + + # `token_size` is the feature grid at the top up-level, i.e. *before* + # the final detokenizer's unpatchify -- this is what RoPE harmonics + # and the coordinate pyramid index. With `out_patch_size > patch_size` + # the top up-level sits at a coarser grid than the output resolution. + token_size = torch.tensor(self.resolution) // torch.tensor(self.out_patch_size) + max_harmonics = (token_size / 2).int() + n_down = len(depths) - 1 + bottleneck_dim = base_channels << n_down + bottleneck_size = (token_size >> n_down).tolist() + + # Project from z_dim to bottleneck channels. + # By default the stem is a per-pixel channel projection (used in the + # full TransformerVAE, where the Encoder's Tokenizer has already + # patchified the input by `patch_size`). When `stem_patchify=True`, + # we instead apply a Conv2d with stride=patch_size, so the decoder + # can be paired with an external encoder (e.g. the WAN encoder) whose + # latent spatial shape is patch_size larger than the bottleneck. + if stem_patchify and tuple(self.patch_size) != (1, 1): + self.stem = nn.Sequential( + nn.Conv2d( + z_dim, + bottleneck_dim, + kernel_size=self.patch_size, + stride=self.patch_size, + bias=False, + ), + Rearrange("B C H W -> B H W C"), + ) + else: + self.stem = nn.Sequential( + Rearrange("B C H W -> B H W C"), + nn.Linear(z_dim, bottleneck_dim, bias=False), + ) + if self.hdmap_inject_stem: + # Sibling stem for hdmap_z, identical shape to ``self.stem`` but + # zero-init. ``stem(z) + stem_hdmap(hdmap_z)`` is mathematically + # equivalent to channel-concating [z; hdmap_z] and using a + # doubled-input projection (see V1 docstring); decomposing it + # this way keeps the original ``stem`` weights loadable as-is + # from the warm-start ckpt and makes iter-0 forward bit- + # identical (zero-init contributes nothing). + if stem_patchify and tuple(self.patch_size) != (1, 1): + hdmap_stem_proj = nn.Conv2d( + z_dim, + bottleneck_dim, + kernel_size=self.patch_size, + stride=self.patch_size, + bias=False, + ) + nn.init.zeros_(hdmap_stem_proj.weight) + self.stem_hdmap = nn.Sequential( + hdmap_stem_proj, + Rearrange("B C H W -> B H W C"), + ) + else: + hdmap_stem_lin = nn.Linear(z_dim, bottleneck_dim, bias=False) + nn.init.zeros_(hdmap_stem_lin.weight) + self.stem_hdmap = nn.Sequential( + Rearrange("B C H W -> B H W C"), + hdmap_stem_lin, + ) + + # Positional embedding at bottleneck resolution + if positional_embedding == "rope_only": + self.spatial_pe = ZeroPositionalEmbedding(out_dim=bottleneck_dim) + elif positional_embedding == "learnable_embedding": + self.spatial_pe = LearnablePositionalEmbedding( + out_dim=bottleneck_dim, + resolution=bottleneck_size, + ) + else: + self.spatial_pe = nn.Sequential( + AbsolutePositionalEmbedding( + method=positional_embedding, + out_dim=bottleneck_dim, + resolution=bottleneck_size, + ), + MappingNetwork( + bottleneck_dim, + int(bottleneck_dim * mlp_ratio), + depth=mapping_depth, + ), + ) + + # Bottleneck: either factorized (temporal + global spatial), or a + # single joint 3D self-attention over (T*H*W) tokens. + if bottleneck_3d: + self.mid_3d = nn.ModuleList() + for _ in range(depths[-1]): + self.mid_3d.append( + Bottleneck3DBlock( + in_dim=bottleneck_dim, + num_heads=num_heads[-1], + max_t=bottleneck_3d_max_t, + rope_max_harmonics=(max_harmonics >> n_down).clamp(min=1), + mlp_ratio=mlp_ratio, + dropout=dropout, + causal_time=bottleneck_3d_causal_time, + use_3d_rope=bottleneck_3d_rope, + # 3D RoPE caches per-axis frequencies up to (len_t, + # len_h, len_w). Spatial caps come from the + # bottleneck's own grid; the temporal cap is shared + # with the learnable-PE path via `bottleneck_3d_max_t`. + len_h=bottleneck_size[0], + len_w=bottleneck_size[1], + ) + ) + else: + self.mid_temporal = nn.ModuleList() + self.mid_spatial = nn.ModuleList() + for _ in range(depths[-1]): + self.mid_temporal.append( + self._temporal_cls( + in_dim=bottleneck_dim, + num_heads=num_heads[-1], + mlp_ratio=mlp_ratio, + dropout=dropout, + ) + ) + self.mid_spatial.append( + SpatialBlock( + in_dim=bottleneck_dim, + num_heads=num_heads[-1], + attn_type="global", + mlp_ratio=mlp_ratio, + dropout=dropout, + rope_max_harmonics=(max_harmonics >> n_down).clamp(min=1), + ) + ) + + # Up levels: temporal expand + spatial expand + temporal→spatial blocks + # Skip temporal attention at level 0 (highest resolution) for efficiency. + self.up_levels = nn.ModuleDict() + for i in reversed(range(n_down)): + dim_i = base_channels << i + dim_above = base_channels << (i + 1) + + if self.temporal_upsample[i]: + self.up_levels[f"temporal_expand_{i}"] = temporal_expand_cls(dim_above) + + self.up_levels[f"expand_{i}"] = PatchExpanding(dim_above) + + if ( + self.hdmap_inject_raw_at_up_levels is not None + and self.hdmap_inject_raw_at_up_levels[i] + ): + # V3 raw-hdmap injection at the entry of up-level i (post- + # ``expand_{i}``, pre-blocks). Per-frame ``avg_pool2d`` of + # the raw hdmap to (Hc, Wc) of this stage, then a zero-init + # 1x1 conv projects 3 -> dim_i. Zero-init keeps the iter-0 + # forward bit-identical; the projection lives under + # ``hdmap_inject_{i}`` to share the up_levels namespace + # (no separate ModuleDict, fewer state_dict prefixes). + inject_conv = nn.Conv2d( + self.hdmap_in_channels, dim_i, kernel_size=1, bias=False + ) + nn.init.zeros_(inject_conv.weight) + self.up_levels[f"hdmap_inject_{i}"] = inject_conv + + spatial_blocks = nn.ModuleList() + for j in range(depths[i]): + spatial_blocks.append( + SpatialBlock( + in_dim=dim_i, + num_heads=num_heads[i], + attn_type="local", + kernel_size=window_size, + dilation=1 if j % 2 == 0 else dilation[i], + mlp_ratio=mlp_ratio, + dropout=dropout, + rope_max_harmonics=(max_harmonics >> i).clamp(min=1), + circular=circular_padding, + ) + ) + self.up_levels[f"spatial_{i}"] = spatial_blocks + # Temporal blocks are needed at every level that does a temporal + # expand (to mix the newly-interpolated frames into a coherent + # sequence), plus -- as a cheap-but-useful compute heuristic -- + # at every level deeper than the top one. The previous condition + # was just `i > 0`, which silently skipped temporal attention at + # the top level even when temporal_upsample[0] was True, leaving + # the just-expanded frames un-mixed. + if i > 0 or self.temporal_upsample[i]: + temporal_blocks = nn.ModuleList() + for j in range(depths[i]): + temporal_blocks.append( + self._temporal_cls( + in_dim=dim_i, + num_heads=num_heads[i], + mlp_ratio=mlp_ratio, + dropout=dropout, + ) + ) + self.up_levels[f"temporal_{i}"] = temporal_blocks + + self.detokenizer = Detokenizer(base_channels, out_channels, self.out_patch_size) + + @staticmethod + def _trim_temporal_kv( + kv: tuple[torch.Tensor, torch.Tensor], + max_cache_frames: int | None, + ) -> tuple[torch.Tensor, torch.Tensor]: + if max_cache_frames is None: + return kv + if max_cache_frames <= 0: + raise ValueError("max_cache_frames must be positive or None") + k, v = kv + return ( + k[:, :, -max_cache_frames:].contiguous(), + v[:, :, -max_cache_frames:].contiguous(), + ) + + def forward( + self, + z: torch.Tensor, + coords: torch.Tensor, + hdmap_z: torch.Tensor | None = None, + hdmap_raw: torch.Tensor | None = None, + temporal_kv_cache: dict[ + str, tuple[torch.Tensor, torch.Tensor] + ] | None = None, + return_temporal_kv_cache: bool = False, + max_cache_frames: int | None = None, + ) -> torch.Tensor | tuple[ + torch.Tensor, dict[str, tuple[torch.Tensor, torch.Tensor]] + ]: + """ + Args: + z: (B, z_dim, T', H_z, W_z) latent + coords: (1, 2, H, W) polar coordinates + hdmap_z: optional (B, z_dim, T', H_z, W_z) hdmap latent (frozen- + encoder output). Used by V1 stem-concat (added to ``stem(z)`` + via ``stem_hdmap``). Silently ignored when + ``hdmap_inject_stem=False`` or this is None. + hdmap_raw: optional (B, hdmap_in_channels, T_full, H_full, W_full) + raw hdmap video at the same temporal length as the decoder's + expected output. Used by V3 per-up-level injections (per- + frame ``avg_pool2d`` to the matching stage grid + zero-init + 1x1 conv). Silently ignored when + ``hdmap_inject_raw_at_up_levels=None`` or this is None. + Returns: + (B, C, T, H, W) reconstructed video + """ + B = z.shape[0] + T_cur = z.shape[2] + n_down = len(self.depths) - 1 + if coords.shape[0] not in (1, B): + raise ValueError( + f"Coordinate batch {coords.shape[0]} must be 1 or latent batch {B}" + ) + streaming = return_temporal_kv_cache + if temporal_kv_cache is not None and not streaming: + raise ValueError( + "temporal_kv_cache requires return_temporal_kv_cache=True" + ) + if max_cache_frames is not None and not streaming: + raise ValueError( + "max_cache_frames requires return_temporal_kv_cache=True" + ) + if streaming: + if self.bottleneck_3d: + raise NotImplementedError( + "streaming decode does not support bottleneck_3d" + ) + if any(self.temporal_upsample): + raise NotImplementedError( + "streaming decode currently requires temporal_upsample=False " + "at every decoder level" + ) + if not all( + isinstance(block, TemporalBlock) + for block in self.mid_temporal + ): + raise NotImplementedError( + "streaming decode currently supports temporal attention, " + "not temporal convolution" + ) + old_cache = temporal_kv_cache or {} + new_cache: dict[str, tuple[torch.Tensor, torch.Tensor]] = {} + + # Build coordinate pyramid. The base sits at the *top up-level* token + # grid (= resolution // out_patch_size), which is the highest-res grid + # the attention blocks actually see -- the final detokenizer's + # pixel-shuffle never gets coords. + c_base = F.avg_pool2d(coords, kernel_size=self.out_patch_size, stride=self.out_patch_size) + c_levels = [c_base] + for i in range(n_down): + c_levels.append(F.avg_pool2d(c_levels[-1], kernel_size=2, stride=2)) + + # Stem per-frame + spatial PE (+ optional V1 hdmap-stem injection) + z = einops.rearrange(z, "B C T H W -> (B T) C H W") + c_frames = ( + einops.repeat( + c_levels[n_down], "B C H W -> (B T) C H W", T=T_cur + ) + if c_levels[n_down].shape[0] == B + else c_levels[n_down] + ) + h = self.stem(z) + self.spatial_pe(c_frames) # (BT, H_z, W_z, C) + if self.hdmap_inject_stem and hdmap_z is not None: + # ``stem(z) + stem_hdmap(hdmap_z)`` is mathematically equivalent + # to a doubled-input stem on ``[z; hdmap_z]``; zero-init at + # iter 0 so this is a no-op until SGD learns to use it. + hdmap_z_flat = einops.rearrange(hdmap_z, "B C T H W -> (B T) C H W") + h = h + self.stem_hdmap(hdmap_z_flat) + h = einops.rearrange(h, "(B T) H W C -> B T H W C", B=B, T=T_cur) + + # Bottleneck + _, _, Hc, Wc, _ = h.shape + if self.bottleneck_3d: + # Joint 3D attention: single pass over (T*H*W) tokens. + for block in self.mid_3d: + h = _run_block( + block, + h, + c_levels[n_down], + activation_checkpointing=self.activation_checkpointing, + ) + else: + # Factorized: temporal then global-spatial (decoder order). + for block_idx, (t_block, s_block) in enumerate( + zip(self.mid_temporal, self.mid_spatial) + ): + h = einops.rearrange(h, "B T H W C -> (B H W) T C") + if streaming: + cache_key = f"mid_temporal.{block_idx}" + h, kv = t_block.forward_stream( + h, old_cache.get(cache_key) + ) + new_cache[cache_key] = self._trim_temporal_kv( + kv, max_cache_frames + ) + else: + h = _run_block( + t_block, + h, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange( + h, "(B H W) T C -> (B T) H W C", B=B, H=Hc, W=Wc + ) + c_frames = ( + einops.repeat( + c_levels[n_down], + "B C H W -> (B T) C H W", + T=T_cur, + ) + if c_levels[n_down].shape[0] == B + else c_levels[n_down] + ) + h = _run_block( + s_block, + h, + c_frames, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange(h, "(B T) H W C -> B T H W C", B=B, T=T_cur) + + # Up levels + for i in reversed(range(n_down)): + # Temporal upsample + if self.temporal_upsample[i]: + h = self.up_levels[f"temporal_expand_{i}"](h) + T_cur = h.shape[1] + + # Spatial upsample per-frame + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + h = self.up_levels[f"expand_{i}"](h) + h = einops.rearrange(h, "(B T) H W C -> B T H W C", B=B, T=T_cur) + + _, _, Hc, Wc, _ = h.shape + + # V3 raw-hdmap injection at the entry of this up-level. Per- + # frame ``avg_pool2d`` is causality-preserving (output frame t + # depends only on input frame t) and the spatial pool target + # matches this stage's (Hc, Wc). Zero-init 1x1 conv keeps + # iter-0 forward bit-identical. + inject_key = f"hdmap_inject_{i}" + if ( + self.hdmap_inject_raw_at_up_levels is not None + and self.hdmap_inject_raw_at_up_levels[i] + and hdmap_raw is not None + and inject_key in self.up_levels + ): + # hdmap_raw: (B, C_h, T_h, H_h, W_h). Rearrange to per-frame + # before the spatial avg_pool, then 1x1 conv to dim_i. + if hdmap_raw.shape[2] != T_cur: + raise ValueError( + f"hdmap_raw temporal length {hdmap_raw.shape[2]} " + f"does not match decoder up-level {i} temporal " + f"grid {T_cur}. Pass a raw hdmap with the same " + f"number of frames as the original lidar video " + f"(per-frame, no temporal downsample)." + ) + hdmap_raw_flat = einops.rearrange( + hdmap_raw, "B C T H W -> (B T) C H W" + ) + hdmap_feat = F.adaptive_avg_pool2d( + hdmap_raw_flat, output_size=(Hc, Wc) + ) + hdmap_feat = self.up_levels[inject_key](hdmap_feat) + hdmap_feat = einops.rearrange( + hdmap_feat, "(B T) C H W -> B T H W C", B=B, T=T_cur + ) + h = h + hdmap_feat + + has_temporal = f"temporal_{i}" in self.up_levels + t_blocks = self.up_levels[f"temporal_{i}"] if has_temporal else [None] * len(self.up_levels[f"spatial_{i}"]) + for block_idx, (t_block, s_block) in enumerate( + zip(t_blocks, self.up_levels[f"spatial_{i}"]) + ): + if t_block is not None: + h = einops.rearrange(h, "B T H W C -> (B H W) T C") + if streaming: + if not isinstance(t_block, TemporalBlock): + raise NotImplementedError( + "streaming decode currently supports temporal " + "attention, not temporal convolution" + ) + cache_key = f"up_levels.temporal_{i}.{block_idx}" + h, kv = t_block.forward_stream( + h, old_cache.get(cache_key) + ) + new_cache[cache_key] = self._trim_temporal_kv( + kv, max_cache_frames + ) + else: + h = _run_block( + t_block, + h, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange( + h, "(B H W) T C -> (B T) H W C", B=B, H=Hc, W=Wc + ) + else: + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + c_frames = ( + einops.repeat( + c_levels[i], "B C H W -> (B T) C H W", T=T_cur + ) + if c_levels[i].shape[0] == B + else c_levels[i] + ) + h = _run_block( + s_block, + h, + c_frames, + activation_checkpointing=self.activation_checkpointing, + ) + h = einops.rearrange( + h, "(B T) H W C -> B T H W C", B=B, T=T_cur + ) + + # Detokenize per-frame + h = einops.rearrange(h, "B T H W C -> (B T) H W C") + h = self.detokenizer(h) # (BT, C_out, H, W) + h = einops.rearrange(h, "(B T) C H W -> B C T H W", B=B, T=T_cur) + if streaming: + missing = set(old_cache) - set(new_cache) + if missing: + raise ValueError( + f"unused temporal KV cache keys: {sorted(missing)}" + ) + return h, new_cache + return h + + +# ============================================================================= +# TransformerVAE +# ============================================================================= + + +class TransformerVAE(nn.Module): + def __init__( + self, + resolution: List[int], + in_channels: int, + out_channels: int | None = None, + z_dim: int = 4, + # Opt-in checkpoint surgery when widening an existing latent. The + # source channels retain their exact encoder/quantizer/decoder path; + # added channels start disconnected at zero. + latent_warmstart_source_dim: int | None = None, + base_channels: int = 128, + patch_size: List[int] = (1, 4), + window_size: List[int] = (3, 9), + depths: List[int] = (3, 3, 3, 3), + num_heads: List[int] = (2, 4, 8, 16), + dilation: List[int] = (1, 1, 1, 1), + temporal_downsample: List[bool] = (True, False, False), + temporal_upsample: List[bool] | None = None, + # ---- Asymmetric decoder (opt-in) ---- + # By default the decoder mirrors the encoder (same depths / num_heads / + # dilation / temporal schedule, out_patch_size = patch_size). To build a + # *plain-ViT* encoder (large patch + few merges) paired with a heavier + # *progressive* decoder (small out_patch + more expand levels), set + # these. ``spatial_compression`` / ``temporal_compression`` are always + # derived from the ENCODER side. The only hard constraint is that the + # decoder's bottleneck spatial grid + # resolution // out_patch_size >> (len(decoder_depths) - 1) + # equals the encoder's latent grid + # resolution // patch_size >> (len(depths) - 1). + # When ``decoder_depths`` is set you MUST also pass + # ``decoder_temporal_upsample`` (length len(decoder_depths) - 1) since + # the encoder's temporal schedule no longer has the matching length. + decoder_depths: List[int] | None = None, + decoder_num_heads: List[int] | None = None, + decoder_dilation: List[int] | None = None, + decoder_temporal_upsample: List[bool] | None = None, + out_patch_size: List[int] | None = None, + mlp_ratio: float = 3.0, + dropout: float = 0.0, + mapping_depth: int = 2, + positional_embedding: Literal[ + "spherical_harmonics", + "polar_coordinates", + "fourier_features", + "learnable_embedding", + "rope_only", + ] = "learnable_embedding", + formulation: str = ContinuousFormulation.AE.name, + noise_aug_sigma: float = 0.0, + # Decoder-only fine-tuning: freeze ``encoder`` + ``quant_conv`` so + # only ``post_quant_conv`` + ``decoder`` are updated. Pair with + # ``latent_stats_path`` + ``latent_norm_noise_sigma`` to fine-tune + # the decoder on noise-degraded latents. + freeze_encoder: bool = False, + # Path to a ``latent_stats.pt`` file (a dict with ``mean``/``std`` + # tensors of shape (z_dim,), or a ``(mean, std)`` tuple) used to + # normalize the latent before adding noise. Required whenever + # ``latent_norm_noise_sigma > 0``. + latent_stats_path: str | None = None, + # Noise added in the NORMALIZED latent space. Interpretation + # depends on ``latent_norm_noise_sigma_mode``: + # "fixed" / "uniform": σ (additive noise stddev) + # "interpolative": γ (noise stddev in the interpolation + # formula z' = (1−τ)z + τγε) + # Applied only during training. Orthogonal to ``noise_aug_sigma`` + # (which acts on the raw, unnormalized latent). + latent_norm_noise_sigma: float = 0.0, + # How to corrupt the normalized latent: + # "fixed": z' = z + σ·ε, σ = latent_norm_noise_sigma (constant). + # "uniform": z' = z + σ·ε, σ ~ U(0, latent_norm_noise_sigma) + # per sample. Continuum including clean (σ=0). + # "interpolative": z' = (1−τ)·z + τ·γ·ε, τ ~ U(0, τ_max) per sample, + # γ = latent_norm_noise_sigma, + # τ_max = latent_norm_noise_tau_max (default 1.0). + # DeTok-style: forces full signal replacement at τ=1, + # prevents the "additive shortcut" where the + # original signal still dominates at high noise + # levels (Yang et al., arXiv 2507.15856, Fig 2a). + # Set τ_max < 1 to mimic LTX-style RF training + # range matching ``--decoder_t1=τ_max`` early-stop + # at inference (but without AdaLN t-conditioning; + # use TransformerVAELTX for that). + latent_norm_noise_sigma_mode: Literal["fixed", "uniform", "interpolative"] = "fixed", + # Upper bound of τ in interpolative mode (ignored for other modes). + # τ ~ U(0, τ_max). Defaults to 1.0 (full DeTok range). Use a smaller + # value (e.g. 0.20) to restrict training to the low-noise regime that + # the diffusion sampler actually leaves uncovered when early-stopping + # at ``--decoder_t1=τ_max``. + latent_norm_noise_tau_max: float = 1.0, + # Per-sample probability of drawing τ = 0 (a perfectly clean latent) + # *in place of* the normal τ ~ U(0, τ_max) draw, in the + # "interpolative" mode. 0.0 (default) keeps the original behavior; + # 0.5 gives a 50/50 mixture of (clean) and (uniform-up-to-τ_max). + # Useful as a "noise-vs-clean mixture" training regime: half the + # gradient signal preserves the base decoder's clean-signal + # behavior (so the decoder doesn't drift off the τ=0 manifold the + # way pure noise-FT does), the other half adds noise robustness. + # Particularly relevant when τ_max is small (e.g. 0.10): without + # this knob, every training sample sees *some* noise, which can + # over-train noise-handling pathways at the expense of clean + # reconstruction fidelity. + latent_norm_noise_clean_prob: float = 0.0, + # Whether to apply the noise in the normalized latent space (default) + # or directly on the raw encoder output (DeTok-pure). + # True (default): encode → (z - mean) / std → corrupt → · std + mean + # → decode. Requires ``latent_stats_path``. Use this + # when the encoder is frozen so the (mean, std) + # reference is stable and τ has a clean unit-Gaussian + # meaning. + # False: encode → corrupt → decode (no normalize/denormalize). Use + # this when the encoder is trainable -- frozen pretrained + # stats become a stale reference frame and the decoder ends + # up trained against a different latent distribution than it + # sees at inference (once stats are recomputed). Matches + # DeTok's recipe (Yang et al., arXiv 2507.15856). ``γ`` / + # ``σ`` now denote noise std in the raw latent space, so set + # them to the empirical encoder std (≈ 1 for a KL-VAE). + latent_norm_noise_use_normalization: bool = True, + # EMA momentum for online tracking of (latent_mean, latent_std) from + # the raw encoder output during training. 0.0 = disabled (the loaded + # ``latent_stats_path`` is used statically, as before). When > 0, each + # training step: + # 1. compute per-channel batch mean / std of z_0 (the raw encoder + # output, pre-normalization), reducing over (B, T, H, W); + # 2. all-reduce across DDP ranks (op = AVG) so every rank tracks + # the same world-wide stats; + # 3. EMA-update the persistent ``latent_mean`` / ``latent_std`` + # buffers in-place: buf = m * buf + (1 - m) * batch_stat. + # Use this when the encoder is unfrozen (DeTok-style FT) so that + # τ keeps its calibrated meaning even as the encoder marginal drifts + # away from ``latent_stats_path``. Requires + # ``latent_norm_noise_use_normalization=True`` and a non-None + # ``latent_stats_path`` (the file is used as the EMA initialization). + # Buffers become persistent when EMA is on, so the warm-start ckpt + # must allow loose loading (set ``strict_resume=False``) or carry + # them already. + # Typical values: 0.999 (slow, ~1k-iter horizon), 0.99 (fast, ~100 + # iters). + latent_norm_noise_ema_momentum: float = 0.0, + # WAN-style first-frame-special temporal merging in the encoder. + # See :class:`TemporalMergingFirstFrameSpecial` for details. + # Pair with ``temporal_expand_wan_style=True`` so the decoder's + # ``TemporalExpandingWanStyle`` mirrors the encoder's chunk + # boundaries: ``T_in = 1 + (2 ** N) * (T_z - 1)`` exactly, + # no front-crop, no boundary information loss. + temporal_first_frame_special: bool = False, + # WAN-style first-frame-special temporal expanding in the decoder. + # When True every level with ``temporal_upsample[i]=True`` uses + # :class:`TemporalExpandingWanStyle` (T_in -> 2*T_in - 1) instead + # of plain :class:`TemporalExpanding` (T_in -> 2*T_in). Designed + # to be paired with ``temporal_first_frame_special=True``. + temporal_expand_wan_style: bool = False, + # ---- Temporal-mixing mechanism (ablation) ---- + # "attention" (default): temporal mixing via + # :class:`CausalTemporalAttention` in the down/mid/up temporal blocks. + # "conv": WAN-style causal temporal convolution + # (:class:`CausalTemporalConv`, kernel ``temporal_conv_kernel``, + # spatial 1x1) instead. Spatial mixing (neighborhood attention) is + # unchanged, so this is a clean temporal-attn-vs-temporal-conv swap. + temporal_mixer: Literal["attention", "conv"] = "attention", + temporal_conv_kernel: int = 3, + # Recompute transformer blocks during backward to reduce activation + # memory. Disabled by default so existing models are unchanged. + activation_checkpointing: bool = False, + # Autocast only the encoder stack and quant projection. Posterior + # sampling, KL math, latent handoff, and the decoder remain FP32. + encoder_autocast_dtype: str | None = None, + # ---- HDmap injection into the decoder (V1 / V3) ---- + # When True (V1): build a sibling zero-init ``stem_hdmap`` + # projection in the decoder, encode the raw hdmap video through + # the (frozen) ``self.encoder`` to produce ``hdmap_z`` of the + # same shape as ``z``, and add ``stem_hdmap(hdmap_z)`` at the + # decoder stem. Iter-0 bit-identical to the warm-start ckpt. + hdmap_inject_stem: bool = False, + # When not None (V3): list of length ``n_down = len(depths) - 1`` + # indexed by up-level i. For each ``True`` entry, the decoder + # builds a zero-init 1x1 conv that injects per-frame avg-pooled + # raw hdmap features at the entry of up-level i (post- + # ``expand_i``, pre-blocks). Same iter-0 guarantee. + hdmap_inject_raw_at_up_levels: list[bool] | None = None, + # ---- PV-VAE-style predictive frame dropping (training only) ---- + # With probability ``frame_drop_prob`` per training forward, replace + # the trailing ``k ~ U(frame_drop_min_latent, frame_drop_max_latent)`` + # *latent* frames (per sample) with a learnable pad token before + # decoding, then reconstruct the FULL video. Because the encoder is + # causal in time, masking trailing latents is equivalent to encoding + # only the observed (past) frames + padding -- the decoder must + # PREDICT the withheld future frames (arxiv:2605.02134). No-op when + # ``frame_drop_prob == 0`` or in eval mode (validation stays clean + # so recon metrics remain comparable). + frame_drop_prob: float = 0.0, + frame_drop_min_latent: int = 1, + frame_drop_max_latent: int = 0, + # ---- Validity (raydrop) mask prediction (arxiv:2605.22809) ---- + # When True, the decoder emits ONE extra output channel of validity + # logits (1 = valid return, 0 = no return). The data channels are + # unchanged; ``decode()`` returns only the data channels by default, + # so all existing call sites are unaffected. The validity logits are + # surfaced via ``forward()`` output for the BCE loss, and can be + # retrieved at inference via ``decode(..., return_validity=True)``. + predict_validity: bool = False, + # ---- Validity mask as INPUT channel ---- + # When True, ``forward()`` derives a binary validity mask from the + # (no-return-clamped) depth channel and concatenates it as an extra + # INPUT channel BEFORE encoding. Pairs with ``predict_validity`` to + # get a symmetric autoencoder: input ``[depth, mask]`` (2 ch) -> + # output ``[depth(recon), validity_logit]`` (2 ch). ``in_channels`` + # MUST include this extra channel (e.g. mono depth -> in_channels=2). + mask_as_input: bool = False, + mask_input_min_value: float = -1.0, + mask_input_eps: float = 0.02, + # ---- Global Skip Connection (GSC, Qwen-Image-VAE-2.0 2605.13565) ---- + # When True, add a residual path that folds the raw ENCODER INPUT + # (post ``mask_as_input`` concat) into the latent via a space-to-channel + # (pixel-unshuffle by ``spatial_compression``) + 1x1 projection, added + # to the sampled latent ``z`` inside ``encode()``. The high-frequency + # input signal therefore lives IN the latent the DiT diffuses -> + # diffusion-safe, unlike encoder->decoder DPT skips. Accelerates + # convergence + sharpens edges at high spatial compression (the paper's + # f16/f32 regime). Deliberately NOT zero-init: the convergence benefit + # requires it active from step 0, so only enable on from-scratch (or + # ``strict_resume=False``) runs. No-op for every existing config + # (default False -> ``gsc_proj`` is never built, forward path + # unchanged). + global_skip: bool = False, + # ---- Bottleneck 3D attention (encoder AND decoder) ---- + # When True, both the encoder and decoder replace their factorized + # bottleneck (global spatial + temporal attention) with a single + # joint 3D self-attention over (T*H*W) tokens (:class:`Bottleneck3DBlock`). + # Default False -> both keep the factorized bottleneck, bit-identical + # to every existing config. ``bottleneck_3d_max_t`` caps the temporal + # PE / RoPE length (set >= largest latent T_z fed to the model); + # ``bottleneck_3d_causal_time`` masks the joint attention to be causal + # in time; ``bottleneck_3d_rope`` swaps the (learnable temporal PE + + # 2D AxialRoPE) for a parameter-free 3D RoPE over (t, h, w). + bottleneck_3d: bool = False, + bottleneck_3d_max_t: int = 32, + bottleneck_3d_causal_time: bool = False, + bottleneck_3d_rope: bool = False, + # ---- Utonia (PTv3) RANGE-VIEW feature alignment (REPA / Volt) ---- + # When True, run a frozen pretrained PTv3 (Pointcept/Utonia) on the + # input range map, masked-pool its per-pixel features down to the + # latent grid (this is RANGE-VIEW alignment, NOT the UniPAD BEV scatter + # -- the teacher already lives in the same elevation x azimuth frame as + # the range-image latent), and minimize a masked cosine distance to a + # trainable 1x1 projection of the latent. Encoder-side alignment: the + # gradient flows into the transformer encoder, pulling the latent toward + # a semantically-meaningful frozen representation (REPA arXiv:2410.06940, + # Volt arXiv:2604.19609). Teacher is fully frozen + eval. Adds one PTv3 + # forward per step (slow CPU GridSample) and needs the ``utonia`` package + # (spconv/torch_scatter/flash_attn) + the HF checkpoint -> cluster only. + # Default False -> no teacher/projector built, every existing config + # bit-identical. + utonia_align: bool = False, + utonia_dataset_name: str = "lidar_range_map_rRow4_smol_norepeat_val", + utonia_scale: float = 0.2, + utonia_download_root: str = "", + # Normalization geometry the teacher uses to unproject the normalized + # range image -> metric XYZ (must match the dataloader's convention). + # Defaults match the lidargen lidar default (configs.py COMMONDATA). + utonia_min_range: float = 5.0, + utonia_max_range: float = 100.0, + utonia_min_value: float = -1.0, + utonia_inverse_depth: bool = False, + # Run the teacher at a REDUCED azimuth width (0 = full self.resolution[1]). + # The PTv3 + CPU GridSample cost scales with point count (H*W); the + # teacher features are pooled to the (Hz, Wz) latent grid anyway, so a + # coarser azimuth (still >= Wz) is a near-free speedup. Only azimuth (W) + # is reduced -- elevation rows are physical beams and stay at 128. + utonia_teacher_width: int = 0, + # VA-VAE VF loss margins (arXiv:2501.01423). ``vf_margin_cos`` = m1 for + # the marginal cosine similarity loss (Eq. 2); ``vf_margin_dist`` = m2 + # for the marginal distance-matrix similarity loss (Eq. 3). The overall + # w_hyper (paper 0.1) is the ``repa_align`` loss weight; the adaptive + # gradient-ratio weighting (Eq. 4) is intentionally NOT implemented. + vf_margin_cos: float = 0.5, + vf_margin_dist: float = 0.25, + # Memory knobs for the VF loss (default 0 = paper-exact, no subsample): + # vf_mdms_window: (wh, ww) -> LOCAL-WINDOW block mdms. Tile the Hz x Wz + # latent grid into non-overlapping (wh, ww) patches and compute the + # self-similarity matrix WITHIN each patch only -> block-diagonal + # (M*nh*nw, P, P), P=wh*ww. Pairs stay spatially local (meaningful + # for the very wide range-image azimuth) and it's deterministic. + # Requires Hz % wh == 0 and Wz % ww == 0. Takes precedence over + # vf_mdms_max_tokens. (0, 0) = disabled. + # vf_mdms_max_tokens: else, cap the GLOBAL mdms matrix to S random + # VALID tokens per frame -> (M, S, S) instead of (M, N, N) (a + # stochastic estimate). mcos is per-pixel/cheap and never subsampled. + # vf_supervise_frames: run the teacher + VF loss on only K random + # frames per clip (cuts PTv3 forwards AND #matrices). Requires no + # temporal compression (latent T == input T); raises otherwise. + vf_mdms_window: tuple[int, int] = (0, 0), + vf_mdms_max_tokens: int = 0, + vf_supervise_frames: int = 0, + ): + super().__init__() + self.resolution = _pair(resolution) + self.in_channels = in_channels + self.out_channels = out_channels if out_channels else in_channels + self.predict_validity = predict_validity + self.mask_as_input = mask_as_input + self.mask_input_min_value = float(mask_input_min_value) + self.mask_input_eps = float(mask_input_eps) + # When True, ``forward(..., valid_mask=...)`` uses an externally-provided + # per-pixel validity mask for the ``mask_as_input`` concat instead of + # deriving it from ``depth > min_value + eps`` (which is unrecoverable + # under per-row normalization). The model only threads ``valid_mask`` + # when this is True; if the kwarg is None at forward time we fall back + # to the derived mask, so existing mask configs are unaffected. + self.uses_valid_mask = mask_as_input + # Decoder produces data channels (+1 validity logit channel if enabled). + self._decoder_out_channels = self.out_channels + (1 if predict_validity else 0) + self.z_dim = z_dim + self.latent_warmstart_source_dim = latent_warmstart_source_dim + if latent_warmstart_source_dim is not None: + assert 0 < latent_warmstart_source_dim < z_dim, ( + "latent_warmstart_source_dim must be positive and smaller than " + f"z_dim, got {latent_warmstart_source_dim=} and {z_dim=}" + ) + self.patch_size = _pair(patch_size) + self.noise_aug_sigma = noise_aug_sigma + self.freeze_encoder = freeze_encoder + self.latent_norm_noise_sigma = latent_norm_noise_sigma + if latent_norm_noise_sigma_mode not in ("fixed", "uniform", "interpolative"): + raise ValueError( + f"latent_norm_noise_sigma_mode must be 'fixed', 'uniform', or " + f"'interpolative', got {latent_norm_noise_sigma_mode!r}" + ) + self.latent_norm_noise_sigma_mode = latent_norm_noise_sigma_mode + if not (0.0 < latent_norm_noise_tau_max <= 1.0): + raise ValueError( + f"latent_norm_noise_tau_max must be in (0, 1], got {latent_norm_noise_tau_max}" + ) + self.latent_norm_noise_tau_max = float(latent_norm_noise_tau_max) + if not (0.0 <= latent_norm_noise_clean_prob <= 1.0): + raise ValueError( + f"latent_norm_noise_clean_prob must be in [0, 1], got " + f"{latent_norm_noise_clean_prob}" + ) + self.latent_norm_noise_clean_prob = float(latent_norm_noise_clean_prob) + self.latent_norm_noise_use_normalization = bool( + latent_norm_noise_use_normalization + ) + if not (0.0 <= latent_norm_noise_ema_momentum < 1.0): + raise ValueError( + f"latent_norm_noise_ema_momentum must be in [0, 1), got " + f"{latent_norm_noise_ema_momentum}" + ) + self.latent_norm_noise_ema_momentum = float(latent_norm_noise_ema_momentum) + if self.latent_norm_noise_ema_momentum > 0.0: + if not self.latent_norm_noise_use_normalization: + raise ValueError( + "latent_norm_noise_ema_momentum > 0 requires " + "latent_norm_noise_use_normalization=True (EMA only " + "tracks the normalize-space reference frame)." + ) + if latent_stats_path is None: + raise ValueError( + "latent_norm_noise_ema_momentum > 0 requires " + "latent_stats_path to be set (used as the EMA " + "initialization)." + ) + + n_down = len(depths) - 1 + self.spatial_compression = ( + self.patch_size[0] * (2 ** n_down), + self.patch_size[1] * (2 ** n_down), + ) + self.temporal_compression = 2 ** sum(temporal_downsample) + self._encoder_autocast_dtype = ( + getattr(torch, encoder_autocast_dtype) + if encoder_autocast_dtype + else None + ) + + coords = encoding.generate_polar_coords(*self.resolution) + self.register_buffer("coords", coords) + + self.encoder = Encoder( + resolution=resolution, + in_channels=in_channels, + z_dim=z_dim, + base_channels=base_channels, + patch_size=patch_size, + window_size=window_size, + depths=depths, + num_heads=num_heads, + dilation=dilation, + temporal_downsample=temporal_downsample, + mlp_ratio=mlp_ratio, + dropout=dropout, + mapping_depth=mapping_depth, + positional_embedding=positional_embedding, + temporal_first_frame_special=temporal_first_frame_special, + bottleneck_3d=bottleneck_3d, + bottleneck_3d_max_t=bottleneck_3d_max_t, + bottleneck_3d_causal_time=bottleneck_3d_causal_time, + bottleneck_3d_rope=bottleneck_3d_rope, + temporal_mixer=temporal_mixer, + temporal_conv_kernel=temporal_conv_kernel, + activation_checkpointing=activation_checkpointing, + ) + + self.distribution = ContinuousFormulation[formulation].value() + logger.info(f"TransformerVAE with {formulation} formulation.") + + self.quant_conv = nn.Conv2d(z_dim * 2, z_dim * 2, 1) + self.post_quant_conv = nn.Conv2d(z_dim, z_dim, 1) + + # Global Skip Connection (GSC): space-to-channel fold of the encoder + # input -> 1x1 proj -> residual added to the latent in ``encode()``. + # in-dim = in_channels * (sh * sw) where (sh, sw) = spatial_compression + # (the pixel-unshuffle factor that brings the input to latent res). + self.global_skip = bool(global_skip) + if self.global_skip: + _sh, _sw = self.spatial_compression + self.gsc_proj = nn.Conv2d(in_channels * _sh * _sw, z_dim, kernel_size=1) + logger.info( + f"TransformerVAE: Global Skip Connection enabled " + f"(S2C fold {self.spatial_compression}, " + f"{in_channels * _sh * _sw} -> {z_dim} channels)." + ) + + # PV-VAE predictive frame dropping. ``frame_drop_pad`` is a single + # learnable latent vector broadcast over the dropped trailing + # positions (and over H, W); zero-init so warm-start is a gentle + # start (decoder sees zeros where it must learn to predict). + self.frame_drop_prob = float(frame_drop_prob) + self.frame_drop_min_latent = int(frame_drop_min_latent) + self.frame_drop_max_latent = int(frame_drop_max_latent) + if not (0.0 <= self.frame_drop_prob <= 1.0): + raise ValueError( + f"frame_drop_prob must be in [0, 1], got {self.frame_drop_prob}" + ) + if self.frame_drop_prob > 0.0: + if self.frame_drop_max_latent < self.frame_drop_min_latent: + raise ValueError( + "frame_drop_max_latent must be >= frame_drop_min_latent " + f"when frame_drop_prob > 0 (got max=" + f"{self.frame_drop_max_latent}, min={self.frame_drop_min_latent})" + ) + self.frame_drop_pad = nn.Parameter(torch.zeros(1, z_dim, 1, 1, 1)) + + # --- Utonia (PTv3) range-view alignment teacher (frozen) + projector --- + self.utonia_align = bool(utonia_align) + if self.utonia_align: + raise ValueError( + "Utonia alignment is not included in the public LidarVerse " + "range-tokenizer recipe" + ) + + self.hdmap_inject_stem = bool(hdmap_inject_stem) + self.hdmap_inject_raw_at_up_levels = ( + list(bool(b) for b in hdmap_inject_raw_at_up_levels) + if hdmap_inject_raw_at_up_levels is not None + else None + ) + # Whether the network needs an hdmap input at forward time at all. + self.uses_hdmap = self.hdmap_inject_stem or ( + self.hdmap_inject_raw_at_up_levels is not None + and any(self.hdmap_inject_raw_at_up_levels) + ) + + # Resolve the (possibly asymmetric) decoder topology. Defaults mirror + # the encoder so every existing config stays bit-identical. + _dec_depths = decoder_depths if decoder_depths is not None else depths + _dec_num_heads = ( + decoder_num_heads if decoder_num_heads is not None else num_heads + ) + _dec_dilation = decoder_dilation if decoder_dilation is not None else dilation + if decoder_depths is not None: + if decoder_temporal_upsample is None: + raise ValueError( + "decoder_depths is set (asymmetric decoder) so the encoder's " + "temporal schedule no longer has the matching length; pass " + "decoder_temporal_upsample with length " + f"len(decoder_depths) - 1 = {len(_dec_depths) - 1}." + ) + _dec_temporal_upsample = decoder_temporal_upsample + _dec_temporal_downsample = decoder_temporal_upsample + else: + _dec_temporal_upsample = temporal_upsample + _dec_temporal_downsample = temporal_downsample + + self.decoder = Decoder( + resolution=resolution, + out_channels=self._decoder_out_channels, + z_dim=z_dim, + base_channels=base_channels, + patch_size=patch_size, + out_patch_size=out_patch_size, + window_size=window_size, + depths=_dec_depths, + num_heads=_dec_num_heads, + dilation=_dec_dilation, + temporal_downsample=_dec_temporal_downsample, + temporal_upsample=_dec_temporal_upsample, + mlp_ratio=mlp_ratio, + dropout=dropout, + mapping_depth=mapping_depth, + positional_embedding=positional_embedding, + temporal_expand_wan_style=temporal_expand_wan_style, + hdmap_inject_stem=self.hdmap_inject_stem, + hdmap_inject_raw_at_up_levels=self.hdmap_inject_raw_at_up_levels, + hdmap_in_channels=in_channels, + bottleneck_3d=bottleneck_3d, + bottleneck_3d_max_t=bottleneck_3d_max_t, + bottleneck_3d_causal_time=bottleneck_3d_causal_time, + bottleneck_3d_rope=bottleneck_3d_rope, + temporal_mixer=temporal_mixer, + temporal_conv_kernel=temporal_conv_kernel, + activation_checkpointing=activation_checkpointing, + ) + self.supports_temporal_kv_cache = ( + not bottleneck_3d + and not any( + _dec_temporal_upsample + if _dec_temporal_upsample is not None + else _dec_temporal_downsample + ) + and temporal_mixer == "attention" + ) + self.supports_encoder_temporal_kv_cache = ( + not bottleneck_3d + and not any(temporal_downsample) + and temporal_mixer == "attention" + ) + + # Latent normalization stats for normalized-space noise + # augmentation. Buffers are normally non-persistent so they don't + # appear in the saved state_dict (the pretrained checkpoint doesn't + # carry them, and we want ``strict_resume=True`` to keep working). + # When EMA tracking is on we flip to persistent=True so the + # accumulated EMA state survives autoresume mid-run; this requires + # the warm-start config to use ``strict_resume=False`` (the + # pretrained ckpt won't have these keys). + self.has_latent_stats = False + _stats_persistent = self.latent_norm_noise_ema_momentum > 0.0 + if latent_stats_path is not None: + stats = torch.load( + latent_stats_path, map_location="cpu", weights_only=False + ) + if isinstance(stats, (tuple, list)): + latent_mean_t, latent_std_t = stats + elif isinstance(stats, dict): + latent_mean_t = stats["mean"] + latent_std_t = stats["std"] + else: + raise ValueError( + f"Unsupported latent_stats format at {latent_stats_path}: " + f"{type(stats)}" + ) + assert latent_mean_t.numel() == z_dim and latent_std_t.numel() == z_dim, ( + f"latent_stats must have z_dim={z_dim} entries, got " + f"mean={latent_mean_t.numel()}, std={latent_std_t.numel()}" + ) + target_shape = (1, z_dim, 1, 1, 1) + self.register_buffer( + "latent_mean", + latent_mean_t.float().reshape(*target_shape), + persistent=_stats_persistent, + ) + self.register_buffer( + "latent_std", + latent_std_t.float().reshape(*target_shape), + persistent=_stats_persistent, + ) + self.has_latent_stats = True + logger.info( + f"TransformerVAE: loaded latent_stats from {latent_stats_path} " + f"(latent_norm_noise_sigma={self.latent_norm_noise_sigma}, " + f"mode={self.latent_norm_noise_sigma_mode}, " + f"tau_max={self.latent_norm_noise_tau_max}, " + f"clean_prob={self.latent_norm_noise_clean_prob}, " + f"ema_momentum={self.latent_norm_noise_ema_momentum}, " + f"stats_persistent={_stats_persistent})" + ) + + if self.latent_norm_noise_sigma > 0: + assert self.has_latent_stats or not self.latent_norm_noise_use_normalization, ( + "latent_norm_noise_sigma > 0 requires either latent_stats_path " + "to be set (use_normalization=True) or " + "latent_norm_noise_use_normalization=False (DeTok-pure, " + "noise applied directly on the raw latent)." + ) + if not self.latent_norm_noise_use_normalization: + logger.info( + f"TransformerVAE: noise injection in RAW latent space " + f"(latent_norm_noise_use_normalization=False, " + f"sigma/gamma={self.latent_norm_noise_sigma}, " + f"mode={self.latent_norm_noise_sigma_mode})." + ) + + if self.freeze_encoder: + for p in self.encoder.parameters(): + p.requires_grad = False + for p in self.quant_conv.parameters(): + p.requires_grad = False + self.encoder.eval() + self.quant_conv.eval() + logger.info( + "TransformerVAE: encoder + quant_conv frozen (decoder-only fine-tuning)." + ) + + def train(self, mode: bool = True): + """Keep frozen submodules in eval mode regardless of model.train().""" + super().train(mode) + if self.freeze_encoder: + self.encoder.eval() + self.quant_conv.eval() + return self + + def adapt_warmstart_tensor( + self, + name: str, + source: torch.Tensor, + target: torch.Tensor, + ) -> torch.Tensor | None: + """Expand the z64 latent interface into a function-preserving z96 one.""" + source_dim = self.latent_warmstart_source_dim + if source_dim is None: + return None + + name = name.removeprefix("network.") + target_dim = self.z_dim + expanded = source.new_zeros(target.shape) + + if name == "encoder.head.1.weight": + if source.shape[0] != 2 * source_dim or target.shape[0] != 2 * target_dim: + raise ValueError(f"Unexpected latent head shapes: {source.shape} -> {target.shape}") + expanded[:source_dim] = source[:source_dim] + expanded[target_dim : target_dim + source_dim] = source[source_dim:] + elif name == "quant_conv.weight": + expected_source = (2 * source_dim, 2 * source_dim) + expected_target = (2 * target_dim, 2 * target_dim) + if source.shape[:2] != expected_source or target.shape[:2] != expected_target: + raise ValueError(f"Unexpected quant_conv shapes: {source.shape} -> {target.shape}") + expanded[:source_dim, :source_dim] = source[:source_dim, :source_dim] + expanded[:source_dim, target_dim : target_dim + source_dim] = source[ + :source_dim, source_dim: + ] + expanded[target_dim : target_dim + source_dim, :source_dim] = source[ + source_dim:, :source_dim + ] + expanded[ + target_dim : target_dim + source_dim, + target_dim : target_dim + source_dim, + ] = source[source_dim:, source_dim:] + elif name == "quant_conv.bias": + if source.shape[0] != 2 * source_dim or target.shape[0] != 2 * target_dim: + raise ValueError(f"Unexpected quant_conv bias shapes: {source.shape} -> {target.shape}") + expanded[:source_dim] = source[:source_dim] + expanded[target_dim : target_dim + source_dim] = source[source_dim:] + elif name == "post_quant_conv.weight": + if source.shape[:2] != (source_dim, source_dim) or target.shape[:2] != ( + target_dim, + target_dim, + ): + raise ValueError(f"Unexpected post_quant_conv shapes: {source.shape} -> {target.shape}") + expanded[:source_dim, :source_dim] = source + elif name == "post_quant_conv.bias": + if source.shape[0] != source_dim or target.shape[0] != target_dim: + raise ValueError( + f"Unexpected post_quant_conv bias shapes: {source.shape} -> {target.shape}" + ) + expanded[:source_dim] = source + elif name == "decoder.stem.1.weight": + if source.shape[1] != source_dim or target.shape[1] != target_dim: + raise ValueError(f"Unexpected decoder stem shapes: {source.shape} -> {target.shape}") + expanded[:, :source_dim] = source + else: + return None + + return expanded + + def _resolve_spatial_coords( + self, + reference: torch.Tensor, + spatial_coords: torch.Tensor | None, + spatial_shape: tuple[int, int] | None = None, + ) -> torch.Tensor: + coords = self.coords if spatial_coords is None else spatial_coords + expected_shape = spatial_shape or tuple(reference.shape[-2:]) + if tuple(coords.shape[-2:]) != tuple(expected_shape): + raise ValueError( + f"Coordinate grid {tuple(coords.shape[-2:])} does not match " + f"input grid {tuple(expected_shape)}" + ) + return coords.to(device=reference.device) + + def encode( + self, x: torch.Tensor, spatial_coords: torch.Tensor | None = None + ): + """ + Args: + x: (B, C, H, W) [single-frame] or (B, C, T, H, W) + Returns: + sample: (B, z_dim, T', H_z, W_z) + posteriors: (mu, log_var) each (B, z_dim, T', H_z, W_z) + """ + # Single-frame (image) input: add a T=1 axis so the video encoder + # path works unchanged. The causal temporal ops degrade gracefully + # at T=1 (TemporalMerging pads -> kernel-3 stride-2 -> T stays 1) and + # ``decode()`` squeezes the axis back. ``_input_T`` records T so the + # decode crop / squeeze stay consistent. + if x.ndim == 4: + x = x.unsqueeze(2) # (B, C, H, W) -> (B, C, 1, H, W) + self._input_T = x.shape[2] + self._input_spatial_shape = tuple(x.shape[-2:]) + coords = self._resolve_spatial_coords(x, spatial_coords) + encoder_amp = ( + torch.autocast("cuda", dtype=self._encoder_autocast_dtype) + if self._encoder_autocast_dtype is not None + and x.device.type == "cuda" + else contextlib.nullcontext() + ) + with encoder_amp: + parameters = self.encoder( + x, coords + ) # (B, z_dim*2, T', H_z, W_z) + + # quant_conv is 2D — apply per-frame + B, C2, Tz, Hz, Wz = parameters.shape + parameters = einops.rearrange( + parameters, "B C T H W -> (B T) C H W" + ) + parameters = self.quant_conv(parameters) + parameters = einops.rearrange( + parameters, "(B T) C H W -> B C T H W", B=B, T=Tz + ) + if self._encoder_autocast_dtype is not None: + parameters = parameters.float() + + sample, (mu, log_var) = self.distribution(parameters, split=True) + + # Global Skip Connection: fold the raw input pixels into the latent as + # a residual so high-frequency signal lives IN z (diffusion-safe). + if self.global_skip: + sample = sample + self._global_skip_residual(x, sample) + + return sample, (mu, log_var) + + def encode_stream( + self, + x_new: torch.Tensor, + temporal_kv_cache: dict[ + str, tuple[torch.Tensor, torch.Tensor] + ] | None = None, + max_cache_frames: int | None = None, + spatial_coords: torch.Tensor | None = None, + ): + """Encode newly appended frames using causal encoder KV caches.""" + if x_new.ndim != 5: + raise ValueError( + f"streaming encode requires (B,C,T,H,W), got {x_new.shape}" + ) + if not self.supports_encoder_temporal_kv_cache: + raise NotImplementedError( + "this TransformerVAE topology does not support streaming encode" + ) + self._input_spatial_shape = tuple(x_new.shape[-2:]) + coords = self._resolve_spatial_coords(x_new, spatial_coords) + parameters, new_cache = self.encoder.forward_stream( + x_new, + coords, + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + ) + B, C2, Tz, Hz, Wz = parameters.shape + parameters = einops.rearrange( + parameters, "B C T H W -> (B T) C H W" + ) + parameters = self.quant_conv(parameters) + parameters = einops.rearrange( + parameters, + "(B T) C H W -> B C T H W", + B=B, + T=Tz, + ) + sample, (mu, log_var) = self.distribution(parameters, split=True) + if self.global_skip: + sample = sample + self._global_skip_residual(x_new, sample) + return (sample, (mu, log_var)), new_cache + + def _global_skip_residual(self, x: torch.Tensor, z: torch.Tensor) -> torch.Tensor: + """Qwen-VAE-2.0 GSC residual (arxiv:2605.13565). + + Space-to-channel (pixel-unshuffle) fold of the encoder input ``x`` down + to the latent grid, then a 1x1 projection to ``z_dim``. Returned as the + residual to add to the sampled latent ``z``. + + Args: + x: (B, C_in, T, H, W) encoder input (already mask-concatenated when + ``mask_as_input`` is on). + z: (B, z_dim, Tz, Hz, Wz) sampled latent (for target shape). + Returns: + (B, z_dim, Tz, Hz, Wz) residual. + + The spatial fold is lossless (the GSC essence). The temporal axis is + aligned by adaptive avg-pool when ``T != Tz`` (identity for the + single-frame stage where T == Tz == 1); a more faithful causal temporal + fold can be revisited for the video stage. + """ + B, _, T, H, W = x.shape + Tz, Hz, Wz = z.shape[2], z.shape[3], z.shape[4] + ph, pw = H // Hz, W // Wz + xf = einops.rearrange( + x, "B C T (h ph) (w pw) -> B (C ph pw) T h w", ph=ph, pw=pw + ) + if T != Tz: + xf = F.adaptive_avg_pool3d(xf, output_size=(Tz, Hz, Wz)) + xf = einops.rearrange(xf, "B C T h w -> (B T) C h w") + g = self.gsc_proj(xf) + g = einops.rearrange(g, "(B T) C h w -> B C T h w", B=B, T=Tz) + return g + + def _utonia_vf_loss(self, sample: torch.Tensor, x: torch.Tensor) -> torch.Tensor: + """VA-VAE VF loss (arXiv:2501.01423) in RANGE-VIEW, minus adaptive weighting. + + Run the frozen PTv3 teacher on the input depth, masked-pool its per-pixel + features to the latent grid (teacher already lives in the same elevation x + azimuth frame as the range-image latent, so no BEV scatter), then sum: + + * mcos (Eq. 2): per-position ReLU(1 - m1 - cos(z'_ij, f_ij)), z' = W z + (linear ``utonia_proj``). Element-wise / point-to-point alignment. + * mdms (Eq. 3): pairwise ReLU(|cos(z_i,z_j) - cos(f_i,f_j)| - m2) on the + RAW latent self-similarity matrix vs the teacher's. Relative-structure + alignment. Computed per (batch, frame) over the H*W latent positions. + + Both terms are averaged over VALID positions/pairs only (lidar range maps + are sparse: no-return pixels have no teacher feature). Returns a scalar + (= mcos + mdms); the overall w_hyper is applied by the ``repa_align`` loss + weight, and the adaptive gradient-ratio weighting is omitted by design. + + Args: + sample: (B, z, Tz, Hz, Wz) clean encoder latent. + x: (B, C, T, H, W) encoder input (channel 0 = normalized depth). + """ + depth = x[:, :1] # (B, 1, [T,] H, W) normalized range + # Explicit GT validity (raydrop) mask, so the teacher never builds + # points at no-return pixels. With ``mask_as_input`` the appended 2nd + # channel IS that mask (1 == return); otherwise derive it from the same + # ``depth > min_value + eps`` threshold the validity BCE uses. + if self.mask_as_input and x.shape[1] >= 2: + vmask = x[:, 1:2] + else: + vmask = ( + depth > (self.mask_input_min_value + self.mask_input_eps) + ).to(depth.dtype) + # ``sample`` is always 5D (encode() unsqueezes single-frame T=1), but the + # raw input ``x`` may be 4D (image dataset). Force depth to 5D so the + # teacher returns 5D and ``adaptive_avg_pool3d`` pools T (not the feature + # channels) -- a 4D input is silently treated as unbatched (C,D,H,W). + if depth.ndim == 4: + depth = depth.unsqueeze(2) # (B, 1, 1, H, W) + vmask = vmask.unsqueeze(2) + + # Optional FRAME subsampling: supervise only K random frames per clip. + # Slices the input (saving K/T of the PTv3 forwards) AND the latent, so + # only requires the latent/input frame counts to match (no temporal + # compression). Skipped for single-frame / when K >= T. + K = getattr(self, "vf_supervise_frames", 0) + if K and K < depth.shape[2]: + T_in = depth.shape[2] + if sample.shape[2] != T_in: + raise ValueError( + f"vf_supervise_frames requires latent T ({sample.shape[2]}) == " + f"input T ({T_in}); not supported with temporal compression." + ) + idx = torch.randperm(T_in, device=depth.device)[:K].sort().values + depth = depth[:, :, idx].contiguous() + vmask = vmask[:, :, idx].contiguous() + sample = sample[:, :, idx].contiguous() + + B, _, Tz, Hz, Wz = sample.shape + # Run the teacher at a coarser azimuth (point count ~ H*W drives the + # PTv3 + CPU GridSample cost). Nearest-exact on W only; rows (beams) + # untouched. depth/vmask are (B, 1, T, H, W) here. + tw = getattr(self, "utonia_teacher_width", depth.shape[-1]) + if tw and tw != depth.shape[-1]: + Bd, _, Td, Hd, _ = depth.shape + depth = F.interpolate( + depth.reshape(Bd * Td, 1, Hd, depth.shape[-1]), + size=(Hd, tw), mode="nearest-exact", + ).reshape(Bd, 1, Td, Hd, tw) + vmask = F.interpolate( + vmask.reshape(Bd * Td, 1, Hd, vmask.shape[-1]), + size=(Hd, tw), mode="nearest-exact", + ).reshape(Bd, 1, Td, Hd, tw) + # Teacher features + masked spatial pool to the latent grid, done ONE + # INPUT FRAME AT A TIME and in bf16. The dense teacher map is + # (B, D~1224, T, H, W): at full res that's ~3 GB/frame in fp32, and the + # ``abs().sum`` / ``* tvalid`` temps each spawn another copy -> the + # multi-frame version OOMs. Per-frame + bf16 bounds the peak to one + # frame; everything here is a frozen, detached TARGET so no autograd + # buffers are kept. Each frame is spatially pooled to (Hz, Wz) first + # (cheap output), then the small stack is temporally pooled T_in -> Tz + # (identity when there's no temporal compression). + pool_dtype = torch.bfloat16 + T_in = depth.shape[2] + with torch.no_grad(): + f_parts: list[torch.Tensor] = [] + v_parts: list[torch.Tensor] = [] + for t in range(T_in): + teacher_t = self.utonia( + depth[:, :, t:t + 1], valid_mask=vmask[:, :, t:t + 1] + ) # (B, D, 1, H, W), 0 at invalid + if teacher_t.ndim == 4: + teacher_t = teacher_t.unsqueeze(2) + teacher_t = teacher_t.to(pool_dtype) + tvalid_t = ( + teacher_t.abs().sum(dim=1, keepdim=True) > 0 + ).to(pool_dtype) # (B, 1, 1, H, W) + num_t = F.adaptive_avg_pool3d(teacher_t * tvalid_t, (1, Hz, Wz)) + den_t = F.adaptive_avg_pool3d(tvalid_t, (1, Hz, Wz)) + f_parts.append(num_t / den_t.clamp_min(1e-6)) # (B, D, 1, Hz, Wz) + v_parts.append(den_t) # (B, 1, 1, Hz, Wz) valid frac + del teacher_t, tvalid_t, num_t, den_t + f_hi = torch.cat(f_parts, dim=2) # (B, D, T_in, Hz, Wz) + v_hi = torch.cat(v_parts, dim=2) # (B, 1, T_in, Hz, Wz) + # Temporal pool T_in -> Tz (identity when T_in == Tz), validity-weighted. + num = F.adaptive_avg_pool3d(f_hi * v_hi, (Tz, Hz, Wz)) + den = F.adaptive_avg_pool3d(v_hi, (Tz, Hz, Wz)) + f_grid = (num / den.clamp_min(1e-6)).to(sample.dtype) # (B, D, Tz, Hz, Wz) + valid = (den > 0).to(sample.dtype) # (B, 1, Tz, Hz, Wz) + f_grid = f_grid.detach() + valid = valid.detach() + + # Fold (batch, frame) so each "image" is one (C, Hz, Wz) latent frame. + z = einops.rearrange(sample, "B C T H W -> (B T) C H W") + f = einops.rearrange(f_grid, "B C T H W -> (B T) C H W") + m = einops.rearrange(valid, "B C T H W -> (B T) C H W") # (M, 1, Hz, Wz) + M = z.shape[0] + + # ---- mcos (Eq. 2): point-to-point cosine, projected latent z' = W z ---- + z_proj = self.utonia_proj(z) # (M, D, Hz, Wz) + z_proj = F.normalize(z_proj, dim=1) + f_n = F.normalize(f, dim=1) + cos = (z_proj * f_n).sum(dim=1, keepdim=True) # (M, 1, Hz, Wz) + mcos_pix = F.relu(1.0 - self.vf_margin_cos - cos) * m + loss_mcos = mcos_pix.sum() / m.sum().clamp_min(1.0) + + # ---- mdms (Eq. 3): self-similarity matrices on RAW z vs teacher f ---- + N = Hz * Wz + zf = einops.rearrange(z, "M C H W -> M (H W) C") + ff = einops.rearrange(f, "M C H W -> M (H W) C") + mf = einops.rearrange(m, "M C H W -> M (H W) C").squeeze(-1) # (M, N) + zf = F.normalize(zf, dim=-1) + ff = F.normalize(ff, dim=-1) + + win = getattr(self, "vf_mdms_window", (0, 0)) + wh, ww = int(win[0]), int(win[1]) + S = getattr(self, "vf_mdms_max_tokens", 0) + if wh > 0 and ww > 0: + # LOCAL-WINDOW block mdms: tile (Hz, Wz) into (wh, ww) patches and + # only match token PAIRS inside the same patch -> block-diagonal + # (M*nh*nw, P, P), P = wh*ww. Pairs stay spatially local. + if Hz % wh != 0 or Wz % ww != 0: + raise ValueError( + f"vf_mdms_window {(wh, ww)} must tile the latent grid " + f"({Hz}x{Wz}); got Hz%wh={Hz % wh}, Wz%ww={Wz % ww}." + ) + zw = einops.rearrange( + z, "M C (nh wh) (nw ww) -> (M nh nw) (wh ww) C", wh=wh, ww=ww + ) + fw = einops.rearrange( + f, "M C (nh wh) (nw ww) -> (M nh nw) (wh ww) C", wh=wh, ww=ww + ) + mw = einops.rearrange( + m, "M C (nh wh) (nw ww) -> (M nh nw) (wh ww) C", wh=wh, ww=ww + ).squeeze(-1) # (Mw, P) + zw = F.normalize(zw, dim=-1) + fw = F.normalize(fw, dim=-1) + z_sim = torch.bmm(zw, zw.transpose(1, 2)) # (Mw, P, P) + f_sim = torch.bmm(fw, fw.transpose(1, 2)) + pair_mask = mw.unsqueeze(2) * mw.unsqueeze(1) # both valid in-window + mdms_pair = F.relu((z_sim - f_sim).abs() - self.vf_margin_dist) * pair_mask + loss_mdms = mdms_pair.sum() / pair_mask.sum().clamp_min(1.0) + elif S and S < N: + # Subsample S random VALID tokens per frame so the matrix is + # (M, S, S) instead of (M, N, N). Sampling weight = validity; for an + # all-invalid frame fall back to uniform and zero its loss. Sampling + # with replacement is fine: duplicate (i,i) pairs have |Δcos|=0 and + # are killed by the m2 margin, so they contribute nothing. + probs = mf.float() + empty = probs.sum(dim=1, keepdim=True) <= 0 # (M, 1) + probs = probs + empty.float() # uniform if empty + idx = torch.multinomial(probs, S, replacement=True) # (M, S) + gidx = idx.unsqueeze(-1).expand(-1, -1, zf.shape[-1]) + zf = torch.gather(zf, 1, gidx) # (M, S, C) + ff = torch.gather(ff, 1, gidx) + z_sim = torch.bmm(zf, zf.transpose(1, 2)) # (M, S, S) + f_sim = torch.bmm(ff, ff.transpose(1, 2)) + mdms_pair = F.relu((z_sim - f_sim).abs() - self.vf_margin_dist) + frame_w = (~empty).to(mdms_pair.dtype).view(-1, 1, 1) # drop empty frames + mdms_pair = mdms_pair * frame_w + loss_mdms = mdms_pair.sum() / frame_w.expand_as(mdms_pair).sum().clamp_min(1.0) + else: + z_sim = torch.bmm(zf, zf.transpose(1, 2)) # (M, N, N) cos(z_i,z_j) + f_sim = torch.bmm(ff, ff.transpose(1, 2)) # (M, N, N) cos(f_i,f_j) + pair_mask = mf.unsqueeze(2) * mf.unsqueeze(1) # (M, N, N) both valid + mdms_pair = F.relu((z_sim - f_sim).abs() - self.vf_margin_dist) * pair_mask + loss_mdms = mdms_pair.sum() / pair_mask.sum().clamp_min(1.0) + + return loss_mcos + loss_mdms + + def decode( + self, + z: torch.Tensor, + hdmap_z: torch.Tensor | None = None, + hdmap_raw: torch.Tensor | None = None, + return_validity: bool = False, + spatial_coords: torch.Tensor | None = None, + ): + """ + Args: + z: (B, z_dim, T', H_z, W_z) + hdmap_z: optional (B, z_dim, T', H_z, W_z) hdmap latent for the V1 + stem-concat injection. Caller is responsible for passing the + already-encoded hdmap latent (typically obtained by running + the raw hdmap through the same frozen ``self.encoder`` -- + see ``TransformerVAE.forward`` for the reference plumbing). + hdmap_raw: optional (B, in_channels, T, H, W) raw hdmap video + for the V3 per-up-level injections. + Returns: + (B, C, T, H, W) — cropped to original T if temporal padding was used + """ + # post_quant_conv is 2D — apply per-frame + B, Cz, Tz, Hz, Wz = z.shape + z = einops.rearrange(z, "B C T H W -> (B T) C H W") + z = self.post_quant_conv(z) + z = einops.rearrange(z, "(B T) C H W -> B C T H W", B=B, T=Tz) + + coords = self._resolve_spatial_coords( + z, + spatial_coords, + spatial_shape=getattr( + self, "_input_spatial_shape", tuple(self.resolution) + ), + ) + out = self.decoder( + z, + coords, + hdmap_z=hdmap_z, + hdmap_raw=hdmap_raw, + ) + + # Crop to original temporal length if padding was applied during encoding + if hasattr(self, "_input_T") and out.shape[2] > self._input_T: + out = out[:, :, -self._input_T :] + + # Single-frame input: drop the T=1 axis so the output matches the 4D + # (B, C, H, W) recon target produced by the image dataloader path. + if getattr(self, "_input_T", None) == 1: + out = out.squeeze(2) + + # Split off the validity-logit channel (last) when enabled. By default + # decode returns only the data channels so all existing call sites + # (inference, callbacks, DiT) are unaffected. + if self.predict_validity: + recon = out[:, : self.out_channels] + validity_logits = out[:, self.out_channels :] + if return_validity: + return recon, validity_logits + return recon + if return_validity: + return out, None + return out + + def decode_stream( + self, + z_new: torch.Tensor, + temporal_kv_cache: dict[ + str, tuple[torch.Tensor, torch.Tensor] + ] | None = None, + hdmap_z: torch.Tensor | None = None, + hdmap_raw: torch.Tensor | None = None, + return_validity: bool = False, + max_cache_frames: int | None = None, + spatial_coords: torch.Tensor | None = None, + ): + """Decode only newly appended latent frames using temporal KV caches. + + This path is exact for the 1x-temporal, attention-based causal decoder: + spatial blocks and projections run only on ``z_new`` while every + temporal-attention layer attends to its cached prefix plus the causal + portion of this new block. + """ + B, _, T_new, _, _ = z_new.shape + z_new = einops.rearrange( + z_new, "B C T H W -> (B T) C H W" + ) + z_new = self.post_quant_conv(z_new) + z_new = einops.rearrange( + z_new, "(B T) C H W -> B C T H W", B=B, T=T_new + ) + coords = self._resolve_spatial_coords( + z_new, + spatial_coords, + spatial_shape=getattr( + self, "_input_spatial_shape", tuple(self.resolution) + ), + ) + out, new_cache = self.decoder( + z_new, + coords, + hdmap_z=hdmap_z, + hdmap_raw=hdmap_raw, + temporal_kv_cache=temporal_kv_cache, + return_temporal_kv_cache=True, + max_cache_frames=max_cache_frames, + ) + + if self.predict_validity: + recon = out[:, : self.out_channels] + validity_logits = out[:, self.out_channels :] + if return_validity: + return (recon, validity_logits), new_cache + return recon, new_cache + if return_validity: + return (out, None), new_cache + return out, new_cache + + @torch.no_grad() + def _update_latent_stats_ema(self, z0: torch.Tensor) -> None: + """In-place EMA update of ``latent_mean`` / ``latent_std`` from z0. + + ``z0`` is the raw encoder output (B, z_dim, T, H, W), BEFORE any + normalization. We compute per-channel batch mean and std by + reducing over (B, T, H, W), all-reduce across DDP ranks so every + rank tracks the same world-wide stats, and then in-place EMA- + update the persistent buffers with momentum + ``self.latent_norm_noise_ema_momentum``. + + Notes + ----- + * Run under ``torch.no_grad()`` -- the stats are normalization + constants, not parameters; no gradient flows through them. + * Uses ``var(unbiased=False)`` so the estimator matches an MLE + (consistent with the empirical std used by + ``scripts/compute_mean_std.py``). + * The reduce shape ``(0, 2, 3, 4)`` keeps the channel axis, + matching the registered buffer shape ``(1, z_dim, 1, 1, 1)``. + * DDP all-reduce uses ``op=AVG`` so the global stat is the mean + of the per-rank micro-batch stats; this is the right answer + when batches per rank are equally sized (the usual case). + """ + # Per-channel batch stats, shape (1, C, 1, 1, 1). + reduce_dims = (0, 2, 3, 4) + batch_mean = z0.mean(dim=reduce_dims, keepdim=True).float() + batch_var = z0.var(dim=reduce_dims, keepdim=True, unbiased=False).float() + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(batch_mean, op=dist.ReduceOp.AVG) + dist.all_reduce(batch_var, op=dist.ReduceOp.AVG) + + batch_std = (batch_var + 1e-6).sqrt() + + m = self.latent_norm_noise_ema_momentum + self.latent_mean.mul_(m).add_((1.0 - m) * batch_mean) + self.latent_std.mul_(m).add_((1.0 - m) * batch_std) + + def forward( + self, + x: torch.Tensor, + hdmap: torch.Tensor | None = None, + valid_mask: torch.Tensor | None = None, + spatial_coords: torch.Tensor | None = None, + ): + """ + Args: + x: (B, C, T, H, W) + hdmap: optional (B, C, T, H, W) hdmap video at the same temporal + length as ``x``. When the network was built with any of the + hdmap injection flags (``hdmap_inject_stem`` / + ``hdmap_inject_raw_at_up_levels``), this is the conditioning + signal. When provided AND ``hdmap_inject_stem=True``, the + hdmap is encoded through the same ``self.encoder`` / + ``self.quant_conv`` (under ``torch.no_grad``) to produce + ``hdmap_z`` aligned with ``z``; this is causally aligned by + construction (same encoder = same temporal kernel + first- + frame anchor convention). The raw hdmap is forwarded as-is + to the decoder for V3 per-up-level injections. When ``hdmap`` + is None or all injection flags are off, this argument is + silently ignored (preserves ``forward(x)`` backward + compatibility for non-hdmap configs). + """ + if self.mask_as_input: + # Append the validity mask as an extra input channel so the + # 2-channel [depth, mask] input matches the [depth_recon, + # validity_logit] 2-channel output. Prefer an externally-provided + # mask (``valid_mask``, computed by the dataloader BEFORE per-row + # normalization) since deriving it from ``depth > min_value + eps`` + # is wrong once per-row z-scoring shifts the sentinel. Fall back to + # the derived mask (same threshold the BCE loss uses) when no + # explicit mask is supplied -> existing mask configs unchanged. + if valid_mask is not None: + valid = valid_mask.to(x.dtype) + else: + valid = ( + x[:, :1] > (self.mask_input_min_value + self.mask_input_eps) + ).to(x.dtype) + x = torch.cat([x, valid], dim=1) + + if self.freeze_encoder: + # Detach the encode pathway from autograd: posteriors/sample + # carry no gradient, KL loss becomes a no-op w.r.t. params. + with torch.no_grad(): + sample, posteriors = self.encode(x, spatial_coords=spatial_coords) + sample = sample.detach() + posteriors = tuple(p.detach() for p in posteriors) + else: + sample, posteriors = self.encode(x, spatial_coords=spatial_coords) + + # Encode the hdmap through the same encoder if any of the V1 + # injection paths is wired up. Always under ``torch.no_grad`` -- + # the typical use-case freezes the encoder, and even if it didn't + # we don't want hdmap-encoding gradients flowing through and + # changing the encoder's marginal. The ``encode()`` call mutates + # ``self._input_T``, so save/restore around it to leave the lidar + # path's value intact (decode() consumes ``_input_T`` for cropping). + hdmap_z = None + if hdmap is not None and self.hdmap_inject_stem: + saved_input_T = getattr(self, "_input_T", None) + with torch.no_grad(): + hdmap_z, _ = self.encode(hdmap, spatial_coords=spatial_coords) + hdmap_z = hdmap_z.detach() + if saved_input_T is not None: + self._input_T = saved_input_T + + z = sample + # Per-sample interpolative noise level (shape (B,)), exposed to the + # loss so a temporal-smoothness term can ramp its weight with the + # noise level. None when no interpolative noise was applied. + noise_tau = None + if self.training: + # Online EMA update of (latent_mean, latent_std) on the RAW + # encoder output. Runs before normalization so the buffers + # track the encoder's true marginal -- not the post-normalize + # tensor (which would always look ~N(0, 1) by construction + # and tell us nothing). + if ( + self.latent_norm_noise_ema_momentum > 0.0 + and self.has_latent_stats + and self.latent_norm_noise_use_normalization + ): + self._update_latent_stats_ema(z) + if self.latent_norm_noise_sigma > 0 and ( + self.has_latent_stats or not self.latent_norm_noise_use_normalization + ): + # Latent-space noise augmentation. Two variants: + # use_normalization=True (default, requires latent_stats): + # encode -> normalize -> corrupt -> denormalize -> decode + # use_normalization=False (DeTok-pure): + # encode -> corrupt -> decode (no normalize/denormalize) + # The corruption formula is identical in both spaces; only the + # reference frame differs. + if self.latent_norm_noise_use_normalization: + latent_mean = self.latent_mean.to(z) + latent_std = self.latent_std.to(z) + z_work = (z - latent_mean) / latent_std + else: + z_work = z + + if self.latent_norm_noise_sigma_mode == "interpolative": + # DeTok: z' = (1−τ)·z + τ·γ·ε, τ ~ U(0, τ_max) per sample. + # Full signal replacement at τ=1 prevents the additive + # shortcut. γ = self.latent_norm_noise_sigma. + # τ_max < 1 restricts to low-noise regime (LTX-style range). + tau_shape = (z_work.shape[0],) + (1,) * (z_work.dim() - 1) + tau = torch.rand( + tau_shape, device=z_work.device, dtype=z_work.dtype + ) * self.latent_norm_noise_tau_max + if self.latent_norm_noise_clean_prob > 0.0: + # Mixed clean / noisy regime: with probability + # `clean_prob`, force τ=0 for the sample so the + # decoder also sees clean latents during FT. Keeps + # the τ=0 manifold sharp while still training the + # low-τ denoising pathway. + clean_mask = torch.rand( + tau_shape, device=z_work.device, dtype=z_work.dtype + ) < self.latent_norm_noise_clean_prob + tau = torch.where(clean_mask, torch.zeros_like(tau), tau) + eps = self.latent_norm_noise_sigma * torch.randn_like(z_work) + z_work = (1.0 - tau) * z_work + tau * eps + noise_tau = tau.reshape(tau.shape[0]) + elif self.latent_norm_noise_sigma_mode == "uniform": + # Per-sample sigma ~ U(0, sigma_max). Shape (B,1,1,1,1) + # broadcasts over (C, T, H, W). Each batch element sees + # a different noise level; expected sigma is sigma_max/2. + sigma_shape = (z_work.shape[0],) + (1,) * (z_work.dim() - 1) + sigma = torch.rand( + sigma_shape, device=z_work.device, dtype=z_work.dtype + ) * self.latent_norm_noise_sigma + z_work = z_work + sigma * torch.randn_like(z_work) + else: # "fixed" + z_work = z_work + self.latent_norm_noise_sigma * torch.randn_like(z_work) + + if self.latent_norm_noise_use_normalization: + z = z_work * latent_std + latent_mean + else: + z = z_work + elif self.noise_aug_sigma > 0: + z = z + self.noise_aug_sigma * torch.randn_like(z) + + # PV-VAE predictive frame dropping: replace trailing latent + # frames with the learnable pad token (per sample). Applied + # AFTER noise so pad tokens are never noised. Decode then + # reconstructs the full video, predicting the withheld future. + if self.frame_drop_prob > 0.0 and self.frame_drop_max_latent > 0: + Bz, _, Tlat = z.shape[0], z.shape[1], z.shape[2] + # Keep at least 1 latent frame; cap the drop at Tlat - 1. + max_k = min(self.frame_drop_max_latent, Tlat - 1) + if max_k >= self.frame_drop_min_latent: + do_drop = ( + torch.rand(Bz, device=z.device) < self.frame_drop_prob + ) + k = torch.randint( + self.frame_drop_min_latent, max_k + 1, + (Bz,), device=z.device, + ) + keep = torch.where( + do_drop, Tlat - k, torch.full_like(k, Tlat) + ) # (B,) number of leading latents to keep + pos = torch.arange(Tlat, device=z.device)[None, :] + replace = (pos >= keep[:, None]) # (B, Tlat) True => pad + replace = replace[:, None, :, None, None] + z = torch.where(replace, self.frame_drop_pad.to(z.dtype), z) + + # Pass hdmap through to decode for V1 (hdmap_z) and/or V3 (hdmap_raw) + # injection paths. Both args are silently ignored by the decoder when + # the corresponding injection flag is off, so this is safe for the + # default no-hdmap configuration. + decoded = self.decode( + z, + hdmap_z=hdmap_z, + hdmap_raw=hdmap, + return_validity=self.predict_validity, + spatial_coords=spatial_coords, + ) + if self.predict_validity: + recon, validity_logits = decoded + else: + recon, validity_logits = decoded, None + if self.training: + out_dict = dict( + reconstructions=recon, + posteriors=posteriors, + latent=sample, + ) + if noise_tau is not None: + out_dict["noise_tau"] = noise_tau + if validity_logits is not None: + out_dict["validity_logits"] = validity_logits + # VA-VAE VF-loss alignment on the CLEAN encoder latent (encoder-side + # regularization; the noised/frame-dropped ``z`` is a decoder trick). + if self.utonia_align: + out_dict["repa_align"] = self._utonia_vf_loss(sample, x) + return out_dict + return NetworkEval( + reconstructions=recon, + posteriors=posteriors, + latent=sample, + validity_logits=validity_logits, + ) + + +# ========================================================================= +# Model factory helpers & registry +# ========================================================================= + + +def _make_tvae(defaults: dict, **kwargs): + """Merge caller kwargs on top of preset defaults, then build TransformerVAE.""" + for d in (defaults, kwargs): + if "patch_size" in d: + ps = d["patch_size"] + if isinstance(ps, int): + d["patch_size"] = (ps, ps) + elif isinstance(ps, list): + d["patch_size"] = tuple(ps) + defaults.update(kwargs) + return TransformerVAE(**defaults) + + +def TransformerVAE_S(**kwargs): + return _make_tvae(dict( + base_channels=64, + depths=[2, 2, 2, 2], + num_heads=[2, 4, 4, 8], + temporal_downsample=[True, False, False], + mlp_ratio=3.0, + mapping_depth=2, + ), **kwargs) + + +def TransformerVAE_B(**kwargs): + return _make_tvae(dict( + base_channels=128, + depths=[3, 3, 3, 3], + num_heads=[2, 4, 8, 16], + temporal_downsample=[True, False, False], + mlp_ratio=3.0, + mapping_depth=2, + ), **kwargs) + + +def TransformerVAE_L(**kwargs): + return _make_tvae(dict( + base_channels=192, + depths=[4, 4, 4, 4], + num_heads=[3, 6, 12, 24], + temporal_downsample=[True, False, False], + mlp_ratio=3.0, + mapping_depth=2, + ), **kwargs) + + +TransformerVAE_models = { + "TransformerVAE-S": TransformerVAE_S, + "TransformerVAE-B": TransformerVAE_B, + "TransformerVAE-L": TransformerVAE_L, +} diff --git a/tokenizer/networks/transformers/transformer_vae_cross_dataset.py b/tokenizer/networks/transformers/transformer_vae_cross_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..d15ef74f941f490ebe5692e07fb9d545d1788efd --- /dev/null +++ b/tokenizer/networks/transformers/transformer_vae_cross_dataset.py @@ -0,0 +1,517 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Dynamic-shape TransformerVAE with sensor-agnostic image-grid coordinates.""" + +import numpy as np +import torch +from torch import nn + +from tokenizer.networks.transformers.transformer_vae import ( + LearnablePositionalEmbedding, + TransformerVAE, +) +from tokenizer.networks.transformers.encoding import generate_polar_coords + + +class CrossDatasetTransformerVAE(TransformerVAE): + """Cross-dataset VAE whose network sees only normalized image-grid RoPE.""" + + uses_sensor_metadata = False + + @staticmethod + def _coords_from_grid( + height: int, width: int, device: torch.device + ) -> torch.Tensor: + return generate_polar_coords(height, width, device=device) + + def _network_coords( + self, height: int, width: int, device: torch.device + ) -> torch.Tensor: + return self._coords_from_grid(height, width, device) + + def encode( + self, x: torch.Tensor, spatial_coords: torch.Tensor | None = None + ): + if spatial_coords is None: + spatial_coords = self._network_coords( + x.shape[-2], x.shape[-1], x.device + ) + return super().encode(x, spatial_coords=spatial_coords) + + def encode_stream( + self, + x_new: torch.Tensor, + temporal_kv_cache: dict[ + str, tuple[torch.Tensor, torch.Tensor] + ] | None = None, + max_cache_frames: int | None = None, + spatial_coords: torch.Tensor | None = None, + ): + if spatial_coords is None: + spatial_coords = self._network_coords( + x_new.shape[-2], x_new.shape[-1], x_new.device + ) + return super().encode_stream( + x_new, + temporal_kv_cache=temporal_kv_cache, + max_cache_frames=max_cache_frames, + spatial_coords=spatial_coords, + ) + + def decode( + self, + z: torch.Tensor, + hdmap_z: torch.Tensor | None = None, + hdmap_raw: torch.Tensor | None = None, + return_validity: bool = False, + spatial_coords: torch.Tensor | None = None, + ): + if spatial_coords is None: + height, width = getattr( + self, "_input_spatial_shape", tuple(self.resolution) + ) + spatial_coords = self._network_coords( + height, width, z.device + ) + return super().decode( + z, + hdmap_z=hdmap_z, + hdmap_raw=hdmap_raw, + return_validity=return_validity, + spatial_coords=spatial_coords, + ) + + def decode_stream( + self, + z_new: torch.Tensor, + temporal_kv_cache: dict[ + str, tuple[torch.Tensor, torch.Tensor] + ] | None = None, + hdmap_z: torch.Tensor | None = None, + hdmap_raw: torch.Tensor | None = None, + return_validity: bool = False, + max_cache_frames: int | None = None, + spatial_coords: torch.Tensor | None = None, + ): + if spatial_coords is None: + height, width = getattr( + self, "_input_spatial_shape", tuple(self.resolution) + ) + spatial_coords = self._network_coords( + height, width, z_new.device + ) + return super().decode_stream( + z_new, + temporal_kv_cache=temporal_kv_cache, + hdmap_z=hdmap_z, + hdmap_raw=hdmap_raw, + return_validity=return_validity, + max_cache_frames=max_cache_frames, + spatial_coords=spatial_coords, + ) + + def forward( + self, + x: torch.Tensor, + valid_mask: torch.Tensor | None = None, + **kwargs, + ): + coords = self._network_coords( + x.shape[-2], x.shape[-1], x.device + ) + return super().forward( + x, + valid_mask=valid_mask, + spatial_coords=coords, + **kwargs, + ) + + +class DatasetEmbeddingCrossDatasetTransformerVAE( + CrossDatasetTransformerVAE +): + """Image-grid RoPE VAE with an additive input map per dataset.""" + + uses_dataset_id = True + + def __init__( + self, + *args, + dataset_embedding_shapes: tuple[tuple[int, int], ...], + dataset_embedding_channels: int, + spatial_rope: bool = True, + **kwargs, + ): + super().__init__(*args, **kwargs) + self.dataset_embedding_shapes = tuple( + tuple(shape) for shape in dataset_embedding_shapes + ) + self.dataset_embedding_channels = int(dataset_embedding_channels) + self.spatial_rope = bool(spatial_rope) + self.dataset_embeddings = nn.ParameterList( + [ + nn.Parameter( + torch.zeros( + 1, + self.dataset_embedding_channels, + height, + width, + ) + ) + for height, width in self.dataset_embedding_shapes + ] + ) + + def _network_coords( + self, height: int, width: int, device: torch.device + ) -> torch.Tensor: + if self.spatial_rope: + return super()._network_coords(height, width, device) + # Every AxialRoPE angle is zero, making all Q/K rotations identity. + return torch.zeros(1, 2, height, width, device=device) + + @staticmethod + def _homogeneous_dataset_id( + sensor_dataset_id: torch.Tensor | int, + ) -> int: + if isinstance(sensor_dataset_id, int): + return sensor_dataset_id + unique_ids = torch.unique(sensor_dataset_id) + if unique_ids.numel() != 1: + raise ValueError( + "Dataset-specific embeddings require a homogeneous batch; " + f"got dataset IDs {unique_ids.tolist()}" + ) + return int(unique_ids.item()) + + def _add_dataset_embedding( + self, + x: torch.Tensor, + sensor_dataset_id: torch.Tensor | int, + ) -> torch.Tensor: + dataset_id = self._homogeneous_dataset_id(sensor_dataset_id) + if not 0 <= dataset_id < len(self.dataset_embeddings): + raise ValueError( + f"Dataset ID {dataset_id} is outside " + f"[0, {len(self.dataset_embeddings)})" + ) + embedding = self.dataset_embeddings[dataset_id] + if x.shape[1] != self.dataset_embedding_channels: + raise ValueError( + f"Dataset embedding has {self.dataset_embedding_channels} " + f"channels but input has {x.shape[1]}" + ) + if tuple(x.shape[-2:]) != tuple(embedding.shape[-2:]): + raise ValueError( + f"Dataset {dataset_id} expects input grid " + f"{tuple(embedding.shape[-2:])}, got {tuple(x.shape[-2:])}" + ) + if x.ndim == 5: + embedding = embedding.unsqueeze(2) + elif x.ndim != 4: + raise ValueError(f"Expected 4D or 5D input, got shape {x.shape}") + return x + embedding.to(dtype=x.dtype) + + def forward( + self, + x: torch.Tensor, + sensor_dataset_id: torch.Tensor | int, + valid_mask: torch.Tensor | None = None, + **kwargs, + ): + x = self._add_dataset_embedding(x, sensor_dataset_id) + return super().forward( + x, + valid_mask=valid_mask, + **kwargs, + ) + + +class DatasetSpecificLearnablePositionalEmbedding(nn.Module): + """Per-dataset PE that preserves one checkpoint-compatible embedding key.""" + + def __init__( + self, + pretrained_embedding: LearnablePositionalEmbedding, + resolutions: tuple[tuple[int, int], ...], + pretrained_dataset_id: int, + ): + super().__init__() + if not 0 <= pretrained_dataset_id < len(resolutions): + raise ValueError( + f"pretrained_dataset_id={pretrained_dataset_id} is outside " + f"[0, {len(resolutions)})" + ) + pretrained_resolution = tuple( + pretrained_embedding.embedding.shape[1:3] + ) + if pretrained_resolution != tuple(resolutions[pretrained_dataset_id]): + raise ValueError( + f"Pretrained PE grid {pretrained_resolution} does not match " + f"dataset {pretrained_dataset_id} grid " + f"{tuple(resolutions[pretrained_dataset_id])}" + ) + + # Keep this exact name so an ordinary TransformerVAE checkpoint loads + # encoder/decoder `spatial_pe.embedding` directly into the source + # dataset's positional map. + self.embedding = pretrained_embedding.embedding + self.pretrained_dataset_id = int(pretrained_dataset_id) + self.dataset_ids = tuple( + dataset_id + for dataset_id in range(len(resolutions)) + if dataset_id != self.pretrained_dataset_id + ) + out_dim = int(self.embedding.shape[-1]) + self.other_embeddings = nn.ParameterList( + [ + nn.Parameter(torch.empty(1, height, width, out_dim)) + for dataset_id, (height, width) in enumerate(resolutions) + if dataset_id != self.pretrained_dataset_id + ] + ) + for embedding in self.other_embeddings: + nn.init.trunc_normal_(embedding, std=0.02) + self.active_dataset_id = self.pretrained_dataset_id + + def set_dataset_id(self, dataset_id: int) -> None: + self.active_dataset_id = int(dataset_id) + + def forward(self, coords=None): + if self.active_dataset_id == self.pretrained_dataset_id: + selected = self.embedding + else: + try: + index = self.dataset_ids.index(self.active_dataset_id) + except ValueError as error: + raise ValueError( + f"Dataset ID {self.active_dataset_id} is not configured" + ) from error + selected = self.other_embeddings[index] + + # Homogeneous batches rotate datasets between iterations. Keep every + # PE parameter in every autograd graph so DDP static_graph sees a fixed + # used-parameter set; inactive maps receive exact-zero gradients. + dependency = self.embedding.sum() * 0.0 + for embedding in self.other_embeddings: + dependency = dependency + embedding.sum() * 0.0 + return selected + dependency + + +class DatasetPositionalEmbeddingCrossDatasetTransformerVAE( + CrossDatasetTransformerVAE +): + """VAE with per-dataset learned PE and optional image-grid RoPE.""" + + uses_dataset_id = True + + def __init__( + self, + *args, + dataset_input_shapes: tuple[tuple[int, int], ...], + pretrained_dataset_id: int, + spatial_rope: bool = False, + validity_prior_paths: tuple[str, ...] | None = None, + validity_residual_gate_init: float = 1.0, + dataset_validity_logit_bias: bool = False, + **kwargs, + ): + if kwargs.get("positional_embedding", "learnable_embedding") != ( + "learnable_embedding" + ): + raise ValueError( + "Dataset positional embeddings require " + "positional_embedding='learnable_embedding'" + ) + super().__init__(*args, **kwargs) + self.spatial_rope = bool(spatial_rope) + self.pretrained_dataset_id = int(pretrained_dataset_id) + self.active_dataset_id = self.pretrained_dataset_id + + patch_h, patch_w = self.patch_size + encoder_resolutions = tuple( + (height // patch_h, width // patch_w) + for height, width in dataset_input_shapes + ) + compression_h, compression_w = self.spatial_compression + decoder_resolutions = tuple( + (height // compression_h, width // compression_w) + for height, width in dataset_input_shapes + ) + self.encoder.spatial_pe = DatasetSpecificLearnablePositionalEmbedding( + self.encoder.spatial_pe, + encoder_resolutions, + self.pretrained_dataset_id, + ) + self.decoder.spatial_pe = DatasetSpecificLearnablePositionalEmbedding( + self.decoder.spatial_pe, + decoder_resolutions, + self.pretrained_dataset_id, + ) + + if validity_prior_paths is not None and dataset_validity_logit_bias: + raise ValueError( + "Fixed validity priors and learned dataset validity-logit " + "biases are mutually exclusive" + ) + self.validity_logit_biases = nn.ParameterList() + if dataset_validity_logit_bias: + if not self.predict_validity: + raise ValueError( + "Dataset validity-logit biases require predict_validity=True" + ) + self.validity_logit_biases.extend( + nn.Parameter(torch.zeros(1, 1, height, width)) + for height, width in dataset_input_shapes + ) + + self.validity_prior_names = () + if validity_prior_paths is not None: + if not self.predict_validity: + raise ValueError( + "Validity priors require predict_validity=True" + ) + if len(validity_prior_paths) != len(dataset_input_shapes): + raise ValueError( + "validity_prior_paths must have one path per dataset; " + f"got {len(validity_prior_paths)} paths for " + f"{len(dataset_input_shapes)} datasets" + ) + prior_names = [] + for dataset_id, (path, expected_shape) in enumerate( + zip(validity_prior_paths, dataset_input_shapes) + ): + with np.load(path, allow_pickle=False) as data: + if "validity_logit" not in data: + raise KeyError( + f"{path} does not contain 'validity_logit'" + ) + prior = np.asarray( + data["validity_logit"], dtype=np.float32 + ) + if prior.shape != tuple(expected_shape): + raise ValueError( + f"Dataset {dataset_id} validity prior has shape " + f"{prior.shape}, expected {tuple(expected_shape)}" + ) + if not np.isfinite(prior).all(): + raise ValueError( + f"Dataset {dataset_id} validity prior contains " + "non-finite values" + ) + name = f"validity_prior_{dataset_id}" + self.register_buffer( + name, + torch.from_numpy(prior)[None, None], + persistent=True, + ) + prior_names.append(name) + self.validity_prior_names = tuple(prior_names) + self.validity_residual_gate = nn.Parameter( + torch.tensor(float(validity_residual_gate_init)) + ) + + def set_dataset_id(self, sensor_dataset_id: torch.Tensor | int) -> None: + """Select the dataset-specific parameters for direct encode/decode.""" + dataset_id = ( + DatasetEmbeddingCrossDatasetTransformerVAE._homogeneous_dataset_id( + sensor_dataset_id + ) + ) + configured_ids = { + self.encoder.spatial_pe.pretrained_dataset_id, + *self.encoder.spatial_pe.dataset_ids, + } + if dataset_id not in configured_ids: + raise ValueError(f"Invalid sensor_dataset_id={dataset_id}") + self.active_dataset_id = dataset_id + self.encoder.spatial_pe.set_dataset_id(dataset_id) + self.decoder.spatial_pe.set_dataset_id(dataset_id) + + def _network_coords( + self, height: int, width: int, device: torch.device + ) -> torch.Tensor: + if self.spatial_rope: + return super()._network_coords(height, width, device) + return torch.zeros(1, 2, height, width, device=device) + + def decode( + self, + z: torch.Tensor, + hdmap_z: torch.Tensor | None = None, + hdmap_raw: torch.Tensor | None = None, + return_validity: bool = False, + spatial_coords: torch.Tensor | None = None, + ): + decoded = super().decode( + z, + hdmap_z=hdmap_z, + hdmap_raw=hdmap_raw, + return_validity=return_validity, + spatial_coords=spatial_coords, + ) + if not return_validity: + return decoded + + recon, validity_logits = decoded + if self.validity_prior_names: + validity_logits = self._combine_validity_logits(validity_logits) + if self.validity_logit_biases: + validity_logits = self._add_validity_logit_bias(validity_logits) + return recon, validity_logits + + def _add_validity_logit_bias( + self, validity_logits: torch.Tensor + ) -> torch.Tensor: + bias = self.validity_logit_biases[self.active_dataset_id] + if validity_logits.ndim == 5: + bias = bias.unsqueeze(2) + if tuple(validity_logits.shape[-2:]) != tuple(bias.shape[-2:]): + raise ValueError( + f"Dataset {self.active_dataset_id} validity-logit bias grid " + f"{tuple(bias.shape[-2:])} does not match decoder output " + f"{tuple(validity_logits.shape[-2:])}" + ) + # Homogeneous batches rotate datasets between iterations. Keep every + # bias map in every graph so DDP static_graph sees a fixed parameter set. + dependency = validity_logits.new_zeros(()) + for item in self.validity_logit_biases: + dependency = dependency + item.sum().to(validity_logits.dtype) * 0.0 + return validity_logits + bias.to(validity_logits.dtype) + dependency + + def _combine_validity_logits( + self, residual_logits: torch.Tensor + ) -> torch.Tensor: + prior = getattr( + self, self.validity_prior_names[self.active_dataset_id] + ) + if residual_logits.ndim == 5: + prior = prior.unsqueeze(2) + if tuple(residual_logits.shape[-2:]) != tuple(prior.shape[-2:]): + raise ValueError( + f"Dataset {self.active_dataset_id} validity prior grid " + f"{tuple(prior.shape[-2:])} does not match decoder output " + f"{tuple(residual_logits.shape[-2:])}" + ) + logits = prior.to( + device=residual_logits.device, dtype=residual_logits.dtype + ) + ( + self.validity_residual_gate.to(residual_logits.dtype) + * residual_logits + ) + return logits + + def forward( + self, + x: torch.Tensor, + sensor_dataset_id: torch.Tensor | int, + valid_mask: torch.Tensor | None = None, + **kwargs, + ): + self.set_dataset_id(sensor_dataset_id) + return super().forward( + x, + valid_mask=valid_mask, + **kwargs, + ) diff --git a/tokenizer/networks/utils.py b/tokenizer/networks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..578bf2fa3f15e0dbe05054d30fda380f6d93e53f --- /dev/null +++ b/tokenizer/networks/utils.py @@ -0,0 +1,116 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared utilities for the networks module.""" + +from typing import Any + +import torch +from einops import pack, rearrange, unpack + + +def time2batch(x: torch.Tensor) -> tuple[torch.Tensor, int]: + batch_size = x.shape[0] + return rearrange(x, "b c t h w -> (b t) c h w"), batch_size + + +def batch2time(x: torch.Tensor, batch_size: int) -> torch.Tensor: + return rearrange(x, "(b t) c h w -> b c t h w", b=batch_size) + + +def space2batch(x: torch.Tensor) -> tuple[torch.Tensor, int]: + batch_size, height = x.shape[0], x.shape[-2] + return rearrange(x, "b c t h w -> (b h w) c t"), batch_size, height + + +def batch2space(x: torch.Tensor, batch_size: int, height: int) -> torch.Tensor: + return rearrange(x, "(b h w) c t -> b c t h w", b=batch_size, h=height) + + +def cast_tuple(t: Any, length: int = 1) -> Any: + return t if isinstance(t, tuple) else ((t,) * length) + + +def replication_pad(x): + return torch.cat([x[:, :, :1, ...], x], dim=2) + + +def divisible_by(num: int, den: int) -> bool: + return (num % den) == 0 + + +def is_odd(n: int) -> bool: + return not divisible_by(n, 2) + + +def nonlinearity(x): + return x * torch.sigmoid(x) + + +def Normalize(in_channels, num_groups=32): + return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True) + + +class CausalNormalize(torch.nn.Module): + def __init__(self, in_channels, num_groups=1): + super().__init__() + self.norm = torch.nn.GroupNorm( + num_groups=num_groups, + num_channels=in_channels, + eps=1e-6, + affine=True, + ) + self.num_groups = num_groups + + def forward(self, x): + # if num_groups !=1, we apply a spatio-temporal groupnorm for backward compatibility purpose. + # All new models should use num_groups=1, otherwise causality is not guaranteed. + if self.num_groups == 1: + x, batch_size = time2batch(x) + return batch2time(self.norm(x), batch_size) + return self.norm(x) + + +def exists(v): + return v is not None + + +def default(*args): + for arg in args: + if exists(arg): + return arg + return None + + +def pack_one(t, pattern): + return pack([t], pattern) + + +def unpack_one(t, ps, pattern): + return unpack(t, ps, pattern)[0] + + +def round_ste(z: torch.Tensor) -> torch.Tensor: + """Round with straight through gradients.""" + zhat = z.round() + return z + (zhat - z).detach() + + +def log(t, eps=1e-5): + return t.clamp(min=eps).log() + + +def entropy(prob): + return (-prob * log(prob)).sum(dim=-1) diff --git a/tokenizer/training/__init__.py b/tokenizer/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/tokenizer/training/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tokenizer/training/callbacks.py b/tokenizer/training/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..b6727561b51d55f3988144dfbaf26400e10a0dc7 --- /dev/null +++ b/tokenizer/training/callbacks.py @@ -0,0 +1,258 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tokenizer callbacks extended from base callbacks.""" + +import math +from typing import Any, Optional + +import numpy as np +import torch +from torch._dynamo.eval_frame import OptimizedModule as torch_OptimizedModule + +from utils import callback, distributed, log +from utils.config import Config +from utils.model import Model +from utils.trainer import Trainer + +_UINT8_MAX_F = float(np.iinfo(np.uint8).max) +_VIDEO_CONSISTENCY_LOSS = "video_consistency" + + +def make_video_grid(video, nrow=None, padding=1): + r"""Make a grid of videos for visualization. + Args: + video (tensor): video of size B x C x T x H x W. + nrow (int): number of rows in the grid. + padding (int): size of paddings between videos. + """ + b, c, t, h, w = video.shape + video = video.permute(0, 2, 3, 4, 1) + video = (video.cpu().detach().numpy() * _UINT8_MAX_F).astype("uint8") + if nrow is None: + nrow = math.ceil(math.sqrt(b)) + ncol = math.ceil(b / nrow) + video_grid = np.zeros((t, (padding + h) * nrow + padding, (padding + w) * ncol + padding, c), dtype="uint8") + + for i in range(b): + r = i // ncol + c = i % ncol + start_r = (padding + h) * r + start_c = (padding + w) * c + video_grid[:, start_r : start_r + h, start_c : start_c + w] = video[i] + video = [] + for i in range(t): + video.append(video_grid[i]) + return video + + +def compute_weight_norm(model): + weight_norm = dict() + for layer_name, param in model.named_parameters(): + if torch.isnan(param).any(): + raise ValueError(f"[weight] {layer_name} NaN detected in gradients") + weight_norm[f"{layer_name}"] = torch.norm(param, p=2).item() + return weight_norm + + +def compute_grad_norm(model): + grad_norm = dict() + for layer_name, param in model.named_parameters(): + if param.grad is not None: + if torch.isnan(param.grad).any(): + raise ValueError(f"[grad] {layer_name} NaN detected in gradients") + grad_norm[f"{layer_name}"] = torch.norm(param.grad, p=2).item() + return grad_norm + + +class AdaptCkptStateDict(callback.Callback): + def __init__(self, config: Config, trainer: Trainer): + super().__init__(config, trainer) + + def on_save_checkpoint(self, model: Model, state_dict: dict[Any, Any]) -> None: + """Adapt the state dict should the model be a compiled one.""" + if not isinstance(model.network, torch_OptimizedModule): + return + + def _uncompiled_key(k): + if k.startswith("network._orig_mod"): + return k.replace("network._orig_mod", "network") + elif k.startswith("ema.network-_orig_mod"): + return k.replace("ema.network-_orig_mod", "ema.network") + return k + + fixed_keys_state_dict = {} + + for k, v in state_dict["model"].items(): + fixed_keys_state_dict[_uncompiled_key(k)] = v + + state_dict["model"] = fixed_keys_state_dict + + def on_load_checkpoint(self, model: Model, state_dict: dict[Any, Any]) -> None: + """Adapt the state dict should the model be a compiled one.""" + if not isinstance(model.network, torch_OptimizedModule): + return + + def _compiled_key(k): + if k.startswith("network."): + return k.replace("network", "network._orig_mod") + elif k.startswith("ema.network-"): + return k.replace("ema.network", "ema.network-_orig_mod") + return k + + fixed_keys_state_dict = {} + + for k, v in state_dict["model"].items(): + fixed_keys_state_dict[_compiled_key(k)] = v + + state_dict["model"] = fixed_keys_state_dict + + +class GradClipCallback(callback.GradClipCallback): + """The verbose tokenizer callback for gradient clipping.""" + + def __init__(self, grad_clip_norm: float, config: Config, trainer: Trainer, verbose: bool): + super().__init__(config, trainer, grad_clip_norm) + self.verbose = verbose + + def on_before_optimizer_step( + self, + model_ddp: distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int = 0, + ) -> None: + grad_scaler.unscale_(optimizer) + total_norm = torch.nn.utils.clip_grad_norm_(model_ddp.module.parameters(), max_norm=self.grad_clip_norm) + if torch.isnan(total_norm): + raise ValueError("[gradient clipping] NaN detected in gradient norms") + if torch.isfinite(total_norm) and total_norm > self.grad_clip_norm and self.verbose: + if model_ddp.module.network.training: + log.warning( + f"[net:{iteration:07d}] Gradient norm {total_norm} > {self.grad_clip_norm}. Clipping gradients." + ) + else: + log.warning( + f"[unknown:{iteration:07d}] Gradient norm {total_norm} > {self.grad_clip_norm}. Clipping gradients." + ) + + +class ExpandLossMask(callback.Callback): + def __init__(self, kernel_size: int, config: Config, trainer: Trainer): + super().__init__(config, trainer) + self.kernel_size = kernel_size + + def on_training_step_start(self, model: Model, data: dict[str, Any], iteration: int = 0) -> None: + """Expand loss_mask with max pooling (to cover some partial human regions)""" + + if "loss_mask" not in data.keys(): + return + # Explicit LiDAR return-validity masks are a sensor measurement, not a + # semantic region mask. Expanding them changes both the VAE's + # mask-as-input channel and every masked loss during training only, + # while validation sees the exact mask. + if data.get("loss_mask_is_validity") is not None: + return + + assert data["loss_mask"].ndim == 4 or data["loss_mask"].ndim == 5, "ndim of loss_mask must be 4 or 5" + + kernel_size = self.kernel_size + if data["loss_mask"].ndim == 4: + data["loss_mask"] = torch.nn.functional.max_pool2d( + data["loss_mask"], kernel_size, stride=1, padding=kernel_size // 2 + ) + else: + data["loss_mask"] = torch.nn.functional.max_pool3d( + data["loss_mask"], + (1, kernel_size, kernel_size), + stride=1, + padding=(0, kernel_size // 2, kernel_size // 2), + ) + + +class TorchCompile(callback.Callback): + """ + Callback to use torch.compile() on network or modules in losses(FlowLoss and PerceptualLoss) or both. + We compile them at later iteration as it prevents NCCL timeouts when times are very unstable during first iterations + """ + + _TORCH_DYNAMO_CACHE_SIZE = 128 + + def __init__( + self, + compile_after_iterations: int = 8, + compile_network: bool = False, + compile_loss: bool = False, + compile_loss_keys: list[str] = ["flow", "perceptual"], + ): + self.initial_iteration: Optional[int] = None + self.compile_after_iterations: int = compile_after_iterations + + self.compile_network: bool = compile_network + self.compile_loss: bool = compile_loss + + self.compile_loss_keys: list[str] = compile_loss_keys + + if self.compile_network or self.compile_loss: + torch._dynamo.config.cache_size_limit = TorchCompile._TORCH_DYNAMO_CACHE_SIZE + + # Hack to make ".training" work on "torch.compile()" module. + # Value of ".training" is incorrectly set on torch.compile() module, when .eval() or .train() + # is invoked, but is correctly set on original module and this hack accesses that value + # I've created issue about this: https://github.com/pytorch/pytorch/issues/132986 + torch_OptimizedModule.training = property( + lambda self: self._orig_mod.training, lambda self, value: None, lambda self: None + ) + + def on_training_step_start(self, model: Model, data: dict[str, torch.Tensor], iteration: int = 0) -> None: + if not (self.compile_network or self.compile_loss): + return + + if self.initial_iteration is None: + log.info(f"Compilation will done on iteration {iteration + self.compile_after_iterations}") + self.initial_iteration = iteration + + if self.compile_network: + if model.config.ema.enabled is True and model.config.ema.torch_compile_buffer_renaming is False: + log.warning( + '"model.config.ema.torch_compile_buffer_renaming" should be turned on for the EMA to work with torch.compile(), network will not be compiled' + ) + + if iteration - self.initial_iteration == self.compile_after_iterations: + if self.compile_network: + if model.config.ema.enabled is True and model.config.ema.torch_compile_buffer_renaming is False: + log.warning( + '"model.config.ema.torch_compile_buffer_renaming" should be turned on for the EMA to work with torch.compile(), skipping network compilation' + ) + else: + log.info("Compiling network") + model.network = torch.compile(model.network, dynamic=False) + + if self.compile_loss: + for key in self.compile_loss_keys: + if key not in model.loss.loss_modules: + log.warning(f"Loss module for compilation with key: {key} not found") + else: + if ( + hasattr(model.loss.loss_modules[key], "checkpoint_activations") + and getattr(model.loss.loss_modules[key], "checkpoint_activations") is True + ): + log.warning( + f"torch.compile() doesn't work with activation checkpointing, skipping compilation for loss with key: {key}" + ) + else: + log.info(f"Compiling loss with key: {key}") + model.loss.loss_modules[key].torch_compile() diff --git a/tokenizer/training/checkpointer.py b/tokenizer/training/checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..10b70865689b92dc767341f3ebb3bcbf4dd239f5 --- /dev/null +++ b/tokenizer/training/checkpointer.py @@ -0,0 +1,152 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import threading + +import torch +from torch._dynamo.eval_frame import OptimizedModule as torch_OptimizedModule + +from utils import callback, distributed, ema, log, misc +from utils.atomic_save import atomic_torch_jit_save, atomic_torch_save +from utils.checkpointer import Checkpointer +from utils.config import CheckpointConfig, JobConfig +from utils.model import Model + + +class TokenizerCheckpointer(Checkpointer): + """The tokenizer checkpointer, extends the shared checkpointer. + + Supports checkpoint saving/loading to local disk: + - network weights and training optimizer states. + - optionally, export a TorchScript version of the EMA model. + """ + + def __init__(self, config_checkpoint: CheckpointConfig, config_job: JobConfig, callbacks: callback.CallBackGroup): + super().__init__(config_checkpoint, config_job, callbacks) + self.callbacks = callbacks + self.config_jit = config_checkpoint.jit + + def save( + self, + model: Model, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int = -1, + **ignore_kwargs, + ) -> None: + """Saves network weights, optimizer parameters, scheduler parameters to a checkpoint. + + Args: + model (Model): The PyTorch model. + optimizer: The model optimizer. + scheduler: The optimization scheduler. + grad_scaler: The gradient scaler (for mixed precision training). + iteration: Current iteration number. + """ + self.callbacks.on_save_checkpoint_start(model, iteration) + model.eval() + checkpoint_file = f"ckpt.pt" + + if distributed.get_rank() == 0: + state_dict = dict( + model=model.state_dict(), + optimizer=optimizer.state_dict(), + scheduler=scheduler.state_dict(), + grad_scaler=grad_scaler.state_dict(), + iteration=iteration, + ) + + state_dict = misc.to(state_dict, device="cpu") + self.callbacks.on_save_checkpoint(model, state_dict=state_dict) + # Wait for previous saver thread to end. + if self.save_thread: + self.save_thread.join() + # Run the checkpoint saver in a separate thread. + self.save_thread = threading.Thread( + target=self._save_worker_local, + daemon=False, + args=(state_dict, self._get_ema_jit(model), checkpoint_file, distributed.get_rank()), + ) + self.save_thread.start() + + # Note: Checkpoints are saved on a separate thread and this callback is not accurate. + # Please check logs from on_save_checkpoint_success() for better accuracy + self.callbacks.on_save_checkpoint_end(model=None, iteration=iteration) + + @misc.timer("checkpoint saving (local)") + def _save_worker_local( + self, + state_dict: dict[str, torch.Tensor], + jit_models: dict[str, torch.ScriptModule], + checkpoint_file: str, + rank: int = 0, + ) -> None: + """Worker to save checkpoint to local disk, spawned with a child thread (runs in parallel with the training). + + Args: + state_dict: The state dict of the model/optimizer/scheduler. + ema_jit: A dict of TorchScript EMA model, representing the encoder, decoder and full model. + checkpoint_file (str): The file name of the model checkpoint. + rank (int): GPU device (default: 0). + """ + checkpoint_path = os.path.join(self.checkpoint_dir_local, checkpoint_file) + os.makedirs(self.checkpoint_dir_local, exist_ok=True) + try: + # tmp+fsync+rename + zip-validity check, so kills mid-save can't + # leave torn .pt / .jit files that break resume. + atomic_torch_save(state_dict, checkpoint_path) + for key, jit_model in jit_models.items(): + checkpoint_jit = checkpoint_path.replace(".pt", f"_{key}.jit") + atomic_torch_jit_save(jit_model, checkpoint_jit) + log.success(f"Saved checkpoint: {checkpoint_jit}") + # Latest pointer is written *only* after every shard above is + # validated and renamed into place. + if rank == 0: + self._write_latest_checkpoint_file(checkpoint_file) + log.success(f"Saved checkpoint (local): {checkpoint_path}") + iteration = int(state_dict["iteration"]) + self.callbacks.on_save_checkpoint_success(iteration=iteration) + except Exception as e: # noqa: BLE001 + log.exception(f"Checkpoint failed to save (local): {e}") + + def _get_ema_jit(self, model: Model) -> dict[str, torch.ScriptModule]: + """Returns a TorchScript version of ema models compiled by PyTorch JIT.""" + if not self.config_jit.enabled: + return dict() + input_shape = tuple(self.config_jit.input_shape) + example_input = torch.randn(input_shape) + dtype = getattr(torch, self.config_jit.dtype) + example_input = example_input.to(self.config_jit.device).to(dtype) + with ema.ema_scope(model, enabled=model.config.ema.enabled): + _model = model.network + if isinstance(_model, torch_OptimizedModule): + _model = _model._orig_mod + + # Make sure jit model output consistenly during consecutive calls + # Check here: https://github.com/pytorch/pytorch/issues/74534 + torch._C._jit_set_texpr_fuser_enabled(False) + ema_jit = torch.jit.trace(_model, example_input, strict=self.config_jit.strict) + encoder_jit = torch.jit.trace(_model.encoder_jit(), example_input, strict=self.config_jit.strict) + decoder_example = encoder_jit(example_input) + if isinstance(decoder_example, tuple): + decoder_example = decoder_example[0] + else: + assert isinstance(decoder_example, torch.Tensor), "decoder_example should be a tensor or tuple" + decoder_jit = torch.jit.trace(_model.decoder_jit(), decoder_example, strict=self.config_jit.strict) + return {"ema": ema_jit, "enc": encoder_jit, "dec": decoder_jit} diff --git a/tokenizer/training/configs/__init__.py b/tokenizer/training/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3159bfe65645499015bd92609b99d476d69544e9 --- /dev/null +++ b/tokenizer/training/configs/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tokenizer/training/configs/base/__init__.py b/tokenizer/training/configs/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/tokenizer/training/configs/base/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tokenizer/training/configs/base/callback.py b/tokenizer/training/configs/base/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..760830a9838d7f994cbf15356b5fce3ab0a49ba6 --- /dev/null +++ b/tokenizer/training/configs/base/callback.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""callbacks config options: + +BASIC_CALLBACKS: always recommended to use +""" + +from tokenizer.training.callbacks import ( + AdaptCkptStateDict, + ExpandLossMask, + GradClipCallback, + TorchCompile, +) +from utils.callback import EMAModelCallback, LowPrecisionCallback, ProgressBarCallback +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from tokenizer.training.lidar_callbacks import WandBLidarCallback + +BASIC_CALLBACKS = dict( + low_precision=L(LowPrecisionCallback)(update_iter=1, config=PLACEHOLDER, trainer=PLACEHOLDER), + grad_clip=L(GradClipCallback)(grad_clip_norm=1, verbose=False, config=PLACEHOLDER, trainer=PLACEHOLDER), + ema=L(EMAModelCallback)(config=PLACEHOLDER, trainer=PLACEHOLDER), + progress_bar=L(ProgressBarCallback)(config=PLACEHOLDER, trainer=PLACEHOLDER), + expand_loss_mask=L(ExpandLossMask)(kernel_size=51, config=PLACEHOLDER, trainer=PLACEHOLDER), + adapt_ckpt_state_dict=L(AdaptCkptStateDict)(config=PLACEHOLDER, trainer=PLACEHOLDER), + torch_compile=L(TorchCompile)( + compile_after_iterations=8, + compile_network=False, + compile_loss=False, + compile_loss_keys=["flow", "perceptual"], + ), +) + + +FLOAT32_CALLBACKS = dict( + grad_clip=L(GradClipCallback)(grad_clip_norm=1, verbose=True, config=PLACEHOLDER, trainer=PLACEHOLDER), + ema=L(EMAModelCallback)(config=PLACEHOLDER, trainer=PLACEHOLDER), + progress_bar=L(ProgressBarCallback)(config=PLACEHOLDER, trainer=PLACEHOLDER), + expand_loss_mask=L(ExpandLossMask)(kernel_size=51, config=PLACEHOLDER, trainer=PLACEHOLDER), + adapt_ckpt_state_dict=L(AdaptCkptStateDict)(config=PLACEHOLDER, trainer=PLACEHOLDER), + torch_compile=L(TorchCompile)( + compile_after_iterations=8, + compile_network=False, + compile_loss=False, + compile_loss_keys=["flow", "perceptual"], + ), +) + +WANDBLIDAR_CALLBACK = dict( + wandbLidar=L(WandBLidarCallback)(config=PLACEHOLDER, trainer=PLACEHOLDER), +) diff --git a/tokenizer/training/configs/base/checkpoint.py b/tokenizer/training/configs/base/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..739fd30881be91d4cdf3230780f383c5ac635641 --- /dev/null +++ b/tokenizer/training/configs/base/checkpoint.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""checkpoints config options: + +CHECKPOINT_LOCAL: store at local file system + +""" +import attrs + +from utils import config +from utils.config import make_freezable +from utils.lazy_config import LazyDict + + +@make_freezable +@attrs.define(slots=False) +class ExperimentConfig: + # Enables enforcing experiment naming. + enabled: bool = True + # The project, e.g. edify_video4. + project: str = None + # The valid groups, e.g ["video"]. + groups: list[str] = None + # The approved name prefixes, e.g. ["DV1024", "DI256"]. + name_prefixes: list[str] = None + + +@make_freezable +@attrs.define(slots=False) +class TokenizerCheckpointConfig(config.CheckpointConfig): + # Experiment naming configs. + experiment: ExperimentConfig = attrs.field(factory=ExperimentConfig) + + +jit_config = config.JITConfig( + enabled=True, + input_shape=[1, 3, 1024, 1024], +) + +experiment_config = ExperimentConfig( + enabled=True, + project="cosmos_tokenizer", + groups=["debug", "video"], + name_prefixes=[ + f"{base}{size}" if base in ["CI", "DI"] else f"{base}{size}_Causal" + for base in ["CI", "DI", "CV", "DV"] + for size in [256, 320, 480, 512, 720, 1024, 1080] + ] + + [f"{base}{size}" for base in ["CV", "DV"] for size in [256, 320, 512, 720]] + + ["mock"], +) + +CHECKPOINT_LOCAL: LazyDict = attrs.asdict( + TokenizerCheckpointConfig( + save_iter=5000, + jit=jit_config, + experiment=experiment_config, + ) +) diff --git a/tokenizer/training/configs/base/loss.py b/tokenizer/training/configs/base/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a170d572ef05d1ce0511d8a129a1244d05bf6593 --- /dev/null +++ b/tokenizer/training/configs/base/loss.py @@ -0,0 +1,384 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Loss config options + +Loss weights are scheduled using a piecewise linear LR schedule. The schedule is defined by a list of boundaries and values. + +`boundaries` is a list of integers representing the iteration at which the weight value changes. +`values` is a list of floats representing the weight value at each boundary. It should have one more value than `boundaries`. + +Example: + A loss's weight will be: + values[0] when step <= boundaries[0], + values[1] when step > boundaries[0] and step <= boundaries[1], + ..., and + values[-1] when step > boundaries[-1]. +""" +import attrs + +from tokenizer.training.losses import ReduceMode +from tokenizer.training.losses.continuous import ( + ColorLoss, + ExtraLidarDepthLoss, + FlowLoss, + GradientLoss, + EikonalLoss, + IntensityTailL1Loss, + InvalidDepthSentinelLoss, + KLLoss, + NormalLoss, + LocalChamferLoss, + PerceptualLoss, + TokenizerLoss, + PointLoss, + RepaAlignLoss, + SurfaceConcentrationLoss, + TemporalDiffLoss, + ValidityBCELoss, + RaydropMSELoss, + ValidityLPIPSLoss, + VideoConsistencyLoss, + VoxelOccupancyBCELoss, +) +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +@attrs.define(slots=False) +class KLConfig: + # each step is greater than boundaries[-1], so weight=values[-1] + boundaries: list[int] = [0] + values: list[float] = [1e-6] + + +@attrs.define(slots=False) +class PerceptualConfig: + lpips_boundaries: list[int] = [500000] + lpips_values: list[float] = [0.1, 0.073] + # Layer weights for linearly combining the multi-layer vgg-based losses. + layer_weights: list[float] = [1.0 / 2.6, 1.0 / 4.8, 1.0 / 3.7, 1.0 / 5.6, 10.0 / 1.5] + # Gram loss, whether to turn on, and what weights to use. + gram_enabled: bool = True + gram_boundaries: list[int] = [500000] + gram_values: list[float] = [0.0, 0.062] + # Corr loss, whether to turn on, and what weights to use. + corr_enabled: bool = False + corr_boundaries: list[int] = [0] + corr_values: list[float] = [0.0] + # In the example training memory usage dropped from 64.03 GiB to 60.54 GiB + # with checkpointing enabled for this loss for about 3.2% slowdown. + # With checkpointing this and PerceptualLoss memory usage dropped + # from 64.03 GiB to 52.94 GiB for about 18% slowdown + # more details in MR:949 + checkpoint_activations: bool = False + + +@attrs.define(slots=False) +class ColorConfig: + # Color (RGB) basic loss and its weight schedule. + norm: str = "L1" + boundaries: list[int] = [0] + values: list[float] = [1.0] + # Opt-in valid-return mean. Default False preserves historical masked + # losses, whose magnitude is proportional to the valid-pixel fraction. + normalize_by_valid_mask: bool = False + + +@attrs.define(slots=False) +class PointConfig: + # Coord loss and its weight schedule. + enabled: bool = False + norm: str = "L1" + boundaries: list[int] = [0] + values: list[float] = [1.0] + normalize_by_valid_mask: bool = False + + +@attrs.define(slots=False) +class FlowConfig: + # Flow loss and its weight schedule. + boundaries: list[int] = [250000] + values: list[float] = [0.0, 0.01] + scale: int = 2 + # Flow loss depends on RAFT, as such it requires a specific dtype. + dtype: str = "bfloat16" + # In the example training memory usage dropped from 28GB to 23GB + # with checkpointing enabled for this loss + # With checkpointing this and PerceptualLoss memory usage dropped + # from 64.03 GiB to 52.94 GiB for about 18% slowdown + # more details in MR:949 + checkpoint_activations: bool = False + enabled: bool = False + + +@attrs.define(slots=False) +class GradientConfig: + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [1.0] + + +@attrs.define(slots=False) +class LocalChamferConfig: + # One-sided windowed Chamfer (recon -> nearest GT in a (2r+1)^2 range-image + # window, meters). Direct floater killer; differentiable (Charbonnier + # sqrt(d^2+eps)); drop-in for point_loss (radius=0 == Euclidean point error). + # Needs the de-repeated point maps (computed when this OR point_loss/normal + # is enabled). Candidates restricted to valid GT returns via MASK_KEY. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + radius: int = 2 # azimuth (W) window half-size + # Elevation (H) window half-size: <0 mirrors ``radius`` (isotropic, default); + # 0 = AZIMUTH-ONLY (no cross-ring matching -> preserves ring texture). + radius_h: int = -1 + eps: float = 1e-4 + + +@attrs.define(slots=False) +class TemporalDiffConfig: + # PV-VAE matched temporal-difference (motion-aware) loss. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + # Normalized no-return clamp value; pairs with either endpoint at/below + # ``min_value + raydrop_eps`` (in either gt or recon) are dropped to + # avoid raydrop / tree-foliage flicker driving the loss. + min_value: float = -1.0 + raydrop_eps: float = 0.02 + # Ramp the per-sample weight by the interpolative noise level + # (``noise_tau`` exposed by the network): ~0 on clean, full on noisy. + tau_ramp: bool = True + tau_ramp_power: float = 1.0 + + +@attrs.define(slots=False) +class ValidityBCEConfig: + # BCE on the decoder's predicted validity (raydrop) mask. Requires the + # network to be built with ``predict_validity=True`` (adds one extra + # decoder output channel of validity logits). arxiv:2605.22809 Eq. 4. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + # Normalized no-return clamp value; GT mask = (range > min_value + eps). + min_value: float = -1.0 + raydrop_eps: float = 0.02 + # When True, the GT validity is read from the dataloader-provided MASK_KEY + # (per-row norm runs) instead of thresholding recon_target. + mask_from_batch: bool = False + # Optional class-balanced BCE. When set, compute the mean BCE separately + # over GT no-return and valid pixels, then assign this fraction of the loss + # to no-return pixels and the remainder to valid pixels. None preserves the + # historical per-pixel mean. + invalid_class_weight: float | None = None + + +@attrs.define(slots=False) +class IntensityTailL1Config: + # Additional valid-return L1 averaged over each sensor's rare bright tail. + # Thresholds are on the raw linear [0,1] scale and indexed by + # sensor_dataset_id. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + intensity_channel: int = 1 + linear_thresholds: list[float] = [0.99] + intensity_transform: str = "log1p" + + +@attrs.define(slots=False) +class InvalidDepthSentinelConfig: + # Low-weight L1 anchor for the otherwise-unsupervised depth output at + # explicit no-return pixels. Requires MASK_KEY to carry GT validity. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + sentinel: float = -1.0 + + +@attrs.define(slots=False) +class RaydropMSEConfig: + # OmniGen L_r: MSE on the rendered raydrop PROBABILITY (sigmoid of the + # validity logits) vs the binary return mask. Same target derivation as + # ValidityBCEConfig; differs only in MSE vs BCE. arXiv:2512.14225. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + min_value: float = -1.0 + raydrop_eps: float = 0.02 + mask_from_batch: bool = False + + +@attrs.define(slots=False) +class NormalConfig: + # Surface-normal consistency (Sensor2Sensor L_normals, arXiv:2605.22809). + # Finite-differences per-pixel normals from the projected 3D points and + # matches recon vs GT on valid returns -- constrains the surface derivative + # (flattens ground) rather than absolute range. Reuses the de-repeated point + # maps the model stashes for point_loss; no-op if neither is enabled. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + mode: str = "cosine" # "cosine" (default) or "l1" + # Match the dataset depth range; no-returns sit at min_range and are dropped. + min_range: float = 5.0 + max_range: float = 100.0 + valid_eps: float = 0.5 + + +@attrs.define(slots=False) +class EikonalConfig: + # Eikonal regularizer (IGR/SIREN; LODE grad_constraint): ||grad phi|| -> 1 on + # the decoded SDF volume so phi is a metric distance field (clean unit-normal + # field, smooth zero level-set -> good normals without GT-normal supervision). + # Only the decomp-BEV SDF tokenizer (use_sdf=True) stashes sdf_density; no-op + # elsewhere. num_samples>0 = random interior voxels/item (memory-frugal); 0 = + # full volume. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + num_samples: int = 65536 + + +@attrs.define(slots=False) +class SurfaceConcentrationConfig: + # Concentrate the renderer's per-ray weight distribution on the GT surface + # (kills floaters so E[d] is clean). Only for the BEV occupancy tokenizers, + # whose forward stashes render_weights / render_sample_depths / + # render_gt_depth / render_valid in the output dict. No-op for other nets. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + # Squared (d_s - d_gt) is divided by depth_scale^2 to keep the loss O(1) + # (set near the sensor max range). Used only in mode="variance". + depth_scale: float = 100.0 + # "variance" (smooth proxy, default) or "surface_indicator" (exact Copilot4D + # Eq.5: Σ_i 1(|h_i-D_gt|>epsilon) w_i). epsilon is in meters. + mode: str = "variance" + epsilon: float = 0.1 + + +@attrs.define(slots=False) +class VoxelOccupancyBCEConfig: + # Direct occupancy supervision (Copilot4D): BCE on the decoder's 3D binary + # voxel logits vs the voxelized input occupancy. Only for the Copilot4D + # tokenizer, whose forward stashes voxel_logits / voxel_occupancy_target in + # the output dict. No-op for other nets. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + # Upweight the rare occupied voxels (occupancy is sparse). 0 disables. + pos_weight: float = 10.0 + + +@attrs.define(slots=False) +class ExtraLidarConfig: + # Multi-lidar depth reconstruction: L1 on the extra (blind-spot) lidars' + # rendered depth vs measured range (normalized space), masked to returns. + # Only for the BEV occupancy tokenizer built with ``multi_lidar=True``, whose + # forward stashes extra_depth / extra_gt_depth / extra_valid. No-op otherwise. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + + +@attrs.define(slots=False) +class ValidityLPIPSConfig: + # LPIPS on the predicted validity mask (arxiv:2605.22809). Requires the + # network to be built with ``predict_validity=True``. Loads its own VGG. + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + min_value: float = -1.0 + raydrop_eps: float = 0.02 + checkpoint_activations: bool = False + mask_from_batch: bool = False + + +@attrs.define(slots=False) +class VideoConsistencyConfig: + # Add consistency loss between overlapped video frames + boundaries: list[int] = [250000] + values: list[float] = [0.0, 0.01] + enabled: bool = False + num_frames: int = 9 + step: int = 1 + + +@attrs.define(slots=False) +class RepaAlignConfig: + # REPA / Volt conv-teacher alignment: pull a trainable projection of the + # latent toward frozen Utonia (PTv3) BEV features (masked cosine). Requires + # the network built with ``utonia_align=True`` (UniPAD tokenizer, bev_patchify). + enabled: bool = False + boundaries: list[int] = [0] + values: list[float] = [0.0] + + +@attrs.define(slots=False) +class VideoLoss: + # The combined loss function, and its reduction mode. + color: LazyDict = L(ColorLoss)(config=ColorConfig()) + kl: LazyDict = L(KLLoss)(config=KLConfig()) + perceptual: LazyDict = L(PerceptualLoss)(config=PerceptualConfig()) + flow: LazyDict = L(FlowLoss)(config=FlowConfig()) + video_consistency: LazyDict = L(VideoConsistencyLoss)(config=VideoConsistencyConfig()) + reduce: str = ReduceMode.MEAN.value # model.config.loss.config.reduce={'MEAN', 'SUM', 'SUM_PER_FRAME'} + point_loss: LazyDict = L(PointLoss)(config=PointConfig()) + local_chamfer: LazyDict = L(LocalChamferLoss)(config=LocalChamferConfig()) + normal: LazyDict = L(NormalLoss)(config=NormalConfig()) + eikonal: LazyDict = L(EikonalLoss)(config=EikonalConfig()) + gradient: LazyDict = L(GradientLoss)(config=GradientConfig()) + temporal_diff: LazyDict = L(TemporalDiffLoss)(config=TemporalDiffConfig()) + intensity_tail_l1: LazyDict = L(IntensityTailL1Loss)( + config=IntensityTailL1Config() + ) + validity_bce: LazyDict = L(ValidityBCELoss)(config=ValidityBCEConfig()) + invalid_depth_sentinel: LazyDict = L(InvalidDepthSentinelLoss)( + config=InvalidDepthSentinelConfig() + ) + raydrop_mse: LazyDict = L(RaydropMSELoss)(config=RaydropMSEConfig()) + validity_lpips: LazyDict = L(ValidityLPIPSLoss)(config=ValidityLPIPSConfig()) + surface_concentration: LazyDict = L(SurfaceConcentrationLoss)(config=SurfaceConcentrationConfig()) + voxel_occupancy_bce: LazyDict = L(VoxelOccupancyBCELoss)(config=VoxelOccupancyBCEConfig()) + extra_lidar: LazyDict = L(ExtraLidarDepthLoss)(config=ExtraLidarConfig()) + repa_align: LazyDict = L(RepaAlignLoss)(config=RepaAlignConfig()) + # Restrict the depth losses (color / gradient / point) to VALID returns. + # When True, the GT validity mask (range channel > min_value + raydrop_eps) + # replaces the all-ones MASK_KEY: color & gradient weight by it, and + # point_loss drops no-return points. The decoder is then not penalized for + # failing to reproduce the no-return clamp value -- that pixel is supervised + # by the validity head instead. Default False = existing all-pixels behavior. + mask_invalid_depth: bool = False + mask_invalid_min_value: float = -1.0 + mask_invalid_raydrop_eps: float = 0.02 + # When True, the per-pixel valid mask used by the depth losses comes from + # the dataloader (``loss_mask`` -> MASK_KEY) rather than being derived from + # recon_target. Pair with ``emit_valid_mask=True`` on the dataset and + # ``mask_from_batch=True`` on validity_bce/validity_lpips. Required when + # per-row normalization is on (the depth sentinel is unrecoverable). + mask_from_batch: bool = False + +@attrs.define(slots=False) +class ImageLoss: + # The combined loss function, and its reduction mode. + color: LazyDict = L(ColorLoss)(config=ColorConfig()) + kl: LazyDict = L(KLLoss)(config=KLConfig()) + perceptual: LazyDict = L(PerceptualLoss)(config=PerceptualConfig()) + reduce: str = ReduceMode.MEAN.value # model.config.loss.config.reduce={'MEAN', 'SUM', 'SUM_PER_FRAME'} + +VideoLossConfig: LazyDict = L(TokenizerLoss)(config=VideoLoss()) +ImageLossConfig: LazyDict = L(TokenizerLoss)(config=ImageLoss()) diff --git a/tokenizer/training/configs/base/metric.py b/tokenizer/training/configs/base/metric.py new file mode 100644 index 0000000000000000000000000000000000000000..0ecf970b42c0d92280b5ae325452c8c28640be72 --- /dev/null +++ b/tokenizer/training/configs/base/metric.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Metric configurations for the tokenizer model. + +Support for PSNR or SSIM, there are validation only metrics. +""" +import attrs + +from tokenizer.training.metrics import CodeUsageMetric, PSNRMetric, SSIMMetric, TokenizerMetric +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +@attrs.define(slots=False) +class Metric: + # The combined loss function, and its reduction mode. + PSNR: LazyDict = L(PSNRMetric)() + SSIM: LazyDict = L(SSIMMetric)() + + +@attrs.define(slots=False) +class DiscreteTokenizerMetric: + # with code usage (perplexity PPL), for discrete tokenizers only + PSNR: LazyDict = L(PSNRMetric)() + SSIM: LazyDict = L(SSIMMetric)() + CodeUsage: LazyDict = L(CodeUsageMetric)(codebook_size=64000) + + +MetricConfig: LazyDict = L(TokenizerMetric)(config=Metric()) + +DiscreteTokenizerMetricConfig: LazyDict = L(TokenizerMetric)(config=DiscreteTokenizerMetric()) diff --git a/tokenizer/training/configs/base/model.py b/tokenizer/training/configs/base/model.py new file mode 100644 index 0000000000000000000000000000000000000000..aa76a89d386b6ab73705625d21adc93534a21c5d --- /dev/null +++ b/tokenizer/training/configs/base/model.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import attrs + +from tokenizer.training.model import TokenizerModel +from utils.config import EMAConfig +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + + +@attrs.define(slots=False) +class ModelConfig: + network: LazyDict = None + loss: LazyDict = None + metric: LazyDict = None + ema: EMAConfig = EMAConfig(enabled=True, beta=0.9999) + precision: str = "bfloat16" + torch_compile: bool = False + disc: LazyDict = None + disc_optimizer: LazyDict = None + disc_scheduler: LazyDict = None + + +DefaultModelConfig: LazyDict = L(TokenizerModel)(config=ModelConfig()) diff --git a/tokenizer/training/configs/base/nets/lidarverse.py b/tokenizer/training/configs/base/nets/lidarverse.py new file mode 100644 index 0000000000000000000000000000000000000000..d720712858db9093044bd7777048d374ddca1b57 --- /dev/null +++ b/tokenizer/training/configs/base/nets/lidarverse.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Network config for the public range-only, native-grid LidarVerse tokenizer.""" + +from tokenizer.networks.common import ContinuousFormulation +from tokenizer.networks.transformers.transformer_vae_cross_dataset import ( + CrossDatasetTransformerVAE, +) +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict + +PAI_TOKENIZER_NAME = ( + "transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema40k" +) + + +LIDARVERSE_TOKENIZER_CONFIG: LazyDict = L(CrossDatasetTransformerVAE)( + resolution=(64, 1024), + in_channels=2, + out_channels=1, + z_dim=64, + base_channels=128, + depths=[4, 2, 4], + num_heads=[4, 16, 16], + patch_size=(2, 2), + window_size=(5, 35), + dilation=[1, 1, 1], + temporal_downsample=[False, False, False], + temporal_upsample=[False, False, False], + decoder_depths=None, + decoder_num_heads=None, + decoder_dilation=None, + decoder_temporal_upsample=None, + out_patch_size=None, + activation_checkpointing=True, + encoder_autocast_dtype=None, + mlp_ratio=3.0, + dropout=0.0, + mapping_depth=2, + positional_embedding="rope_only", + formulation=ContinuousFormulation.VAE.name, + bottleneck_3d=False, + bottleneck_3d_max_t=32, + bottleneck_3d_causal_time=True, + bottleneck_3d_rope=False, + mask_as_input=True, + predict_validity=True, +) diff --git a/tokenizer/training/configs/base/optim.py b/tokenizer/training/configs/base/optim.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc0b104eb8b38bf220193d3621ea16ae690805d --- /dev/null +++ b/tokenizer/training/configs/base/optim.py @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""optimizer config options: + +fused_adam - FusedAdamConfig +adamw - AdamWConfig +""" + +import torch + +from utils import fused_adam +from utils.lazy_config import PLACEHOLDER +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict +from utils.scheduler import WarmupCosineLR, WarmupLambdaLR + +FusedAdamConfig: LazyDict = L(fused_adam.FusedAdam)( + capturable=True, + master_weights=True, + adam_w_mode=True, + params=PLACEHOLDER, + lr=1e-4, + betas=(0.5, 0.999), + eps=1e-8, + weight_decay=0.01, +) + +AdamWConfig: LazyDict = L(torch.optim.AdamW)( + params=PLACEHOLDER, + lr=1e-4, + betas=(0.5, 0.999), + eps=1e-8, + weight_decay=0.01, +) + +WarmupLRConfig: LazyDict = L(WarmupLambdaLR)(optimizer=PLACEHOLDER, warmup=5000) + +FusedAdamDiscConfig: LazyDict = L(fused_adam.FusedAdam)( + capturable=True, + master_weights=True, + adam_w_mode=True, + params=PLACEHOLDER, + lr=4e-4, + betas=(0.5, 0.999), + eps=1e-8, + weight_decay=0.01, +) + +WarmupLRDiscConfig: LazyDict = L(WarmupLambdaLR)(optimizer=PLACEHOLDER, warmup=5000) + +WarmupCosineLRConfig: LazyDict = L(WarmupCosineLR)( + optimizer=PLACEHOLDER, warmup_iters=5000, lr_decay_iters=1000000, min_lr=1e-8 +) diff --git a/tokenizer/training/configs/config.py b/tokenizer/training/configs/config.py new file mode 100644 index 0000000000000000000000000000000000000000..63ad952970556e331eaf38f0bb67499ec6f64ac3 --- /dev/null +++ b/tokenizer/training/configs/config.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Default config for cosmos/tokenizer project.""" + +from typing import Any, List + +import attrs + +from tokenizer.training.configs.base.model import DefaultModelConfig +from tokenizer.training.configs.registry import register_configs +from tokenizer.training.trainer import TokenizerTrainer +from utils import config + + +@attrs.define(slots=False) +class Config(config.Config): + defaults: List[Any] = attrs.field( + factory=lambda: [ + "_self_", + {"data_train": "lidarverse_cross_dataset_range_video"}, + {"data_val": "lidarverse_cross_dataset_range_video"}, + {"optimizer": "fused_adam"}, + {"scheduler": "warmup"}, + {"network": "lidarverse_tokenizer"}, + {"loss": "video"}, + {"metric": "reconstruction"}, + {"checkpoint": "local"}, + {"callbacks": "float32"}, + {"experiment": None}, + ] + ) + + +def make_config(): + c = Config( + model=DefaultModelConfig, + optimizer=None, + scheduler=None, + dataloader_train=None, + dataloader_val=None, + checkpoint=None, + ) + c.job.project = "posttraining" + c.job.group = "debug" + c.job.name = "default_${now:%Y-%m-%d}_${now:%H-%M-%S}" + + c.trainer.type = TokenizerTrainer + c.trainer.run_validation = True + + c.trainer.seed = 1234 + c.trainer.max_iter = 10_000_000 + c.trainer.validation_iter = 5000 + c.trainer.max_val_iter = 1 + c.trainer.logging_iter = 100 + + c.trainer.callbacks = None + c.trainer.ddp.static_graph = True + c.trainer.ddp.find_unused_parameters = False + register_configs() + + # Import only the public experiment. Dynamic package discovery previously + # registered hundreds of internal and ablation configs at startup. + from tokenizer.training.configs.experiments import ( # noqa: F401 + transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_nuscenes32_gridrope_mask_pts_scratch_200k, + pai_release, + ) + + return c diff --git a/tokenizer/training/configs/experiments/__init__.py b/tokenizer/training/configs/experiments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/tokenizer/training/configs/experiments/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tokenizer/training/configs/experiments/pai_release.py b/tokenizer/training/configs/experiments/pai_release.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1dfc736d10ee83f0f585c26dfc3e8c12554565 --- /dev/null +++ b/tokenizer/training/configs/experiments/pai_release.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Strict EMA warm-start of the released PAI tokenizer.""" + +from copy import deepcopy +from collections.abc import Mapping +import os +from hydra.core.config_store import ConfigStore + +from tokenizer.training.configs.experiments.transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_nuscenes32_gridrope_mask_pts_scratch_200k import LIDARVERSE_TOKENIZER_EXPERIMENT +from utils.processed_pai import loader_config + +config = deepcopy(LIDARVERSE_TOKENIZER_EXPERIMENT) +config.defaults = [item for item in config.defaults + if not isinstance(item, Mapping) or not any(k in item for k in ("override /data_train", "override /data_val"))] +# Override the registered groups so no legacy loader arguments survive a merge. +config.defaults.insert(0, {"override /data_train": "pai_release"}) +config.defaults.insert(1, {"override /data_val": "pai_release"}) +del config["dataloader_train"] +del config["dataloader_val"] +config.job.name = "lidarverse_tokenizer_pai_finetune" +config.checkpoint.update(load_path=os.environ.get("LIDARVERSE_TOKENIZER_CHECKPOINT", + "checkpoints/lidarverse-tokenizer-pai/ckpt.pt"), load_training_state=False, strict_resume=True, save_iter=200) +config.trainer.update(max_iter=2000, run_validation=False) +config["scheduler"] = dict(warmup=0) +cs = ConfigStore.instance() +for validation in (False, True): + cs.store(group="data_val" if validation else "data_train", package="dataloader_val" if validation else "dataloader_train", + name="pai_release", node=loader_config(tokenizer=True, validation=validation)) +cs.store(group="experiment", package="_global_", name="lidarverse_tokenizer_pai_finetune", node=config) diff --git a/tokenizer/training/configs/experiments/transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_nuscenes32_gridrope_mask_pts_scratch_200k.py b/tokenizer/training/configs/experiments/transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_nuscenes32_gridrope_mask_pts_scratch_200k.py new file mode 100644 index 0000000000000000000000000000000000000000..49ed36504a4015c9d09b0e34c6c7424641699393 --- /dev/null +++ b/tokenizer/training/configs/experiments/transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_nuscenes32_gridrope_mask_pts_scratch_200k.py @@ -0,0 +1,188 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Train the Waymo-free LidarVerse range tokenizer from scratch.""" + +from hydra.core.config_store import ConfigStore + +from utils import log +from utils.lazy_config import LazyDict + + +EXPERIMENT_NAME = ( + "transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_" + "nuscenes32_gridrope_mask_pts_scratch_200k" +) +DATA_GROUP = "lidarverse_cross_dataset_range_video" + +LIDARVERSE_TOKENIZER_EXPERIMENT = LazyDict( + dict( + defaults=[ + {"override /network": "lidarverse_tokenizer"}, + {"override /loss": "video"}, + {"override /data_train": DATA_GROUP}, + {"override /data_val": DATA_GROUP}, + {"override /optimizer": "fused_adam"}, + {"override /callbacks": ["float32", "wandbLidar"]}, + "_self_", + ], + job=dict( + project="lidarverse", + group="tokenizer", + name="LidarVerse-Tokenizer-8x8x1-Z64-CrossDataset-Scratch-200K", + ), + checkpoint=dict( + load_path=None, + load_training_state=False, + strict_resume=True, + save_iter=2000, + jit=dict(enabled=False), + ), + trainer=dict( + max_iter=200000, + validation_iter=1000, + max_val_iter=15, + logging_iter=100, + ), + model=dict( + config=dict( + disc_optimizer=dict(lr=0.00016), + ema=dict(enabled=True, beta=0.999), + precision="float32", + loss=dict( + config=dict( + perceptual=None, + mask_from_batch=True, + color=dict( + config=dict(normalize_by_valid_mask=True) + ), + point_loss=dict( + config=dict( + enabled=True, + values=[1.0], + normalize_by_valid_mask=True, + ) + ), + local_chamfer=dict( + config=dict(enabled=False, values=[0.0]) + ), + gradient=dict( + config=dict(enabled=False, values=[0.0]) + ), + validity_bce=dict( + config=dict( + enabled=True, + boundaries=[0], + values=[1.0], + min_value=-1.0, + raydrop_eps=0.02, + mask_from_batch=True, + ) + ), + kl=dict( + config=dict(boundaries=[0], values=[1e-6]) + ), + ) + ), + ) + ), + optimizer=dict(lr=2e-5), + dataloader_train=dict( + batch_size=1, + mix_datasets_across_ranks=True, + dataset_sampling_weights=(1.0 / 3.0,) * 3, + dataset=dict( + shared_overrides=dict( + process_input="mono", + process_output="mono", + sample_n_frames=8, + load_intensity=False, + emit_valid_mask=True, + repeat_col=1, + repeat_temporal=1, + ), + per_dataset_overrides=dict( + nvidia_pai_range_video_train=dict( + min_range=2.5, + max_range=100.0, + downsample_factor_col=3, + repeat_row=1, + lidar_size=[128, 1200], + lidar_resize_size=[-1, -1], + ), + pandaset_range_video_train=dict( + min_range=2.5, + max_range=100.0, + repeat_row=1, + lidar_size=[64, 1024], + lidar_resize_size=[-1, -1], + ), + nuscenes_range_video_train=dict( + min_range=2.5, + max_range=100.0, + LIDAR_FPS=20, + frame_sampling_every_n_frames=1, + center_vehicle_forward=True, + repeat_row=1, + resample_width=1024, + lidar_size=[32, 1024], + lidar_resize_size=[-1, -1], + ), + ), + ), + ), + dataloader_val=dict( + batch_size=1, + dataset=dict( + shared_overrides=dict( + process_input="mono", + process_output="mono", + sample_n_frames=8, + load_intensity=False, + emit_valid_mask=True, + repeat_col=1, + repeat_temporal=1, + ), + per_dataset_overrides=dict( + nvidia_pai_range_video_val=dict( + min_range=2.5, + max_range=100.0, + downsample_factor_col=3, + repeat_row=1, + lidar_size=[128, 1200], + lidar_resize_size=[-1, -1], + ), + pandaset_range_video_val=dict( + min_range=2.5, + max_range=100.0, + repeat_row=1, + lidar_size=[64, 1024], + lidar_resize_size=[-1, -1], + ), + nuscenes_range_video_val=dict( + min_range=2.5, + max_range=100.0, + LIDAR_FPS=20, + frame_sampling_every_n_frames=1, + center_vehicle_forward=True, + repeat_row=1, + resample_width=1024, + lidar_size=[32, 1024], + lidar_resize_size=[-1, -1], + ), + ), + ), + ), + ) +) + +if LIDARVERSE_TOKENIZER_EXPERIMENT["checkpoint"]["load_path"] is not None: + raise ValueError("The public tokenizer must train from scratch") + +log.info(f"Registering experiment: {EXPERIMENT_NAME}") +ConfigStore.instance().store( + group="experiment", + package="_global_", + name=EXPERIMENT_NAME, + node=LIDARVERSE_TOKENIZER_EXPERIMENT, +) diff --git a/tokenizer/training/configs/registry.py b/tokenizer/training/configs/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..60d764037cead3a3b56ba58d2ee857da93b895f7 --- /dev/null +++ b/tokenizer/training/configs/registry.py @@ -0,0 +1,122 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +"""Minimal Hydra registry for the public LidarVerse tokenizer.""" + +from hydra.core.config_store import ConfigStore + +from tokenizer.training.configs.base.callback import ( + FLOAT32_CALLBACKS, + WANDBLIDAR_CALLBACK, +) +from tokenizer.training.configs.base.checkpoint import CHECKPOINT_LOCAL +from tokenizer.training.configs.base.loss import VideoLossConfig +from tokenizer.training.configs.base.metric import MetricConfig +from tokenizer.training.configs.base.nets.lidarverse import ( + LIDARVERSE_TOKENIZER_CONFIG, +) +from tokenizer.training.configs.base.optim import ( + FusedAdamConfig, + WarmupCosineLRConfig, + WarmupLRConfig, +) +from tokenizer.training.datasets.lidar_datasets.tokenizer_dataloader import ( + get_cross_dataset_lidar_range_map_dataloader, +) + + +TRAIN_DATASETS = ( + "nvidia_pai_range_video_train", + "pandaset_range_video_train", + "nuscenes_range_video_train", +) +VAL_DATASETS = ( + "nvidia_pai_range_video_val", + "pandaset_range_video_val", + "nuscenes_range_video_val", +) + + +def register_configs(): + cs = ConfigStore.instance() + cs.store( + group="data_train", + package="dataloader_train", + name="lidarverse_cross_dataset_range_video", + node=get_cross_dataset_lidar_range_map_dataloader( + dataset_names=TRAIN_DATASETS, + validation=False, + mix_datasets_across_ranks=True, + dataset_sampling_weights=(1.0 / 3.0,) * 3, + seed=0, + num_workers=4, + prefetch_factor=2, + ), + ) + cs.store( + group="data_val", + package="dataloader_val", + name="lidarverse_cross_dataset_range_video", + node=get_cross_dataset_lidar_range_map_dataloader( + dataset_names=VAL_DATASETS, + validation=True, + seed=0, + num_workers=4, + prefetch_factor=2, + ), + ) + cs.store( + group="network", + package="model.config.network", + name="lidarverse_tokenizer", + node=LIDARVERSE_TOKENIZER_CONFIG, + ) + cs.store( + group="optimizer", + package="optimizer", + name="fused_adam", + node=FusedAdamConfig, + ) + cs.store( + group="scheduler", + package="scheduler", + name="warmup", + node=WarmupLRConfig, + ) + cs.store( + group="scheduler", + package="scheduler", + name="warmup_cosine", + node=WarmupCosineLRConfig, + ) + cs.store( + group="loss", + package="model.config.loss", + name="video", + node=VideoLossConfig, + ) + cs.store( + group="metric", + package="model.config.metric", + name="reconstruction", + node=MetricConfig, + ) + cs.store( + group="checkpoint", + package="checkpoint", + name="local", + node=CHECKPOINT_LOCAL, + ) + cs.store( + group="callbacks", + package="trainer.callbacks", + name="float32", + node=FLOAT32_CALLBACKS, + ) + cs.store( + group="callbacks", + package="trainer.callbacks", + name="wandbLidar", + node=WANDBLIDAR_CALLBACK, + ) diff --git a/tokenizer/training/datasets/__init__.py b/tokenizer/training/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52a7a9daf028f654d6a02f65c99cc609a57b492f --- /dev/null +++ b/tokenizer/training/datasets/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tokenizer/training/datasets/lidar_datasets/configs.py b/tokenizer/training/datasets/lidar_datasets/configs.py new file mode 100644 index 0000000000000000000000000000000000000000..d13dad13308959dbbbcf4699ce96fcbe4048344b --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/configs.py @@ -0,0 +1,165 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +"""Public native-grid LiDAR dataset contracts used by LidarVerse. + +No split files are distributed with the repository. Paths can be changed with +the environment variables below or by adapting these dictionaries to another +dataset that exposes the same range-map sampler contract. +""" + +import os + + +def _path(name: str, default: str) -> str: + return os.path.expanduser(os.environ.get(name, default)) + + +def _base_range_video( + *, + data_name: str, + root: str, + split: str, + backend: str, + height: int, + width: int, + lidar_length: int, + lidar_fps: int, +) -> dict: + return { + "data_name": data_name, + "root_path": root, + "filter_list_path": split, + "t5_embedding_path": "", + "custom_folders": [root], + "custom_fields": ["lidar"], + "metadata_folder": "", + "max_range": 100.0, + "min_range": 2.5, + "downsample_factor_row": 1, + "downsample_factor_col": 1, + "repeat_row": 1, + "repeat_col": 1, + "repeat_temporal": 1, + "lidar_crop_size": [-1, -1], + "rgb_crop_size": [-1, -1], + "rgb_resize_size": [-1, -1], + "lidar_size": [height, width], + "lidar_resize_size": [-1, -1], + "downsample_method": "scatter_min", + "min_value": -1.0, + "num_views": 0, + # The video sampler prepends its first sweep, producing nine frames. + "sample_n_frames": 8, + "lidar_length": lidar_length, + "frame_sampling_method": "sequential", + "frame_sampling_every_n_frames": 1, + "sample_lidar_prob": 1.0, + "is_video_tokenizer": True, + "load_lidar_only": True, + "load_rgb_only": False, + "load_lidar_and_rgb": False, + "load_lidar_or_rgb": False, + "RGB_FPS": 30, + "LIDAR_FPS": lidar_fps, + "load_t5_embeddings": False, + "inverse_depth": False, + "process_input": "mono", + "process_output": "mono", + "load_intensity": False, + "emit_valid_mask": True, + "dataset_backend": backend, + "resample_width": width if backend.endswith("_ncore") else -1, + "center_vehicle_forward": backend == "nuscenes_ncore", + } + + +_PAI_ROOT = _path("LIDARVERSE_NVIDIA_PAI_ROOT", "data/nvidia_pai") +_PANDASET_ROOT = _path( + "LIDARVERSE_PANDASET_ROOT", "data/pandaset_rangemap_64x1024" +) +_NUSCENES_ROOT = _path("LIDARVERSE_NUSCENES_ROOT", "data/nuscenes_ncore") + +COMMONDATA_CONFIG = { + "nvidia_pai_range_video_train": _base_range_video( + data_name="mads_range_map", + root=_PAI_ROOT, + split=_path( + "LIDARVERSE_NVIDIA_PAI_TRAIN_LIST", + "data/splits/nvidia_pai_train.lst", + ), + backend="radym", + height=128, + width=1200, + lidar_length=200, + lidar_fps=10, + ), + "pandaset_range_video_train": _base_range_video( + data_name="pandaset_lidar_range_map", + root=_PANDASET_ROOT, + split=_path( + "LIDARVERSE_PANDASET_TRAIN_LIST", + "data/splits/pandaset_train.lst", + ), + backend="pandaset", + height=64, + width=1024, + lidar_length=80, + lidar_fps=10, + ), + "nuscenes_range_video_train": _base_range_video( + data_name="nuscenes_lidar_range_map", + root=_NUSCENES_ROOT, + split=_path( + "LIDARVERSE_NUSCENES_TRAIN_LIST", + "data/splits/nuscenes_train.lst", + ), + backend="nuscenes_ncore", + height=32, + width=1024, + lidar_length=380, + lidar_fps=20, + ), +} + +for dataset, env_name, default in ( + ( + "nvidia_pai", + "LIDARVERSE_NVIDIA_PAI_VAL_LIST", + "data/splits/nvidia_pai_val.lst", + ), + ( + "pandaset", + "LIDARVERSE_PANDASET_VAL_LIST", + "data/splits/pandaset_val.lst", + ), + ( + "nuscenes", + "LIDARVERSE_NUSCENES_VAL_LIST", + "data/splits/nuscenes_val.lst", + ), +): + source = f"{dataset}_range_video_train" + target = f"{dataset}_range_video_val" + COMMONDATA_CONFIG[target] = dict(COMMONDATA_CONFIG[source]) + COMMONDATA_CONFIG[target]["filter_list_path"] = _path(env_name, default) + +# The public PAI layout stores metadata beside its range-map payloads. +for split in ("train", "val"): + config = COMMONDATA_CONFIG[f"nvidia_pai_range_video_{split}"] + config["metadata_folder"] = _path( + "LIDARVERSE_NVIDIA_PAI_METADATA", "data/nvidia_pai/metadata" + ) + # Native PAI columns are reduced to the trained 1200-column grid. + config["downsample_factor_col"] = 3 + + +LIDAR_DATASET_NAMES = { + "nvidia_pai_train": "nvidia_pai_range_video_train", + "nvidia_pai_val": "nvidia_pai_range_video_val", + "pandaset_train": "pandaset_range_video_train", + "pandaset_val": "pandaset_range_video_val", + "nuscenes_train": "nuscenes_range_video_train", + "nuscenes_val": "nuscenes_range_video_val", +} diff --git a/tokenizer/training/datasets/lidar_datasets/data_fileds.py b/tokenizer/training/datasets/lidar_datasets/data_fileds.py new file mode 100644 index 0000000000000000000000000000000000000000..9845d3e7cf437aaceaccdf3389bc982d9ffbc12b --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/data_fileds.py @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from enum import Enum + +class DataField(Enum): + # [B, C, H, W], float32, RGB image ranges from 0 to 1. + IMAGE_RGB = "image_rgb" + # [B, 4, 4], float32, camera-to-world transformation matrix. + CAMERA_C2W_TRANSFORM = "camera_c2w_transform" + # [B, 4, 4], float32, camera-to-lidar transformation matrix. + CAMERA_C2LIDAR_TRANSFORM = "camera_c2lidar_transform" + # [B, 4], float32, OpenCV pinhole intrinsics represented as [fx, fy, cx, cy]. + CAMERA_INTRINSICS = "camera_intrinsics" + # [B, H, W, 3], float32, hdmap image. + IMAGE_HDMAP = "image_hdmap" + # list of captions of size B. + CAPTION = "caption" + # [B, H, W], float32, depth map in metric scale. + METRIC_DEPTH = "metric_depth" + # [B, H, W], uint8, instance mask (0 is background). + DYNAMIC_INSTANCE_MASK = "dynamic_instance_mask" + # [B, H, W], float32, backward flow from this frame to previous frame. + BACKWARD_FLOW = "backward_flow" + # [B, H, W, 3], float32, ray direction (assume no motion/RS). + RAY_DIRECTION = "ray_direction" + # TODO [Add description] + OBJECT_BBOX = "object_bbox" + # TODO [Add description] a list of float32 point cloud. + POINT_CLOUD = "point_cloud" + # [B, N, (3 + 3x3)], N future positions. For the last dim, + # the first 3 are xyz locations, and tha last 9 are rots + # B corresponds to the number of timestamps for the base camera type + TRAJECTORY = "trajectory" + # [V,] dictionary of meta data + META_DATA = "meta_data" + # [V, N, C] N is variable for different V float32 + LANGUAGE_EMBEDDING = "language_embedding" diff --git a/tokenizer/training/datasets/lidar_datasets/datasets.py b/tokenizer/training/datasets/lidar_datasets/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..8b039db7582fddff27cb03797549cef101df0934 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/datasets.py @@ -0,0 +1,294 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os, torch, tarfile +from pathlib import Path +from typing import Any, List, Optional +import numpy as np +import torch.utils.data +from decord import VideoReader +from lru import LRU +from abc import ABC +from webdataset import WebDataset, non_empty +from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField +from utils.lidar_rangemap import load_each_frame_from_tar_data + +def get_sample(url): + """Get a sample from a URL with basic auto-decoding.""" + if isinstance(url, Path): + url = url.as_posix() + + dataset = WebDataset(url, nodesplitter=non_empty, shardshuffle=False, workersplitter=None).decode() + return next(iter(dataset)) + + + +view_idx_to_camera_mapping = { + 0: "camera_front_wide_120fov", + 1: "camera_cross_left_120fov", + 2: "camera_cross_right_120fov", + 3: "camera_rear_left_70fov", + 4: "camera_rear_right_70fov", + 5: "camera_rear_tele_30fov", +} + + +class RadymLidar(ABC): + MAX_ZIP_DESCRIPTORS = 10 + MAX_MP4_READERS = 1 + MAX_TAR_READERS = 1 + + def __init__( + self, root_path, filter_list_path: Optional[str] = None, num_views: int = -1, metadata_folder: Optional[str] = None, + custom_folders: Optional[List[str]] = None, custom_fields: Optional[List[str]] = None, view_indices: Optional[List[int]] = None, + load_intensity: bool = False, + ): + # For multi-view datasets, root_path is the path to camera idx 0. + self.root_path = root_path + + # filter_list_path is a text file containing the list of mp4 files to load. + # Each line in the file should contain the name of the mp4 file with or without the extension. + if filter_list_path is None: + self.filter_set = None + else: + self.filter_list_path = filter_list_path + with open(self.filter_list_path, "r") as f: + self.filter_set = [line.strip() for line in f.readlines()] + # self.filter_set = set([x.split(".")[0] for x in self.filter_set]) + self.filter_set = [x.split(".")[0] for x in self.filter_set] + self.n_views = num_views + self.view_indices = view_indices + # Process-dependent LRU cache for file handles of the tar files. + self.worker_id = None + self.zip_descriptors = LRU( + self.MAX_ZIP_DESCRIPTORS, callback=self._evict_zip_handle + ) + self.mp4_readers = LRU(self.MAX_MP4_READERS, callback=self._evict_mp4_reader) + self.tar_readers = LRU(self.MAX_TAR_READERS, callback=self._evict_tar_reader) + + self.custom_folders = custom_folders + self.custom_fields = custom_fields + self.metadata_folder = metadata_folder + self.load_intensity = load_intensity + + @staticmethod + def _evict_zip_handle(_, zip_handle): + zip_handle.close() + + @staticmethod + def _evict_mp4_reader(_, mp4_reader: VideoReader): + # This is no-op, just a placeholder. + del mp4_reader + + @staticmethod + def _evict_tar_reader(_, tar_reader): + tar_reader.close() + + def _check_worker_id(self): + # Protect handle boundary: + worker_info = torch.utils.data.get_worker_info() + if worker_info is not None: + if self.worker_id is not None: + assert self.worker_id == worker_info.id, "Worker id mismatch" + else: + self.worker_id = worker_info.id + + + def _get_tar_handle(self, custom_folder, custom_fields, data_key): + """ + here we read the tar file + """ + self._check_worker_id() + tar_path = os.path.join(custom_folder, custom_fields, f"{data_key}.tar") + if tar_path in self.tar_readers: + return self.tar_readers[tar_path] + tar_handle = tarfile.open(tar_path, "r") + self.tar_readers[tar_path] = tar_handle + return tar_handle + + + def _get_mp4_reader(self, custom_folder, custom_fields, data_key): + self._check_worker_id() + mp4_path = os.path.join(custom_folder, custom_fields, f"{data_key}.mp4") + mp4_reader = VideoReader(mp4_path, num_threads=4) + self.mp4_readers[mp4_path] = mp4_reader + return mp4_reader + + def available_data_fields(self) -> list[DataField]: + return [ + DataField.IMAGE_RGB, + DataField.CAMERA_C2W_TRANSFORM, + DataField.CAMERA_INTRINSICS, + DataField.METRIC_DEPTH, + DataField.DYNAMIC_INSTANCE_MASK, + DataField.BACKWARD_FLOW, + DataField.OBJECT_BBOX, + DataField.CAPTION, + ] + + def size_of_filter_set(self) -> int: + return len(self.filter_set) + + def num_videos(self) -> int: + return len(self.mp4_file_paths) + + def num_views(self, video_idx: int) -> int: + return 1 if self.n_views == -1 else self.n_views + + def num_frames(self, video_idx: int, view_idx: int = 0) -> int: + return len(self._get_mp4_reader(video_idx, "rgb", view_idx)) + + + def parse_range_map_tar(self, tar_file, frame_idx, n_rows=128, n_cols=3600, load_intensity=False): + frame_idx_list = np.array([x.strip('.lidar_row.npz') for x in tar_file.getnames() if 'lidar_row' in x]) + + if frame_idx.max() > frame_idx_list.shape[0]-1: # replace those values with random integer within the range + frame_idx[frame_idx > frame_idx_list.shape[0]-1] = np.random.randint(0, frame_idx_list.shape[0]-1, size=np.sum(frame_idx > frame_idx_list.shape[0]-1)) + + frame_idx_list = frame_idx_list[frame_idx] + range_map_list = [] + intensity_map_list = [] if load_intensity else None + + for frame_idx in frame_idx_list: + result = load_each_frame_from_tar_data(tar_file, frame_idx, n_rows, n_cols, load_intensity=load_intensity) + if load_intensity: + range_map, intensity_map = result + intensity_map_list.append(intensity_map) + else: + range_map = result + range_map_list.append(range_map) + range_map = np.stack(range_map_list, axis=0) + if load_intensity: + intensity_map = np.stack(intensity_map_list, axis=0) + return range_map, intensity_map + return range_map + + + def parse_hdmap_tar(self, tar_file, frame_idx, n_rows=128, n_cols=3600): + frame_idx_list = np.array([x.strip('.lidar_row.npz') for x in tar_file.getnames() if 'lidar_row' in x]) + + if frame_idx.max() > frame_idx_list.shape[0]-1: # replace those values with random integer within the range + frame_idx[frame_idx > frame_idx_list.shape[0]-1] = np.random.randint(0, frame_idx_list.shape[0]-1, size=np.sum(frame_idx > frame_idx_list.shape[0]-1)) + + frame_idx_list = frame_idx_list[frame_idx] + hdmap_list = [] + + for frame_idx in frame_idx_list: + hdmap = load_each_frame_from_tar_data(tar_file, frame_idx, n_rows, n_cols) + hdmap_list.append(hdmap) + hdmap = np.stack(hdmap_list, axis=0) + return hdmap + + + def _parse_rgb_entries(self,lidar_idx, custom_folder, custom_fields, rgb_frame_indices, chunk_size=128): + rgb_frame_indices = [int(ele) for ele in rgb_frame_indices] + if chunk_size is not None: + rgb_video_chunk_id = rgb_frame_indices[0] // chunk_size + c_data_key = self.filter_set[lidar_idx] + f"_{rgb_video_chunk_id}" + + local_rgb_frame_indices = [ele % chunk_size for ele in rgb_frame_indices] + local_rgb_frame_indices = np.asarray(local_rgb_frame_indices).astype(np.int64) + rgb_reader = self._get_mp4_reader(custom_folder, custom_fields, c_data_key) + rgb_read = rgb_reader.get_batch(local_rgb_frame_indices) + else: # we read the raw videos + c_data_key = self.filter_set[lidar_idx] + rgb_reader = self._get_mp4_reader(custom_folder, custom_fields, c_data_key) + rgb_read = rgb_reader.get_batch(rgb_frame_indices) + + try: + rgb_np = rgb_read.asnumpy() + except AttributeError: + rgb_np = rgb_read.numpy() + rgb_np = rgb_np.astype(np.float32) / 255.0 + rgb_torch = torch.from_numpy(rgb_np).moveaxis(-1, 1).contiguous() + return rgb_torch + + def _read_rgb_and_lidar(self, lidar_idx, lidar_frame_idx, data_fields): + """ + We just use the custom fields to read both lidar and rgb related data + """ + data_key = self.filter_set[lidar_idx] + lidar_frame_idx = np.asarray(lidar_frame_idx).astype(np.int64) + + # load the metadata + metadata_path = os.path.join(self.metadata_folder, f"{data_key}.npz") + metadata = np.load(metadata_path) + lidar_pose_list = np.array(metadata['pose_list'])[lidar_frame_idx] # list + lidar_timestamp_list = np.array(metadata['timestamps_list'])[lidar_frame_idx] + rgb_frame_indices = np.array(metadata['frame_indices'])[lidar_frame_idx].tolist() # this can be different from lidar_frame_idx + lidar_to_world = lidar_pose_list[:,0] # N x 4 x 4 + lidar_to_world_next = lidar_pose_list[:,1] # N x 4 x 4 + sensor_pose_start_end = np.linalg.inv(lidar_to_world_next) @ lidar_to_world + + output_dict: dict[str | DataField, Any] = {"__key__": data_key} + camera_type = 'ftheta' + output_dict['timestamp_list'] = lidar_timestamp_list + output_dict['pose_sensor_start_end'] = sensor_pose_start_end + output_dict['lidar_to_world'] = lidar_to_world # (N, 4, 4), frame-aligned to lidar_frame_idx + output_dict['rgb_frame_indices'] = rgb_frame_indices + view_indices = self.view_indices if self.view_indices is not None else range(self.n_views) + + for data_field in data_fields: + if data_field == "custom": + if self.custom_folders is not None: + output_dict[data_field] = {} + assert len(self.custom_folders) == len(self.custom_fields), "Custom folders and types must have the same length" + for custom_folder, custom_fields in zip(self.custom_folders, self.custom_fields): + if custom_fields in ['lidar']: # read the lidar data + tar_handle = self._get_tar_handle(custom_folder, custom_fields, data_key) + result = self.parse_range_map_tar(tar_handle, lidar_frame_idx, load_intensity=self.load_intensity) + if self.load_intensity: + range_maps, intensity_maps = result + output_dict[data_field][custom_fields] = range_maps + output_dict[data_field]["lidar_intensity"] = intensity_maps + else: + output_dict[data_field][custom_fields] = result + elif custom_fields in ['hdmap']: + tar_handle = self._get_tar_handle(custom_folder, custom_fields, data_key) + hdmap = self.parse_hdmap_tar(tar_handle, lidar_frame_idx) + output_dict[data_field][custom_fields] = hdmap + else: + raise NotImplementedError(f"Can't handle custom data field {data_field}") + elif data_field == DataField.CAMERA_INTRINSICS: + output_dict[data_field] = {} + + for c_view_idx, view_idx in enumerate(view_indices): + camera_name = view_idx_to_camera_mapping[view_idx] + intrinsic_tar = os.path.join(self.root_path, f"{camera_type}_intrinsic", f"{data_key}.tar") + intrinsic_data = get_sample(intrinsic_tar)[f'{camera_type}_intrinsic.{camera_name}.npy'] + intrinsic_data = torch.from_numpy(intrinsic_data).contiguous() + output_dict[data_field][c_view_idx] = intrinsic_data + elif data_field == DataField.CAMERA_C2LIDAR_TRANSFORM: + output_dict[data_field] = {} + for c_view_idx, view_idx in enumerate(view_indices): + camera_name = view_idx_to_camera_mapping[view_idx] + camera_pose_path = os.path.join(self.root_path, "pose", f"{data_key}.tar") + camera_pose_data = get_sample(camera_pose_path) + camera_to_world = np.array([camera_pose_data[f'{frame_idx}.pose.{camera_name}.npy'] for frame_idx in rgb_frame_indices]) + camera_to_lidar = np.linalg.inv(lidar_to_world) @ camera_to_world + camera_to_lidar = torch.from_numpy(camera_to_lidar).contiguous() + output_dict[data_field][c_view_idx] = camera_to_lidar + elif data_field == DataField.IMAGE_RGB: # here we directly read the raw videos + output_dict[data_field] = {} + for c_view_idx, view_idx in enumerate(view_indices): + custom_folder = self.root_path + custom_fields = f"{camera_type}_{view_idx_to_camera_mapping[view_idx]}" + rgb_torch = self._parse_rgb_entries(lidar_idx, custom_folder, custom_fields, rgb_frame_indices, chunk_size=None) + output_dict[data_field][c_view_idx] = rgb_torch + else: + raise NotImplementedError(f"Can't handle data field {data_field}") + + return output_dict \ No newline at end of file diff --git a/tokenizer/training/datasets/lidar_datasets/nuscenes_hdmap.py b/tokenizer/training/datasets/lidar_datasets/nuscenes_hdmap.py new file mode 100644 index 0000000000000000000000000000000000000000..16f5ec4244a275942496ac78f93a9f29ebb8d629 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/nuscenes_hdmap.py @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""nuScenes on-the-fly HDMap composer. + +Thin subclass of ``WaymoHDMapComposer``: the rasterization / projection / box +geometry is dataset-agnostic and reused verbatim. The ONLY nuScenes-specific +piece is the projection frame. NCore's re-derived pose graph drifts from +nuScenes' ``ego_pose`` trajectory, so instead of the NCore ``lidar_to_world`` we +project the map/boxes (kept in the nuScenes GLOBAL frame by +``scripts/data/dump_nuscenes_hdmap.py``) with the per-sweep nuScenes +``lidar_to_global`` stored alongside them -- nuScenes map + ego_pose are +self-consistent, so the map lands on the actual returns. + +Frame indices are 1:1 with the NCore lidar frames (verified: same ordered sweep +list, same count), so a sampled NCore ``frame_idx`` indexes this NPZ directly. +""" + +import numpy as np + +from tokenizer.training.datasets.lidar_datasets.waymo_hdmap import WaymoHDMapComposer + + +class NuScenesHDMapComposer(WaymoHDMapComposer): + """Per-scene nuScenes HDMap rasterizer (map/boxes in the nuScenes global frame).""" + + def __init__( + self, + *args, + virtual_sensor_height_m=None, + virtual_sensor_yaw_deg=0.0, + **kwargs, + ): + super().__init__(*args, **kwargs) + # npz_path is the first positional (parent already validated + loaded it). + npz_path = args[0] if args else kwargs["npz_path"] + d = np.load(npz_path, allow_pickle=False) + # per-sweep nuScenes lidar->global; the frame the composer projects from. + self.lidar_to_global = d["lidar_to_global"].astype(np.float32) # (F,4,4) + self.frame_timestamps_us = d["frame_timestamps_us"].astype(np.int64) # (F,) + self.virtual_sensor_height_m = ( + None if virtual_sensor_height_m is None + else float(virtual_sensor_height_m) + ) + self.virtual_sensor_yaw_deg = float(virtual_sensor_yaw_deg) + + def pose_for_frame(self, frame_idx: int) -> np.ndarray: + """nuScenes lidar->global for sweep ``frame_idx`` (the projection frame).""" + pose = self.lidar_to_global[int(frame_idx)] + if ( + self.virtual_sensor_height_m is None + and self.virtual_sensor_yaw_deg == 0.0 + ): + return pose + pose = pose.copy() + if self.virtual_sensor_yaw_deg != 0.0: + # nuScenes LIDAR_TOP uses x-right/y-forward. The canonical + # nuScenes->Waymo config supplies the yaw needed to map the NCore + # Waymo TOP sensor axes into these native lidar axes before the + # stored lidar->global transform. + yaw = np.deg2rad(self.virtual_sensor_yaw_deg) + c, s = np.cos(yaw), np.sin(yaw) + correction = np.array( + [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]], + dtype=np.float32, + ) + pose[:3, :3] = pose[:3, :3] @ correction + if self.virtual_sensor_height_m is not None: + # nuScenes maps are 2D at global z=0. Canonical generation therefore + # uses an explicit virtual sensor height instead of inheriting the + # nuScenes HDL-32E height (~1.84 m). + pose[2, 3] = self.virtual_sensor_height_m + return pose diff --git a/tokenizer/training/datasets/lidar_datasets/nuscenes_ncore.py b/tokenizer/training/datasets/lidar_datasets/nuscenes_ncore.py new file mode 100644 index 0000000000000000000000000000000000000000..12932c6d83ef6eb82be1e2b2561c0eeebd194454 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/nuscenes_ncore.py @@ -0,0 +1,745 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""NCore-backed nuScenes lidar reader (the RadymLidar analog for NCore V4 data). + +This is the nuScenes sibling of ``waymo_ncore.py``. nuScenes NCore stores the +lidar (a 32-beam Velodyne HDL-32E spinning sensor) as the SAME *structured +sparse ray bundle* per frame that Waymo uses -- each ray carries a +``model_element`` (row, col) index into the sensor grid plus per-return +``distance_m`` / ``intensity`` / ``valid_mask``. The sensor grid is defined by a +``RowOffsetStructuredSpinningLidarModel`` whose ``row_elevations_rad`` (32) and +``column_azimuths_rad`` tables give the beam geometry. + +Because the ray-bundle API and the structured-spinning model are identical to +Waymo's (only the row/column counts differ), this module REUSES the verified, +sensor-agnostic geometry helpers from ``waymo_ncore`` (``get_waymo_model_tables`` +etc.) and only diverges on: + + * the default ``lidar_id`` / camera-name map (nuScenes 6-camera rig), + * hdmap rasterized from a per-scene NPZ (scripts/data/dump_nuscenes_hdmap.py) but + projected with the nuScenes per-sweep ``lidar_to_global`` stored in the NPZ + (the NCore pose graph drifts from nuScenes' ego_pose), NOT the NCore pose, + * NO dumped blind-spot extra lidars (nuScenes has a single lidar). + +The reader returns the same dict keys ``LidarRangeMapSampler`` depends on, so the +rest of the pipeline works unchanged. All reads are strictly read-only. +""" + +import os +import threading +from typing import Any, List, Optional, Tuple + +import numpy as np +import torch +import torch.utils.data +from lru import LRU + +from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField + +# Sensor-agnostic NCore geometry helpers (defined for the Waymo reader but they +# only read a RowOffsetStructuredSpinningLidarModel's angle tables, so they apply +# to any NCore structured-spinning lidar, nuScenes included). +from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + get_waymo_model_tables as get_ncore_model_tables, + load_waymo_lidar_geometry, + waymo_range_map_to_ray_directions as ncore_range_map_to_ray_directions, + waymo_resampled_azimuth_table as ncore_resampled_azimuth_table, +) + +try: + from ncore.data.v4 import SequenceComponentGroupsReader, SequenceLoaderV4 + from ncore.impl.data.types import FrameTimepoint + + _NCORE_AVAILABLE = True + _NCORE_IMPORT_ERROR: Optional[Exception] = None +except Exception as _e: # pragma: no cover - import guard for CPU-only envs + _NCORE_AVAILABLE = False + _NCORE_IMPORT_ERROR = _e + FrameTimepoint = None # type: ignore + + +# Camera view index -> NCore camera instance name (nuScenes 6-camera rig). +NUSCENES_VIEW_IDX_TO_CAMERA = { + 0: "camera_front", + 1: "camera_front_left", + 2: "camera_front_right", + 3: "camera_back", + 4: "camera_back_left", + 5: "camera_back_right", +} + + +def canonicalize_vehicle_forward_columns( + values: np.ndarray, + ray_directions: np.ndarray, + lidar_to_rig: np.ndarray, + column_axis: int = -1, +) -> np.ndarray: + """Put rig-forward at W/2 with azimuth decreasing left-to-right.""" + width = values.shape[column_axis] + if width != ray_directions.shape[1]: + raise ValueError( + f"values width {width} != ray width " + f"{ray_directions.shape[1]}" + ) + rotation = np.asarray(lidar_to_rig, dtype=np.float64)[:3, :3] + rays_rig = np.asarray(ray_directions, dtype=np.float64) @ rotation.T + horizontal = rays_rig[..., :2] + horizontal /= np.linalg.norm(horizontal, axis=-1, keepdims=True).clip( + min=1e-12 + ) + column_xy = horizontal.mean(axis=0) + column_azimuth = np.arctan2(column_xy[:, 1], column_xy[:, 0]) + front_column = int(np.argmax(column_xy[:, 0])) + next_column = (front_column + 1) % column_azimuth.shape[0] + azimuth_step = np.arctan2( + np.sin(column_azimuth[next_column] - column_azimuth[front_column]), + np.cos(column_azimuth[next_column] - column_azimuth[front_column]), + ) + + output = np.asarray(values) + if azimuth_step > 0: + output = np.flip(output, axis=column_axis) + front_column = width - 1 - front_column + output = np.roll(output, width // 2 - front_column, axis=column_axis) + return np.ascontiguousarray(output) + + +def _lidar_to_rig(loader, lidar, lidar_id: str) -> np.ndarray: + timestamp = np.asarray( + [lidar.frames_timestamps_us[0, FrameTimepoint.START.value]], + dtype=np.uint64, + ) + return loader.pose_graph.evaluate_poses( + lidar_id, "rig", timestamp + )[0].astype(np.float64) + + +def load_nuscenes_lidar_geometry( + root_path: str, + filter_list_path: Optional[str] = None, + lidar_id: str = "lidar_top", + resample_width: int = -1, + itar_index_tail_read_size: int = 1 << 20, + center_vehicle_forward: bool = True, +) -> tuple[np.ndarray, np.ndarray]: + """Return native ray directions and the LiDAR-to-rig calibration. + + Opens the FIRST clip in the filter list ONCE to read the sensor's + ``row_elevations_rad`` / ``column_azimuths_rad`` / ``row_azimuth_offsets_rad`` + tables (all nuScenes top-lidar scenes share the same structured spinning + model). When ``resample_width > 0`` the azimuth axis is the uniform-azimuth + rebin grid the reader scatters onto; otherwise the native column grid. + + Strictly read-only. Mirrors ``load_waymo_ray_directions``. + """ + if not _NCORE_AVAILABLE: + raise ImportError( + "load_nuscenes_lidar_geometry requires the `ncore` package (pip " + f"install nvidia-ncore). Import failed with: {_NCORE_IMPORT_ERROR}" + ) + stems: List[str] = [] + if filter_list_path is not None and os.path.isfile(filter_list_path): + with open(filter_list_path, "r") as f: + stems = [line.strip() for line in f.readlines() if line.strip()] + stems = [s.split(".ncore4")[0].split(".json")[0] for s in stems] + if not stems and os.path.isdir(root_path): + for name in sorted(os.listdir(root_path)): + d = os.path.join(root_path, name) + if os.path.isdir(d) and os.path.isfile( + os.path.join(d, f"{name}.ncore4-{lidar_id}.zarr.itar") + ): + stems.append(name) + break + if not stems: + raise RuntimeError( + f"load_nuscenes_lidar_geometry: no clips found (root={root_path}, " + f"filter_list_path={filter_list_path})." + ) + stem = stems[0] + clip_dir = os.path.join(root_path, stem) + paths = [ + os.path.join(clip_dir, f"{stem}.ncore4.zarr.itar"), + os.path.join(clip_dir, f"{stem}.ncore4-{lidar_id}.zarr.itar"), + ] + reader = SequenceComponentGroupsReader( + paths, itar_index_tail_read_size=itar_index_tail_read_size + ) + loader = SequenceLoaderV4( + reader, masks_component_group_name=None, cuboids_component_group_name=None + ) + lidar = loader.get_lidar_sensor(lidar_id) + elev, azim, row_off = get_ncore_model_tables(lidar.model_parameters) + if resample_width and int(resample_width) > 0: + azim = ncore_resampled_azimuth_table(azim, int(resample_width)) + dirs = ncore_range_map_to_ray_directions(elev, azim, row_off) # (R, W, 3) + lidar_to_rig = _lidar_to_rig(loader, lidar, lidar_id) + if center_vehicle_forward: + dirs = canonicalize_vehicle_forward_columns( + dirs, + dirs, + lidar_to_rig, + column_axis=-2, + ) + del loader, reader + return dirs, lidar_to_rig + + +def load_nuscenes_ray_directions( + root_path: str, + filter_list_path: Optional[str] = None, + lidar_id: str = "lidar_top", + resample_width: int = -1, + itar_index_tail_read_size: int = 1 << 20, + center_vehicle_forward: bool = True, +) -> np.ndarray: + """Per-pixel unit ray directions ``(R, W, 3)`` for the nuScenes range image.""" + dirs, _ = load_nuscenes_lidar_geometry( + root_path=root_path, + filter_list_path=filter_list_path, + lidar_id=lidar_id, + resample_width=resample_width, + itar_index_tail_read_size=itar_index_tail_read_size, + center_vehicle_forward=center_vehicle_forward, + ) + return dirs + + +# ----------------------------------------------------------------------------- # +# Reader +# ----------------------------------------------------------------------------- # +class NuScenesNCoreLidar: + """RadymLidar-compatible reader backed by nuScenes NCore V4 ``.zarr.itar``. + + Mirrors ``WaymoNCoreLidar`` (same surface ``LidarRangeMapSampler`` depends on: + ``custom_fields``, ``size_of_filter_set()``, + ``_read_rgb_and_lidar(lidar_idx, lidar_frame_idx, data_fields)``). hdmap is + supported via a dumped NPZ (nuScenes-pose-projected); blind-spot extra lidars + are not (nuScenes has a single lidar). + """ + + MAX_LOADERS = 4 # per-worker cache of opened NCore sequences (.itar handles) + + def __init__( + self, + root_path: str, + filter_list_path: Optional[str] = None, + num_views: int = -1, + metadata_folder: Optional[str] = None, + custom_folders: Optional[List[str]] = None, + custom_fields: Optional[List[str]] = None, + view_indices: Optional[List[int]] = None, + load_intensity: bool = False, + min_range: float = 1.0, + max_range: float = 100.0, + # --- NCore specifics --- + lidar_id: str = "lidar_top", + return_index: int = 0, + load_cameras: bool = False, + itar_index_tail_read_size: int = 1 << 20, + resample_width: int = -1, + center_vehicle_forward: bool = True, + # --- hdmap (on-the-fly rasterized from dump_nuscenes_hdmap.py NPZs) --- + hdmap_root: Optional[str] = None, + hdmap_box_edge_spacing: float = 0.15, + hdmap_moving_only: bool = False, + hdmap_include_boxes: bool = True, + hdmap_map_max_dist: Optional[float] = None, + hdmap_multichannel: bool = False, + hdmap_bev: bool = False, + hdmap_bev_size: Tuple[int, int] = (256, 256), + hdmap_bev_pc_range: Tuple[float, float, float, float, float, float] = ( + -50.0, 50.0, -50.0, 50.0, -5.0, 5.0, + ), + # --- optional nuScenes-layout -> Waymo-sensor canonicalization --- + hdmap_sensor_template: str = "native", + hdmap_template_root_path: Optional[str] = None, + hdmap_template_filter_list_path: Optional[str] = None, + hdmap_virtual_sensor_height_m: Optional[float] = None, + hdmap_virtual_sensor_yaw_deg: float = 0.0, + canonical_lidar_mode: str = "native", + hdmap_pose_for_lidar_to_world: bool = False, + **_ignored: Any, + ): + if not _NCORE_AVAILABLE: + raise ImportError( + "NuScenesNCoreLidar requires the `ncore` package (pip install " + f"nvidia-ncore). Import failed with: {_NCORE_IMPORT_ERROR}" + ) + + self.root_path = root_path + self.num_views = num_views + self.n_views = num_views + self.view_indices = view_indices + self.custom_folders = custom_folders + self.custom_fields = custom_fields if custom_fields is not None else ["lidar"] + self.metadata_folder = metadata_folder + self.load_intensity = load_intensity + + self.min_range = float(min_range) + self.max_range = float(max_range) + + self.lidar_id = lidar_id + self.return_index = return_index + self.load_cameras = load_cameras + self.itar_index_tail_read_size = itar_index_tail_read_size + # >0 -> rebin the native column/azimuth axis onto a uniform grid of this + # width. <=0 -> keep the native grid. Rows (beams) are never resampled. + self.resample_width = int(resample_width) + self.center_vehicle_forward = bool(center_vehicle_forward) + + # HDMap: no native NCore component; rasterized on the fly from the per-scene + # NPZ written by scripts/data/dump_nuscenes_hdmap.py. Unlike Waymo, the composer + # projects with the nuScenes per-sweep lidar_to_global stored in the NPZ (the + # NCore pose graph drifts from nuScenes' ego_pose), NOT the NCore lidar pose. + self.hdmap_root = hdmap_root + self.hdmap_box_edge_spacing = float(hdmap_box_edge_spacing) + self.hdmap_moving_only = bool(hdmap_moving_only) + self.hdmap_include_boxes = bool(hdmap_include_boxes) + self.hdmap_multichannel = bool(hdmap_multichannel) + self.hdmap_bev = bool(hdmap_bev) + self.hdmap_bev_size = tuple(hdmap_bev_size) + self.hdmap_bev_pc_range = tuple(hdmap_bev_pc_range) + self.hdmap_map_max_dist = ( + self.max_range if hdmap_map_max_dist is None else float(hdmap_map_max_dist) + ) + if hdmap_sensor_template not in ("native", "waymo"): + raise ValueError( + "hdmap_sensor_template must be 'native' or 'waymo', got " + f"{hdmap_sensor_template!r}" + ) + if canonical_lidar_mode not in ("native", "empty"): + raise ValueError( + "canonical_lidar_mode must be 'native' or 'empty', got " + f"{canonical_lidar_mode!r}" + ) + if hdmap_sensor_template == "waymo" and canonical_lidar_mode != "empty": + raise ValueError( + "Waymo-template HDMap projection requires canonical_lidar_mode='empty' " + "so video and conditioning share the 64-row Waymo tensor shape." + ) + self.hdmap_sensor_template = hdmap_sensor_template + self.hdmap_virtual_sensor_height_m = ( + None if hdmap_virtual_sensor_height_m is None + else float(hdmap_virtual_sensor_height_m) + ) + self.hdmap_virtual_sensor_yaw_deg = float( + hdmap_virtual_sensor_yaw_deg + ) + self.canonical_lidar_mode = canonical_lidar_mode + self.hdmap_pose_for_lidar_to_world = bool( + hdmap_pose_for_lidar_to_world + ) + self._template_geometry = None + if self.hdmap_sensor_template == "waymo": + if not hdmap_template_root_path: + raise ValueError( + "hdmap_template_root_path is required when " + "hdmap_sensor_template='waymo'" + ) + _, elev, azim, row_off = load_waymo_lidar_geometry( + root_path=hdmap_template_root_path, + filter_list_path=hdmap_template_filter_list_path, + lidar_id="lidar_top", + resample_width=-1, + itar_index_tail_read_size=self.itar_index_tail_read_size, + ) + self._template_geometry = (elev, azim, row_off, int(azim.shape[0])) + self.composers: dict[str, Any] = {} + + # nuScenes has a single spinning lidar (no dumped blind-spot extras). + if "extra_lidar" in self.custom_fields: + raise NotImplementedError( + "NuScenesNCoreLidar does not support custom_fields ['extra_lidar'] " + "(nuScenes has a single lidar). Use custom_fields=['lidar'] or " + "['lidar', 'hdmap']." + ) + if "hdmap" in self.custom_fields and not self.hdmap_root: + raise NotImplementedError( + "nuScenes NCore has no native hdmap component. Set hdmap_root= to rasterize one on the fly, or remove " + "'hdmap' from custom_fields." + ) + if ( + self.hdmap_pose_for_lidar_to_world + and "hdmap" not in self.custom_fields + ): + raise ValueError( + "hdmap_pose_for_lidar_to_world requires the HDMap composer" + ) + + # Build the clip list (stems). Each clip is a subdir // that + # holds .ncore4*.zarr.itar + .json. + self.filter_set: List[str] = self._build_filter_set(filter_list_path) + if len(self.filter_set) == 0: + raise RuntimeError( + f"No nuScenes NCore clips found (root={root_path}, " + f"filter_list_path={filter_list_path})." + ) + + # Per-worker handle cache (opened lazily inside the worker process). + self.worker_id: Optional[int] = None + self._lock = threading.Lock() + self.loaders = LRU(self.MAX_LOADERS, callback=self._evict_loader) + + def canonicalize_columns( + self, loader, lidar, values: np.ndarray + ) -> np.ndarray: + if ( + not self.center_vehicle_forward + or self.canonical_lidar_mode != "native" + ): + return np.ascontiguousarray(values) + elev, azim, row_off = get_ncore_model_tables(lidar.model_parameters) + if self.resample_width > 0: + azim = ncore_resampled_azimuth_table(azim, self.resample_width) + rays = ncore_range_map_to_ray_directions(elev, azim, row_off) + return canonicalize_vehicle_forward_columns( + values, rays, _lidar_to_rig(loader, lidar, self.lidar_id) + ) + + # --------------------------------------------------------------------- # + @staticmethod + def _evict_loader(_key, value): + loader, reader = value + del loader, reader + + def _build_filter_set(self, filter_list_path: Optional[str]) -> List[str]: + if filter_list_path is not None and os.path.isfile(filter_list_path): + with open(filter_list_path, "r") as f: + stems = [line.strip() for line in f.readlines() if line.strip()] + stems = [s.split(".ncore4")[0].split(".json")[0] for s in stems] + return stems + # Fallback: scan root for clip subdirs containing the lidar itar. + stems = [] + if os.path.isdir(self.root_path): + for name in sorted(os.listdir(self.root_path)): + d = os.path.join(self.root_path, name) + if os.path.isdir(d) and os.path.isfile( + os.path.join(d, f"{name}.ncore4-{self.lidar_id}.zarr.itar") + ): + stems.append(name) + return stems + + def _check_worker_id(self): + info = torch.utils.data.get_worker_info() + if info is not None: + if self.worker_id is not None: + assert self.worker_id == info.id, "Worker id mismatch" + else: + self.worker_id = info.id + + def _clip_component_paths(self, stem: str) -> List[str]: + clip_dir = os.path.join(self.root_path, stem) + paths = [ + os.path.join(clip_dir, f"{stem}.ncore4.zarr.itar"), + os.path.join(clip_dir, f"{stem}.ncore4-{self.lidar_id}.zarr.itar"), + ] + if self.load_cameras: + view_indices = ( + self.view_indices + if self.view_indices is not None + else range(max(self.num_views, 0)) + ) + for v in view_indices: + cam_name = NUSCENES_VIEW_IDX_TO_CAMERA[v] + paths.append( + os.path.join(clip_dir, f"{stem}.ncore4-{cam_name}.zarr.itar") + ) + return paths + + def _get_loader(self, stem: str): + """Open (and cache) the NCore sequence loader for a clip.""" + self._check_worker_id() + if stem in self.loaders: + return self.loaders[stem][0] + paths = self._clip_component_paths(stem) + reader = SequenceComponentGroupsReader( + paths, itar_index_tail_read_size=self.itar_index_tail_read_size + ) + loader = SequenceLoaderV4( + reader, + masks_component_group_name=None, + cuboids_component_group_name=None, + ) + self.loaders[stem] = (loader, reader) + return loader + + def _get_composer(self, stem: str, lidar): + """Open (and cache) the per-scene HDMap composer (nuScenes-pose-projected).""" + if stem in self.composers: + return self.composers[stem] + from tokenizer.training.datasets.lidar_datasets.nuscenes_hdmap import ( + NuScenesHDMapComposer, + ) + + npz_path = os.path.join(self.hdmap_root, f"{stem}.npz") + if not os.path.isfile(npz_path): + raise FileNotFoundError( + f"HDMap NPZ not found: {npz_path} (run scripts/data/dump_nuscenes_hdmap.py " + f"--scene {stem} --out_root {self.hdmap_root})." + ) + if self._template_geometry is None: + elev, azim, row_off = get_ncore_model_tables(lidar.model_parameters) + native_columns = int(lidar.model_parameters.n_columns) + else: + elev, azim, row_off, native_columns = self._template_geometry + comp = NuScenesHDMapComposer( + npz_path, + elev, + azim, + row_off, + native_columns, + box_edge_spacing=self.hdmap_box_edge_spacing, + map_max_dist=self.hdmap_map_max_dist, + virtual_sensor_height_m=self.hdmap_virtual_sensor_height_m, + virtual_sensor_yaw_deg=self.hdmap_virtual_sensor_yaw_deg, + ) + # Frame indices are 1:1 with NCore lidar frames (same ordered sweep list). + if comp.lidar_to_global.shape[0] != int(lidar.frames_count): + raise RuntimeError( + f"[{stem}] hdmap NPZ has {comp.lidar_to_global.shape[0]} frames but " + f"NCore lidar has {int(lidar.frames_count)} -- re-dump with the " + "matching nuScenes version so frame indices align." + ) + self.composers[stem] = comp + return comp + + # --------------------------------------------------------------------- # + def size_of_filter_set(self) -> int: + return len(self.filter_set) + + @staticmethod + def _clamp_frame_indices(frame_idx: np.ndarray, frames_count: int) -> np.ndarray: + """Replace out-of-range indices with random valid ones (mirrors + RadymLidar.parse_range_map_tar).""" + frame_idx = np.asarray(frame_idx).astype(np.int64).copy() + oob = frame_idx > frames_count - 1 + if oob.any(): + frame_idx[oob] = np.random.randint(0, frames_count - 1, size=int(oob.sum())) + return frame_idx + + def _scatter_frame( + self, lidar, fi: int, R: int, C: int + ) -> Tuple[np.ndarray, Optional[np.ndarray]]: + """Build a dense (R, outW) range map (and optional intensity) for frame + fi. ``outW = resample_width`` if >0 (uniform-azimuth rebin), else ``C``. + On a collision (multiple native columns -> one target bin) the NEAREST + return wins (smallest range = closest surface).""" + elem = lidar.get_frame_ray_bundle_model_element(fi) # (N, 2) row,col + if elem is None: + raise RuntimeError( + f"Lidar frame {fi} has no model_element (cannot rasterize)." + ) + dist = lidar.get_frame_ray_bundle_return_distance_m(fi, return_index=self.return_index) + valid = lidar.get_frame_ray_bundle_return_valid_mask(fi, return_index=self.return_index) + mask = valid & np.isfinite(dist) & (dist > 0) + rows = elem[mask, 0].astype(np.int64) + cols = elem[mask, 1].astype(np.int64) + d = dist[mask].astype(np.float32) + inten = None + if self.load_intensity: + inten = lidar.get_frame_ray_bundle_return_intensity( + fi, return_index=self.return_index + )[mask].astype(np.float32) + + if self.resample_width > 0: + outW = self.resample_width + cols = np.minimum((cols * outW) // C, outW - 1) + # nearest-range wins on collision: sort descending so the smallest + # range is written LAST (overwrites). + order = np.argsort(-d, kind="stable") + rows, cols, d = rows[order], cols[order], d[order] + if inten is not None: + inten = inten[order] + else: + outW = C + + range_map = np.zeros((R, outW), dtype=np.float32) + range_map[rows, cols] = d + + intensity_map = None + if inten is not None: + intensity_map = np.zeros((R, outW), dtype=np.float32) + intensity_map[rows, cols] = inten + return range_map, intensity_map + + def _poses_for_frames(self, loader, lidar, frame_idx: np.ndarray): + """Return (lidar_to_world (N,4,4), sensor_pose_start_end (N,4,4), + timestamp_list (N,)).""" + fts = lidar.frames_timestamps_us # (F, 2) uint64 [START, END] + t_start = fts[frame_idx, FrameTimepoint.START.value].astype(np.uint64) + t_end = fts[frame_idx, FrameTimepoint.END.value].astype(np.uint64) + pg = loader.pose_graph + l2w_start = pg.evaluate_poses(self.lidar_id, "world", t_start).astype(np.float32) + l2w_end = pg.evaluate_poses(self.lidar_id, "world", t_end).astype(np.float32) + # Mirror LidarGEN: relative within-sweep motion = inv(end) @ start. + sensor_pose_start_end = (np.linalg.inv(l2w_end) @ l2w_start).astype(np.float32) + return l2w_start, sensor_pose_start_end, t_end.astype(np.int64) + + def _read_rgb_and_lidar(self, lidar_idx, lidar_frame_idx, data_fields): + """Mirror RadymLidar._read_rgb_and_lidar, NCore-backed (nuScenes).""" + stem = self.filter_set[lidar_idx] + loader = self._get_loader(stem) + lidar = loader.get_lidar_sensor(self.lidar_id) + frames_count = lidar.frames_count + frame_idx = self._clamp_frame_indices(lidar_frame_idx, frames_count) + + mp = lidar.model_parameters + R, C = int(mp.n_rows), int(mp.n_columns) + if self._template_geometry is None: + output_rows = R + else: + output_rows = int(self._template_geometry[0].shape[0]) + output_width = self.resample_width if self.resample_width > 0 else ( + int(self._template_geometry[3]) if self._template_geometry is not None else C + ) + + output_dict: dict[str | DataField, Any] = {"__key__": stem} + + l2w_start, sensor_pose_start_end, ts = self._poses_for_frames(loader, lidar, frame_idx) + if self.canonical_lidar_mode == "empty": + comp = self._get_composer(stem, lidar) + l2w_start = np.stack( + [comp.pose_for_frame(int(fi)) for fi in frame_idx], axis=0 + ).astype(np.float32) + sensor_pose_start_end = np.repeat( + np.eye(4, dtype=np.float32)[None], len(frame_idx), axis=0 + ) + ts = comp.frame_timestamps_us[frame_idx].astype(np.int64) + elif self.hdmap_pose_for_lidar_to_world: + # Keep accumulated-geometry registration in the same nuScenes + # global frame used to render the map. NCore's start/end relative + # pose remains the within-sweep rolling-shutter correction. + comp = self._get_composer(stem, lidar) + l2w_start = np.stack( + [comp.pose_for_frame(int(fi)) for fi in frame_idx], axis=0 + ).astype(np.float32) + ts = comp.frame_timestamps_us[frame_idx].astype(np.int64) + output_dict["timestamp_list"] = ts + output_dict["pose_sensor_start_end"] = sensor_pose_start_end + output_dict["lidar_to_world"] = l2w_start # (N, 4, 4), sweep-start + output_dict["rgb_frame_indices"] = frame_idx.tolist() + + for data_field in data_fields: + if data_field == "custom": + output_dict[data_field] = {} + range_list, intensity_list = [], [] + if self.canonical_lidar_mode == "empty": + range_list = [ + np.zeros((output_rows, output_width), dtype=np.float32) + for _ in frame_idx + ] + else: + for fi in frame_idx: + rmap, imap = self._scatter_frame(lidar, int(fi), R, C) + range_list.append( + self.canonicalize_columns(loader, lidar, rmap) + ) + if imap is not None: + intensity_list.append( + self.canonicalize_columns(loader, lidar, imap) + ) + output_dict[data_field]["lidar"] = np.stack(range_list, axis=0) # [N, R, C] + if self.load_intensity: + if self.canonical_lidar_mode == "empty": + intensity_list = [ + np.zeros((output_rows, output_width), dtype=np.float32) + for _ in frame_idx + ] + output_dict[data_field]["lidar_intensity"] = np.stack(intensity_list, axis=0) + if "hdmap" in self.custom_fields: + comp = self._get_composer(stem, lidar) + outW = output_width + # Project with the nuScenes per-sweep pose (NOT the NCore l2w): + # map/boxes live in the nuScenes global frame. + hdmap_list = [] + for fi in frame_idx: + pose = comp.pose_for_frame(int(fi)) + if self.hdmap_multichannel: + hdmap = comp.rasterize_multichannel( + int(fi), + pose, + outW, + self.min_range, + self.max_range, + moving_only=self.hdmap_moving_only, + ) + else: + hdmap = comp.rasterize( + int(fi), + pose, + outW, + self.min_range, + self.max_range, + include_boxes=self.hdmap_include_boxes, + moving_only=self.hdmap_moving_only, + ) + hdmap_list.append( + self.canonicalize_columns(loader, lidar, hdmap) + ) + # multichannel -> (N, NUM_CLASSES, R, W); else (N, R, W). + output_dict[data_field]["hdmap"] = np.stack(hdmap_list, axis=0) + if self.hdmap_bev: + bev_list = [ + comp.rasterize_bev( + int(fi), comp.pose_for_frame(int(fi)), + self.hdmap_bev_size, self.hdmap_bev_pc_range, + include_boxes=self.hdmap_include_boxes, + moving_only=self.hdmap_moving_only, + ) + for fi in frame_idx + ] + output_dict[data_field]["hdmap_bev"] = np.stack(bev_list, axis=0) + elif data_field == DataField.IMAGE_RGB: + # Camera RGB conditioning: read each requested view's image + # nearest (in time) to every sampled lidar frame, as (N, 3, H, W) + # in [0, 1] -- the format the sampler's get_rgb()/process_rgb() + # expects. Cameras must have been opened (load_cameras=True). + output_dict[data_field] = {} + view_indices = ( + self.view_indices + if self.view_indices is not None + else list(range(max(self.num_views, 0))) + ) + for c_view_idx, view_idx in enumerate(view_indices): + cam_name = NUSCENES_VIEW_IDX_TO_CAMERA[view_idx] + cam = loader.get_camera_sensor(cam_name) + frames = [] + for t_us in ts: + ci = cam.get_closest_frame_index(int(t_us)) + img = np.asarray(cam.get_frame_image_array(ci)) # (H,W,3) uint8 + frames.append(img) + rgb = np.stack(frames, axis=0) # (N, H, W, 3) + rgb = ( + torch.from_numpy(rgb).permute(0, 3, 1, 2).contiguous().float() + / 255.0 + ) # (N, 3, H, W) in [0, 1] + output_dict[data_field][c_view_idx] = rgb + elif data_field in ( + DataField.CAMERA_INTRINSICS, + DataField.CAMERA_C2LIDAR_TRANSFORM, + ): + # Image-conditioned RF models only VAE-encode the RGB as context; + # they never project points, so intrinsics / extrinsics are + # unused. Emit empty dicts (sampler treats as no-op). + output_dict[data_field] = {} + else: + raise NotImplementedError( + f"NuScenesNCoreLidar does not yet handle data field {data_field}." + ) + + return output_dict diff --git a/tokenizer/training/datasets/lidar_datasets/pandaset.py b/tokenizer/training/datasets/lidar_datasets/pandaset.py new file mode 100644 index 0000000000000000000000000000000000000000..14094bd0ac24c8d4955b07ac26b5955e5f911898 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/pandaset.py @@ -0,0 +1,1161 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +# SPDX-License-Identifier: Apache-2.0 + +"""PandaSet Pandar64 range-image projection and cache reader. + +The official raw release preserves Pandar64 firing rows and physical azimuths +and is the source of truth for the 64-row image. The processed release stores +motion-compensated world points; paired raw/processed points recover and verify +the unpublished Pandar64-to-pose-reference extrinsic when a cache is built. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any, Optional, Sequence + +import numpy as np + + +PANDASET_CACHE_VERSION = "pandaset_pandar64_64x1024_v6" +PANDASET_HEIGHT = 64 +PANDASET_WIDTH = 1024 +PANDASET_NATIVE_WIDTH = 1800 +PANDASET_MIN_RANGE = 1.0 +PANDASET_MAX_RANGE = 100.0 +PANDASET_CALIBRATION_FRAMES = 3 +PANDASET_CALIBRATION_MAX_POINTS_PER_FRAME = 50_000 +PANDASET_CALIBRATION_MEDIAN_ERROR_MAX_M = 0.05 +PANDASET_CALIBRATION_P90_ERROR_MAX_M = 0.15 +PANDASET_AZIMUTH_GRID_P90_ERROR_MAX_DEG = 0.25 +PANDASET_AZIMUTH_PHASE_QUANTIZATION_DEG = 0.01 + +# Exact values from the official devkit's +# tutorials/raw_depth_projection/pandar64_channel_distribution.csv. +PANDAR64_ELEVATION_DEG = np.asarray( + [ + 14.870, 11.020, 8.047, 5.045, 3.028, 2.016, 1.848, 1.676, + 1.510, 1.339, 1.172, 1.001, 0.834, 0.663, 0.496, 0.325, + 0.157, -0.012, -0.181, -0.349, -0.520, -0.687, -0.857, + -1.025, -1.196, -1.363, -1.534, -1.700, -1.872, -2.040, + -2.210, -2.377, -2.548, -2.712, -2.885, -3.052, -3.222, + -3.387, -3.560, -3.724, -3.896, -4.062, -4.233, -4.397, + -4.570, -4.732, -4.904, -5.069, -5.241, -5.403, -5.577, + -5.738, -5.910, -6.073, -7.075, -8.071, -9.072, -9.897, + -11.044, -12.018, -12.986, -13.942, -18.901, -24.909, + ], + dtype=np.float64, +) +PANDAR64_ELEVATION_RAD = np.deg2rad(PANDAR64_ELEVATION_DEG) +PANDAR64_HORIZONTAL_OFFSET_DEG = np.asarray( + [ + -1.042, -1.042, -1.042, -1.042, -1.042, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + 1.042, 3.125, 5.208, -5.208, -3.125, -1.042, + -1.042, -1.042, -1.042, -1.042, -1.042, -1.042, + -1.042, -1.042, -1.042, -1.042, + ], + dtype=np.float64, +) +# PandaSet ego axes are x-right/y-forward/z-up. The repository convention is +# x-forward/y-left/z-up. +PANDASET_EGO_TO_REPO = np.asarray( + [[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], + dtype=np.float64, +) + + +def pandaset_ray_directions( + width: int = PANDASET_WIDTH, + *, + azimuth_y_sign: int = 1, + azimuth_phase_rad: float = 0.0, + azimuth_column_sign: int = 1, +) -> np.ndarray: + """Return Pandar64 rays on the calibrated scan-ordered azimuth grid. + + ``azimuth_y_sign`` is recovered together with the rigid Pandar64-to-pose + calibration because the raw release does not publish that extrinsic or its + azimuth handedness. ``azimuth_phase_rad`` and ``azimuth_column_sign`` map + the official devkit's corrected scan-relative columns to physical azimuth. + Keeping scan-relative column order preserves the rolling-shutter time axis. + """ + width = int(width) + if width <= 0: + raise ValueError(f"PandaSet ray width must be positive, got {width}.") + if int(azimuth_y_sign) not in (-1, 1): + raise ValueError( + f"PandaSet azimuth_y_sign must be -1 or 1, got {azimuth_y_sign}." + ) + if int(azimuth_column_sign) not in (-1, 1): + raise ValueError( + "PandaSet azimuth_column_sign must be -1 or 1, got " + f"{azimuth_column_sign}." + ) + azimuth = float(azimuth_phase_rad) + int(azimuth_column_sign) * ( + np.arange(width, dtype=np.float64) + 0.5 + ) * ( + 2.0 * np.pi / width + ) + elevation = PANDAR64_ELEVATION_RAD[:, None] + cos_elevation = np.cos(elevation) + rays = np.stack( + [ + cos_elevation * np.cos(azimuth)[None, :], + int(azimuth_y_sign) * cos_elevation * np.sin(azimuth)[None, :], + np.sin(elevation) * np.ones((1, width), dtype=np.float64), + ], + axis=-1, + ) + return rays.astype(np.float32) + + +def quaternion_wxyz_to_matrix(quaternion: np.ndarray) -> np.ndarray: + """Convert normalized ``[..., w, x, y, z]`` quaternions to rotations.""" + quaternion = np.asarray(quaternion, dtype=np.float64) + quaternion = quaternion / np.linalg.norm(quaternion, axis=-1, keepdims=True) + w, x, y, z = np.moveaxis(quaternion, -1, 0) + return np.stack( + [ + 1 - 2 * (y * y + z * z), + 2 * (x * y - z * w), + 2 * (x * z + y * w), + 2 * (x * y + z * w), + 1 - 2 * (x * x + z * z), + 2 * (y * z - x * w), + 2 * (x * z - y * w), + 2 * (y * z + x * w), + 1 - 2 * (x * x + y * y), + ], + axis=-1, + ).reshape(quaternion.shape[:-1] + (3, 3)) + + +def _normalize_quaternion(quaternion: np.ndarray) -> np.ndarray: + quaternion = np.asarray(quaternion, dtype=np.float64) + return quaternion / np.linalg.norm(quaternion, axis=-1, keepdims=True) + + +def interpolate_poses( + query_timestamps: np.ndarray, + pose_timestamps: np.ndarray, + positions: np.ndarray, + quaternions_wxyz: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Linearly interpolate translation and SLERP rotation at query times.""" + query_timestamps = np.asarray(query_timestamps, dtype=np.float64) + pose_timestamps = np.asarray(pose_timestamps, dtype=np.float64) + positions = np.asarray(positions, dtype=np.float64) + quaternions_wxyz = _normalize_quaternion(quaternions_wxyz) + if pose_timestamps.ndim != 1 or len(pose_timestamps) < 2: + raise ValueError("PandaSet pose interpolation requires at least two poses.") + if np.any(np.diff(pose_timestamps) <= 0): + raise ValueError("PandaSet pose timestamps must be strictly increasing.") + + right = np.searchsorted(pose_timestamps, query_timestamps, side="right") + right = np.clip(right, 1, len(pose_timestamps) - 1) + left = right - 1 + denom = pose_timestamps[right] - pose_timestamps[left] + # PandaSet frame timestamps mark sweep ends, so frame-0 points precede the + # first available pose by up to one sweep. Extrapolate from the nearest + # pose pair at either boundary instead of collapsing those points onto the + # first/last pose. + alpha = (query_timestamps - pose_timestamps[left]) / denom + + translation = ( + positions[left] * (1.0 - alpha[:, None]) + + positions[right] * alpha[:, None] + ) + q0 = quaternions_wxyz[left] + q1 = quaternions_wxyz[right] + dot = np.sum(q0 * q1, axis=-1) + q1 = np.where((dot < 0.0)[:, None], -q1, q1) + dot = np.abs(dot) + linear = dot > 0.9995 + theta = np.arccos(np.clip(dot, -1.0, 1.0)) + sin_theta = np.sin(theta) + safe_sin = np.where(linear, 1.0, sin_theta) + weight0 = np.sin((1.0 - alpha) * theta) / safe_sin + weight1 = np.sin(alpha * theta) / safe_sin + quaternion = weight0[:, None] * q0 + weight1[:, None] * q1 + quaternion[linear] = ( + (1.0 - alpha[linear, None]) * q0[linear] + + alpha[linear, None] * q1[linear] + ) + return translation, _normalize_quaternion(quaternion) + + +def pose_components_from_json( + poses: Sequence[dict[str, Any]], +) -> tuple[np.ndarray, np.ndarray]: + """Extract translations and wxyz quaternions from PandaSet pose JSON.""" + positions = np.asarray( + [[p["position"]["x"], p["position"]["y"], p["position"]["z"]] for p in poses], + dtype=np.float64, + ) + quaternions = np.asarray( + [ + [ + p["heading"]["w"], + p["heading"]["x"], + p["heading"]["y"], + p["heading"]["z"], + ] + for p in poses + ], + dtype=np.float64, + ) + return positions, quaternions + + +def _poses_to_pandar64_lidar_to_world( + positions: np.ndarray, + quaternions_wxyz: np.ndarray, + pandar64_to_pose: np.ndarray, +) -> np.ndarray: + """Compose PandaSet pose-reference motion with the recovered lidar extrinsic.""" + world_from_pose = np.broadcast_to( + np.eye(4, dtype=np.float64), (len(positions), 4, 4) + ).copy() + world_from_pose[:, :3, :3] = quaternion_wxyz_to_matrix(quaternions_wxyz) + world_from_pose[:, :3, 3] = positions + return (world_from_pose @ np.asarray(pandar64_to_pose)).astype(np.float32) + + +def resolve_point_timestamps( + point_timestamps: np.ndarray, frame_timestamp: float +) -> np.ndarray: + """Resolve PandaSet point timestamps to absolute Unix seconds.""" + point_timestamps = np.asarray(point_timestamps, dtype=np.float64) + finite = point_timestamps[np.isfinite(point_timestamps)] + if finite.size == 0: + return np.full(point_timestamps.shape, frame_timestamp, dtype=np.float64) + if np.median(np.abs(finite)) > 1.0e8: + return point_timestamps + return frame_timestamp + point_timestamps + + +def world_points_to_repo_sensor( + points_world: np.ndarray, + query_timestamps: np.ndarray, + pose_timestamps: np.ndarray, + positions: np.ndarray, + quaternions_wxyz: np.ndarray, +) -> np.ndarray: + """Motion-compensate world points into their instantaneous lidar frames.""" + translations, quaternions = interpolate_poses( + query_timestamps, pose_timestamps, positions, quaternions_wxyz + ) + rotations = quaternion_wxyz_to_matrix(quaternions) + points_pandaset_ego = np.einsum( + "nij,nj->ni", rotations.transpose(0, 2, 1), points_world - translations + ) + return points_pandaset_ego @ PANDASET_EGO_TO_REPO.T + + +def world_points_to_pose_frame( + points_world: np.ndarray, + query_timestamps: np.ndarray, + pose_timestamps: np.ndarray, + positions: np.ndarray, + quaternions_wxyz: np.ndarray, +) -> np.ndarray: + """Motion-compensate world points into PandaSet's pose-reference frame.""" + translations, quaternions = interpolate_poses( + query_timestamps, pose_timestamps, positions, quaternions_wxyz + ) + rotations = quaternion_wxyz_to_matrix(quaternions) + return np.einsum( + "nij,nj->ni", rotations.transpose(0, 2, 1), points_world - translations + ) + + +def raw_pandar64_points( + distance: np.ndarray, + elevation_deg: np.ndarray, + azimuth_deg: np.ndarray, + *, + azimuth_y_sign: int, +) -> np.ndarray: + """Convert official raw firing angles and ranges to Pandar64-frame XYZ.""" + distance = np.asarray(distance, dtype=np.float64) + elevation = np.deg2rad(np.asarray(elevation_deg, dtype=np.float64)) + azimuth = np.deg2rad(np.mod(np.asarray(azimuth_deg, dtype=np.float64), 360.0)) + cos_elevation = np.cos(elevation) + return distance[:, None] * np.stack( + [ + cos_elevation * np.cos(azimuth), + int(azimuth_y_sign) * cos_elevation * np.sin(azimuth), + np.sin(elevation), + ], + axis=-1, + ) + + +def raw_pandar64_scan_columns( + laser_id: np.ndarray, column_id: np.ndarray +) -> np.ndarray: + """Apply official offsets to obtain the scan-relative spherical columns.""" + laser_id = np.asarray(laser_id, dtype=np.int64) + column_id = np.asarray(column_id, dtype=np.int64) + if laser_id.shape != column_id.shape: + raise ValueError( + f"laser_id/column_id shapes differ: {laser_id.shape}/{column_id.shape}." + ) + if np.any((laser_id < 0) | (laser_id >= PANDASET_HEIGHT)): + raise ValueError("PandaSet laser_id lies outside [0, 64).") + column_shift = ( + PANDASET_NATIVE_WIDTH / 360.0 * PANDAR64_HORIZONTAL_OFFSET_DEG + ).astype(np.int64) + scan_column = column_id - int(column_id.min()) + return np.mod( + scan_column + column_shift[laser_id] + PANDASET_NATIVE_WIDTH, + PANDASET_NATIVE_WIDTH, + ).astype(np.int64) + + +def recover_pandar64_azimuth_grid( + scan_columns: np.ndarray, + corrected_azimuth_deg: np.ndarray, +) -> tuple[float, int, float]: + """Fit physical azimuth phase/direction to official scan-relative columns.""" + scan_columns = np.asarray(scan_columns, dtype=np.float64) + azimuth = np.deg2rad( + np.mod(np.asarray(corrected_azimuth_deg, dtype=np.float64), 360.0) + ) + if scan_columns.shape != azimuth.shape: + raise ValueError( + f"PandaSet scan-column/azimuth shapes differ: " + f"{scan_columns.shape}/{azimuth.shape}." + ) + finite = np.isfinite(scan_columns) & np.isfinite(azimuth) + scan_columns, azimuth = scan_columns[finite], azimuth[finite] + if scan_columns.size < 1_000: + raise ValueError("PandaSet azimuth-grid fit requires 1,000 samples.") + + def _wrap(angle: np.ndarray) -> np.ndarray: + return (angle + np.pi) % (2.0 * np.pi) - np.pi + + candidates = [] + scan_angle = scan_columns * (2.0 * np.pi / PANDASET_NATIVE_WIDTH) + for column_sign in (-1, 1): + phase_samples = _wrap(azimuth - column_sign * scan_angle) + phase = float( + np.angle(np.mean(np.exp(1j * phase_samples), dtype=np.complex128)) + ) + error_deg = np.rad2deg( + np.abs(_wrap(azimuth - (phase + column_sign * scan_angle))) + ) + candidates.append( + ( + float(np.percentile(error_deg, 90.0)), + column_sign, + phase, + ) + ) + _, column_sign, phase = min(candidates) + phase_deg = ( + round( + np.rad2deg(phase) / PANDASET_AZIMUTH_PHASE_QUANTIZATION_DEG + ) + * PANDASET_AZIMUTH_PHASE_QUANTIZATION_DEG + ) + phase = float(np.deg2rad(phase_deg)) + error_deg = np.rad2deg( + np.abs(_wrap(azimuth - (phase + column_sign * scan_angle))) + ) + p90_error_deg = float(np.percentile(error_deg, 90.0)) + if p90_error_deg > PANDASET_AZIMUTH_GRID_P90_ERROR_MAX_DEG: + raise ValueError( + "Official PandaSet corrected azimuths do not form a stable " + f"scan-relative grid: p90={p90_error_deg:.4f} deg, expected <= " + f"{PANDASET_AZIMUTH_GRID_P90_ERROR_MAX_DEG:.3f} deg." + ) + return phase, int(column_sign), p90_error_deg + + +def _fit_rigid_transform(source: np.ndarray, target: np.ndarray) -> np.ndarray: + """Least-squares proper rigid transform ``target ~= T @ source``.""" + source = np.asarray(source, dtype=np.float64) + target = np.asarray(target, dtype=np.float64) + if source.shape != target.shape or source.ndim != 2 or source.shape[1] != 3: + raise ValueError( + f"Rigid-fit source/target must both be (N,3), got " + f"{source.shape} and {target.shape}." + ) + if source.shape[0] < 3: + raise ValueError("Rigid fit requires at least three correspondences.") + source_center = source.mean(axis=0) + target_center = target.mean(axis=0) + covariance = (source - source_center).T @ (target - target_center) + u, _, vt = np.linalg.svd(covariance) + rotation = vt.T @ u.T + if np.linalg.det(rotation) < 0: + vt[-1] *= -1.0 + rotation = vt.T @ u.T + transform = np.eye(4, dtype=np.float64) + transform[:3, :3] = rotation + transform[:3, 3] = target_center - rotation @ source_center + return transform + + +def _transform_points(points: np.ndarray, transform: np.ndarray) -> np.ndarray: + return ( + np.asarray(points, dtype=np.float64) @ transform[:3, :3].T + + transform[:3, 3] + ) + + +def recover_pandar64_to_pose( + raw_by_sign: dict[int, np.ndarray], + pose_points: np.ndarray, +) -> tuple[np.ndarray, int, float, float]: + """Recover the unpublished raw-Pandar64-to-pose rigid calibration. + + The raw and processed PandaSet releases preserve point order for Pandar64. + The processed points are first motion-compensated into the pose-reference + frame. We then robustly fit both possible raw azimuth handednesses and + retain the proper rigid transform with the lower residual. + """ + pose_points = np.asarray(pose_points, dtype=np.float64) + candidates = [] + for sign in (-1, 1): + source = np.asarray(raw_by_sign[sign], dtype=np.float64) + if source.shape != pose_points.shape: + raise ValueError( + f"PandaSet calibration shape mismatch for sign {sign}: " + f"{source.shape} versus {pose_points.shape}." + ) + keep = np.ones(source.shape[0], dtype=bool) + transform = np.eye(4, dtype=np.float64) + for _ in range(4): + transform = _fit_rigid_transform(source[keep], pose_points[keep]) + residual = np.linalg.norm( + _transform_points(source, transform) - pose_points, axis=-1 + ) + median = float(np.median(residual[keep])) + mad = float(np.median(np.abs(residual[keep] - median))) + threshold = max(median + 6.0 * max(mad, 1e-4), 0.05) + updated = residual <= threshold + if updated.sum() < 1_000 or np.array_equal(updated, keep): + break + keep = updated + residual = np.linalg.norm( + _transform_points(source, transform) - pose_points, axis=-1 + ) + candidates.append( + ( + float(np.median(residual)), + float(np.percentile(residual, 90.0)), + sign, + transform, + ) + ) + median_error, p90_error, sign, transform = min( + candidates, key=lambda item: (item[0], item[1]) + ) + if median_error > PANDASET_CALIBRATION_MEDIAN_ERROR_MAX_M or ( + p90_error > PANDASET_CALIBRATION_P90_ERROR_MAX_M + ): + raise ValueError( + "Recovered PandaSet Pandar64 calibration failed registration: " + f"median={median_error:.4f} m, p90={p90_error:.4f} m; expected " + f"<= {PANDASET_CALIBRATION_MEDIAN_ERROR_MAX_M:.3f} m and " + f"<= {PANDASET_CALIBRATION_P90_ERROR_MAX_M:.3f} m." + ) + return transform, int(sign), median_error, p90_error + + +def spherical_bins( + points_repo: np.ndarray, *, width: int = PANDASET_WIDTH +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Assign processed points to calibrated rows and wrapped azimuth columns.""" + width = int(width) + if width <= 0: + raise ValueError(f"PandaSet projection width must be positive, got {width}.") + points_repo = np.asarray(points_repo, dtype=np.float64) + distance = np.linalg.norm(points_repo, axis=-1) + elevation = np.arcsin( + np.divide( + points_repo[:, 2], + distance, + out=np.zeros_like(distance), + where=distance > 0, + ) + ) + row = np.argmin( + np.abs(elevation[:, None] - PANDAR64_ELEVATION_RAD[None, :]), axis=1 + ).astype(np.int64) + azimuth = np.arctan2(points_repo[:, 1], points_repo[:, 0]) + column = np.floor( + np.mod(azimuth + np.pi, 2.0 * np.pi) + * (width / (2.0 * np.pi)) + ).astype(np.int64) + column = np.clip(column, 0, width - 1) + return row, column, distance + + +def project_processed_points( + points_repo: np.ndarray, + intensity: np.ndarray, + *, + min_range: float = PANDASET_MIN_RANGE, + max_range: float = PANDASET_MAX_RANGE, + width: int = PANDASET_WIDTH, +) -> tuple[np.ndarray, np.ndarray]: + """Nearest-return z-buffer processed points into a 64-row range image.""" + width = int(width) + row, column, distance = spherical_bins(points_repo, width=width) + intensity = np.asarray(intensity, dtype=np.float32) + valid = ( + np.isfinite(points_repo).all(axis=-1) + & np.isfinite(distance) + & np.isfinite(intensity) + & (distance >= min_range) + & (distance <= max_range) + ) + row, column = row[valid], column[valid] + distance = distance[valid].astype(np.float32) + intensity = intensity[valid] + + # Descending range means the closest return is written last. + order = np.argsort(-distance, kind="stable") + range_map = np.zeros((PANDASET_HEIGHT, width), dtype=np.float32) + intensity_map = np.zeros_like(range_map) + range_map[row[order], column[order]] = distance[order] + intensity_map[row[order], column[order]] = intensity[order] + return range_map, intensity_map + + +def project_raw_pandar64( + laser_id: np.ndarray, + column_id: np.ndarray, + distance: np.ndarray, + intensity: np.ndarray, + *, + min_range: float = PANDASET_MIN_RANGE, + max_range: float = PANDASET_MAX_RANGE, + width: int = PANDASET_WIDTH, +) -> tuple[np.ndarray, np.ndarray]: + """Project raw firings on the calibrated scan-ordered azimuth grid.""" + laser_id = np.asarray(laser_id, dtype=np.int64) + column_id = np.asarray(column_id, dtype=np.int64) + distance = np.asarray(distance, dtype=np.float32) + intensity = np.asarray(intensity, dtype=np.float32) + if not ( + laser_id.shape == column_id.shape == distance.shape == intensity.shape + ): + raise ValueError("PandaSet raw firing arrays must have identical shapes.") + + valid = ( + (laser_id >= 0) + & (laser_id < PANDASET_HEIGHT) + & np.isfinite(distance) + & np.isfinite(intensity) + & (distance >= min_range) + & (distance <= max_range) + ) + row = laser_id[valid] + scan_column = raw_pandar64_scan_columns(laser_id, column_id)[valid] + column = scan_column * int(width) // PANDASET_NATIVE_WIDTH + distance, intensity = distance[valid], intensity[valid] + + order = np.argsort(-distance, kind="stable") + range_map = np.zeros((PANDASET_HEIGHT, int(width)), dtype=np.float32) + intensity_map = np.zeros_like(range_map) + range_map[row[order], column[order]] = distance[order] + intensity_map[row[order], column[order]] = intensity[order] + return range_map, intensity_map + + +def build_pandaset_sequence_cache( + sequence_dir: str | Path, + *, + packet_sequence_dir: str | Path | None = None, + min_range: float = PANDASET_MIN_RANGE, + max_range: float = PANDASET_MAX_RANGE, +) -> dict[str, np.ndarray]: + """Build one physically registered cache from raw and processed PandaSet.""" + try: + import pandas as pd + except ImportError as error: + raise ImportError( + "Building PandaSet caches requires pandas; cache-backed training does not." + ) from error + + sequence_dir = Path(sequence_dir) + if packet_sequence_dir is None: + raise ValueError( + "A raw PandaSet Pandar64 packet directory is required. The processed " + "release cannot recover firing rows, physical azimuths, or the " + "unpublished Pandar64-to-pose calibration." + ) + lidar_dir = sequence_dir / "lidar" + with (lidar_dir / "poses.json").open("r") as handle: + poses = json.load(handle) + with (lidar_dir / "timestamps.json").open("r") as handle: + pose_timestamps = np.asarray(json.load(handle), dtype=np.float64) + positions, quaternions = pose_components_from_json(poses) + if not (len(poses) == len(pose_timestamps)): + raise ValueError( + f"{sequence_dir.name}: {len(poses)} poses != " + f"{len(pose_timestamps)} timestamps." + ) + + frame_paths = sorted(lidar_dir.glob("*.pkl.gz")) + if not frame_paths: + frame_paths = sorted(lidar_dir.glob("*.pkl")) + if len(frame_paths) != len(poses): + raise ValueError( + f"{sequence_dir.name}: {len(frame_paths)} lidar frames != " + f"{len(poses)} poses." + ) + packet_sequence_dir = Path(packet_sequence_dir) + packet_lidar_dir = ( + packet_sequence_dir / "lidar" + if (packet_sequence_dir / "lidar").is_dir() + else packet_sequence_dir + ) + packet_paths = sorted(packet_lidar_dir.glob("*.pkl.gz")) + if not packet_paths: + packet_paths = sorted(packet_lidar_dir.glob("*.pkl")) + if len(packet_paths) != len(frame_paths): + raise ValueError( + f"{sequence_dir.name}: {len(packet_paths)} raw packet frames != " + f"{len(frame_paths)} processed frames." + ) + + raw_calibration = {-1: [], 1: []} + pose_calibration = [] + azimuth_grid_columns = [] + azimuth_grid_angles_deg = [] + intensity_match_fractions = [] + # Frame 0 points precede the first available end-of-sweep pose and require + # pose extrapolation. That is adequate for cache metadata but can bias the + # rigid sensor calibration on sequences that begin while accelerating. + # Recover the fixed extrinsic only from sweeps bracketed by measured poses. + calibration_start = 1 if len(frame_paths) > PANDASET_CALIBRATION_FRAMES else 0 + calibration_frame_indices = np.arange( + calibration_start, + min( + calibration_start + PANDASET_CALIBRATION_FRAMES, + len(frame_paths), + ), + dtype=np.int32, + ) + calibration_frames = len(calibration_frame_indices) + for frame_index in calibration_frame_indices: + frame = pd.read_pickle(frame_paths[frame_index]) + required_processed = {"x", "y", "z", "i", "t", "d"} + missing_processed = required_processed.difference(frame.columns) + if missing_processed: + raise ValueError( + f"{frame_paths[frame_index]}: missing PandaSet columns " + f"{sorted(missing_processed)}." + ) + frame = frame.loc[frame["d"].to_numpy() == 0] + packet = pd.read_pickle(packet_paths[frame_index]) + required_packet = { + "laser_id", + "column_id", + "elevation", + "azimuth_col_corrected", + "distance", + "intensity", + } + missing_packet = required_packet.difference(packet.columns) + if missing_packet: + raise ValueError( + f"{packet_paths[frame_index]}: missing PandaSet raw columns " + f"{sorted(missing_packet)}." + ) + if len(frame) != len(packet): + raise ValueError( + f"{sequence_dir.name} frame {frame_index}: processed/raw Pandar64 " + f"point counts differ ({len(frame)} != {len(packet)})." + ) + processed_intensity = frame["i"].to_numpy(dtype=np.float64) + packet_intensity = packet["intensity"].to_numpy(dtype=np.float64) + intensity_match = np.isclose( + processed_intensity, packet_intensity, atol=0.5, rtol=0.0 + ) + intensity_match_fractions.append(float(intensity_match.mean())) + point_timestamps = resolve_point_timestamps( + frame["t"].to_numpy(dtype=np.float64), pose_timestamps[frame_index] + ) + pose_points = world_points_to_pose_frame( + frame[["x", "y", "z"]].to_numpy(dtype=np.float64), + point_timestamps, + pose_timestamps, + positions, + quaternions, + ) + packet_distance = packet["distance"].to_numpy(dtype=np.float64) + select = ( + intensity_match + & np.isfinite(pose_points).all(axis=-1) + & np.isfinite(packet_distance) + & (packet_distance >= 3.0) + & (packet_distance <= 80.0) + ) + selected = np.flatnonzero(select) + if selected.size > PANDASET_CALIBRATION_MAX_POINTS_PER_FRAME: + selected = selected[ + np.linspace( + 0, + selected.size - 1, + PANDASET_CALIBRATION_MAX_POINTS_PER_FRAME, + dtype=np.int64, + ) + ] + if selected.size < 1_000: + raise ValueError( + f"{sequence_dir.name} frame {frame_index}: only {selected.size} " + "usable raw/processed calibration correspondences." + ) + pose_calibration.append(pose_points[selected]) + azimuth_grid_columns.append( + raw_pandar64_scan_columns( + packet["laser_id"].to_numpy(dtype=np.int64), + packet["column_id"].to_numpy(dtype=np.int64), + ) + ) + azimuth_grid_angles_deg.append( + packet["azimuth_col_corrected"].to_numpy(dtype=np.float64) + ) + for sign in (-1, 1): + raw_calibration[sign].append( + raw_pandar64_points( + packet_distance[selected], + packet["elevation"].to_numpy(dtype=np.float64)[selected], + packet["azimuth_col_corrected"].to_numpy(dtype=np.float64)[ + selected + ], + azimuth_y_sign=sign, + ) + ) + intensity_match_fraction = float(np.mean(intensity_match_fractions)) + if intensity_match_fraction < 0.95: + raise ValueError( + f"{sequence_dir.name}: raw/processed point-order validation failed; " + f"only {intensity_match_fraction:.2%} of intensities match." + ) + try: + pandar64_to_pose, azimuth_y_sign, calibration_median, calibration_p90 = ( + recover_pandar64_to_pose( + { + sign: np.concatenate(raw_calibration[sign], axis=0) + for sign in (-1, 1) + }, + np.concatenate(pose_calibration, axis=0), + ) + ) + except ValueError as error: + raise ValueError(f"{sequence_dir.name}: {error}") from error + azimuth_phase_rad, azimuth_column_sign, azimuth_grid_p90_error_deg = ( + recover_pandar64_azimuth_grid( + np.concatenate(azimuth_grid_columns), + np.concatenate(azimuth_grid_angles_deg), + ) + ) + ray_directions = pandaset_ray_directions( + PANDASET_WIDTH, + azimuth_y_sign=azimuth_y_sign, + azimuth_phase_rad=azimuth_phase_rad, + azimuth_column_sign=azimuth_column_sign, + ) + + range_frames, intensity_frames = [], [] + start_timestamps, end_timestamps = [], [] + start_positions, start_quaternions = [], [] + end_positions, end_quaternions = [], [] + for frame_index, frame_path in enumerate(frame_paths): + frame = pd.read_pickle(frame_path) + required = {"x", "y", "z", "i", "t", "d"} + missing = required.difference(frame.columns) + if missing: + raise ValueError( + f"{frame_path}: missing PandaSet columns {sorted(missing)}." + ) + frame = frame.loc[frame["d"].to_numpy() == 0] + point_timestamps = resolve_point_timestamps( + frame["t"].to_numpy(dtype=np.float64), pose_timestamps[frame_index] + ) + finite_timestamps = point_timestamps[np.isfinite(point_timestamps)] + if finite_timestamps.size == 0: + start_timestamp = end_timestamp = pose_timestamps[frame_index] + else: + start_timestamp = float(finite_timestamps.min()) + end_timestamp = float(finite_timestamps.max()) + + packet = pd.read_pickle(packet_paths[frame_index]) + required_packet = { + "laser_id", + "azimuth_col_corrected", + "distance", + "intensity", + } + missing_packet = required_packet.difference(packet.columns) + if missing_packet: + raise ValueError( + f"{packet_paths[frame_index]}: missing PandaSet raw columns " + f"{sorted(missing_packet)}." + ) + range_map, intensity_map = project_raw_pandar64( + packet["laser_id"].to_numpy(), + packet["column_id"].to_numpy(), + packet["distance"].to_numpy(), + packet["intensity"].to_numpy(), + min_range=min_range, + max_range=max_range, + ) + range_frames.append(range_map) + intensity_frames.append(intensity_map) + start_timestamps.append(start_timestamp) + end_timestamps.append(end_timestamp) + start_position, start_quaternion = interpolate_poses( + np.asarray([start_timestamp]), + pose_timestamps, + positions, + quaternions, + ) + end_position, end_quaternion = interpolate_poses( + np.asarray([end_timestamp]), + pose_timestamps, + positions, + quaternions, + ) + start_positions.append(start_position[0]) + start_quaternions.append(start_quaternion[0]) + end_positions.append(end_position[0]) + end_quaternions.append(end_quaternion[0]) + + lidar_to_world = _poses_to_pandar64_lidar_to_world( + np.asarray(start_positions), + np.asarray(start_quaternions), + pandar64_to_pose, + ) + lidar_to_world_end = _poses_to_pandar64_lidar_to_world( + np.asarray(end_positions), + np.asarray(end_quaternions), + pandar64_to_pose, + ) + pose_sensor_start_end = ( + np.linalg.inv(lidar_to_world_end) @ lidar_to_world + ).astype(np.float32) + return { + "cache_version": np.asarray(PANDASET_CACHE_VERSION), + "projection_mode": np.asarray("raw_pandar64_calibrated_scan_order"), + "geometry_calibration_source": np.asarray( + "raw_processed_correspondence_rigid_fit" + ), + "pandar64_to_pose": pandar64_to_pose.astype(np.float32), + "azimuth_y_sign": np.asarray(azimuth_y_sign, dtype=np.int8), + "azimuth_phase_rad": np.asarray(azimuth_phase_rad, dtype=np.float64), + "azimuth_column_sign": np.asarray(azimuth_column_sign, dtype=np.int8), + "azimuth_grid_p90_error_deg": np.asarray( + azimuth_grid_p90_error_deg, dtype=np.float32 + ), + "calibration_frame_count": np.asarray(calibration_frames, dtype=np.int32), + "calibration_frame_indices": calibration_frame_indices, + "calibration_intensity_match_fraction": np.asarray( + intensity_match_fraction, dtype=np.float32 + ), + "calibration_median_error_m": np.asarray( + calibration_median, dtype=np.float32 + ), + "calibration_p90_error_m": np.asarray(calibration_p90, dtype=np.float32), + "sequence": np.asarray(sequence_dir.name), + "range": np.stack(range_frames, axis=0), + "intensity": np.stack(intensity_frames, axis=0), + "lidar_to_world": lidar_to_world, + "pose_sensor_start_end": pose_sensor_start_end, + "timestamp_start_us": np.rint( + np.asarray(start_timestamps) * 1.0e6 + ).astype(np.int64), + "timestamp_end_us": np.rint( + np.asarray(end_timestamps) * 1.0e6 + ).astype(np.int64), + "ray_directions": ray_directions, + "elevation_rad": PANDAR64_ELEVATION_RAD.astype(np.float32), + "min_range": np.asarray(min_range, dtype=np.float32), + "max_range": np.asarray(max_range, dtype=np.float32), + "height": np.asarray(PANDASET_HEIGHT, dtype=np.int32), + "width": np.asarray(PANDASET_WIDTH, dtype=np.int32), + } + + +def validate_pandaset_cache( + payload: Any, *, path: str | Path = "" +) -> None: + """Reject stale or incompatible PandaSet caches.""" + required = { + "cache_version", + "projection_mode", + "geometry_calibration_source", + "pandar64_to_pose", + "azimuth_y_sign", + "azimuth_phase_rad", + "azimuth_column_sign", + "azimuth_grid_p90_error_deg", + "calibration_frame_count", + "calibration_frame_indices", + "calibration_intensity_match_fraction", + "calibration_median_error_m", + "calibration_p90_error_m", + "range", + "intensity", + "lidar_to_world", + "pose_sensor_start_end", + "timestamp_start_us", + "timestamp_end_us", + "ray_directions", + "min_range", + "max_range", + "height", + "width", + } + missing = required.difference(payload.files) + if missing: + raise ValueError(f"{path}: PandaSet cache is missing {sorted(missing)}.") + version = str(np.asarray(payload["cache_version"]).item()) + if version != PANDASET_CACHE_VERSION: + raise ValueError( + f"{path}: stale PandaSet cache version {version!r}; " + f"expected {PANDASET_CACHE_VERSION!r}." + ) + projection_mode = str(np.asarray(payload["projection_mode"]).item()) + if projection_mode != "raw_pandar64_calibrated_scan_order": + raise ValueError(f"{path}: unknown projection mode {projection_mode!r}.") + calibration_source = str( + np.asarray(payload["geometry_calibration_source"]).item() + ) + if calibration_source != "raw_processed_correspondence_rigid_fit": + raise ValueError( + f"{path}: unsupported PandaSet calibration source " + f"{calibration_source!r}." + ) + shape = tuple(payload["range"].shape) + if len(shape) != 3 or shape[1:] != (PANDASET_HEIGHT, PANDASET_WIDTH): + raise ValueError( + f"{path}: expected range shape (F, {PANDASET_HEIGHT}, " + f"{PANDASET_WIDTH}), got {shape}." + ) + if payload["intensity"].shape != payload["range"].shape: + raise ValueError(f"{path}: intensity/range shape mismatch.") + min_range = float(np.asarray(payload["min_range"]).item()) + max_range = float(np.asarray(payload["max_range"]).item()) + if not np.isclose(min_range, PANDASET_MIN_RANGE) or not np.isclose( + max_range, PANDASET_MAX_RANGE + ): + raise ValueError( + f"{path}: expected PandaSet bounds " + f"[{PANDASET_MIN_RANGE}, {PANDASET_MAX_RANGE}] m, got " + f"[{min_range}, {max_range}] m." + ) + frame_count = shape[0] + for key in ( + "lidar_to_world", + "pose_sensor_start_end", + ): + if payload[key].shape != (frame_count, 4, 4): + raise ValueError(f"{path}: invalid {key} shape {payload[key].shape}.") + if payload["ray_directions"].shape != ( + PANDASET_HEIGHT, + PANDASET_WIDTH, + 3, + ): + raise ValueError( + f"{path}: invalid ray_directions shape " + f"{payload['ray_directions'].shape}." + ) + azimuth_y_sign = int(np.asarray(payload["azimuth_y_sign"]).item()) + azimuth_phase_rad = float(np.asarray(payload["azimuth_phase_rad"]).item()) + azimuth_column_sign = int( + np.asarray(payload["azimuth_column_sign"]).item() + ) + if not np.isfinite(azimuth_phase_rad): + raise ValueError(f"{path}: azimuth_phase_rad is non-finite.") + expected_rays = pandaset_ray_directions( + PANDASET_WIDTH, + azimuth_y_sign=azimuth_y_sign, + azimuth_phase_rad=azimuth_phase_rad, + azimuth_column_sign=azimuth_column_sign, + ) + ray_error = float( + np.max(np.abs(np.asarray(payload["ray_directions"]) - expected_rays)) + ) + if ray_error > 1e-6: + raise ValueError( + f"{path}: cached PandaSet rays do not match the calibrated " + f"scan-ordered azimuth contract (max error {ray_error})." + ) + azimuth_grid_p90_error_deg = float( + np.asarray(payload["azimuth_grid_p90_error_deg"]).item() + ) + if azimuth_grid_p90_error_deg > PANDASET_AZIMUTH_GRID_P90_ERROR_MAX_DEG: + raise ValueError( + f"{path}: PandaSet azimuth-grid p90 error is " + f"{azimuth_grid_p90_error_deg:.4f} deg." + ) + if payload["pandar64_to_pose"].shape != (4, 4): + raise ValueError( + f"{path}: invalid pandar64_to_pose shape " + f"{payload['pandar64_to_pose'].shape}." + ) + pandar64_to_pose = np.asarray(payload["pandar64_to_pose"], dtype=np.float64) + rotation = pandar64_to_pose[:3, :3] + if ( + not np.isfinite(pandar64_to_pose).all() + or not np.allclose(pandar64_to_pose[3], [0.0, 0.0, 0.0, 1.0], atol=1e-6) + or not np.allclose(rotation @ rotation.T, np.eye(3), atol=1e-5) + or not np.isclose(np.linalg.det(rotation), 1.0, atol=1e-5) + ): + raise ValueError(f"{path}: pandar64_to_pose is not a proper SE(3) transform.") + calibration_frame_count = int( + np.asarray(payload["calibration_frame_count"]).item() + ) + if calibration_frame_count < 1: + raise ValueError(f"{path}: calibration_frame_count must be positive.") + calibration_frame_indices = np.asarray( + payload["calibration_frame_indices"], dtype=np.int32 + ) + if ( + calibration_frame_indices.shape != (calibration_frame_count,) + or np.any(calibration_frame_indices < 0) + or np.any(np.diff(calibration_frame_indices) <= 0) + ): + raise ValueError( + f"{path}: invalid calibration_frame_indices " + f"{calibration_frame_indices.tolist()}." + ) + median_error = float(np.asarray(payload["calibration_median_error_m"]).item()) + p90_error = float(np.asarray(payload["calibration_p90_error_m"]).item()) + intensity_match = float( + np.asarray(payload["calibration_intensity_match_fraction"]).item() + ) + if median_error > PANDASET_CALIBRATION_MEDIAN_ERROR_MAX_M or ( + p90_error > PANDASET_CALIBRATION_P90_ERROR_MAX_M + ): + raise ValueError( + f"{path}: failed PandaSet calibration residuals " + f"(median={median_error:.4f} m, p90={p90_error:.4f} m)." + ) + if intensity_match < 0.95: + raise ValueError( + f"{path}: raw/processed intensity correspondence is only " + f"{intensity_match:.2%}." + ) + + +class PandaSetCachedLidar: + """Cache-backed low-level reader matching the NCore reader contract.""" + + MAX_CACHED_SEQUENCES = 2 + + def __init__( + self, + root_path: str, + filter_list_path: Optional[str] = None, + num_views: int = -1, + metadata_folder: Optional[str] = None, + custom_folders: Optional[list[str]] = None, + custom_fields: Optional[list[str]] = None, + view_indices: Optional[list[int]] = None, + load_intensity: bool = False, + ): + del metadata_folder, custom_folders, view_indices + self.root_path = root_path + self.num_views = num_views + self.n_views = num_views + self.custom_fields = custom_fields if custom_fields is not None else ["lidar"] + self.load_intensity = bool(load_intensity) + self.filter_set = self._build_filter_set(filter_list_path) + if not self.filter_set: + raise RuntimeError( + f"No PandaSet caches found (root={root_path}, " + f"filter_list_path={filter_list_path})." + ) + self._cache: dict[str, dict[str, np.ndarray]] = {} + + def _build_filter_set(self, filter_list_path: Optional[str]) -> list[str]: + if filter_list_path and os.path.isfile(filter_list_path): + with open(filter_list_path, "r") as handle: + return [ + Path(line.strip()).stem + for line in handle + if line.strip() + ] + root = Path(self.root_path) + return sorted(path.stem for path in root.glob("*.npz")) + + def _load(self, stem: str) -> dict[str, np.ndarray]: + if stem in self._cache: + return self._cache[stem] + path = Path(self.root_path) / f"{stem}.npz" + with np.load(path, allow_pickle=False) as payload: + validate_pandaset_cache(payload, path=path) + cache = {key: np.asarray(payload[key]) for key in payload.files} + if self._cache: + reference = next(iter(self._cache.values()))["ray_directions"] + ray_error = float(np.max(np.abs(cache["ray_directions"] - reference))) + if ray_error > 1e-6: + raise ValueError( + f"{path}: PandaSet azimuth handedness differs from the other " + f"loaded sequence (ray max error {ray_error})." + ) + if len(self._cache) >= self.MAX_CACHED_SEQUENCES: + self._cache.pop(next(iter(self._cache))) + self._cache[stem] = cache + return cache + + def sensor_ray_directions(self) -> np.ndarray: + cache = self._load(self.filter_set[0]) + return cache["ray_directions"].astype(np.float32, copy=False) + + def size_of_filter_set(self) -> int: + return len(self.filter_set) + + @staticmethod + def _clamp_frame_indices( + frame_indices: np.ndarray, frame_count: int + ) -> np.ndarray: + frame_indices = np.asarray(frame_indices, dtype=np.int64).copy() + out_of_bounds = (frame_indices < 0) | (frame_indices >= frame_count) + if out_of_bounds.any(): + frame_indices[out_of_bounds] = np.random.randint( + 0, frame_count, size=int(out_of_bounds.sum()) + ) + return frame_indices + + def _read_rgb_and_lidar(self, lidar_idx, lidar_frame_idx, data_fields): + stem = self.filter_set[int(lidar_idx)] + cache = self._load(stem) + frame_indices = self._clamp_frame_indices( + lidar_frame_idx, cache["range"].shape[0] + ) + output: dict[str, Any] = { + "__key__": stem, + "timestamp_list": cache["timestamp_end_us"][frame_indices], + "pose_sensor_start_end": cache["pose_sensor_start_end"][frame_indices], + "lidar_to_world": cache["lidar_to_world"][frame_indices], + "rgb_frame_indices": frame_indices.tolist(), + } + for data_field in data_fields: + if data_field != "custom": + raise NotImplementedError( + f"PandaSetCachedLidar does not handle data field {data_field}." + ) + custom = {"lidar": cache["range"][frame_indices]} + if self.load_intensity: + custom["lidar_intensity"] = cache["intensity"][frame_indices] + output[data_field] = custom + return output diff --git a/tokenizer/training/datasets/lidar_datasets/rangemap_sampler.py b/tokenizer/training/datasets/lidar_datasets/rangemap_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..7a804580c6ebf90abf92b67a0436c5d1d3c24edf --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/rangemap_sampler.py @@ -0,0 +1,924 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import os + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision.transforms as transforms + +from utils import log + +try: + from megatron.core import parallel_state + USE_MEGATRON = True +except ImportError: + USE_MEGATRON = False + +from torch.utils.data import Dataset + + +def _safe_pickle_load(path: str): + """Load a legacy .pkl file using a restricted unpickler. + + Only allows basic Python types and numpy arrays to be deserialized, + blocking arbitrary code execution. + """ + import pickle as _pickle + + _SAFE_MODULES = frozenset({ + "builtins", "collections", "collections.abc", + "numpy", "numpy.core.multiarray", "numpy.core._multiarray_umath", + "numpy._core.multiarray", "numpy._core._multiarray_umath", + }) + + class _SafeUnpickler(_pickle.Unpickler): + def find_class(self, module: str, name: str): + if module in _SAFE_MODULES: + return super().find_class(module, name) + raise _pickle.UnpicklingError( + f"Blocked unpickling of {module}.{name} — only basic types " + f"and numpy arrays are allowed." + ) + + with open(path, "rb") as f: + return _SafeUnpickler(f).load() + +from tokenizer.training.datasets.lidar_datasets.datasets import RadymLidar +from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField +from utils.lidar_rangemap import RangeMapDownsampler, normalize_range_map, RANGE_BANDS, SinusoidalEncoder +from utils.per_row_norm import get_per_row_normalizer, apply_per_row_norm + + +class LidarRangeMapSampler(Dataset): + def __init__( + self, + data_name, + root_path, + filter_list_path, + t5_embedding_path, + custom_folders, + custom_fields, + metadata_folder, + max_range, + min_range, + downsample_factor_row, + downsample_factor_col, + repeat_row, + repeat_col, + repeat_temporal, + lidar_crop_size, + rgb_crop_size, + rgb_resize_size, + lidar_size, + downsample_method, # for range map + min_value, + num_views, # the number of RGB cameras + sample_n_frames, + lidar_length, + frame_sampling_method, + frame_sampling_every_n_frames, + sample_lidar_prob, + is_video_tokenizer, + sequential_start_idx=0, + random_n_frames=False, + load_lidar_only=True, + load_rgb_only=False, + load_lidar_and_rgb=False, # load both lidar and rgb + load_lidar_or_rgb=False, + RGB_FPS=30, + LIDAR_FPS=10, + load_t5_embeddings=False, + inverse_depth=False, + process_input="repeat", # "repeat", "concat", "band", "log", or "mono" — normalizing / model input + process_output="repeat", # unnormalizing and loss target; "mono" = single channel [N,1,H,W] + num_bands=3, + fourier_max_freq=10, + inv_depth_threshold=20, + view_indices=None, + load_intensity=False, + intensity_only=False, + intensity_transform="legacy", + intensity_raw_max=1.0, + emit_sensor_metadata=False, + sensor_dataset_id=-1, + sensor_dataset_name="", + lidar_resize_size=(-1, -1), + per_row_normalize=False, + per_row_stats_path="", + per_row_smooth_sigma=5.0, + emit_valid_mask=False, + dataset_backend="radym", # "radym", "*_ncore", or cached "pandaset" + resample_width=-1, # waymo_ncore only: rebin azimuth to this width (e.g. 2048); <=0 native + center_vehicle_forward=False, + # --- waymo_ncore hdmap (on-the-fly rasterized from dump_waymo_hdmap NPZs) --- + hdmap_root=None, + hdmap_multichannel=False, + hdmap_moving_only=False, + hdmap_include_boxes=True, + hdmap_box_edge_spacing=0.15, + hdmap_map_max_dist=None, + hdmap_sensor_template="native", + hdmap_template_root_path=None, + hdmap_template_filter_list_path=None, + hdmap_virtual_sensor_height_m=None, + hdmap_virtual_sensor_yaw_deg=0.0, + canonical_lidar_mode="native", + hdmap_pose_for_lidar_to_world=False, + ): + super().__init__() + self.data_name = data_name + self.load_intensity = load_intensity + self.intensity_only = bool(intensity_only) + if self.intensity_only and not self.load_intensity: + raise ValueError("intensity_only=True requires load_intensity=True") + self.intensity_transform = intensity_transform + if self.intensity_transform not in ("legacy", "log1p"): + raise ValueError(f"Unknown intensity_transform: {self.intensity_transform!r}") + self.intensity_raw_max = float(intensity_raw_max) + if self.intensity_raw_max <= 0: + raise ValueError( + f"intensity_raw_max must be positive, got {self.intensity_raw_max}" + ) + self.emit_sensor_metadata = bool(emit_sensor_metadata) + self.sensor_dataset_id = int(sensor_dataset_id) + self.sensor_dataset_name = str(sensor_dataset_name or data_name) + self._sensor_root_path = root_path + self._sensor_filter_list_path = filter_list_path + self._sensor_ray_directions = None + self.dataset_backend = dataset_backend + self.resample_width = resample_width + self.center_vehicle_forward = bool(center_vehicle_forward) + # waymo_ncore hdmap rasterization knobs (consumed in _build_dataset). + self._hdmap_kwargs = dict( + hdmap_root=hdmap_root, + min_range=min_range, + max_range=max_range, + hdmap_multichannel=hdmap_multichannel, + hdmap_moving_only=hdmap_moving_only, + hdmap_include_boxes=hdmap_include_boxes, + hdmap_box_edge_spacing=hdmap_box_edge_spacing, + hdmap_map_max_dist=hdmap_map_max_dist, + ) + self._nuscenes_canonical_kwargs = dict( + hdmap_sensor_template=hdmap_sensor_template, + hdmap_template_root_path=hdmap_template_root_path, + hdmap_template_filter_list_path=hdmap_template_filter_list_path, + hdmap_virtual_sensor_height_m=hdmap_virtual_sensor_height_m, + hdmap_virtual_sensor_yaw_deg=hdmap_virtual_sensor_yaw_deg, + canonical_lidar_mode=canonical_lidar_mode, + center_vehicle_forward=self.center_vehicle_forward, + hdmap_pose_for_lidar_to_world=hdmap_pose_for_lidar_to_world, + ) + # build the dataset + self.dataset = self._build_dataset( + root_path=root_path, + filter_list_path=filter_list_path, + num_views=num_views, + metadata_folder=metadata_folder, + custom_folders=custom_folders, + custom_fields=custom_fields, + view_indices=view_indices, + load_intensity=load_intensity, + ) + self.plus = 1 if "hdmap" not in self.dataset.custom_fields else 2 + self.num_views = num_views + + self.LIDAR_FPS = LIDAR_FPS + self.RGB_FPS = RGB_FPS + + self.sample_n_frames = sample_n_frames + self.random_n_frames = random_n_frames + self.lidar_length = lidar_length + self.rgb_length = lidar_length * (RGB_FPS // LIDAR_FPS) + self.frame_sampling_method = frame_sampling_method + assert self.frame_sampling_method in ["random", "sequential", "sequential_from_zero"] + self.frame_sampling_every_n_frames = frame_sampling_every_n_frames + # Chunk offset for sequential_from_zero: render frames [start, start+n). + # Default 0 preserves existing behavior bit-for-bit. + self.sequential_start_idx = int(sequential_start_idx) + + self.inverse_depth = inverse_depth + self.min_distance = min_range + self.max_distance = max_range + self.max_range = max_range if not inverse_depth else 1 / min_range + self.min_range = min_range if not inverse_depth else 1 / max_range + + self.min_value = min_value # min value after normalisation, if 0 then [0, 1],if -1, then [-1, 1] + + self.repeat_row = repeat_row + self.repeat_col = repeat_col + self.repeat_temporal = repeat_temporal + self.process_input = process_input + self.process_output = process_output + assert self.process_input in ["repeat", "concat", "band", "log", "mono", "fourier"] + assert self.process_output in ["repeat", "concat", "band", "log", "mono"] + self.num_bands = num_bands + assert self.num_bands in RANGE_BANDS.keys() + + # Per-row depth normalization (post min-max; mono only). Built once here + # from training-set stats; None when disabled (no-op downstream). + self.per_row_normalizer = get_per_row_normalizer( + per_row_normalize, + per_row_stats_path, + min_range=self.min_distance, + max_range=self.max_distance, + min_value=self.min_value, + smooth_sigma=per_row_smooth_sigma, + log_depth=False, + ) + if self.per_row_normalizer is not None: + assert not self.inverse_depth, "per_row_normalize requires inverse_depth=False" + assert self.process_input == "mono" and self.process_output == "mono", ( + "per_row_normalize is only supported with process_input/output='mono'" + ) + + # Emit an explicit per-pixel valid (return) mask computed from the + # min-max depth BEFORE per-row normalization. Required when per-row norm + # is on AND the network/loss use a validity head: per-row z-scoring + # shifts the no-return sentinel by a row-dependent amount, so the + # downstream ``depth > min_value + eps`` derivation no longer separates + # returns from raydrop. The mask (1 = return) is carried as + # ``sample["loss_mask"]`` -> MASK_KEY (losses) and threaded into the + # network's ``mask_as_input`` concat. mono only. + self.emit_valid_mask = emit_valid_mask + if self.emit_valid_mask: + assert self.process_input == "mono", ( + "emit_valid_mask is only supported with process_input='mono'" + ) + + self.lidar_size = lidar_size + self.lidar_crop_size = lidar_crop_size + self.rgb_crop_size = rgb_crop_size + self.rgb_resize_size = rgb_resize_size + # Optional resize of the final range map to a fixed [H, W] (use -1 to + # keep a dim). Done with nearest-exact interpolation (NOT bilinear): + # range/depth pixels must not be averaged across depth discontinuities + # (that invents phantom points / blurs thin structure). Mirrors + # r2flow's F.interpolate(..., mode="nearest-exact") resize. + self.lidar_resize_size = lidar_resize_size + + self.sample_lidar_prob = sample_lidar_prob if not load_rgb_only else -1 + self.load_lidar_only = load_lidar_only + self.load_rgb_only = load_rgb_only + self.load_lidar_and_rgb = load_lidar_and_rgb + self.load_lidar_or_rgb = load_lidar_or_rgb + + assert sum([self.load_lidar_only, self.load_rgb_only, self.load_lidar_and_rgb, self.load_lidar_or_rgb]) == 1 + + # t5 text embedding + self.load_t5_embeddings = load_t5_embeddings + self.t5_embedding_path = t5_embedding_path + + self.length = self.dataset.size_of_filter_set() + log.critical(f"load_lidar_only: {self.load_lidar_only}") + log.critical(f"dataset size: {self.length}") + + self.is_video_tokenizer = is_video_tokenizer # if true, then the frame sampling method is sequential, also we need to upsample the lidar to the rgb fps + if self.is_video_tokenizer: + assert self.frame_sampling_method == "sequential" or self.frame_sampling_method == "sequential_from_zero" + + self.range_map_downsampler = RangeMapDownsampler(row_factor = downsample_factor_row, col_factor = downsample_factor_col, method = downsample_method) + + # image transform + self.img_transform = transforms.Compose( + [ + transforms.Resize( + self.rgb_resize_size, interpolation=transforms.InterpolationMode.BILINEAR, antialias=True + ), + transforms.CenterCrop(self.rgb_crop_size), + ] + ) + self.norm_image = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) + + # Prepare infinite dataset logic + self.n_data = self.length + if parallel_state.is_initialized(): + dp_group_id = parallel_state.get_data_parallel_rank() + dp_world_size = parallel_state.get_data_parallel_world_size() + log.critical( + f"Using parallelism size CP :{parallel_state.get_context_parallel_world_size()}, " + + f"TP :{parallel_state.get_tensor_model_parallel_world_size()} for video dataset, " + + f"DP: {dp_group_id}, DP World size: {dp_world_size}" + ) + else: + dp_world_size = 1 + dp_group_id = 0 + + # Data partitioning. Clamp to >=1 so that a split smaller than the + # data-parallel world size (e.g. the 20-sequence Waymo val set on 32 + # GPUs) doesn't divide to zero -- ranks beyond the split then replicate + # samples (start index wrapped mod n_data). For every split with + # n_data >= dp_world_size this is a no-op (bit-identical to before). + self.n_data_per_node = max(1, self.n_data // dp_world_size) + self.data_start_idx = (dp_group_id * self.n_data_per_node) % self.n_data + self.dp_group_id = dp_group_id + + # Infinite loop multiplier + maximum_iter = 2000000 # hack to create infinite loop + self.multiplier = max(1, maximum_iter // self.n_data_per_node) + # self.multiplier = 1 + + # Fourier encoder + self.fourier_max_freq = fourier_max_freq + self.fourier_encoder = SinusoidalEncoder( + n_input_dims=1, + min_deg=0, + max_deg=self.fourier_max_freq, + enable_identity=True, + ) + + def _build_dataset(self, **kwargs): + """Construct the selected low-level reader.""" + if self.dataset_backend == "waymo_ncore": + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + WaymoNCoreLidar, + ) + + return WaymoNCoreLidar( + resample_width=self.resample_width, + **self._hdmap_kwargs, + **kwargs, + ) + if self.dataset_backend == "nuscenes_ncore": + from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import ( + NuScenesNCoreLidar, + ) + + return NuScenesNCoreLidar( + resample_width=self.resample_width, + **self._hdmap_kwargs, + **self._nuscenes_canonical_kwargs, + **kwargs, + ) + if self.dataset_backend == "pandaset": + from tokenizer.training.datasets.lidar_datasets.pandaset import ( + PandaSetCachedLidar, + ) + + return PandaSetCachedLidar(**kwargs) + return RadymLidar(**kwargs) + + def __len__(self): + """ + Return the artificially multiplied length + """ + return self.multiplier * self.n_data_per_node + + def sample_random_frames(self, n_frames, total_frames): + # sample self.sample_n_frames frames from the video + # return the frame indices + frame_indices = np.random.randint(0, total_frames, size=n_frames) + return frame_indices + + def sample_sequential_frames(self, n_frames, total_frames): + # sample every self.frame_sampling_every_n_frames frames + if self.frame_sampling_method == "sequential_from_zero": + start_idx = self.sequential_start_idx + else: + start_idx = np.random.randint(0, total_frames - n_frames * self.frame_sampling_every_n_frames) + frame_indices = np.arange(start_idx, start_idx + n_frames * self.frame_sampling_every_n_frames, self.frame_sampling_every_n_frames) + return frame_indices + + + def _draw_n_frames(self): + """Return sample_n_frames, or a random T in [1, sample_n_frames] if random_n_frames is set.""" + if not self.random_n_frames: + return self.sample_n_frames + return np.random.randint(2, self.sample_n_frames+1) + + def sample_frame_indices(self, load_lidar): + n_frames = self._draw_n_frames() + if load_lidar: + if self.frame_sampling_method == "random": + frame_indices = self.sample_random_frames(n_frames, self.lidar_length) + else: + frame_indices = self.sample_sequential_frames( + n_frames // self.repeat_temporal, self.lidar_length + ) + + else: # load rgb + if self.frame_sampling_method == "random": + frame_indices = self.sample_random_frames(n_frames, self.rgb_length) + else: + frame_indices = self.sample_sequential_frames( + n_frames + 1, self.rgb_length + ) # + 1 because the video tokenizer will need one more additional frame + return frame_indices + + def normalise_and_process_range_map_with_mode(self, range_maps, mode): + # Input: [N, H, W]. Output: [N, C, H, W] with C=3 for repeat/concat/band/log, C=1 for mono. + # mode: "repeat", "concat", "band", "log", or "mono" + if mode == "repeat": + range_maps = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth + ) # shape: [N, H, W] + range_maps = range_maps[:, None, :, :].repeat(3, axis=1) # shape: [N, 3, 128, 1800] + elif mode == "mono": + range_maps = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth + ) # shape: [N, H, W] + # Per-row z-score on top of min-max (no-op when normalizer is None). + range_maps = apply_per_row_norm(range_maps, self.per_row_normalizer) + range_maps = range_maps[:, None, :, :] # shape: [N, 1, H, W] + elif mode == "concat": + inverse_depth = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, True + ) # shape: [N, H, W] + depth = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, False + ) # shape: [N, H, W] + range_maps = np.concatenate( + [inverse_depth[:, None, :, :], depth[:, None, :, :], depth[:, None, :, :]], axis=1 + ) # shape: [N, 3, 128, 1800] + elif mode == "band": + range_maps_list = [] + for i in range(self.num_bands): + band_range_map = normalize_range_map( + range_maps, + RANGE_BANDS[self.num_bands][i+1], + RANGE_BANDS[self.num_bands][i], + self.min_value, + self.inverse_depth + )[:, None, :, :] # shape: [N, 1, H, W] + range_maps_list.append(band_range_map) + range_maps = np.concatenate(range_maps_list, axis=1) # shape: [N, 3, 128, 1800] + elif mode == "log": + max_scale = np.log2(self.max_distance + 1) + range_maps = np.clip(range_maps, self.min_distance, self.max_distance) # 5-100 + range_maps = np.log2(range_maps + 1) / max_scale # 0-1 + if self.min_value == -1: + range_maps = range_maps * 2 - 1 # -1-1 + range_maps = range_maps[:, None, :, :].repeat(3, axis=1) # shape: [N, 3, 128, 1800] + elif mode == "fourier": + range_maps = normalize_range_map( + range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth + ) # shape: [N, H, W] + x = torch.from_numpy(range_maps).float().unsqueeze(-1) # [N, H, W, 1] + encoded = self.fourier_encoder(x) # [N, H, W, n_output_dims] + range_maps = encoded.permute(0, 3, 1, 2).numpy() # [N, n_output_dims, H, W] + return range_maps + + def normalise_and_convert_range_map_to_three_channels(self, range_maps): + """Uses process_input.""" + return self.normalise_and_process_range_map_with_mode( + range_maps, self.process_input + ) + + def _apply_repeat_crop_temporal(self, range_maps_np, start_col_idx=None): + # range_maps_np: [N, C, H, W] (C=3 or 1 for mono). When two tensors use same crop, pass shared start_col_idx. + range_maps_np = range_maps_np.repeat(self.repeat_row, axis=2) + range_maps_np = range_maps_np.repeat(self.repeat_col, axis=3) + if self.lidar_crop_size[1] != -1: + if self.lidar_crop_size[1] > 1600: + start_col_idx = (range_maps_np.shape[-1] - self.lidar_crop_size[1]) // 2 + range_maps_np = range_maps_np[:, :, :, start_col_idx : start_col_idx + self.lidar_crop_size[1]] + else: + if start_col_idx is None: + start_col_idx = np.random.randint(0, range_maps_np.shape[-1] - self.lidar_crop_size[1]) + range_maps_np = range_maps_np[:, :, :, start_col_idx : start_col_idx + self.lidar_crop_size[1]] + if self.frame_sampling_method in ("sequential", "sequential_from_zero") and self.is_video_tokenizer: + first_range_map = range_maps_np[0] + range_maps_np = range_maps_np.repeat(self.repeat_temporal, axis=0) + range_maps_np = np.concatenate([first_range_map[None], range_maps_np], axis=0) + range_maps_t = torch.from_numpy(range_maps_np).float() + # Optional fixed-size resize (nearest-exact, see __init__). Applied to + # the [N, C, H, W] tensor so depth values are resampled, never blended. + if self.lidar_resize_size is not None and ( + self.lidar_resize_size[0] != -1 or self.lidar_resize_size[1] != -1 + ): + _, _, H, W = range_maps_t.shape + target_h = self.lidar_resize_size[0] if self.lidar_resize_size[0] != -1 else H + target_w = self.lidar_resize_size[1] if self.lidar_resize_size[1] != -1 else W + if (target_h, target_w) != (H, W): + range_maps_t = F.interpolate( + range_maps_t, size=(target_h, target_w), mode="nearest-exact" + ) + return range_maps_t + + def _normalize_intensity(self, intensity_maps): + """Apply the selected intensity transform and add a channel dimension.""" + intensity_maps = intensity_maps.copy() + if self.intensity_transform == "log1p": + intensity_maps = np.clip( + intensity_maps / self.intensity_raw_max, 0.0, 1.0 + ) + intensity_maps = np.log1p(intensity_maps) / np.log(2.0) + intensity_maps = intensity_maps * 2.0 - 1.0 + return intensity_maps[:, None, :, :] + if self.min_value == -1: + intensity_maps = intensity_maps * 2 - 1 + return intensity_maps[:, None, :, :] # [N, 1, H, W] + + def get_sensor_metadata(self, height, width): + """Return true sensor geometry for opt-in cross-dataset training.""" + if not self.emit_sensor_metadata: + return {} + if self._sensor_ray_directions is None: + if self.dataset_backend == "waymo_ncore": + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_ray_directions, + ) + + rays = load_waymo_ray_directions( + root_path=self._sensor_root_path, + filter_list_path=self._sensor_filter_list_path, + lidar_id="lidar_top", + resample_width=self.resample_width, + ) + elif self.dataset_backend == "nuscenes_ncore": + from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import ( + load_nuscenes_ray_directions, + ) + + rays = load_nuscenes_ray_directions( + root_path=self._sensor_root_path, + filter_list_path=self._sensor_filter_list_path, + lidar_id="lidar_top", + resample_width=self.resample_width, + center_vehicle_forward=self.center_vehicle_forward, + ) + elif self.dataset_backend == "pandaset": + rays = self.dataset.sensor_ray_directions() + else: + from utils.lidar_rangemap import ( + load_pandar128_elevations, + range_map_to_ray_directions, + ) + + elevations = torch.tensor(load_pandar128_elevations(), dtype=torch.float32) + rays = range_map_to_ray_directions( + width // self.repeat_col, elevations + ) + rays = torch.as_tensor(rays, dtype=torch.float32) + rays = rays.repeat_interleave(self.repeat_row, dim=0) + rays = rays.repeat_interleave(self.repeat_col, dim=1) + if tuple(rays.shape[:2]) != (height, width): + raise ValueError( + "True-ray metadata must match the repeated sensor grid; " + f"got rays {tuple(rays.shape[:2])} and sample {(height, width)}" + ) + self._sensor_ray_directions = rays + return { + "sensor_ray_directions": self._sensor_ray_directions, + "sensor_depth_bounds": torch.tensor( + [self.min_distance, self.max_distance], dtype=torch.float32 + ), + "sensor_dataset_id": self.sensor_dataset_id, + "sensor_dataset_name": self.sensor_dataset_name, + } + + def _compute_valid_mask_np(self, range_maps): + # range_maps: [N, H, W] metric depth (post-downsample, pre per-row). + # Returns [N, 1, H, W] float {0,1}: 1 = real return, 0 = no-return. + # Use raw metric support rather than a normalized epsilon. A threshold + # at ``min_value + 0.02`` incorrectly removes the first 1% of every + # sensor's configured range (e.g. valid Pandar returns at 5--5.95 m). + valid = ( + np.isfinite(range_maps) + & (range_maps >= self.min_distance) + & (range_maps <= self.max_distance) + ).astype(np.float32) + return valid[:, None, :, :] # [N, 1, H, W] + + def process_lidar(self, range_maps, intensity_maps=None): + # Returns (input_tensor, supervision_tensor, valid_tensor). Same crop/temporal for all. + # valid_tensor is None unless ``emit_valid_mask`` (then [N, 1, H, W] {0,1}). + # When intensity_maps is provided, it is appended as extra channel(s) to both tensors. + if intensity_maps is not None: + range_maps, [intensity_maps] = self.range_map_downsampler.downsample(range_maps, [intensity_maps]) + else: + range_maps = self.range_map_downsampler.downsample(range_maps) # shape: [N, H, W] + + # Replace every unsupported metric depth with the raw no-return + # sentinel before normalization. Otherwise np.clip maps +inf and + # finite >max returns to +1, while NaNs survive normalization. Keep the + # optional explicit mask from this exact same support predicate. + metric_valid_np = self._compute_valid_mask_np(range_maps) + valid_np = metric_valid_np if self.emit_valid_mask else None + range_maps = np.where( + metric_valid_np[:, 0].astype(bool), range_maps, 0.0 + ).astype(np.float32, copy=False) + if intensity_maps is not None: + intensity_maps = np.where( + metric_valid_np[:, 0].astype(bool), intensity_maps, 0.0 + ).astype(np.float32, copy=False) + intensity_np = self._normalize_intensity(intensity_maps) if intensity_maps is not None else None + + if self.intensity_only: + if intensity_np is None: + raise ValueError( + "intensity_only=True but this sample has no intensity map" + ) + # The depth image remains available only to define return validity. + # Model input and reconstruction target are strictly one-channel + # intensity; no-return pixels are excluded by ``valid_tensor``. + start_col_idx = None + if self.lidar_crop_size[1] != -1 and self.lidar_crop_size[1] <= 1600: + w = intensity_np.shape[-1] * self.repeat_col + start_col_idx = np.random.randint( + 0, w - self.lidar_crop_size[1] + ) + intensity_tensor = self._apply_repeat_crop_temporal( + intensity_np, start_col_idx + ) + valid_tensor = ( + self._apply_repeat_crop_temporal(valid_np, start_col_idx) + if valid_np is not None + else None + ) + return intensity_tensor, intensity_tensor, valid_tensor + + if self.process_output != self.process_input: + range_maps_input = self.normalise_and_process_range_map_with_mode( + range_maps, self.process_input + ) + range_maps_supervision = self.normalise_and_process_range_map_with_mode( + range_maps, self.process_output + ) + if intensity_np is not None: + range_maps_input = np.concatenate([range_maps_input, intensity_np], axis=1) + range_maps_supervision = np.concatenate([range_maps_supervision, intensity_np], axis=1) + # Share random crop when applicable + start_col_idx = None + if self.lidar_crop_size[1] != -1 and self.lidar_crop_size[1] <= 1600: + w = range_maps_input.shape[-1] * self.repeat_col + start_col_idx = np.random.randint(0, w - self.lidar_crop_size[1]) + input_tensor = self._apply_repeat_crop_temporal(range_maps_input, start_col_idx) + supervision_tensor = self._apply_repeat_crop_temporal(range_maps_supervision, start_col_idx) + valid_tensor = ( + self._apply_repeat_crop_temporal(valid_np, start_col_idx) + if valid_np is not None else None + ) + return input_tensor, supervision_tensor, valid_tensor + else: + range_maps = self.normalise_and_convert_range_map_to_three_channels(range_maps) + if intensity_np is not None: + range_maps = np.concatenate([range_maps, intensity_np], axis=1) + # Generate the (possibly random) crop offset once so depth and the + # validity mask are cropped identically. + start_col_idx = None + if ( + valid_np is not None + and self.lidar_crop_size[1] != -1 + and self.lidar_crop_size[1] <= 1600 + ): + w = range_maps.shape[-1] * self.repeat_col + start_col_idx = np.random.randint(0, w - self.lidar_crop_size[1]) + input_tensor = self._apply_repeat_crop_temporal(range_maps, start_col_idx) + valid_tensor = ( + self._apply_repeat_crop_temporal(valid_np, start_col_idx) + if valid_np is not None else None + ) + return input_tensor, input_tensor, valid_tensor + + def process_rgb(self, rgb_images): + rgb_images = self.img_transform(rgb_images) + rgb_images = self.norm_image(rgb_images) # N C H W + return rgb_images + + def prepare_dummy_data(self): + data = {} + dummy_text_embedding = torch.zeros(512, 1024) + dummy_text_mask = torch.zeros(512) + dummy_text_mask[0] = 1 + data["t5_text_embeddings"] = dummy_text_embedding + data["t5_text_mask"] = dummy_text_mask + + return data + + def prepare_t5_embeddings(self, example, frame_indices): + # determine which chunk to use based on the frame indices + mid_indice = frame_indices[len(frame_indices) // 2] + chunk_id = mid_indice // int(self.lidar_length / 5) + + if self.load_t5_embeddings: + # t5_embed_path = os.path.join(self.t5_embedding_path, example["__key__"] + f"_{chunk_id}.pkl") + t5_embed_path = os.path.join(self.t5_embedding_path, example["__key__"] + ".pkl") + if os.path.exists(t5_embed_path): + t5_embed_pickle = _safe_pickle_load(t5_embed_path) + t5_embed = {} + text_embedding = t5_embed_pickle["pickle"]["ground_truth"]["embeddings"]["t5_xxl"] + dummy_text_embedding = torch.zeros(512, 1024) + dummy_text_mask = torch.zeros(512) + n_text = text_embedding.shape[0] # 512 + dummy_text_embedding[:n_text] = torch.from_numpy(text_embedding) + dummy_text_mask[:n_text] = 1 + t5_embed["t5_text_embeddings"] = dummy_text_embedding + t5_embed["t5_text_mask"] = dummy_text_mask + del t5_embed_pickle + else: + log.info(f"t5 embedding not found for {example['__key__']}", rank0_only=False) + t5_embed = self.prepare_dummy_data() + else: + t5_embed = self.prepare_dummy_data() + + if self.num_views > 1: + t5_embed["t5_text_embeddings"] = torch.cat([t5_embed["t5_text_embeddings"]] * (self.num_views+self.plus), dim=0) + t5_embed["t5_text_mask"] = torch.cat([t5_embed["t5_text_mask"]] * (self.num_views+self.plus), dim=0) + + return t5_embed + + def get_lidar(self, example, lidar_key="lidar"): + """Returns (input_tensor, recon_target, valid_mask). First two [C, N, H, W]. + valid_mask is [1, N, H, W] (or None when emit_valid_mask is off).""" + if lidar_key in example["custom"]: + range_maps = example["custom"][lidar_key] # shape: [N, 128, 3600] + intensity_maps = example["custom"].get("lidar_intensity") if self.load_intensity else None + input_tensor, recon_target, valid_mask = self.process_lidar(range_maps, intensity_maps) + input_tensor = input_tensor.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + recon_target = recon_target.permute(1, 0, 2, 3).contiguous() + if valid_mask is not None: + valid_mask = valid_mask.permute(1, 0, 2, 3).contiguous() # [1, N, H, W] + return input_tensor, recon_target, valid_mask + return None, None, None + + def process_hdmap_multichannel(self, hdmap): + """Per-class semantic hdmap [N, K, H, W] (metric range, 0=empty) -> torch + [K, N', H, W]. Each class channel is normalized like a mono depth map + (empty -> min_value sentinel) and shares the lidar's downsample / repeat / + temporal-prepend / resize so channels stay pixel-aligned with the lidar.""" + N, K, H, W = hdmap.shape + chans = [] + for k in range(K): + rm = self.range_map_downsampler.downsample(hdmap[:, k]) # [N, H, W] + rm = normalize_range_map( + np.asarray(rm, dtype=np.float32).copy(), + self.max_distance, + self.min_distance, + self.min_value, + self.inverse_depth, + ) # [N, H, W] in [min_value, 1] + chans.append(rm[:, None, :, :]) # [N, 1, H, W] + arr = np.concatenate(chans, axis=1) # [N, K, H, W] + t = self._apply_repeat_crop_temporal(arr) # [N', K, H, W] + return t.permute(1, 0, 2, 3).contiguous() # [K, N', H, W] + + def get_lidar_hdmap(self, example, hdmap_key="hdmap"): + if hdmap_key not in example["custom"]: + return None + hd = example["custom"][hdmap_key] + # Multi-channel semantic hdmap (one range-image channel per class) -> + # [N, K, H, W]; normalize per channel. Single-channel depth hdmap -> + # [N, H, W]; reuse the lidar pipeline. + if np.asarray(hd).ndim == 4: + return self.process_hdmap_multichannel(hd) + hdmap_input, _, _ = self.process_lidar(hd) + return hdmap_input.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + + def get_rgb(self, example): + key = DataField.IMAGE_RGB + if key in example.keys(): + rgb_images_dict = dict() + view_keys = example[key].keys() + for view_key in view_keys: + rgb_images = example[key][view_key] + rgb_images = self.process_rgb(rgb_images) + rgb_images = rgb_images.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + rgb_images_dict[key.value + "_" + str(view_key)] = rgb_images + else: + rgb_images_dict = None + return rgb_images_dict + + def get_rgb_hdmap(self, example): + key = DataField.IMAGE_HDMAP + if key in example.keys(): + rgb_hdmap_dict = dict() + view_keys = example[key].keys() + for view_key in view_keys: + rgb_hdmap = example[key][view_key] + rgb_hdmap = self.process_rgb(rgb_hdmap) + rgb_hdmap = rgb_hdmap.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W] + rgb_hdmap_dict[key.value + "_" + str(view_key)] = rgb_hdmap + else: + rgb_hdmap_dict = None + return rgb_hdmap_dict + + def get_camera_c2lidar_transform(self, example): + key = DataField.CAMERA_C2LIDAR_TRANSFORM + if key in example.keys(): + camera_c2lidar_transform_dict = dict() + view_keys = example[key].keys() + for view_key in view_keys: + camera_c2lidar_transform = example[key][view_key] + camera_c2lidar_transform_dict[key.value + "_" + str(view_key)] = camera_c2lidar_transform + else: + camera_c2lidar_transform_dict = None + return camera_c2lidar_transform_dict + + def get_camera_intrinsics(self, example): + key = DataField.CAMERA_INTRINSICS + if key in example.keys(): + view_keys = example[key].keys() + camera_intrinsics_dict = dict() + for view_key in view_keys: + camera_intrinsics = example[key][view_key] + camera_intrinsics_dict[key.value + "_" + str(view_key)] = camera_intrinsics + else: + camera_intrinsics_dict = None + return camera_intrinsics_dict + + + + def __getitem__(self, idx): + if self.load_rgb_only: + raise NotImplementedError + if self.load_lidar_or_rgb: + raise NotImplementedError + + # sample the video index + lidar_data_idx = (idx % self.n_data_per_node) + self.data_start_idx # frame idx + lidar_frame_indices = self.sample_frame_indices(load_lidar=True) + + # load the data + try: + if self.load_lidar_and_rgb: # we also load the camera intrinsics and camera-to-lidar transformation matrix as well as the timestamp for motion compensation + # example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom", DataField.CAMERA_C2LIDAR_TRANSFORM, DataField.CAMERA_INTRINSICS, DataField.IMAGE_HDMAP, DataField.IMAGE_RGB]) + example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom", DataField.CAMERA_C2LIDAR_TRANSFORM, DataField.CAMERA_INTRINSICS, DataField.IMAGE_RGB]) + else: + example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom"]) + except Exception as e: + log.info(f"Error loading data for index {idx}: {e}", rank0_only=False) + return self.__getitem__(np.random.randint(0, self.__len__())) + + lidar_rangemap, recon_target, lidar_valid_mask = self.get_lidar(example) + lidar_hdmap = self.get_lidar_hdmap(example) + rgb_images = self.get_rgb(example) + rgb_hdmap = self.get_rgb_hdmap(example) + t5_embed = self.prepare_t5_embeddings(example, lidar_frame_indices) + + + cam_intrinsics = self.get_camera_intrinsics(example) + cam_c2lidar_transform = self.get_camera_c2lidar_transform(example) + + key = "video" + + sample = {} + sample[key] = lidar_rangemap + sample["recon_target"] = recon_target + if lidar_valid_mask is not None: + # Explicit per-pixel return mask (pre per-row). Routed to MASK_KEY in + # model.{training,validation}_step and into the mask_as_input concat. + sample["loss_mask"] = lidar_valid_mask + sample["loss_mask_is_validity"] = True + sample["__key__"] = example["__key__"] + sample["clip_name"] = "%s-%s-%d" % (self.data_name, example["__key__"], idx) + sample["data_type"] = "lidar" + sample["num_frames"] = self.sample_n_frames + 1 if self.is_video_tokenizer else self.sample_n_frames + sample["is_preprocessed"] = True + sample["image_size"] = torch.tensor(self.lidar_size) + sample["padding_mask"] = torch.zeros(1, self.lidar_size[0], self.lidar_size[1]) + sample["fps"] = 24 # unsure why this value + sample['num_views'] = self.num_views + sample["view_indices"] = torch.arange(self.num_views + self.plus) # +1 for the lidar view + sample["timestamp_list"] = example["timestamp_list"] + sample["pose_sensor_start_end"] = example["pose_sensor_start_end"] + sample["rgb_frame_indices"]=example["rgb_frame_indices"] + # Ego poses (lidar->world, sweep-start) aligned to the *video* temporal + # layout: mirror the repeat_temporal + frame-0 prepend applied to the + # range maps in `_apply_repeat_crop_temporal` so pose[t] indexes the + # same frame as video[:, t]. Shape: (T, 4, 4). + lidar_to_world = np.asarray(example["lidar_to_world"], dtype=np.float32) # (N, 4, 4) + if self.is_video_tokenizer and self.frame_sampling_method in ( + "sequential", + "sequential_from_zero", + ): + lidar_to_world = np.concatenate( + [lidar_to_world[:1], np.repeat(lidar_to_world, self.repeat_temporal, axis=0)], + axis=0, + ) + sample["lidar_to_world"] = torch.from_numpy(lidar_to_world).float() + sample.update(t5_embed) + + if lidar_hdmap is not None: + sample["lidar_hdmap"] = lidar_hdmap + if rgb_images is not None: + sample.update(rgb_images) + if rgb_hdmap is not None: + sample.update(rgb_hdmap) + if self.load_lidar_and_rgb: + + sample.update(cam_intrinsics) + sample.update(cam_c2lidar_transform) + + + del example + gc.collect() + # from imaginaire.utils import distributed, log + # rank = distributed.get_rank() + # print(f"RANK {rank}, {data_idx}: Working on clip {sample['clip_name']}.") + return sample diff --git a/tokenizer/training/datasets/lidar_datasets/tokenizer_dataloader.py b/tokenizer/training/datasets/lidar_datasets/tokenizer_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..638e948cf641f92ad13fc961ef2680d05efa6725 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/tokenizer_dataloader.py @@ -0,0 +1,373 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import omegaconf +from omegaconf import OmegaConf +import torch +from torch.utils.data import DataLoader, Dataset, Sampler + +from utils.lazy_config import LazyCall as L +from tokenizer.training.datasets.lidar_datasets.configs import COMMONDATA_CONFIG +from tokenizer.training.datasets.lidar_datasets.rangemap_sampler import LidarRangeMapSampler +import numpy as np + +def dict_collation_fn(samples, combine_tensors=True, combine_scalars=True, ignore_keys=None): + """Take a list of samples (as dictionary) and create a batch, preserving the keys. + If `tensors` is True, `ndarray` objects are combined into + tensor batches. + :param dict samples: list of samples + :param bool tensors: whether to turn lists of ndarrays into a single ndarray + :returns: single sample consisting of a batch + :rtype: dict + """ + + batched = {key: [] for key in samples[0]} + # assert isinstance(samples[0][first_key], (list, tuple)), type(samples[first_key]) + + for s in samples: + [batched[key].append(s[key]) for key in batched if not (ignore_keys is not None and key in ignore_keys)] + + result = {} + for key in batched: + if ignore_keys and key in ignore_keys: + continue + try: + if isinstance(batched[key][0], bool): + assert key in {"is_preprocessed", "loss_mask_is_validity"} + assert all(value == batched[key][0] for value in batched[key]) + result[key] = batched[key][0] # this is a hack to align with cosmos data + elif isinstance(batched[key][0], (int, float)): + if combine_scalars: + result[key] = torch.from_numpy(np.array(list(batched[key]))) + elif isinstance(batched[key][0], torch.Tensor): + if combine_tensors: + result[key] = torch.stack(list(batched[key])) + elif isinstance(batched[key][0], np.ndarray): + if combine_tensors: + result[key] = np.array(list(batched[key])) + elif isinstance(batched[key][0], list) and isinstance(batched[key][0][0], int): + result[key] = [torch.Tensor(elems).long() for elems in zip(*batched[key])] + else: + result[key] = list(batched[key]) + except Exception as e: + print(key) + raise e + # result.append(b) + del batched + return result + +def get_lidar_range_map_dataloader( + dataset_name: str, + shuffle=True, + num_workers=4, + prefetch_factor=4, + **kwargs, +) -> omegaconf.dictconfig.DictConfig: + return L(MyDataLoader)( + dataset=L(LidarRangeMapDataset)( + dataset_name=dataset_name, + **kwargs, + ), + batch_size=1, + num_workers=num_workers, + shuffle=shuffle, + prefetch_factor=prefetch_factor, + pin_memory=True, + ) + + +def get_cross_dataset_lidar_range_map_dataloader( + dataset_names, + validation=False, + mix_datasets_across_ranks=False, + dataset_sampling_weights=None, + seed=0, + num_workers=4, + prefetch_factor=4, + **kwargs, +) -> omegaconf.dictconfig.DictConfig: + """Build opt-in native-grid homogeneous batches from multiple sensors.""" + return L(HomogeneousMultiDataLoader)( + dataset=L(CrossDatasetRangeMapDataset)( + dataset_names=dataset_names, + shared_overrides=kwargs, + uses_sensor_metadata=True, + ), + batch_size=1, + validation=validation, + mix_datasets_across_ranks=mix_datasets_across_ranks, + dataset_sampling_weights=dataset_sampling_weights, + seed=seed, + num_workers=num_workers, + prefetch_factor=prefetch_factor, + pin_memory=True, + ) + + +class MyDataLoader(DataLoader): + def __init__(self, dataset, batch_size: int = 1, *args, **kw): + dataset_obj = dataset.build_dataset() + print("dl", kw.get("dataloaders")) + if "dataloaders" in kw: + kw.pop("dataloaders") # HACK? + print("dl2", kw.get("dataloaders")) + super().__init__(dataset_obj, batch_size, collate_fn=dict_collation_fn, *args, **kw) + + +class CrossDatasetRangeMapDataset: + def __init__( + self, + dataset_names, + shared_overrides=None, + per_dataset_overrides=None, + uses_sensor_metadata=True, + ): + self.dataset_names = list(dataset_names) + self.shared_overrides = dict(shared_overrides or {}) + self.per_dataset_overrides = dict(per_dataset_overrides or {}) + self.uses_sensor_metadata = bool(uses_sensor_metadata) + + def build_dataset(self): + children = [] + for dataset_id, dataset_name in enumerate(self.dataset_names): + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + overrides = OmegaConf.create( + { + **self.shared_overrides, + **self.per_dataset_overrides.get(dataset_name, {}), + "emit_sensor_metadata": True, + "sensor_dataset_id": dataset_id, + "sensor_dataset_name": dataset_name, + } + ) + config = OmegaConf.to_container( + OmegaConf.merge(dataset_config, overrides), resolve=True + ) + children.append(LidarRangeMapSamplerTokenizer(**config)) + return HomogeneousMultiDataset(children) + + +class HomogeneousMultiDataset(Dataset): + """Route a batch of tuple indices to exactly one native-grid child.""" + + def __init__(self, children): + self.children = list(children) + if not self.children: + raise ValueError("At least one child dataset is required") + + def __len__(self): + return sum(len(child) for child in self.children) + + def __getitem__(self, index): + dataset_id, local_index = index + return self.children[dataset_id][local_index] + + +class HomogeneousDatasetBatchSampler(Sampler): + """Keep local batches homogeneous, with optional rank-balanced mixing.""" + + def __init__( + self, + dataset, + batch_size, + validation=False, + mix_datasets_across_ranks=False, + dataset_sampling_weights=None, + seed=0, + ): + self.dataset = dataset + self.batch_size = int(batch_size) + self.validation = bool(validation) + self.mix_datasets_across_ranks = bool(mix_datasets_across_ranks) + self.dataset_sampling_weights = None + if dataset_sampling_weights is not None: + weights = torch.as_tensor( + dataset_sampling_weights, dtype=torch.float64 + ) + if weights.numel() != len(dataset.children): + raise ValueError( + "dataset_sampling_weights must have one value per dataset; " + f"got {weights.numel()} values for {len(dataset.children)} datasets" + ) + if ( + not torch.isfinite(weights).all() + or (weights < 0).any() + or weights.sum() <= 0 + ): + raise ValueError( + "dataset_sampling_weights must be finite, non-negative, and sum positive" + ) + if self.mix_datasets_across_ranks and not torch.allclose( + weights, weights.new_full(weights.shape, weights.mean()) + ): + raise ValueError( + "Non-uniform dataset sampling is incompatible with " + "mix_datasets_across_ranks=True" + ) + self.dataset_sampling_weights = weights / weights.sum() + self.seed = int(seed) + self.num_batches = ( + sum(len(child) for child in dataset.children) // self.batch_size + ) + + def __len__(self): + return self.num_batches + + def __iter__(self): + generator = torch.Generator().manual_seed(self.seed) + cursors = [0] * len(self.dataset.children) + for step in range(self.num_batches): + if self.validation: + dataset_id = step % len(self.dataset.children) + elif self.mix_datasets_across_ranks: + rank = ( + torch.distributed.get_rank() + if torch.distributed.is_initialized() + else 0 + ) + dataset_id = (rank + step) % len(self.dataset.children) + else: + if self.dataset_sampling_weights is None: + dataset_id = int( + torch.randint( + len(self.dataset.children), (1,), generator=generator + ).item() + ) + else: + dataset_id = int( + torch.multinomial( + self.dataset_sampling_weights, + 1, + generator=generator, + ).item() + ) + child_len = len(self.dataset.children[dataset_id]) + start = cursors[dataset_id] + batch = [ + (dataset_id, (start + offset) % child_len) + for offset in range(self.batch_size) + ] + cursors[dataset_id] = (start + self.batch_size) % child_len + yield batch + + +class HomogeneousMultiDataLoader(DataLoader): + def __init__( + self, + dataset, + batch_size=1, + validation=False, + mix_datasets_across_ranks=False, + dataset_sampling_weights=None, + seed=0, + *args, + **kwargs, + ): + dataset_obj = dataset.build_dataset() + batch_sampler = HomogeneousDatasetBatchSampler( + dataset_obj, + batch_size=batch_size, + validation=validation, + mix_datasets_across_ranks=mix_datasets_across_ranks, + dataset_sampling_weights=dataset_sampling_weights, + seed=seed, + ) + super().__init__( + dataset_obj, + batch_sampler=batch_sampler, + collate_fn=dict_collation_fn, + *args, + **kwargs, + ) + + +class LidarRangeMapDataset: + def __init__(self, dataset_name, **kwargs): + self.dataset_name = dataset_name + self.dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + self.extra_config = OmegaConf.create(kwargs) + + def build_dataset(self): + # Merge extra_config (from kwargs/overrides) into dataset_config + if self.extra_config: + merged_config = OmegaConf.merge(self.dataset_config, self.extra_config) + else: + merged_config = self.dataset_config + config_dict = OmegaConf.to_container(merged_config, resolve=True) + return LidarRangeMapSamplerTokenizer(**config_dict) + + +class LidarRangeMapSamplerTokenizer(LidarRangeMapSampler): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def __getitem__(self, idx): + if self.load_rgb_only: + raise NotImplementedError + if self.load_lidar_or_rgb: + raise NotImplementedError + if self.load_lidar_and_rgb: + raise NotImplementedError + + # sample the video index + lidar_data_idx = (idx % self.n_data_per_node) + self.data_start_idx # frame idx + lidar_frame_indices = self.sample_frame_indices(load_lidar=True) + + # load the data + example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom"]) + + lidar_rangemap, recon_target, lidar_valid_mask = self.get_lidar(example) + + if self.is_video_tokenizer: + key = "video" + else: + key = "images" + + sample = {} + sample[key] = lidar_rangemap + sample["recon_target"] = recon_target + if lidar_valid_mask is not None: + # Explicit per-pixel return mask (pre per-row) -> MASK_KEY + + # mask_as_input concat. See LidarRangeMapSampler.process_lidar. + sample["loss_mask"] = lidar_valid_mask + sample["loss_mask_is_validity"] = True + sample["__key__"] = example["__key__"] + clip_name = "%s-%s-%d" % (self.data_name, example["__key__"], idx) + sample["clip_name"] = clip_name + sample["data_type"] = "lidar" + sample.update(self.get_sensor_metadata(*lidar_rangemap.shape[-2:])) + # Ego poses (lidar->world, sweep-start), aligned to the video temporal + # layout: mirror the repeat_temporal + frame-0 prepend applied to the + # range maps in `_apply_repeat_crop_temporal`, so pose[t] indexes the + # same frame as video[:, t]. Shape: (T, 4, 4). + lidar_to_world = np.asarray(example["lidar_to_world"], dtype=np.float32) # (N, 4, 4) + if self.is_video_tokenizer and self.frame_sampling_method in ( + "sequential", + "sequential_from_zero", + ): + lidar_to_world = np.concatenate( + [lidar_to_world[:1], np.repeat(lidar_to_world, self.repeat_temporal, axis=0)], + axis=0, + ) + sample["lidar_to_world"] = torch.from_numpy(lidar_to_world).float() + + del example + + return sample + + +if __name__ == "__main__": + pass diff --git a/tokenizer/training/datasets/lidar_datasets/waymo_hdmap.py b/tokenizer/training/datasets/lidar_datasets/waymo_hdmap.py new file mode 100644 index 0000000000000000000000000000000000000000..514b9a5693f7e2f5cf3985c322ac89e58a316163 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/waymo_hdmap.py @@ -0,0 +1,970 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""On-the-fly HDMap range-image composer for the Waymo NCore dataloader. + +Consumes the per-clip NPZ written by ``scripts/data/dump_waymo_hdmap.py`` (static map +polylines pre-sampled to world-frame points + per-frame dynamic boxes) and +rasterizes a single-channel metric-depth (range) image for a given frame, using +the SAME beam grid + uniform-azimuth rebin as the lidar range image +(``WaymoNCoreLidar._scatter_frame``), so hdmap and lidar pixels line up. + +Projection (world point -> range pixel), matching the lidar grid convention: + p_s = R^T (p_w - t) # world -> sweep-start sensor frame + r = ||p_s|| # metric range + row = argmin_r |elev[r] - asin(z/r)| # nearest beam (elevation table) + az = atan2(y, x) - row_offset[row] # per-row azimuth offset (row-offset model) + col = round((az - azim0)/daz) % C # native column (uniform azimuths) + then (col * out_width)//C # SAME rebin the lidar scatter uses +On a (row,col) collision the NEAREST return wins (scatter-min over range). + +All static map points are pose-independent; only the ego ``lidar_to_world`` (and +per-frame box poses) change with the frame. +""" + +from typing import Optional, Sequence, Tuple + +import numpy as np +import torch + +# ----------------------------------------------------------------------------- # +# Box wireframe geometry +# ----------------------------------------------------------------------------- # +# Corner order: bit index = 4*xi + 2*yi + zi (xi,yi,zi in {0:+, 1:-}) +_BOX_SIGNS = np.array( + [[sx, sy, sz] for sx in (1.0, -1.0) for sy in (1.0, -1.0) for sz in (1.0, -1.0)], + dtype=np.float64, +) # (8, 3) +_BOX_EDGES = [ + (i, j) for i in range(8) for j in range(i + 1, 8) if bin(i ^ j).count("1") == 1 +] # 12 edges + + +def sample_box_edges(o2w: np.ndarray, lwh: np.ndarray, spacing: float) -> np.ndarray: + """Sample the 12 wireframe edges of one box to world-frame points (P, 3).""" + half = 0.5 * np.asarray(lwh, dtype=np.float64) # (3,) + corners = _BOX_SIGNS * half[None, :] # (8, 3) object frame + pts = [] + for i, j in _BOX_EDGES: + a, b = corners[i], corners[j] + L = float(np.linalg.norm(b - a)) + n = max(int(np.ceil(L / max(spacing, 1e-3))), 2) + ts = np.linspace(0.0, 1.0, n)[:, None] + pts.append(a[None, :] + ts * (b - a)[None, :]) + obj_pts = np.concatenate(pts, axis=0) # (P, 3) + return obj_pts @ o2w[:3, :3].T + o2w[:3, 3] + + +# ----------------------------------------------------------------------------- # +# Projection +# ----------------------------------------------------------------------------- # +def project_world_points( + pts_world: np.ndarray, + lidar_to_world: np.ndarray, + elev: np.ndarray, + azim_native: np.ndarray, + row_off: np.ndarray, + C_native: int, + out_width: int, + min_range: float, + max_range: float, + max_horizontal: Optional[float] = None, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """World points -> (rows, cols, ranges) on the (R, out_width) range grid. + + ``max_horizontal`` (m), if given, additionally drops points whose BEV (xy) + distance exceeds it -- a natural "map crop" radius for the lane graph.""" + if pts_world.shape[0] == 0: + z = np.zeros((0,), np.int64) + return z, z, np.zeros((0,), np.float32) + Rm = lidar_to_world[:3, :3].astype(np.float64) + t = lidar_to_world[:3, 3].astype(np.float64) + ps = (pts_world.astype(np.float64) - t[None, :]) @ Rm # == R^T (p - t) + r = np.linalg.norm(ps, axis=1) + keep = (r >= min_range) & (r <= max_range) + if max_horizontal is not None: + keep = keep & (np.hypot(ps[:, 0], ps[:, 1]) <= max_horizontal) + ps, r = ps[keep], r[keep] + if ps.shape[0] == 0: + z = np.zeros((0,), np.int64) + return z, z, np.zeros((0,), np.float32) + el = np.arcsin(np.clip(ps[:, 2] / r, -1.0, 1.0)) + # Memory-bounded nearest-beam lookup. The old ``(P,R)`` broadcast costs + # hundreds of MB for an all-history union (up to 6*64*1024 points). + elev_order = np.argsort(elev, kind="stable") + elev_sorted = np.asarray(elev)[elev_order] + ei = np.searchsorted(elev_sorted, el) + ei0 = np.clip(ei - 1, 0, elev_sorted.shape[0] - 1) + ei1 = np.clip(ei, 0, elev_sorted.shape[0] - 1) + ed0 = np.abs(el - elev_sorted[ei0]) + ed1 = np.abs(el - elev_sorted[ei1]) + nearest_ei = np.where( + ed0 < ed1, + ei0, + np.where( + ed1 < ed0, + ei1, + # Preserve np.argmin's original-index tie break. + np.where(elev_order[ei0] <= elev_order[ei1], ei0, ei1), + ), + ) + row = elev_order[nearest_ei] + + # Native column = the column whose azimuth best matches (point az - row off). + # The azimuth table is ROLLED (starts mid-circle, wraps through +/-pi), so a + # linear (az - az0)/daz inversion is invalid; use a circular nearest search. + def _wrap(a): + return (a + np.pi) % (2.0 * np.pi) - np.pi + + az = _wrap(np.arctan2(ps[:, 1], ps[:, 0]) - row_off[row]) # (P,) + azn = _wrap(np.asarray(azim_native)) # (C,) + order = np.argsort(azn, kind="stable") + azn_sorted = azn[order] + i = np.searchsorted(azn_sorted, az) + i0 = (i - 1) % C_native + i1 = i % C_native + d0 = np.abs(_wrap(az - azn_sorted[i0])) + d1 = np.abs(_wrap(az - azn_sorted[i1])) + col_native = order[np.where(d0 <= d1, i0, i1)] + col = np.minimum((col_native * out_width) // C_native, out_width - 1) + return row.astype(np.int64), col.astype(np.int64), r.astype(np.float32) + + +def scatter_min_range( + R: int, out_width: int, rows: np.ndarray, cols: np.ndarray, ranges: np.ndarray +) -> np.ndarray: + """Scatter ranges into (R, out_width); nearest (smallest) wins on collision.""" + rmap = np.zeros((R, out_width), dtype=np.float32) + if rows.shape[0] == 0: + return rmap + order = np.argsort(-ranges, kind="stable") # write smallest LAST -> wins + rmap[rows[order], cols[order]] = ranges[order] + return rmap + + +# ----------------------------------------------------------------------------- # +# Semantic channel layout +# ----------------------------------------------------------------------------- # +# Channel order for the multi-channel rasterizer. Static map classes first +# (indexed by NPZ ``map_type`` 0..3), then dynamic box classes (NPZ +# ``box_type`` 0..2). One range-image channel per class; 0 == empty. +MAP_CLASS_NAMES = ["lane", "road_line", "road_edge", "crosswalk"] # map_type 0..3 +BOX_CLASS_NAMES = ["vehicle", "pedestrian", "cyclist"] # box_type 0..2 +CLASS_NAMES = MAP_CLASS_NAMES + BOX_CLASS_NAMES # 7 channels +NUM_CLASSES = len(CLASS_NAMES) + + +# ----------------------------------------------------------------------------- # +# Composer +# ----------------------------------------------------------------------------- # +class WaymoHDMapComposer: + """Per-clip HDMap rasterizer loaded from ``/.npz``.""" + + def __init__( + self, + npz_path: str, + elev: np.ndarray, + azim_native: np.ndarray, + row_off: np.ndarray, + C_native: int, + box_edge_spacing: float = 0.15, + map_max_dist: Optional[float] = None, + ): + d = np.load(npz_path, allow_pickle=False) + self.map_points = d["map_points"].astype(np.float32) # (M,3) world + self.map_type = d["map_type"].astype(np.int8) + self.box_frame = d["box_frame"].astype(np.int64) # (K,) + self.box_o2w = d["box_o2w"].astype(np.float32) # (K,4,4) + self.box_lwh = d["box_lwh"].astype(np.float32) # (K,3) + self.box_type = d["box_type"].astype(np.int8) + self.box_moving = d["box_moving"].astype(bool) + self.box_track_id = ( + d["box_track_id"].astype(np.int64) + if "box_track_id" in d.files + else np.full(self.box_frame.shape, -1, dtype=np.int64) + ) + self.box_extrapolated = np.zeros(self.box_frame.shape, dtype=bool) + self.num_frames = int(d["num_frames"]) + self.vehicle_to_world_f0 = d["vehicle_to_world_f0"].astype(np.float32) + + self.elev = np.asarray(elev, dtype=np.float64) + self.azim_native = np.asarray(azim_native, dtype=np.float64) + self.row_off = np.asarray(row_off, dtype=np.float64) + self.C_native = int(C_native) + self.R = int(self.elev.shape[0]) + self.box_edge_spacing = float(box_edge_spacing) + self.map_max_dist = None if map_max_dist is None else float(map_max_dist) + + def persist_static_box_tracks_across_timeline( + self, + track_ids: np.ndarray, + through_frame: Optional[int] = None, + ) -> dict[str, int | str]: + """Hold every non-moving track at its latest pose for all frames.""" + track_ids = np.asarray(track_ids, dtype=np.int64) + if track_ids.shape != self.box_frame.shape: + raise ValueError( + "track_ids must align with box rows, got " + f"{track_ids.shape} and {self.box_frame.shape}" + ) + if np.any(track_ids < 0): + raise ValueError("static box persistence requires valid track IDs") + target_frame = ( + self.num_frames - 1 + if through_frame is None + else int(through_frame) + ) + if not 0 <= target_frame < self.num_frames: + raise ValueError( + f"through_frame must lie in [0,{self.num_frames - 1}], " + f"got {target_frame}" + ) + + keep = np.ones(self.box_frame.shape[0], dtype=bool) + persistent_frame = [] + persistent_o2w = [] + persistent_lwh = [] + persistent_type = [] + persistent_moving = [] + persistent_track_id = [] + persistent_extrapolated = [] + static_tracks = 0 + original_static_rows = 0 + filled_rows = 0 + for track_id in np.unique(track_ids): + rows = np.nonzero(track_ids == int(track_id))[0] + if self.box_moving[rows].any(): + continue + static_tracks += 1 + original_static_rows += int(rows.shape[0]) + keep[rows] = False + order = np.argsort(self.box_frame[rows], kind="stable") + canonical_row = int(rows[order[-1]]) + annotated_frames = set( + int(frame) for frame in self.box_frame[rows].tolist() + ) + for frame_idx in range(target_frame + 1): + persistent_frame.append(frame_idx) + persistent_o2w.append(self.box_o2w[canonical_row]) + persistent_lwh.append(self.box_lwh[canonical_row]) + persistent_type.append(self.box_type[canonical_row]) + persistent_moving.append(False) + persistent_track_id.append(int(track_id)) + extrapolated = frame_idx not in annotated_frames + persistent_extrapolated.append(extrapolated) + filled_rows += int(extrapolated) + + if persistent_frame: + self.box_frame = np.concatenate( + [ + self.box_frame[keep], + np.asarray(persistent_frame, dtype=np.int64), + ] + ) + self.box_o2w = np.concatenate( + [ + self.box_o2w[keep], + np.stack(persistent_o2w).astype(np.float32), + ], + axis=0, + ) + self.box_lwh = np.concatenate( + [ + self.box_lwh[keep], + np.stack(persistent_lwh).astype(np.float32), + ], + axis=0, + ) + self.box_type = np.concatenate( + [ + self.box_type[keep], + np.asarray(persistent_type, dtype=self.box_type.dtype), + ] + ) + self.box_moving = np.concatenate( + [ + self.box_moving[keep], + np.asarray(persistent_moving, dtype=bool), + ] + ) + self.box_track_id = np.concatenate( + [ + track_ids[keep], + np.asarray(persistent_track_id, dtype=np.int64), + ] + ) + self.box_extrapolated = np.concatenate( + [ + self.box_extrapolated[keep], + np.asarray(persistent_extrapolated, dtype=bool), + ] + ) + order = np.lexsort((self.box_track_id, self.box_frame)) + self.box_frame = self.box_frame[order] + self.box_o2w = self.box_o2w[order] + self.box_lwh = self.box_lwh[order] + self.box_type = self.box_type[order] + self.box_moving = self.box_moving[order] + self.box_track_id = self.box_track_id[order] + self.box_extrapolated = self.box_extrapolated[order] + else: + self.box_track_id = track_ids.copy() + + return { + "policy": "static_latest_pose_hold_full_timeline", + "through_frame": target_frame, + "static_tracks": static_tracks, + "original_static_rows": original_static_rows, + "persistent_static_rows": len(persistent_frame), + "filled_static_rows": filled_rows, + } + + def extrapolate_box_tracks_forward( + self, + track_ids: np.ndarray, + through_frame: Optional[int] = None, + ) -> dict[str, int | str]: + """Extend every box track after its final annotated frame.""" + track_ids = np.asarray(track_ids, dtype=np.int64) + if track_ids.shape != self.box_frame.shape: + raise ValueError( + "track_ids must align with box rows, got " + f"{track_ids.shape} and {self.box_frame.shape}" + ) + if np.any(track_ids < 0): + raise ValueError("box extrapolation requires valid track IDs") + target_frame = ( + self.num_frames - 1 + if through_frame is None + else int(through_frame) + ) + if not 0 <= target_frame < self.num_frames: + raise ValueError( + f"through_frame must lie in [0,{self.num_frames - 1}], " + f"got {target_frame}" + ) + + new_frame = [] + new_o2w = [] + new_lwh = [] + new_type = [] + new_moving = [] + new_track_id = [] + linear_tracks = 0 + held_tracks = 0 + single_observation_tracks = 0 + for track_id in np.unique(track_ids): + rows = np.nonzero(track_ids == int(track_id))[0] + order = np.argsort(self.box_frame[rows], kind="stable") + rows = rows[order] + last_row = int(rows[-1]) + last_frame = int(self.box_frame[last_row]) + if last_frame >= target_frame: + continue + + last_pose = self.box_o2w[last_row].astype(np.float64) + track_moving = bool(self.box_moving[rows].any()) + if rows.shape[0] >= 2 and track_moving: + previous_row = int(rows[-2]) + previous_frame = int(self.box_frame[previous_row]) + frame_delta = last_frame - previous_frame + if frame_delta <= 0: + raise ValueError( + f"track {track_id} has non-increasing box frames" + ) + translation_per_frame = ( + last_pose[:3, 3] + - self.box_o2w[previous_row, :3, 3].astype(np.float64) + ) / frame_delta + previous_rotation = self.box_o2w[ + previous_row, :3, :3 + ].astype(np.float64) + relative_rotation = last_pose[:3, :3] @ previous_rotation.T + yaw_per_frame = np.arctan2( + relative_rotation[1, 0], relative_rotation[0, 0] + ) / frame_delta + linear_tracks += 1 + else: + translation_per_frame = np.zeros(3, dtype=np.float64) + yaw_per_frame = 0.0 + held_tracks += 1 + single_observation_tracks += int(rows.shape[0] == 1) + + for frame_idx in range(last_frame + 1, target_frame + 1): + elapsed = frame_idx - last_frame + yaw = elapsed * yaw_per_frame + c, s = np.cos(yaw), np.sin(yaw) + yaw_rotation = np.asarray( + [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]], + dtype=np.float64, + ) + pose = last_pose.copy() + pose[:3, :3] = yaw_rotation @ last_pose[:3, :3] + pose[:3, 3] = ( + last_pose[:3, 3] + elapsed * translation_per_frame + ) + new_frame.append(frame_idx) + new_o2w.append(pose.astype(np.float32)) + new_lwh.append(self.box_lwh[last_row]) + new_type.append(self.box_type[last_row]) + new_moving.append(track_moving) + new_track_id.append(int(track_id)) + + original_rows = int(self.box_frame.shape[0]) + if new_frame: + self.box_frame = np.concatenate( + [self.box_frame, np.asarray(new_frame, dtype=np.int64)] + ) + self.box_o2w = np.concatenate( + [self.box_o2w, np.stack(new_o2w).astype(np.float32)], axis=0 + ) + self.box_lwh = np.concatenate( + [self.box_lwh, np.stack(new_lwh).astype(np.float32)], axis=0 + ) + self.box_type = np.concatenate( + [self.box_type, np.asarray(new_type, dtype=self.box_type.dtype)] + ) + self.box_moving = np.concatenate( + [self.box_moving, np.asarray(new_moving, dtype=bool)] + ) + self.box_track_id = np.concatenate( + [track_ids, np.asarray(new_track_id, dtype=np.int64)] + ) + self.box_extrapolated = np.concatenate( + [ + self.box_extrapolated, + np.ones(len(new_frame), dtype=bool), + ] + ) + order = np.lexsort((self.box_track_id, self.box_frame)) + self.box_frame = self.box_frame[order] + self.box_o2w = self.box_o2w[order] + self.box_lwh = self.box_lwh[order] + self.box_type = self.box_type[order] + self.box_moving = self.box_moving[order] + self.box_track_id = self.box_track_id[order] + self.box_extrapolated = self.box_extrapolated[order] + else: + self.box_track_id = track_ids.copy() + + return { + "policy": "moving_last_two_pose_linear_yaw_static_hold", + "through_frame": target_frame, + "original_box_rows": original_rows, + "extrapolated_box_rows": len(new_frame), + "extrapolated_tracks": linear_tracks + held_tracks, + "linear_velocity_tracks": linear_tracks, + "constant_pose_tracks": held_tracks, + "single_observation_tracks": single_observation_tracks, + } + + def _box_world_points( + self, frame_idx: int, moving_only: bool, box_type: Optional[int] = None + ) -> np.ndarray: + sel = self.box_frame == int(frame_idx) + if moving_only: + sel = sel & self.box_moving + if box_type is not None: + sel = sel & (self.box_type == int(box_type)) + idx = np.nonzero(sel)[0] + if idx.shape[0] == 0: + return np.zeros((0, 3), np.float32) + return np.concatenate( + [ + sample_box_edges(self.box_o2w[k], self.box_lwh[k], self.box_edge_spacing) + for k in idx + ], + axis=0, + ) + + def _project( + self, + pts: np.ndarray, + lidar_to_world: np.ndarray, + out_width: int, + min_range: float, + max_range: float, + max_horizontal: Optional[float] = None, + ): + return project_world_points( + pts, + lidar_to_world, + self.elev, + self.azim_native, + self.row_off, + self.C_native, + out_width, + min_range, + max_range, + max_horizontal=max_horizontal, + ) + + def rasterize( + self, + frame_idx: int, + lidar_to_world: np.ndarray, + out_width: int, + min_range: float, + max_range: float, + include_boxes: bool = True, + moving_only: bool = False, + return_parts: bool = False, + ): + """Compose the hdmap range image for ``frame_idx``. + + Returns ``(R, out_width)`` float32 (metres; 0 == empty). If + ``return_parts`` also returns a dict with separate ``map`` / ``boxes`` + range images (for visualization).""" + + def _proj(pts, max_horizontal=None): + return self._project( + pts, lidar_to_world, out_width, min_range, max_range, max_horizontal + ) + + mr, mc, md = _proj(self.map_points, max_horizontal=self.map_max_dist) + rows, cols, rng = [mr], [mc], [md] + parts = {} + if return_parts: + parts["map"] = scatter_min_range(self.R, out_width, mr, mc, md) + if include_boxes: + bpts = self._box_world_points(frame_idx, moving_only) + br, bc, bd = _proj(bpts) + rows.append(br) + cols.append(bc) + rng.append(bd) + if return_parts: + parts["boxes"] = scatter_min_range(self.R, out_width, br, bc, bd) + full = scatter_min_range( + self.R, + out_width, + np.concatenate(rows), + np.concatenate(cols), + np.concatenate(rng), + ) + if return_parts: + return full, parts + return full + + def _to_sensor( + self, + pts_world: np.ndarray, + Rm: np.ndarray, + t: np.ndarray, + min_range: float, + max_range: float, + max_horizontal: Optional[float] = None, + ) -> np.ndarray: + """World points -> top-sensor frame (P, 3), range/BEV-cropped (no projection).""" + if pts_world.shape[0] == 0: + return np.zeros((0, 3), np.float32) + ps = (pts_world.astype(np.float64) - t[None, :]) @ Rm # == R^T (p - t) + r = np.linalg.norm(ps, axis=1) + keep = (r >= min_range) & (r <= max_range) + if max_horizontal is not None: + keep = keep & (np.hypot(ps[:, 0], ps[:, 1]) <= max_horizontal) + return ps[keep].astype(np.float32) + + def sensor_points( + self, + frame_idx: int, + lidar_to_world: np.ndarray, + min_range: float, + max_range: float, + include_boxes: bool = True, + moving_only: bool = False, + ) -> np.ndarray: + """HDMap points in the TOP-SENSOR frame ``(P, 3)`` metres. + + Same world-point set :meth:`rasterize` composes (static map polylines + + dynamic box wireframes), transformed ``p_s = R^T (p_w - t)`` and + range/BEV-cropped exactly like the rasterizer -- but WITHOUT the range- + image projection, so the metric points can be fed straight to a BEV + voxelizer (e.g. TransformerVAEDecompBEV's ``extra_points`` path) instead + of being rasterized -> unprojected (which puts ground-plane map elements + on grazing rays). Static map points are BEV-cropped by ``map_max_dist``; + box points use the full range (mirrors :meth:`rasterize`).""" + Rm = lidar_to_world[:3, :3].astype(np.float64) + t = lidar_to_world[:3, 3].astype(np.float64) + parts = [ + self._to_sensor( + self.map_points, Rm, t, min_range, max_range, self.map_max_dist + ) + ] + if include_boxes: + bpts = self._box_world_points(frame_idx, moving_only) + parts.append(self._to_sensor(bpts, Rm, t, min_range, max_range, None)) + return np.concatenate(parts, axis=0) + + def _box_indices( + self, frame_idx: int, moving_only: bool, box_type: Optional[int] = None + ) -> np.ndarray: + sel = self.box_frame == int(frame_idx) + if moving_only: + sel = sel & self.box_moving + if box_type is not None: + sel = sel & (self.box_type == int(box_type)) + return np.nonzero(sel)[0] + + @staticmethod + def _fill_quad_bev( + out_ch: np.ndarray, poly: np.ndarray, grid: Tuple[float, float, float, float, int, int] + ) -> None: + """Fill a convex quad (4, 2) into ``out_ch`` (Y, X). ``grid`` = + (x_min, y_min, vx, vy, Y, X). Cell centre inside-test over the quad's + bbox (CCW half-plane intersection) -> solid/closed box footprint.""" + x_min, y_min, vx, vy, Y, X = grid + ixs = np.floor((poly[:, 0] - x_min) / vx) + iys = np.floor((poly[:, 1] - y_min) / vy) + ix0, ix1 = max(int(ixs.min()), 0), min(int(ixs.max()) + 1, X) + iy0, iy1 = max(int(iys.min()), 0), min(int(iys.max()) + 1, Y) + if ix1 <= ix0 or iy1 <= iy0: + return + xs = x_min + (np.arange(ix0, ix1) + 0.5) * vx + ys = y_min + (np.arange(iy0, iy1) + 0.5) * vy + gx, gy = np.meshgrid(xs, ys) # (h, w) + # Orient CCW (positive signed area) so the half-plane test is consistent. + area = 0.0 + n = poly.shape[0] + for i in range(n): + x1, y1 = poly[i] + x2, y2 = poly[(i + 1) % n] + area += x1 * y2 - x2 * y1 + pp = poly if area > 0 else poly[::-1] + inside = np.ones(gx.shape, dtype=bool) + for i in range(n): + x1, y1 = pp[i] + x2, y2 = pp[(i + 1) % n] + inside &= ((x2 - x1) * (gy - y1) - (y2 - y1) * (gx - x1)) >= 0 + out_ch[iy0:iy1, ix0:ix1][inside] = 1.0 + + def rasterize_bev( + self, + frame_idx: int, + lidar_to_world: np.ndarray, + bev_size: Tuple[int, int], + pc_range: Tuple[float, float, float, float, float, float], + include_boxes: bool = True, + moving_only: bool = False, + ) -> np.ndarray: + """Multi-channel BEV occupancy raster in the TOP-SENSOR frame. + + Returns ``(NUM_CLASSES, Y, X)`` float32 in {0, 1}, one channel per + semantic class (:data:`CLASS_NAMES`: lane, road_line, road_edge, + crosswalk, vehicle, pedestrian, cyclist). Static map classes splat their + pre-sampled polyline points into BEV cells; dynamic box classes fill the + CLOSED (solid) rotated BEV footprint of each box. Uses the SAME + ``x,y -> cell`` mapping as ``PillarVoxelizer`` (row = iy over y, col = ix + over x) so the raster is spatially aligned with the VAE's BEV latent + grid. ``bev_size`` = (Y, X); ``pc_range`` = (x_min, x_max, y_min, y_max, + z_min, z_max) (z unused here -- pure top-down).""" + Y, X = int(bev_size[0]), int(bev_size[1]) + x_min, x_max, y_min, y_max = (float(v) for v in pc_range[:4]) + vx = (x_max - x_min) / X + vy = (y_max - y_min) / Y + out = np.zeros((NUM_CLASSES, Y, X), dtype=np.float32) + Rm = lidar_to_world[:3, :3].astype(np.float64) + t = lidar_to_world[:3, 3].astype(np.float64) + + # Static map: splat sampled polyline points, one channel per map_type. + for ci in range(len(MAP_CLASS_NAMES)): + pw = self.map_points[self.map_type == ci] + if pw.shape[0] == 0: + continue + ps = (pw.astype(np.float64) - t[None, :]) @ Rm # (P, 3) sensor + ix = np.floor((ps[:, 0] - x_min) / vx).astype(np.int64) + iy = np.floor((ps[:, 1] - y_min) / vy).astype(np.int64) + keep = (ix >= 0) & (ix < X) & (iy >= 0) & (iy < Y) + out[ci, iy[keep], ix[keep]] = 1.0 + + # Dynamic boxes: fill the solid rotated footprint, one channel per box_type. + if include_boxes: + grid = (x_min, y_min, vx, vy, Y, X) + xy_signs = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]], dtype=np.float64) + for bi in range(len(BOX_CLASS_NAMES)): + ch = len(MAP_CLASS_NAMES) + bi + for k in self._box_indices(frame_idx, moving_only, box_type=bi): + o2w = self.box_o2w[k].astype(np.float64) + half = 0.5 * self.box_lwh[k].astype(np.float64) + corners_obj = np.concatenate( + [xy_signs * half[:2], np.zeros((4, 1))], axis=1 + ) # (4, 3) object frame, z=0 (footprint) + corners_w = corners_obj @ o2w[:3, :3].T + o2w[:3, 3] + poly = ((corners_w - t[None, :]) @ Rm)[:, :2] # (4, 2) sensor xy + self._fill_quad_bev(out[ch], poly, grid) + + return out + + def rasterize_multichannel( + self, + frame_idx: int, + lidar_to_world: np.ndarray, + out_width: int, + min_range: float, + max_range: float, + moving_only: bool = False, + ) -> np.ndarray: + """One metric-range channel per semantic class -> ``(NUM_CLASSES, R, out_width)``. + + Channel order is :data:`CLASS_NAMES` (lane, road_line, road_edge, + crosswalk, vehicle, pedestrian, cyclist). Each channel holds the nearest + return's range in metres (0 == empty). Static-map channels are BEV-cropped + by ``self.map_max_dist``; box channels use the full range.""" + out = np.zeros((NUM_CLASSES, self.R, out_width), dtype=np.float32) + + # Static map: one channel per map_type (0..3). + for ci in range(len(MAP_CLASS_NAMES)): + pts = self.map_points[self.map_type == ci] + r, c, d = self._project( + pts, lidar_to_world, out_width, min_range, max_range, self.map_max_dist + ) + out[ci] = scatter_min_range(self.R, out_width, r, c, d) + + # Dynamic boxes: one channel per box_type (0..2), offset by the map channels. + for bi in range(len(BOX_CLASS_NAMES)): + pts = self._box_world_points(frame_idx, moving_only, box_type=bi) + r, c, d = self._project(pts, lidar_to_world, out_width, min_range, max_range) + out[len(MAP_CLASS_NAMES) + bi] = scatter_min_range(self.R, out_width, r, c, d) + + return out + + +class TorchWaymoHDMapRasterizer: + """GPU-resident single-channel counterpart to :meth:`rasterize`. + + Static map points, beam lookup tables, and all selected per-frame box + wireframes are uploaded once in FP64 to preserve the CPU composer's pixel + assignment. Calls accept CUDA poses and return FP32 CUDA metric range + images without a per-block host/device transfer. + """ + + def __init__( + self, + composer: WaymoHDMapComposer, + device: torch.device, + include_boxes: bool = True, + moving_only: bool = False, + ): + self.device = torch.device(device) + self.compute_dtype = torch.float64 + self.height = composer.R + self.native_width = composer.C_native + self.map_max_dist = composer.map_max_dist + self.static_points = torch.as_tensor( + composer.map_points, + dtype=self.compute_dtype, + device=self.device, + ) + + elev = torch.as_tensor( + composer.elev, + dtype=self.compute_dtype, + device=self.device, + ) + self.elev_order = torch.argsort(elev, stable=True) + self.elev_sorted = elev[self.elev_order] + azim = self._wrap_angle( + torch.as_tensor( + composer.azim_native, + dtype=self.compute_dtype, + device=self.device, + ) + ) + self.azim_order = torch.argsort(azim, stable=True) + self.azim_sorted = azim[self.azim_order] + self.row_off = torch.as_tensor( + composer.row_off, + dtype=self.compute_dtype, + device=self.device, + ) + + box_parts = [] + box_frame_offsets = [0] + for frame_idx in range(composer.num_frames): + points = ( + composer._box_world_points(frame_idx, moving_only) + if include_boxes + else np.zeros((0, 3), dtype=np.float64) + ) + box_parts.append(points.astype(np.float64, copy=False)) + box_frame_offsets.append( + box_frame_offsets[-1] + int(points.shape[0]) + ) + box_points = ( + np.concatenate(box_parts, axis=0) + if box_frame_offsets[-1] > 0 + else np.zeros((0, 3), dtype=np.float64) + ) + self.box_points = torch.as_tensor( + box_points, + dtype=self.compute_dtype, + device=self.device, + ) + self.box_frame_offsets = tuple(box_frame_offsets) + + @staticmethod + def _wrap_angle(angle: torch.Tensor) -> torch.Tensor: + return torch.remainder(angle + np.pi, 2.0 * np.pi) - np.pi + + @property + def resident_bytes(self) -> int: + tensors = ( + self.static_points, + self.box_points, + self.elev_order, + self.elev_sorted, + self.azim_order, + self.azim_sorted, + self.row_off, + ) + return sum(t.numel() * t.element_size() for t in tensors) + + def _project_points( + self, + points_world: torch.Tensor, + pose: torch.Tensor, + out_width: int, + min_range: float, + max_range: float, + max_horizontal: Optional[float], + ) -> Tuple[torch.Tensor, torch.Tensor]: + if points_world.shape[0] == 0: + empty_indices = torch.empty( + (0,), dtype=torch.int64, device=self.device + ) + return empty_indices, points_world.new_empty((0,)) + + points_sensor = ( + points_world - pose[:3, 3].unsqueeze(0) + ) @ pose[:3, :3] + ranges = torch.linalg.vector_norm(points_sensor, dim=1) + keep = (ranges >= min_range) & (ranges <= max_range) + if max_horizontal is not None: + keep &= ( + points_sensor[:, :2].square().sum(dim=1) + <= max_horizontal * max_horizontal + ) + points_sensor = points_sensor[keep] + ranges = ranges[keep] + if points_sensor.shape[0] == 0: + empty_indices = torch.empty( + (0,), dtype=torch.int64, device=self.device + ) + return empty_indices, ranges + + point_elev = torch.asin( + (points_sensor[:, 2] / ranges).clamp(-1.0, 1.0) + ) + elev_idx = torch.searchsorted(self.elev_sorted, point_elev) + elev_idx0 = (elev_idx - 1).clamp(0, self.height - 1) + elev_idx1 = elev_idx.clamp(0, self.height - 1) + elev_dist0 = (point_elev - self.elev_sorted[elev_idx0]).abs() + elev_dist1 = (point_elev - self.elev_sorted[elev_idx1]).abs() + choose0 = (elev_dist0 < elev_dist1) | ( + (elev_dist0 == elev_dist1) + & (self.elev_order[elev_idx0] <= self.elev_order[elev_idx1]) + ) + rows = self.elev_order[ + torch.where(choose0, elev_idx0, elev_idx1) + ] + + point_azim = self._wrap_angle( + torch.atan2(points_sensor[:, 1], points_sensor[:, 0]) + - self.row_off[rows] + ) + azim_idx = torch.searchsorted(self.azim_sorted, point_azim) + azim_idx0 = torch.remainder(azim_idx - 1, self.native_width) + azim_idx1 = torch.remainder(azim_idx, self.native_width) + azim_dist0 = self._wrap_angle( + point_azim - self.azim_sorted[azim_idx0] + ).abs() + azim_dist1 = self._wrap_angle( + point_azim - self.azim_sorted[azim_idx1] + ).abs() + nearest_azim = torch.where( + azim_dist0 <= azim_dist1, azim_idx0, azim_idx1 + ) + native_cols = self.azim_order[nearest_azim] + cols = torch.clamp( + torch.div( + native_cols * out_width, + self.native_width, + rounding_mode="floor", + ), + max=out_width - 1, + ) + return rows * out_width + cols, ranges + + @torch.inference_mode() + def rasterize( + self, + frame_indices: Sequence[int], + lidar_to_world: torch.Tensor, + out_width: int, + min_range: float, + max_range: float, + ) -> torch.Tensor: + poses = lidar_to_world.to( + device=self.device, + dtype=self.compute_dtype, + ) + if poses.ndim != 3 or poses.shape[1:] != (4, 4): + raise ValueError( + "lidar_to_world must have shape [T,4,4], got " + f"{tuple(poses.shape)}" + ) + if len(frame_indices) != poses.shape[0]: + raise ValueError( + "frame_indices must align with lidar poses: " + f"{len(frame_indices)} vs {poses.shape[0]}" + ) + + rasters = [] + for frame_idx, pose in zip(frame_indices, poses): + frame_idx = int(frame_idx) + if not 0 <= frame_idx < len(self.box_frame_offsets) - 1: + raise IndexError(f"HDMap frame index out of range: {frame_idx}") + metric = torch.full( + (self.height * out_width,), + torch.inf, + dtype=self.compute_dtype, + device=self.device, + ) + flat_indices, ranges = self._project_points( + self.static_points, + pose, + out_width, + min_range, + max_range, + self.map_max_dist, + ) + metric.scatter_reduce_( + 0, flat_indices, ranges, reduce="amin", include_self=True + ) + box_start = self.box_frame_offsets[frame_idx] + box_end = self.box_frame_offsets[frame_idx + 1] + flat_indices, ranges = self._project_points( + self.box_points[box_start:box_end], + pose, + out_width, + min_range, + max_range, + None, + ) + metric.scatter_reduce_( + 0, flat_indices, ranges, reduce="amin", include_self=True + ) + metric.masked_fill_(~torch.isfinite(metric), 0.0) + rasters.append(metric.view(self.height, out_width)) + return torch.stack(rasters, dim=0).to(dtype=torch.float32) diff --git a/tokenizer/training/datasets/lidar_datasets/waymo_ncore.py b/tokenizer/training/datasets/lidar_datasets/waymo_ncore.py new file mode 100644 index 0000000000000000000000000000000000000000..20400de22fdfa4c9639cecd5874c8c314680b6f8 --- /dev/null +++ b/tokenizer/training/datasets/lidar_datasets/waymo_ncore.py @@ -0,0 +1,644 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""NCore-backed Waymo lidar reader (the RadymLidar analog for NCore V4 data). + +Waymo NCore stores lidar as a *structured sparse ray bundle* per frame, NOT a +dense range image and NOT a flat xyz cloud. Each ray carries: + + * ``model_element`` (N, 2) uint16 -> (row, col) index into the sensor grid + * ``direction`` (N, 3) float32 -> unit ray direction (sensor frame) + * per-return ``distance_m`` / ``intensity`` / ``valid_mask`` + +The sensor grid for the Waymo top lidar is 64 rows x ~2650 cols, defined by a +``RowOffsetStructuredSpinningLidarModel`` whose ``row_elevations_rad`` (64) and +``column_azimuths_rad`` (~2650) tables give the exact beam geometry (the stored +``direction`` equals the angle-table ray, verified cos == 1.0). + +This module scatters ``distance_m`` into ``model_element`` to losslessly build a +dense ``(R, C)`` range image (missing grid cells == no-return == range 0, i.e. +raydrop is implicit). That is exactly the ``(row, col, range)`` sparse-triplet +form the existing LidarGEN tar pipeline (``load_each_frame_from_tar_data``) +already consumes, so the rest of ``LidarRangeMapSampler`` works unchanged. + +All reads are strictly read-only; the dataset on disk is never modified. +""" + +import os +import threading +from typing import Any, List, Optional, Tuple + +import numpy as np +import torch +import torch.utils.data +from lru import LRU + +from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField + +try: + from ncore.data.v4 import SequenceComponentGroupsReader, SequenceLoaderV4 + from ncore.impl.data.types import FrameTimepoint + + _NCORE_AVAILABLE = True + _NCORE_IMPORT_ERROR: Optional[Exception] = None +except Exception as _e: # pragma: no cover - import guard for CPU-only envs + _NCORE_AVAILABLE = False + _NCORE_IMPORT_ERROR = _e + FrameTimepoint = None # type: ignore + + +# ----------------------------------------------------------------------------- # +# Geometry helpers (native Waymo grid; uses the model's actual angle tables) +# ----------------------------------------------------------------------------- # +def get_waymo_model_tables(model_parameters) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return (row_elevations_rad (R,), column_azimuths_rad (C,), + row_azimuth_offsets_rad (R,)) from a + ``RowOffsetStructuredSpinningLidarModelParameters``. + + The per-row azimuth offset is part of the geometry (this is a *row-offset* + spinning model, like the Hesai P128): the azimuth of cell (r, c) is + ``column_azimuths_rad[c] + row_azimuth_offsets_rad[r]`` -- see NCore's + ``LidarModel.elements_to_sensor_angles``.""" + elev = np.asarray(model_parameters.row_elevations_rad, dtype=np.float64) + azim = np.asarray(model_parameters.column_azimuths_rad, dtype=np.float64) + row_az_off = np.asarray(model_parameters.row_azimuth_offsets_rad, dtype=np.float64) + return elev, azim, row_az_off + + +def waymo_range_map_to_ray_directions( + row_elevations_rad: np.ndarray, + column_azimuths_rad: np.ndarray, + row_azimuth_offsets_rad: Optional[np.ndarray] = None, +) -> np.ndarray: + """Per-pixel unit ray directions for the native Waymo grid. + + Mirrors NCore's canonical (row,col)->direction EXACTLY (verified against + ``impl/sensors/lidar.py`` ``elements_to_sensor_angles`` + + ``sensor_angles_to_sensor_rays``): + + az(r,c) = column_azimuths_rad[c] + row_azimuth_offsets_rad[r] + el(r,c) = row_elevations_rad[r] + x = cos(az)cos(el), y = sin(az)cos(el), z = sin(el) + + The spinning direction (cw/ccw) is already baked into the stored azimuth + values, so there is NO extra sign flip. Unlike + ``utils.lidar_rangemap.range_map_to_ray_directions`` (uniform linspace + azimuth + degree elevations for Pandar128), this uses the sensor's measured + tables + per-row offset, so column ``c`` / row ``r`` map to exactly the + cells ``model_element`` scatters into. + + Returns (R, C, 3) float32 unit vectors in the lidar sensor frame. + """ + elev = np.asarray(row_elevations_rad, dtype=np.float64) # (R,) + azim = np.asarray(column_azimuths_rad, dtype=np.float64) # (C,) + if row_azimuth_offsets_rad is None: + row_off = np.zeros_like(elev) + else: + row_off = np.asarray(row_azimuth_offsets_rad, dtype=np.float64) # (R,) + # az(r,c) = column_azimuths[c] + row_offset[r]; el(r,c) = elev[r] + azim_grid = azim[None, :] + row_off[:, None] # (R, C) + elev_grid = np.broadcast_to(elev[:, None], azim_grid.shape) # (R, C) + x = np.cos(azim_grid) * np.cos(elev_grid) + y = np.sin(azim_grid) * np.cos(elev_grid) + z = np.sin(elev_grid) + return np.stack([x, y, z], axis=-1).astype(np.float32) # (R, C, 3) + + +def waymo_resampled_azimuth_table(column_azimuths_rad: np.ndarray, width: int) -> np.ndarray: + """Azimuth (rad) of each column on a ``width``-wide uniform-azimuth grid that + the native ``C``-column azimuths are rebinned onto. + + The reader maps a native column ``c`` to target bin ``t = (c * width) // C``. + The representative azimuth of bin ``t`` is the native azimuth at the bin + centre native column ``floor((t + 0.5) * C / width)``. Because the native + Waymo column azimuths are uniform (~0.1359 deg step), this is a uniform + azimuth table -- it matches LidarDM's 64x2048 Waymo range-image convention + (``WAYMO_RANGE_CONFIG``: width 2048 vs the 0.13585 deg / 2650-col raycast). + + Returns (width,) float64 azimuths in radians. + """ + azim = np.asarray(column_azimuths_rad, dtype=np.float64) # (C,) + C = azim.shape[0] + idx = np.minimum(((np.arange(width) + 0.5) * C / width).astype(np.int64), C - 1) + return azim[idx] + + +def load_waymo_lidar_geometry( + root_path: str, + filter_list_path: Optional[str] = None, + lidar_id: str = "lidar_top", + resample_width: int = -1, + itar_index_tail_read_size: int = 1 << 20, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Load fixed Waymo beam geometry as ``(dirs, elev, azim, row_offset)``. + + Opens the FIRST clip in the filter list ONCE to read the sensor's + ``row_elevations_rad`` / ``column_azimuths_rad`` / ``row_azimuth_offsets_rad`` + tables. All Waymo top-lidar clips share the same structured spinning model, so + a single representative read suffices -- this mirrors the existing single + fixed Pandar128 elevation table used for LidarGEN (the loss assumes one sensor + geometry across the dataset). When ``resample_width > 0`` the azimuth axis is + the uniform-azimuth rebin grid (``waymo_resampled_azimuth_table``) that the + reader scatters returns onto; otherwise the native column grid. + + When ``resample_width > 0``, ``azim`` and ``dirs`` describe the same rebinned + azimuth grid emitted by :class:`WaymoNCoreLidar`. The returned tables are also + sufficient for projecting arbitrary sensor/world points back to that grid. + Strictly read-only. + """ + if not _NCORE_AVAILABLE: + raise ImportError( + "load_waymo_lidar_geometry requires the `ncore` package (pip install " + f"nvidia-ncore). Import failed with: {_NCORE_IMPORT_ERROR}" + ) + stems: List[str] = [] + if filter_list_path is not None and os.path.isfile(filter_list_path): + with open(filter_list_path, "r") as f: + stems = [line.strip() for line in f.readlines() if line.strip()] + stems = [s.split(".ncore4")[0].split(".json")[0] for s in stems] + if not stems and os.path.isdir(root_path): + for name in sorted(os.listdir(root_path)): + d = os.path.join(root_path, name) + if os.path.isdir(d) and os.path.isfile( + os.path.join(d, f"{name}.ncore4-{lidar_id}.zarr.itar") + ): + stems.append(name) + break + if not stems: + raise RuntimeError( + f"load_waymo_lidar_geometry: no clips found (root={root_path}, " + f"filter_list_path={filter_list_path})." + ) + stem = stems[0] + clip_dir = os.path.join(root_path, stem) + paths = [ + os.path.join(clip_dir, f"{stem}.ncore4.zarr.itar"), + os.path.join(clip_dir, f"{stem}.ncore4-{lidar_id}.zarr.itar"), + ] + reader = SequenceComponentGroupsReader( + paths, itar_index_tail_read_size=itar_index_tail_read_size + ) + loader = SequenceLoaderV4( + reader, masks_component_group_name=None, cuboids_component_group_name=None + ) + lidar = loader.get_lidar_sensor(lidar_id) + elev, azim, row_off = get_waymo_model_tables(lidar.model_parameters) + if resample_width and int(resample_width) > 0: + azim = waymo_resampled_azimuth_table(azim, int(resample_width)) + dirs = waymo_range_map_to_ray_directions(elev, azim, row_off) # (R, W, 3) + del loader, reader + return dirs, elev, azim, row_off + + +def load_waymo_ray_directions( + root_path: str, + filter_list_path: Optional[str] = None, + lidar_id: str = "lidar_top", + resample_width: int = -1, + itar_index_tail_read_size: int = 1 << 20, +) -> np.ndarray: + """Per-pixel unit ray directions ``(R, W, 3)`` for the Waymo range image.""" + dirs, _, _, _ = load_waymo_lidar_geometry( + root_path=root_path, + filter_list_path=filter_list_path, + lidar_id=lidar_id, + resample_width=resample_width, + itar_index_tail_read_size=itar_index_tail_read_size, + ) + return dirs + + +# ----------------------------------------------------------------------------- # +# Reader +# ----------------------------------------------------------------------------- # +class WaymoNCoreLidar: + """RadymLidar-compatible reader backed by NCore V4 ``.zarr.itar`` stores. + + Mirrors the surface that ``LidarRangeMapSampler`` depends on: + * ``custom_fields`` attribute + * ``size_of_filter_set()`` + * ``_read_rgb_and_lidar(lidar_idx, lidar_frame_idx, data_fields)`` -> dict + + Args mirror ``RadymLidar`` (extra args are accepted/ignored so the sampler + can build either backend with the same call), plus a few NCore specifics. + """ + + MAX_LOADERS = 4 # per-worker cache of opened NCore sequences (.itar handles) + + def __init__( + self, + root_path: str, + filter_list_path: Optional[str] = None, + num_views: int = -1, + metadata_folder: Optional[str] = None, + custom_folders: Optional[List[str]] = None, + custom_fields: Optional[List[str]] = None, + view_indices: Optional[List[int]] = None, + load_intensity: bool = False, + # --- NCore specifics --- + lidar_id: str = "lidar_top", + return_index: int = 0, + load_cameras: bool = False, + itar_index_tail_read_size: int = 1 << 20, + resample_width: int = -1, + # --- hdmap (on-the-fly rasterized from dump_waymo_hdmap.py NPZs) --- + hdmap_root: Optional[str] = None, + min_range: float = 2.5, + max_range: float = 75.0, + hdmap_box_edge_spacing: float = 0.15, + hdmap_moving_only: bool = False, + hdmap_include_boxes: bool = True, + hdmap_map_max_dist: Optional[float] = None, + hdmap_multichannel: bool = False, + # --- BEV hdmap: multi-channel top-down occupancy raster (one channel per + # semantic class, solid box footprints) for BEV-latent conditioning --- + hdmap_bev: bool = False, + hdmap_bev_size: Tuple[int, int] = (256, 256), + hdmap_bev_pc_range: Tuple[float, float, float, float, float, float] = ( + -75.0, 75.0, -75.0, 75.0, -3.0, 5.0, + ), + ): + if not _NCORE_AVAILABLE: + raise ImportError( + "WaymoNCoreLidar requires the `ncore` package (pip install " + f"nvidia-ncore). Import failed with: {_NCORE_IMPORT_ERROR}" + ) + + self.root_path = root_path + self.num_views = num_views + self.n_views = num_views + self.view_indices = view_indices + self.custom_folders = custom_folders + self.custom_fields = custom_fields if custom_fields is not None else ["lidar"] + self.metadata_folder = metadata_folder + self.load_intensity = load_intensity + + self.lidar_id = lidar_id + self.return_index = return_index + self.load_cameras = load_cameras + self.itar_index_tail_read_size = itar_index_tail_read_size + # >0 -> rebin the native column/azimuth axis onto a uniform grid of this + # width (e.g. 2048, LidarDM's Waymo range-image convention). The native + # 2650-col raycast grid is finer than the ~2200 samples/beam, so it has + # structural gaps; pooling onto 2048 densifies while keeping real + # raydrop. <=0 -> keep the native grid. Rows (beams) are never resampled. + self.resample_width = int(resample_width) + + # HDMap: no native NCore component; rasterized on the fly from the + # per-clip NPZ written by scripts/data/dump_waymo_hdmap.py. + self.hdmap_root = hdmap_root + self.min_range = float(min_range) + self.max_range = float(max_range) + self.hdmap_box_edge_spacing = float(hdmap_box_edge_spacing) + self.hdmap_moving_only = bool(hdmap_moving_only) + self.hdmap_include_boxes = bool(hdmap_include_boxes) + # One range-image channel per semantic class (lane/road_line/road_edge/ + # crosswalk/vehicle/pedestrian/cyclist) -> hdmap is (N, NUM_CLASSES, R, W). + # False -> single composited depth channel -> (N, R, W). + self.hdmap_multichannel = bool(hdmap_multichannel) + # BEV hdmap raster (top-down, one channel per semantic class). + self.hdmap_bev = bool(hdmap_bev) + self.hdmap_bev_size = tuple(hdmap_bev_size) + self.hdmap_bev_pc_range = tuple(hdmap_bev_pc_range) + # BEV (xy) crop radius for the static lane graph; None -> use max_range. + self.hdmap_map_max_dist = ( + self.max_range if hdmap_map_max_dist is None else float(hdmap_map_max_dist) + ) + self.composers: dict[str, Any] = {} + if "hdmap" in self.custom_fields and not self.hdmap_root: + raise NotImplementedError( + "Waymo NCore has no native hdmap component. Set hdmap_root= to rasterize one on the fly, or remove " + "'hdmap' from custom_fields." + ) + + # Build the clip list (stems). Each clip is a subdir // that + # holds .ncore4*.zarr.itar + .json. + self.filter_set: List[str] = self._build_filter_set(filter_list_path) + if len(self.filter_set) == 0: + raise RuntimeError( + f"No Waymo NCore clips found (root={root_path}, " + f"filter_list_path={filter_list_path})." + ) + + # Per-worker handle cache. Opened lazily inside the worker process; the + # callback closes evicted sequence readers' underlying .itar stores. + self.worker_id: Optional[int] = None + self._lock = threading.Lock() + self.loaders = LRU(self.MAX_LOADERS, callback=self._evict_loader) + + # --------------------------------------------------------------------- # + @staticmethod + def _evict_loader(_key, value): + # IndexedTarStore file objects are closed when the reader is GC'd; we + # just drop the references here so the LRU can reclaim them. + loader, reader = value + del loader, reader + + def _build_filter_set(self, filter_list_path: Optional[str]) -> List[str]: + if filter_list_path is not None and os.path.isfile(filter_list_path): + with open(filter_list_path, "r") as f: + stems = [line.strip() for line in f.readlines() if line.strip()] + # tolerate ".json"/extension suffixes in the list + stems = [s.split(".ncore4")[0].split(".json")[0] for s in stems] + return stems + # Fallback: scan root for clip subdirs containing the lidar itar. + stems = [] + if os.path.isdir(self.root_path): + for name in sorted(os.listdir(self.root_path)): + d = os.path.join(self.root_path, name) + if os.path.isdir(d) and os.path.isfile( + os.path.join(d, f"{name}.ncore4-{self.lidar_id}.zarr.itar") + ): + stems.append(name) + return stems + + def _check_worker_id(self): + info = torch.utils.data.get_worker_info() + if info is not None: + if self.worker_id is not None: + assert self.worker_id == info.id, "Worker id mismatch" + else: + self.worker_id = info.id + + def _clip_component_paths(self, stem: str) -> List[str]: + clip_dir = os.path.join(self.root_path, stem) + paths = [ + os.path.join(clip_dir, f"{stem}.ncore4.zarr.itar"), + os.path.join(clip_dir, f"{stem}.ncore4-{self.lidar_id}.zarr.itar"), + ] + if self.load_cameras: + view_indices = ( + self.view_indices + if self.view_indices is not None + else range(max(self.num_views, 0)) + ) + for v in view_indices: + cam_name = WAYMO_VIEW_IDX_TO_CAMERA[v] + paths.append( + os.path.join(clip_dir, f"{stem}.ncore4-{cam_name}.zarr.itar") + ) + return paths + + def _get_loader(self, stem: str): + """Open (and cache) the NCore sequence loader for a clip.""" + self._check_worker_id() + if stem in self.loaders: + return self.loaders[stem][0] + paths = self._clip_component_paths(stem) + reader = SequenceComponentGroupsReader( + paths, itar_index_tail_read_size=self.itar_index_tail_read_size + ) + loader = SequenceLoaderV4( + reader, + masks_component_group_name=None, + cuboids_component_group_name=None, + ) + self.loaders[stem] = (loader, reader) + return loader + + def _get_composer(self, stem: str, lidar): + """Open (and cache) the per-clip HDMap composer.""" + if stem in self.composers: + return self.composers[stem] + from tokenizer.training.datasets.lidar_datasets.waymo_hdmap import ( + WaymoHDMapComposer, + ) + + npz_path = os.path.join(self.hdmap_root, f"{stem}.npz") + if not os.path.isfile(npz_path): + raise FileNotFoundError( + f"HDMap NPZ not found: {npz_path} (run scripts/data/dump_waymo_hdmap.py " + f"--clip {stem} --out_root {self.hdmap_root})." + ) + elev, azim, row_off = get_waymo_model_tables(lidar.model_parameters) + comp = WaymoHDMapComposer( + npz_path, + elev, + azim, + row_off, + int(lidar.model_parameters.n_columns), + box_edge_spacing=self.hdmap_box_edge_spacing, + map_max_dist=self.hdmap_map_max_dist, + ) + # Cap the cache so a full-dataset scan doesn't grow it unbounded. + if len(self.composers) >= self.MAX_LOADERS: + self.composers.pop(next(iter(self.composers))) + self.composers[stem] = comp + return comp + + # --------------------------------------------------------------------- # + def size_of_filter_set(self) -> int: + return len(self.filter_set) + + @staticmethod + def _clamp_frame_indices(frame_idx: np.ndarray, frames_count: int) -> np.ndarray: + """Replace out-of-range indices with random valid ones (mirrors + RadymLidar.parse_range_map_tar).""" + frame_idx = np.asarray(frame_idx).astype(np.int64).copy() + oob = frame_idx > frames_count - 1 + if oob.any(): + frame_idx[oob] = np.random.randint(0, frames_count - 1, size=int(oob.sum())) + return frame_idx + + def _scatter_frame( + self, lidar, fi: int, R: int, C: int + ) -> Tuple[np.ndarray, Optional[np.ndarray]]: + """Build a dense (R, outW) range map (and optional intensity) for frame + fi. ``outW = resample_width`` if >0 (uniform-azimuth rebin), else ``C``. + On a collision (multiple native columns -> one target bin) the NEAREST + return wins (smallest range = closest surface).""" + elem = lidar.get_frame_ray_bundle_model_element(fi) # (N, 2) row,col + if elem is None: + raise RuntimeError( + f"Lidar frame {fi} has no model_element (cannot rasterize)." + ) + dist = lidar.get_frame_ray_bundle_return_distance_m(fi, return_index=self.return_index) + valid = lidar.get_frame_ray_bundle_return_valid_mask(fi, return_index=self.return_index) + mask = valid & np.isfinite(dist) & (dist > 0) + rows = elem[mask, 0].astype(np.int64) + cols = elem[mask, 1].astype(np.int64) + d = dist[mask].astype(np.float32) + inten = None + if self.load_intensity: + inten = lidar.get_frame_ray_bundle_return_intensity( + fi, return_index=self.return_index + )[mask].astype(np.float32) + + if self.resample_width > 0: + outW = self.resample_width + cols = np.minimum((cols * outW) // C, outW - 1) + # nearest-range wins on collision: sort descending so the smallest + # range is written LAST (overwrites). Native grid has no collisions + # (each ray is a unique cell), so this is a no-op there. + order = np.argsort(-d, kind="stable") + rows, cols, d = rows[order], cols[order], d[order] + if inten is not None: + inten = inten[order] + else: + outW = C + + range_map = np.zeros((R, outW), dtype=np.float32) + range_map[rows, cols] = d + + intensity_map = None + if inten is not None: + intensity_map = np.zeros((R, outW), dtype=np.float32) + intensity_map[rows, cols] = inten + return range_map, intensity_map + + def _poses_for_frames(self, loader, lidar, frame_idx: np.ndarray): + """Return (lidar_to_world (N,4,4), sensor_pose_start_end (N,4,4), + timestamp_list (N,)).""" + fts = lidar.frames_timestamps_us # (F, 2) uint64 [START, END] + t_start = fts[frame_idx, FrameTimepoint.START.value].astype(np.uint64) + t_end = fts[frame_idx, FrameTimepoint.END.value].astype(np.uint64) + pg = loader.pose_graph + l2w_start = pg.evaluate_poses(self.lidar_id, "world", t_start).astype(np.float32) + l2w_end = pg.evaluate_poses(self.lidar_id, "world", t_end).astype(np.float32) + # Mirror LidarGEN: relative within-sweep motion = inv(end) @ start. + sensor_pose_start_end = (np.linalg.inv(l2w_end) @ l2w_start).astype(np.float32) + return l2w_start, sensor_pose_start_end, t_end.astype(np.int64) + + def _read_rgb_and_lidar(self, lidar_idx, lidar_frame_idx, data_fields): + """Mirror RadymLidar._read_rgb_and_lidar, NCore-backed.""" + stem = self.filter_set[lidar_idx] + loader = self._get_loader(stem) + lidar = loader.get_lidar_sensor(self.lidar_id) + frames_count = lidar.frames_count + frame_idx = self._clamp_frame_indices(lidar_frame_idx, frames_count) + + mp = lidar.model_parameters + R, C = int(mp.n_rows), int(mp.n_columns) + + output_dict: dict[str | DataField, Any] = {"__key__": stem} + + l2w_start, sensor_pose_start_end, ts = self._poses_for_frames(loader, lidar, frame_idx) + output_dict["timestamp_list"] = ts + output_dict["pose_sensor_start_end"] = sensor_pose_start_end + output_dict["lidar_to_world"] = l2w_start # (N, 4, 4), sweep-start + output_dict["rgb_frame_indices"] = frame_idx.tolist() + + for data_field in data_fields: + if data_field == "custom": + output_dict[data_field] = {} + range_list, intensity_list = [], [] + for fi in frame_idx: + rmap, imap = self._scatter_frame(lidar, int(fi), R, C) + range_list.append(rmap) + if imap is not None: + intensity_list.append(imap) + output_dict[data_field]["lidar"] = np.stack(range_list, axis=0) # [N, R, C] + if self.load_intensity: + output_dict[data_field]["lidar_intensity"] = np.stack(intensity_list, axis=0) + if "hdmap" in self.custom_fields: + comp = self._get_composer(stem, lidar) + outW = self.resample_width if self.resample_width > 0 else C + hdmap_list = [] + for k, fi in enumerate(frame_idx): + if self.hdmap_multichannel: + hdmap_list.append( + comp.rasterize_multichannel( + int(fi), + l2w_start[k], + outW, + self.min_range, + self.max_range, + moving_only=self.hdmap_moving_only, + ) + ) + else: + hdmap_list.append( + comp.rasterize( + int(fi), + l2w_start[k], + outW, + self.min_range, + self.max_range, + include_boxes=self.hdmap_include_boxes, + moving_only=self.hdmap_moving_only, + ) + ) + # multichannel -> (N, NUM_CLASSES, R, W); else (N, R, W). + output_dict[data_field]["hdmap"] = np.stack(hdmap_list, axis=0) + if self.hdmap_bev: + bev_list = [ + comp.rasterize_bev( + int(fi), + l2w_start[k], + self.hdmap_bev_size, + self.hdmap_bev_pc_range, + include_boxes=self.hdmap_include_boxes, + moving_only=self.hdmap_moving_only, + ) + for k, fi in enumerate(frame_idx) + ] + # (N, NUM_CLASSES, Y, X) + output_dict[data_field]["hdmap_bev"] = np.stack(bev_list, axis=0) + elif data_field == DataField.IMAGE_RGB: + # Camera RGB conditioning: read each requested view's image + # nearest (in time) to every sampled lidar frame, as a + # (N, 3, H, W) float tensor in [0, 1] -- the exact format the + # sampler's get_rgb() -> process_rgb() expects (matches + # RadymLidar). Cameras must have been opened (load_cameras=True + # -> _clip_component_paths added the camera zarrs). + output_dict[data_field] = {} + view_indices = ( + self.view_indices + if self.view_indices is not None + else list(range(max(self.num_views, 0))) + ) + for c_view_idx, view_idx in enumerate(view_indices): + cam_name = WAYMO_VIEW_IDX_TO_CAMERA[view_idx] + cam = loader.get_camera_sensor(cam_name) + frames = [] + for t_us in ts: + ci = cam.get_closest_frame_index(int(t_us)) + img = np.asarray(cam.get_frame_image_array(ci)) # (H,W,3) uint8 + frames.append(img) + rgb = np.stack(frames, axis=0) # (N, H, W, 3) + rgb = ( + torch.from_numpy(rgb).permute(0, 3, 1, 2).contiguous().float() + / 255.0 + ) # (N, 3, H, W) in [0, 1] + output_dict[data_field][c_view_idx] = rgb + elif data_field in ( + DataField.CAMERA_INTRINSICS, + DataField.CAMERA_C2LIDAR_TRANSFORM, + ): + # The image-conditioned RF models only VAE-encode the RGB as + # cross-attention / canvas context -- they never project points, + # so intrinsics / camera->lidar extrinsics are unused. Emit empty + # dicts (the sampler's get_camera_* returns {} -> sample.update + # is a no-op) instead of fabricating values. Populate from the + # NCore CameraModel here if a projection-based waymo model needs + # them later. + output_dict[data_field] = {} + else: + raise NotImplementedError( + f"WaymoNCoreLidar does not yet handle data field {data_field}." + ) + + return output_dict + + +# Camera view index -> NCore camera instance name (Waymo 5-camera rig). +WAYMO_VIEW_IDX_TO_CAMERA = { + 0: "camera_front_50fov", + 1: "camera_front_left_50fov", + 2: "camera_front_right_50fov", + 3: "camera_side_left_50fov", + 4: "camera_side_right_50fov", +} diff --git a/tokenizer/training/datasets/utils.py b/tokenizer/training/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d7981fd06534c1958e573fd31818103467ec649d --- /dev/null +++ b/tokenizer/training/datasets/utils.py @@ -0,0 +1,232 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for datasets creation.""" + +IMAGE_KEY = "images" +VIDEO_KEY = "video" +RECON_KEY = "reconstructions" +LATENT_KEY = "latent" +INPUT_KEY = "INPUT" +MASK_KEY = "loss_mask" +# When present in batch/inputs, loss uses this as reconstruction target instead of INPUT_KEY (e.g. process_output != process_input) +RECON_TARGET_KEY = "recon_target" + +_SPATIAL_ALIGN = 16 + + +import math +from typing import Union + +import torch +from PIL import Image + +# This is your "for short_side=720" map: +_ASPECT_SIZE_DICT = { + "1,1": (720, 720), + "4,3": (960, 720), + "3,4": (720, 960), + "16,9": (1280, 720), + "9,16": (720, 1280), +} + + +VIDEO_RES_SIZE_INFO: dict[str, tuple[int, int]] = { + "1080": { # 1080p doesn't have 1:1 + "4,3": (1440, 1072), + "3,4": (1072, 1440), + "16,9": (1920, 1072), + "9,16": (1072, 1920), + }, + "720": {"1,1": (720, 720), "4,3": (960, 720), "3,4": (720, 960), "16,9": (1280, 720), "9,16": (720, 1280)}, + "480": {"1,1": (480, 480), "4,3": (640, 480), "3,4": (480, 640), "16,9": (854, 480), "9,16": (480, 854)}, + "512": {"1,1": (512, 512), "4,3": (672, 512), "3,4": (512, 672), "16,9": (896, 512), "9,16": (512, 896)}, + "360": {"1,1": (320, 320), "4,3": (416, 320), "3,4": (320, 416), "16,9": (544, 320), "9,16": (320, 544)}, + "256": {"1,1": (256, 256), "4,3": (320, 256), "3,4": (256, 320), "16,9": (320, 192), "9,16": (192, 320)}, + "128": { # Note that we set res lower than 256 to the same resolution as 256 + "1,1": (256, 256), + "4,3": (320, 256), + "3,4": (256, 320), + "16,9": (448, 256), + "9,16": (256, 448), + }, +} + +VIDEO_VAL_CROP_SIZE_INFO: dict[str, tuple[int, int]] = { + "1080": { # 1080p doesn't have 1:1 + "4,3": (1424, 1072), + "3,4": (1072, 1424), + "16,9": (1904, 1072), + "9,16": (1072, 1904), + "16,10": (1715, 1072), + }, + "720": {"1,1": (704, 704), "4,3": (944, 704), "3,4": (704, 944), "16,9": (1264, 704), "9,16": (704, 1264)}, + "480": {"1,1": (464, 464), "4,3": (624, 464), "3,4": (464, 624), "16,9": (848, 464), "9,16": (464, 848)}, + "360": {"1,1": (320, 320), "4,3": (416, 320), "3,4": (320, 416), "16,9": (544, 320), "9,16": (320, 544)}, + "512": {"1,1": (512, 512), "4,3": (672, 512), "3,4": (512, 672), "16,9": (896, 512), "9,16": (512, 896)}, + "256": {"1,1": (256, 256), "4,3": (320, 256), "3,4": (256, 320), "16,9": (320, 192), "9,16": (192, 320)}, + "128": { # Note that we set res lower than 256 to the same resolution as 256 + "1,1": (256, 256), + "4,3": (320, 256), + "3,4": (256, 320), + "16,9": (320, 192), + "9,16": (192, 320), + "16,10": (410, 256), + }, +} + + +def _pick_closest_aspect_ratio(height, width): + """ + Given a video's height and width, return the closest aspect ratio key + from aspect_dict. + """ + if height == 0: + return "1,1" # fallback if something weird, to avoid div by zero + + actual_ratio = width / height + + best_key = None + min_diff = math.inf + + for ratio_key, (w_target, h_target) in _ASPECT_SIZE_DICT.items(): + # for "16,9" -> (1280, 720), ratio is 1280/720 = 1.7777... + ratio = w_target / h_target + diff = abs(actual_ratio - ratio) + if diff < min_diff: + min_diff = diff + best_key = ratio_key + + return best_key + + +def categorize_aspect_and_store(data_sample): + """ + data_sample: a dict with 'video' shaped [C,T,H,W]. + We will determine the aspect ratio, pick the closest "1,1", "4,3", etc., + and store a new dict entry. + """ + # Suppose 'video' is [C, T, H, W]. + video_tensor = data_sample["video"] + H = video_tensor.shape[-2] + W = video_tensor.shape[-1] + data_sample["aspect_ratio"] = _pick_closest_aspect_ratio(H, W) + return data_sample + + +def get_crop_size_info(crop_sz: int = 128): + aspect_ratios = [(1, 1), (4, 3), (3, 4), (16, 9), (9, 16)] + crop_sizes = dict() + for aspect_ratio in aspect_ratios: + if aspect_ratio[0] < aspect_ratio[1]: + crop_h = crop_sz // _SPATIAL_ALIGN * _SPATIAL_ALIGN + crop_w = int(crop_h * aspect_ratio[0] / aspect_ratio[1] + 0.5) + crop_w = crop_w // _SPATIAL_ALIGN * _SPATIAL_ALIGN + else: + crop_w = crop_sz // _SPATIAL_ALIGN * _SPATIAL_ALIGN + crop_h = int(crop_w * aspect_ratio[1] / aspect_ratio[0] + 0.5) + crop_h = crop_h // _SPATIAL_ALIGN * _SPATIAL_ALIGN + key = f"{aspect_ratio[0]},{aspect_ratio[1]}" + crop_sizes.update({key: (crop_w, crop_h)}) + return crop_sizes + + +def obtain_image_size(data_dict: dict, input_keys: list) -> tuple[int, int]: + r"""Function for obtaining the image size from the data dict. + + Args: + data_dict (dict): Input data dict + input_keys (list): List of input keys + Returns: + width (int): Width of the input image + height (int): Height of the input image + """ + + data1 = data_dict[input_keys[0]] + if isinstance(data1, Image.Image): + width, height = data1.size + elif isinstance(data1, torch.Tensor): + height, width = data1.size()[-2:] + else: + raise ValueError("data to random crop should be PIL Image or tensor") + + return width, height + + +def obtain_augmentation_size(data_dict: dict, augmentor_cfg: dict) -> Union[int, tuple]: + r"""Function for obtaining size of the augmentation. + When dealing with multi-aspect ratio dataloaders, we need to + find the augmentation size from the aspect ratio of the data. + + Args: + data_dict (dict): Input data dict + augmentor_cfg (dict): Augmentor config + Returns: + aug_size (int): Size of augmentation + """ + if "__url__" in data_dict and "aspect_ratio" in data_dict["__url__"].meta.opts: + aspect_ratio = data_dict["__url__"].meta.opts["aspect_ratio"] + aug_size = augmentor_cfg["size"][aspect_ratio] + else: # Non-webdataset format + aspect_ratio = data_dict["aspect_ratio"] + aug_size = augmentor_cfg["size"][aspect_ratio] + return aug_size + +class ToTensorVideo: + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + """ + + def __init__(self): + pass + + def __call__(self, clip): + """ + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, C, H, W) + Return: + clip (torch.tensor, dtype=torch.float): Size is (T, C, H, W) + """ + return to_tensor(clip) + + def __repr__(self) -> str: + return self.__class__.__name__ + + +def to_tensor(clip): + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, C, H, W) + Return: + clip (torch.tensor, dtype=torch.float): Size is (T, C, H, W) + """ + _is_tensor_video_clip(clip) + if not clip.dtype == torch.uint8: + raise TypeError("clip tensor should have data type uint8. Got %s" % str(clip.dtype)) + # return clip.float().permute(3, 0, 1, 2) / 255.0 + return clip.float() / 255.0 + + +def _is_tensor_video_clip(clip): + if not torch.is_tensor(clip): + raise TypeError("clip should be Tensor. Got %s" % type(clip)) + + if not clip.ndimension() == 4: + raise ValueError("clip should be 4D. Got %dD" % clip.dim()) + + return True diff --git a/tokenizer/training/geo_converter.py b/tokenizer/training/geo_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..af320b143f2b047c30da408b1f269f182846bfe2 --- /dev/null +++ b/tokenizer/training/geo_converter.py @@ -0,0 +1,234 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import torch +from torch import nn +from omegaconf import OmegaConf + +from utils.lidar_rangemap import ( + range_map_to_ray_directions, + load_pandar128_elevations, + undo_row_col_temporal_repeat, +) +from utils.lidar_rangemap import unnormalize_and_reduce_channels +from utils.per_row_norm import get_per_row_normalizer, invert_per_row_norm +from tokenizer.training.datasets.lidar_datasets.configs import COMMONDATA_CONFIG + +class GeoConverter(nn.Module): + def __init__(self, data_config=dict()): + super().__init__() + + if data_config.get("uses_sensor_metadata", False): + shared = OmegaConf.to_container( + OmegaConf.create(data_config.get("shared_overrides", {})), + resolve=True, + ) + self.config = { + "repeat_row": 1, + "repeat_col": 1, + "repeat_temporal": 1, + **shared, + } + if any( + self.config[key] != 1 + for key in ("repeat_row", "repeat_col", "repeat_temporal") + ): + raise ValueError( + "Metadata-driven geometry requires un-repeated native grids" + ) + self.depth_min = self.depth_max = None + self.process_output = self.config.get("process_output", "mono") + self.has_intensity = self.config.get("load_intensity", False) + self.per_row_normalizer = None + self.ray_directions = self.ray_origins = None + return + + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[data_config.dataset_name]) + extra_config = OmegaConf.create(data_config) + config = OmegaConf.merge(dataset_config, extra_config) + self.config = OmegaConf.to_container(config, resolve=True) + + self.depth_min, self.depth_max = self.config["min_range"], self.config["max_range"] + self.process_output = self.config["process_output"] + self.has_intensity = self.config.get("load_intensity", False) + + # Per-row normalizer (None when disabled): inverted before unnormalize. + self.per_row_normalizer = get_per_row_normalizer( + self.config.get("per_row_normalize", False), + self.config.get("per_row_stats_path", ""), + min_range=self.depth_min, + max_range=self.depth_max, + min_value=self.config["min_value"], + smooth_sigma=self.config.get("per_row_smooth_sigma", 5.0), + log_depth=False, + ) + + self.init_ray_directions() + + def init_ray_directions(self): + # Waymo NCore backend: use the sensor's measured elevation/azimuth tables + # (+ per-row offset) instead of the Pandar128 uniform-linspace geometry, + # otherwise the back-projection is geometrically wrong AND the ray grid + # shape (Pandar128 128xWidth) would not even match the 64xW Waymo range + # map. Built once from the first clip (all top-lidar clips share the model). + _backend = self.config.get("dataset_backend", "radym") + if _backend in ("waymo_ncore", "nuscenes_ncore"): + if _backend == "waymo_ncore": + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_ray_directions as load_ncore_ray_directions, + ) + else: + from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import ( + load_nuscenes_ray_directions as load_ncore_ray_directions, + ) + ray_kwargs = { + "root_path": self.config["root_path"], + "filter_list_path": self.config.get("filter_list_path", None), + "lidar_id": self.config.get("lidar_id", "lidar_top"), + "resample_width": self.config.get("resample_width", -1), + } + if _backend == "nuscenes_ncore": + ray_kwargs["center_vehicle_forward"] = self.config.get( + "center_vehicle_forward", False + ) + ray_np = load_ncore_ray_directions(**ray_kwargs) + ray_directions = torch.from_numpy(ray_np).float() # (H, W, 3) + self.ray_directions = ray_directions[None, None, ...].cuda() + self.ray_origins = torch.zeros_like(self.ray_directions).cuda() + return + + lidar_width = 3600 // self.config["downsample_factor_col"] + # If the range map is resized to a fixed width (nearest-exact, see + # rangemap_sampler), build the azimuth grid at that width so the + # per-column ray directions line up with the resized range image. + # The FOV is unchanged (uniform over the full azimuth), so a linspace + # over the resized width is the correct correspondence. + resize = self.config.get("lidar_resize_size", None) + if resize is not None and resize[1] != -1: + lidar_width = int(resize[1]) + elevation_angles = torch.tensor(load_pandar128_elevations(), dtype=torch.float32) + + ray_directions = torch.from_numpy( + range_map_to_ray_directions(lidar_width, elevation_angles) + ).float() # shape: (H, W, 3) + + self.ray_directions = ray_directions[None, None, ...].cuda() # shape: (1, 1, H, W, 3) + self.ray_origins = torch.zeros_like(self.ray_directions).cuda() # shape: (1, 1, H, W, 3) + + def _forward_sensor_metadata( + self, + input: torch.Tensor, + ray_directions: torch.Tensor, + depth_bounds: torch.Tensor, + return_valid: bool, + ): + """Back-project a homogeneous batch with its exact sensor metadata.""" + depth_norm = input[:, :1] + depth_norm = undo_row_col_temporal_repeat( + depth_norm, + self.config["repeat_row"], + self.config["repeat_col"], + self.config["repeat_temporal"], + ) + if depth_norm.ndim == 4: + depth_norm = depth_norm.unsqueeze(2) + depth_norm = depth_norm[:, 0] + + bounds = depth_bounds.to(device=input.device, dtype=input.dtype) + if bounds.ndim == 1: + bounds = bounds.unsqueeze(0) + if bounds.shape != (input.shape[0], 2): + raise ValueError( + f"sensor_depth_bounds must have shape (B,2), got {tuple(bounds.shape)}" + ) + depth_min = bounds[:, 0, None, None, None] + depth_max = bounds[:, 1, None, None, None] + depth = (depth_norm.clamp(-1, 1) + 1.0) * 0.5 + depth = depth * (depth_max - depth_min) + depth_min + + rays = ray_directions.to(device=input.device, dtype=input.dtype) + if rays.ndim == 3: + rays = rays.unsqueeze(0) + if rays.shape != (input.shape[0], *depth.shape[-2:], 3): + raise ValueError( + "sensor_ray_directions must match (B,H,W,3): " + f"got {tuple(rays.shape)} for depth {tuple(depth.shape)}" + ) + points = depth[..., None] * rays[:, None] + valid = (depth > depth_min) & (depth < depth_max) + if return_valid: + return points, valid + return points + + def forward( + self, + input, + return_valid: bool = False, + ray_directions: torch.Tensor | None = None, + depth_bounds: torch.Tensor | None = None, + ): + """ + input: [N, C, H, W] or [N, C, T, H, W] in normalized space (matching + the dataset's ``min_value`` convention -- typically [-1, 1]). + + Returns: + points: [N, 1, H, W, 3] (4D input) or [N, T, H, W, 3] (5D input) + in metric meters (i.e. unnormalized to [min_range, max_range]). + valid_mask (only if return_valid=True): same leading shape as + ``points`` minus the trailing 3 (i.e. [N, 1, H, W] / [N, T, H, W]) + bool tensor marking pixels whose recovered depth lies within + [min_range, max_range]. + """ + if (ray_directions is None) != (depth_bounds is None): + raise ValueError( + "ray_directions and depth_bounds must be provided together" + ) + if ray_directions is not None: + return self._forward_sensor_metadata( + input, ray_directions, depth_bounds, return_valid + ) + + # Invert per-row z-score back to [-1, 1] space BEFORE the clamp (no-op + # when disabled). Operates on the H dim, broadcasting over N/C/T. + input = invert_per_row_norm(input, self.per_row_normalizer) + input = input.clamp(-1, 1) + input = undo_row_col_temporal_repeat( + input, + self.config["repeat_row"], + self.config["repeat_col"], + self.config["repeat_temporal"], + ) + + unnorm_result = unnormalize_and_reduce_channels( + input, + self.depth_max, + self.depth_min, + self.config["min_value"], + self.config["inverse_depth"], + self.process_output, + near_buffer=0, + far_buffer=0, + inv_depth_threshold=self.config["inv_depth_threshold"], + num_bands=self.config["num_bands"], + apply_valid_mask=False, + has_intensity=self.has_intensity, + intensity_transform=self.config.get("intensity_transform", "legacy"), + ) + if self.has_intensity: + depth, valid_mask, _intensity = unnorm_result + else: + depth, valid_mask = unnorm_result + # depth / valid_mask shape: (N, H, W) or (N, T, H, W) + + assert depth.shape[-2:] == self.ray_directions.shape[-3:-1], \ + f"Input shape {depth.shape} does not match ray directions shape {self.ray_directions.shape}" + + if depth.ndim == 3: + depth = depth.unsqueeze(1) + valid_mask = valid_mask.unsqueeze(1) + + points = self.ray_origins + self.ray_directions * depth[..., None] + + if return_valid: + return points, valid_mask + return points diff --git a/tokenizer/training/lidar_callbacks.py b/tokenizer/training/lidar_callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..7319a31c06c76eb8222ae922863b29e0b633311b --- /dev/null +++ b/tokenizer/training/lidar_callbacks.py @@ -0,0 +1,1784 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tokenizer callbacks extended from base callbacks.""" + +import io +import math +import time +from typing import Any + +from omegaconf import OmegaConf +import imageio +import numpy as np +import torch.distributed as dist +import torch +import torch.nn.functional as F +import torchvision +import wandb +from PIL import Image +from torch._dynamo.eval_frame import OptimizedModule as torch_OptimizedModule + +from utils.config import Config +from utils.model import Model +from utils.trainer import Trainer +from utils import callback, distributed, log, wandb_utils +from tokenizer.training.callbacks import make_video_grid +from tokenizer.training.datasets.lidar_datasets.configs import COMMONDATA_CONFIG +from utils.per_row_norm import get_per_row_normalizer, invert_per_row_norm +from tokenizer.training.model import PREDICTION + +_UINT8_MAX_F = float(np.iinfo(np.uint8).max) + +from utils.lidar_rangemap import ( + undo_row_col_temporal_repeat, + unnormalize_and_reduce_channels, + unnormalize_intensity, + colorcode_depth_maps, +) +from utils.visualize.point_cloud import ( + render_range_map_to_point_cloud, + render_range_map_to_point_cloud_with_intensity, + vis_point_cloud_to_numpy, +) + +# Per-lidar viz palette: top lidar gray, blind-spot lidars distinct bold colors +# (order = local laser index in the dumped NPZ, typically FRONT / SIDE_LEFT / +# SIDE_RIGHT / REAR). +_TOP_COLOR = np.array([0.55, 0.55, 0.55], dtype=np.float32) +_LASER_PALETTE = np.array( + [ + [1.00, 0.20, 0.20], # red + [0.20, 0.90, 0.30], # green + [0.25, 0.55, 1.00], # blue + [1.00, 0.70, 0.10], # orange + [0.85, 0.35, 1.00], # purple + [0.10, 0.85, 0.85], # cyan + ], + dtype=np.float32, +) + + +def wandb_range_image(range_map_input, range_map_recon, ray_directions=None): + # range_map_input: [N, H, W] + # range_map_recon: [N, H, W] + + device = range_map_input.device + vis = render_range_map_to_point_cloud( + range_map_input.cpu().numpy(), range_map_recon.cpu().numpy(), filter_outlier=False, + ray_directions=ray_directions, + ) # shape: (bs, H, W, 3), uint8 + + vis_images = torch.from_numpy(vis).float() / _UINT8_MAX_F + vis_images = vis_images.permute(0, 3, 1, 2).to(device) # shape: (bs, 3, H, W) + + image_grid = torchvision.utils.make_grid(vis_images.clamp_(0, 1), nrow=1, pad_value=0, normalize=False) + image_grid = image_grid.permute(1, 2, 0).cpu().detach().numpy() + pil_image = Image.fromarray((image_grid * _UINT8_MAX_F).astype("uint8")) + return wandb.Image(pil_image) + + +def wandb_range_video(range_map_input, range_map_recon, fps=10, ray_directions=None): + # range_map_input: [N, T, H, W] + # range_map_recon: [N, T, H, W] + + device = range_map_input.device + vis = render_range_map_to_point_cloud( + range_map_input.squeeze(0).cpu().numpy(), range_map_recon.squeeze(0).cpu().numpy(), filter_outlier=False, + ray_directions=ray_directions, + ) # shape: (t, H, W, 3), uint8 + vis_videos = torch.from_numpy(vis).float() / _UINT8_MAX_F + vis_videos = vis_videos.unsqueeze(0).permute(0, -1, 1, 2, 3).to(device) # shape: (1, 3, t, H, W) + + video_grid = make_video_grid(vis_videos.clamp_(0, 1), nrow=vis_videos.shape[0], padding=0) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, video_grid, "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +@torch.no_grad() +def _fit_pca_basis(fv: torch.Tensor): + """fv: (M, D) valid features -> (mean (D,), V (D, 3)) top-3 PCA basis.""" + if fv.shape[0] > 200_000: + idx = torch.randperm(fv.shape[0], device=fv.device)[:200_000] + fv = fv[idx] + mean = fv.mean(0) + _, _, Vt = torch.pca_lowrank(fv - mean, q=3, niter=4) + return mean, Vt[:, :3] + + +@torch.no_grad() +def _apply_pca_rgb(feat: torch.Tensor, valid: torch.Tensor, mean: torch.Tensor, + V: torch.Tensor, n_sigma: float = 2.0, std3=None): + """feat (D,T,H,W), valid (T,H,W) bool -> (T,H,W,3) uint8 (invalid=black). + + Projects ``feat`` onto the supplied basis ``(mean, V)`` and normalizes each + PC channel by ``n_sigma * std`` (std fit on valid entries, or reuse ``std3`` + so two maps share the same color scale).""" + D = feat.shape[0] + u = torch.einsum("dthw,dk->kthw", feat - mean.view(D, 1, 1, 1), V) # (3,T,H,W) + u_np = u.float().cpu().numpy() + vm = valid.cpu().numpy() + if std3 is None: + std3 = np.stack([u_np[k][vm].std() if vm.any() else 1.0 for k in range(3)]) + rgb = np.zeros(u_np.shape[1:] + (3,), dtype=np.uint8) + for k in range(3): + n = np.clip(u_np[k] / (n_sigma * (std3[k] + 1e-6)), -1.0, 1.0) + rgb[..., k] = (0.5 * (n + 1.0) * 255.0).astype(np.uint8) + rgb[~vm] = 0 + return rgb, std3 + + +def _upsample_nn_rgb(rgb: np.ndarray, factor: int) -> np.ndarray: + if factor <= 1: + return rgb + return rgb.repeat(factor, axis=1).repeat(factor, axis=2) + + +def wandb_rgb_media(rgb: np.ndarray, fps: int = 10): + """rgb: (T, H, W, 3) uint8 -> wandb.Image (T==1) or wandb.Video.""" + if rgb.shape[0] == 1: + return wandb.Image(Image.fromarray(rgb[0])) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, rgb, "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +def wandb_image(images, iteration): + vis_images = (images + 1) / 2 # [-1,1] to [0,1] + image_grid = torchvision.utils.make_grid(vis_images.clamp_(0, 1), nrow=1, pad_value=0, normalize=False) + image_grid = image_grid.permute(1, 2, 0).cpu().detach().numpy() + pil_image = Image.fromarray((image_grid * _UINT8_MAX_F).astype("uint8")) + return wandb.Image(pil_image) + + +def wandb_video(videos, iteration, fps=10): + # videos: [B, C, T, H, W] + vis_videos = (videos + 1.0) / 2.0 + video_grid = make_video_grid(vis_videos.clamp_(0, 1), nrow=vis_videos.shape[0], padding=0) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, video_grid, "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +def wandb_intensity_image(intensity_gt, intensity_recon): + """Visualize intensity maps as colormapped images (viridis). Input: [N, H, W] in [0,1].""" + from matplotlib import cm + cmap = cm.get_cmap("viridis") + + gt_rgb = torch.from_numpy(cmap(intensity_gt.cpu().clamp(0, 1).numpy())[..., :3]).float() + re_rgb = torch.from_numpy(cmap(intensity_recon.cpu().clamp(0, 1).numpy())[..., :3]).float() + + paired = torch.cat([gt_rgb, re_rgb], dim=-2) # [N, H, 2W, 3] + paired = paired.permute(0, 3, 1, 2) # [N, 3, H, 2W] + + grid = torchvision.utils.make_grid(paired.clamp_(0, 1), nrow=1, pad_value=0, normalize=False) + grid = grid.permute(1, 2, 0).cpu().numpy() + return wandb.Image(Image.fromarray((grid * _UINT8_MAX_F).astype("uint8"))) + + +def wandb_intensity_video(intensity_gt, intensity_recon, fps=10): + """Visualize intensity maps as colormapped video. Input: [N, T, H, W] in [0,1].""" + from matplotlib import cm + cmap = cm.get_cmap("viridis") + + gt_rgb = torch.from_numpy(cmap(intensity_gt.squeeze(0).cpu().clamp(0, 1).numpy())[..., :3]).float() + re_rgb = torch.from_numpy(cmap(intensity_recon.squeeze(0).cpu().clamp(0, 1).numpy())[..., :3]).float() + + paired = torch.cat([gt_rgb, re_rgb], dim=-2) # [T, H, 2W, 3] + paired = paired.unsqueeze(0).permute(0, 4, 1, 2, 3) # [1, 3, T, H, 2W] + + video_grid = make_video_grid(paired.clamp_(0, 1), nrow=1, padding=0) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, video_grid, "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +def wandb_range_image_intensity(range_map_input, range_map_recon, intensity_input, intensity_recon, ray_directions=None): + """Point cloud visualization colored by intensity. Input: all [N, H, W] numpy.""" + vis = render_range_map_to_point_cloud_with_intensity( + range_map_input, range_map_recon, intensity_input, intensity_recon, filter_outlier=False, + ray_directions=ray_directions, + ) # uint8 + vis_images = torch.from_numpy(vis).float() / _UINT8_MAX_F + vis_images = vis_images.permute(0, 3, 1, 2) + grid = torchvision.utils.make_grid(vis_images.clamp_(0, 1), nrow=1, pad_value=0, normalize=False) + grid = grid.permute(1, 2, 0).cpu().numpy() + return wandb.Image(Image.fromarray((grid * _UINT8_MAX_F).astype("uint8"))) + + +def wandb_range_video_intensity(range_map_input, range_map_recon, intensity_input, intensity_recon, fps=10, ray_directions=None): + """Point cloud video colored by intensity. Input: all [N, T, H, W] numpy.""" + vis = render_range_map_to_point_cloud_with_intensity( + range_map_input.squeeze(0), range_map_recon.squeeze(0), + intensity_input.squeeze(0), intensity_recon.squeeze(0), filter_outlier=False, + ray_directions=ray_directions, + ) # uint8 + vis_videos = torch.from_numpy(vis).float() / _UINT8_MAX_F + vis_videos = vis_videos.unsqueeze(0).permute(0, -1, 1, 2, 3) + video_grid = make_video_grid(vis_videos.clamp_(0, 1), nrow=1, padding=0) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, video_grid, "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +def wandb_mask_image(mask_gt, mask_pred): + """Side-by-side validity mask (grayscale). Input: [N, H, W] in [0,1] + (white = valid return, black = no-return). ``mask_gt`` is the binary GT + return mask; ``mask_pred`` is the decoder's predicted validity prob.""" + gt = mask_gt.cpu().clamp(0, 1).unsqueeze(-1).repeat(1, 1, 1, 3) # [N,H,W,3] + pr = mask_pred.cpu().clamp(0, 1).unsqueeze(-1).repeat(1, 1, 1, 3) + paired = torch.cat([gt, pr], dim=-2).permute(0, 3, 1, 2) # [N,3,H,2W] + grid = torchvision.utils.make_grid(paired, nrow=1, pad_value=0, normalize=False) + grid = grid.permute(1, 2, 0).cpu().numpy() + return wandb.Image(Image.fromarray((grid * _UINT8_MAX_F).astype("uint8"))) + + +def wandb_mask_video(mask_gt, mask_pred, fps=10): + """Side-by-side validity mask video (grayscale). Input: [N, T, H, W].""" + gt = mask_gt.squeeze(0).cpu().clamp(0, 1).unsqueeze(-1).repeat(1, 1, 1, 3) # [T,H,W,3] + pr = mask_pred.squeeze(0).cpu().clamp(0, 1).unsqueeze(-1).repeat(1, 1, 1, 3) + paired = torch.cat([gt, pr], dim=-2).unsqueeze(0).permute(0, 4, 1, 2, 3) # [1,3,T,H,2W] + video_grid = make_video_grid(paired.clamp_(0, 1), nrow=1, padding=0) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, video_grid, "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +def _multilidar_colored_points( + top_pts, ex_pts, ex_valid, ex_laser, ex_keep=None +): + """Stack top + per-laser-colored blind-spot points into (P,3) xyz + (P,3) rgb. + + top_pts: (Nt,3) top-lidar points (already validity-filtered) or None. + ex_pts: (K,3) extra points; ex_valid: (K,) real-return mask; ex_laser: (K,) + local laser index (-1 = padding); ex_keep: extra per-ray keep mask (e.g. + opacity>=thr) AND-ed with ex_valid, or None.""" + pts_list, col_list = [], [] + if top_pts is not None and top_pts.shape[0] > 0: + pts_list.append(top_pts) + col_list.append(np.tile(_TOP_COLOR, (top_pts.shape[0], 1))) + if ex_pts is not None: + m = ex_valid.astype(bool) + if ex_keep is not None: + m = m & ex_keep.astype(bool) + if m.any(): + ep = ex_pts[m] + el = ex_laser[m].astype(np.int64) + ec = _LASER_PALETTE[np.clip(el, 0, len(_LASER_PALETTE) - 1)] + pts_list.append(ep) + col_list.append(ec) + if not pts_list: + return np.zeros((0, 3), np.float32), np.zeros((0, 3), np.float32) + return ( + np.concatenate(pts_list, 0).astype(np.float32), + np.concatenate(col_list, 0).astype(np.float32), + ) + + +def _multilidar_pcd_frame( + top_gt, top_recon, ex_gt, ex_recon, ex_valid, ex_laser, ex_keep=None, +): + """One (H, 2W, 3) uint8 frame: perspective point-cloud render (GT | recon) + in the same front view as ``val/range_map``, top lidar gray + each + blind-spot lidar a distinct color, overlaid in ONE scene.""" + g_pts, g_col = _multilidar_colored_points(top_gt, ex_gt, ex_valid, ex_laser) + r_pts, r_col = _multilidar_colored_points( + top_recon, ex_recon, ex_valid, ex_laser, ex_keep=ex_keep + ) + img_g = vis_point_cloud_to_numpy(g_pts, g_col) + img_r = vis_point_cloud_to_numpy(r_pts, r_col) + return np.concatenate([img_g, img_r], axis=1).astype(np.uint8) + + +def _fig_to_rgb(fig) -> np.ndarray: + """Rasterize a Matplotlib fig to a FIXED-size (figsize*dpi) (H,W,3) uint8 + array via the Agg canvas buffer -- fixed size (no bbox_inches='tight') so + per-frame arrays stack into a valid mp4.""" + fig.canvas.draw() + w, h = fig.canvas.get_width_height() + buf = np.frombuffer(fig.canvas.buffer_rgba(), dtype=np.uint8).reshape(h, w, 4) + return buf[..., :3].copy() + + +def _frames_to_media(frames, fps=4): + """Pack a list of equal-size (H,W,3) uint8 frames into a wandb.Video (mp4) + when >1 frame, else a single wandb.Image.""" + if len(frames) == 1: + return wandb.Image(Image.fromarray(frames[0])) + mem_file = io.BytesIO() + imageio.mimsave(mem_file, np.stack(frames, 0), "mp4", fps=fps, codec="libx264") + mem_file.seek(0) + return wandb.Video(mem_file, fps=fps, format="mp4") + + +def _multilidar_bev_frame( + top_gt, top_recon, ex_gt, ex_recon, ex_valid, ex_laser, ex_keep=None, + laser_names=None, R=None, +): + """One BEV (x-y, top) + side (x-z, bottom) scatter frame, GT (left) | + recon (right), as an (H,W,3) uint8 array. + + Top lidar gray for context; each blind-spot lidar a distinct color. Auto- + zoomed to the extra-lidar extent (pass a fixed ``R`` for a stable video). + ``ex_keep`` (opacity>=thr) additionally masks the recon extras.""" + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.lines import Line2D + + vm = ex_valid.astype(bool) + eg = ex_gt[vm] + el = ex_laser[vm].astype(np.int64) + rm = vm & (ex_keep.astype(bool) if ex_keep is not None else np.ones_like(vm)) + er = ex_recon[rm] + erl = ex_laser[rm].astype(np.int64) + + # Zoom to the blind-spot extent (they're near-range), padded; clamp [15, 80]. + if R is None: + if eg.shape[0] > 0: + R = float(np.percentile(np.abs(eg[:, :2]), 99)) * 1.3 + else: + R = 40.0 + R = float(np.clip(R, 15.0, 80.0)) + + fig, axes = plt.subplots(2, 2, figsize=(12, 12), dpi=100) + + def _scatter(ax, top, ex, exl, a, b): + if top is not None and top.shape[0] > 0: + ax.scatter(top[:, a], top[:, b], c=[_TOP_COLOR], s=0.4, alpha=0.35) + if ex.shape[0] > 0: + cols = _LASER_PALETTE[np.clip(exl, 0, len(_LASER_PALETTE) - 1)] + ax.scatter(ex[:, a], ex[:, b], c=cols, s=1.5) + + _scatter(axes[0, 0], top_gt, eg, el, 0, 1) + _scatter(axes[0, 1], top_recon, er, erl, 0, 1) + _scatter(axes[1, 0], top_gt, eg, el, 0, 2) + _scatter(axes[1, 1], top_recon, er, erl, 0, 2) + + axes[0, 0].set_title(f"BEV GT (x-y) [{eg.shape[0]} extra pts]", fontsize=11) + axes[0, 1].set_title("BEV recon (x-y)", fontsize=11) + axes[1, 0].set_title("side GT (x-z)", fontsize=11) + axes[1, 1].set_title("side recon (x-z)", fontsize=11) + for ax in axes[0]: + ax.set_xlim(-R, R); ax.set_ylim(-R, R); ax.set_aspect("equal") + for ax in axes[1]: + ax.set_xlim(-R, R); ax.set_ylim(-5, 8); ax.set_aspect("equal") + for ax in axes.ravel(): + ax.set_xticks([]); ax.set_yticks([]); ax.set_facecolor("black") + + # Legend (top + per-laser). + n_lasers = int(ex_laser[vm].max()) + 1 if vm.any() else 0 + handles = [Line2D([0], [0], marker="o", color="w", markerfacecolor=_TOP_COLOR, + markersize=6, label="top")] + for li in range(n_lasers): + name = laser_names[li] if (laser_names is not None and li < len(laser_names)) else f"laser {li}" + handles.append(Line2D([0], [0], marker="o", color="w", + markerfacecolor=_LASER_PALETTE[li % len(_LASER_PALETTE)], + markersize=6, label=str(name))) + axes[0, 0].legend(handles=handles, loc="upper right", fontsize=8, framealpha=0.6) + fig.tight_layout() + arr = _fig_to_rgb(fig) + plt.close(fig) + return arr + + +# Default blind-spot laser names (dump order in scripts/dump_waymo_lidar_extra.py). +_EXTRA_LASER_NAMES = ("FRONT", "SIDE_LEFT", "SIDE_RIGHT", "REAR") + + +def _multilidar_range_frame( + gt_depth, recon_depth, pred_valid, laser, row, col, laser_hw, max_range=75.0, +): + """One (H,W,3) uint8 frame: per-blind-spot-lidar range image + mask. Rows = + lasers; cols = [GT range | recon range | GT mask | predicted-validity mask]. + The extra lidars are sparse returns, so each laser's (H,W) grid is scatter- + filled at its measured (row,col) pixels (GT + recon depth at SAME pixels).""" + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + L = int(laser_hw.shape[0]) + fig, axes = plt.subplots(L, 4, figsize=(18, 2.6 * L + 0.5), dpi=100, squeeze=False) + col_titles = ["GT range", "recon range", "GT mask", "pred validity"] + for li in range(L): + H, W = int(laser_hw[li, 0]), int(laser_hw[li, 1]) + gt_img = np.full((H, W), np.nan, np.float32) + rc_img = np.full((H, W), np.nan, np.float32) + gm = np.zeros((H, W), np.float32) + pm = np.zeros((H, W), np.float32) + idx = laser == li + r, c = row[idx], col[idx] + keep = (r >= 0) & (c >= 0) & (r < H) & (c < W) + r, c = r[keep], c[keep] + gt_img[r, c] = gt_depth[idx][keep] + rc_img[r, c] = recon_depth[idx][keep] + gm[r, c] = 1.0 + pm[r, c] = pred_valid[idx][keep].astype(np.float32) + name = _EXTRA_LASER_NAMES[li] if li < len(_EXTRA_LASER_NAMES) else f"laser {li}" + for j, (img, cmap, vmax) in enumerate( + [(gt_img, "turbo", max_range), (rc_img, "turbo", max_range), + (gm, "gray", 1.0), (pm, "gray", 1.0)] + ): + ax = axes[li, j] + ax.imshow(img, cmap=cmap, vmin=0, vmax=vmax, aspect="auto", interpolation="nearest") + ax.set_xticks([]); ax.set_yticks([]) + if li == 0: + ax.set_title(col_titles[j], fontsize=11) + if j == 0: + ax.set_ylabel(f"{name}\n({H}x{W})", fontsize=10) + fig.tight_layout() + arr = _fig_to_rgb(fig) + plt.close(fig) + return arr + + +# --------------------------------------------------------------------------- +# SSVAE-style latent spectral diagnostics (arXiv:2512.05394). See +# scripts/analyze_latent_spectral_ssvae.py for the standalone / documented +# version; these are the lightweight single-number forms logged at val time. +# --------------------------------------------------------------------------- + + +def _dct_matrix(n: int, device, dtype) -> torch.Tensor: + """Orthonormal DCT-II basis (n x n), DC at row 0.""" + idx = torch.arange(n, device=device, dtype=dtype) + k = idx.unsqueeze(1) + M = torch.cos((2.0 * idx + 1.0) * k * math.pi / (2.0 * n)) * math.sqrt(2.0 / n) + M[0, :] = M[0, :] / math.sqrt(2.0) + return M + + +def _dct3d_energy(z: torch.Tensor, Mt, Mh, Mw) -> torch.Tensor: + """z: (B, C, T, H, W). Global separable 3D-DCT; returns per-coef energy + |coef|^2 summed over (B, C): shape (T, H, W).""" + d = torch.einsum("ti,bcihw->bcthw", Mt, z) + d = torch.einsum("hj,bctjw->bcthw", Mh, d) + d = torch.einsum("wk,bcthk->bcthw", Mw, d) + return d.pow(2).sum(dim=(0, 1)) + + +def _spectral_centroid_lf(energy_grid: torch.Tensor): + """Energy-weighted centroid on the normalized L1-frequency axis + the + low-frequency (first-quartile) energy fraction. Returns + (centroid, bias_index, lf_frac) as python floats. White spectrum -> + centroid ~ 0.5, bias_index ~ 0; low-freq biased -> centroid < 0.5, + bias_index > 0 (more diffusable).""" + T, H, W = energy_grid.shape + dev = energy_grid.device + ii, jj, kk = torch.meshgrid( + torch.arange(T, device=dev), torch.arange(H, device=dev), + torch.arange(W, device=dev), indexing="ij", + ) + freq = (ii + jj + kk).double() + fmax = freq.max().clamp_min(1.0) + e = energy_grid.double() + tot = e.sum().clamp_min(1e-12) + centroid = float((freq / fmax * e).sum() / tot) + lf_frac = float(e[freq <= 0.25 * fmax].sum() / tot) + return centroid, 1.0 - 2.0 * centroid, lf_frac + + +# --- LCR local correlation (ported verbatim from the official SSVAE +# ssvae/modules/autoencoding/regularizers/calc_local_corr.py) ----------------- + + +def _pearson_autocorr(x: torch.Tensor, renorm: bool = True) -> torch.Tensor: + D = x.size(-1) + if renorm: + x = x - x.mean(dim=-1, keepdim=True) + x = x / (torch.norm(x, dim=-1, keepdim=True) + 1e-8) + sim = torch.matmul(x, x.transpose(1, 2)) + N = x.size(1) + mask = torch.triu(torch.ones(N, N, device=x.device), diagonal=1) + mean_corr = sim[:, mask == 1].mean() + return mean_corr if renorm else mean_corr / D + + +def _windowed_localcorr(latents: torch.Tensor, ws=(2, 2, 2)): + """latents: (B, D, F, H, W). Returns (LC_first, LC_video, LC_avg).""" + B, D, F, H, W = latents.shape + tw, hw, ww = ws + t = latents.reshape(B, D, F, H // hw, hw, W // ww, ww).permute( + 0, 2, 3, 5, 4, 6, 1, + ).reshape(B, F, H // hw * W // ww, hw * ww, D) + first = t[:, :1].reshape(-1, hw * ww, D) + lc_first = _pearson_autocorr(first) + if F > 1 and (F - 1) % tw == 0: + vid = t[:, 1:] + _, Fv, SWN, SN, _ = vid.size() + vid = vid.reshape(B, Fv // tw, tw, SWN, SN, D).permute( + 0, 1, 3, 2, 4, 5, + ).reshape(B * (Fv // tw) * SWN, tw * SN, D) + lc_video = _pearson_autocorr(vid) + lc_avg = (lc_first + lc_video) / 2 + else: + lc_video, lc_avg = None, lc_first + return lc_first, lc_video, lc_avg + + +class WandBLidarCallback(callback.Callback): + """Extends the base WandBCallback for Tokenizers.""" + + def __init__(self, config: Config, trainer: Trainer): + super().__init__(config, trainer) + + def on_train_start(self, model: Model, iteration: int = 0) -> None: + wandb_utils.init_wandb(self.config, model=model) + if distributed.is_rank0(): + self.start_iteration_time = time.time() + + def on_before_optimizer_step( + self, + model_ddp: distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int = 0, + ) -> None: # Log the curent learning rate. + if iteration % self.config.trainer.logging_iter == 0 and distributed.is_rank0(): + if model_ddp.module.network.training: + wandb.log({"optim/lr": scheduler.get_last_lr()[0]}, step=iteration) + wandb.log({"optim/grad_scale": grad_scaler.get_scale()}, step=iteration) + if model_ddp.module.disc is not None and model_ddp.module.disc.training: + wandb.log({"optim_disc/lr": scheduler.get_last_lr()[0]}, step=iteration) + wandb.log({"optim_disc/grad_scale": grad_scaler.get_scale()}, step=iteration) + + def on_training_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: # Log the timing results (over a number of iterations) and the training loss. + if (iteration % self.config.trainer.logging_iter == 0) and distributed.is_rank0(): + timer_results = self.trainer.training_timer.compute_average_results() + network = model.network if not isinstance(model.network, torch_OptimizedModule) else model.network._orig_mod + avg_time = (time.time() - self.start_iteration_time) / self.config.trainer.logging_iter + wandb.log({"timer/iter": avg_time}, step=iteration) + wandb.log({f"timer/{key}": value for key, value in timer_results.items()}, step=iteration) + wandb.log({"train/loss": loss}, step=iteration) + wandb.log({"iteration": iteration}, step=iteration) + for loss_key in output_batch.get("loss", dict()): + loss_val = output_batch["loss"][loss_key] + wandb.log({f"train/{loss_key}": loss_val}, step=iteration) + + self.trainer.training_timer.reset() + + def on_validation_start( + self, model: Model, dataloader_val: torch.utils.data.DataLoader, iteration: int = 0 + ) -> None: + # Cache for collecting data/output batches. + self._val_cache: dict[str, Any] = dict( + data_batches=[], + output_batches=[], + loss=torch.tensor(0.0, device="cuda"), + sample_size=torch.tensor(0, device="cuda"), + # Render one media batch per sensor dataset. Single-dataset + # validation still renders only its first batch. + media_logged_datasets=set(), + # Cross-dataset scalar metrics are reduced once at validation end; + # logging rank-0 batch values repeatedly at the same W&B step is + # both noisy and order-dependent. + dataset_metrics={}, + # SSVAE-style latent spectral accumulators (lazily shaped on the + # first lidar batch; reduced + logged in on_validation_end). + spec_energy=None, + spec_sum_xx=None, + spec_n=torch.tensor(0.0, device="cuda"), + lc_sum=torch.zeros(3, device="cuda"), + lc_n=torch.tensor(0.0, device="cuda"), + ) + + def _accumulate_dataset_metrics( + self, + dataset_tag: str, + metrics: dict[str, Any], + batch_size: int, + ) -> None: + dataset_cache = self._val_cache["dataset_metrics"].setdefault( + dataset_tag, {} + ) + device = self._val_cache["loss"].device + for name, value in metrics.items(): + if value is None: + continue + scalar = torch.as_tensor( + value, device=device, dtype=torch.float32 + ).detach().mean() + entry = dataset_cache.setdefault( + name, + { + "sum": torch.zeros((), device=device), + "count": torch.zeros((), device=device), + }, + ) + entry["sum"] += scalar * batch_size + entry["count"] += batch_size + + # Fixed t values used for noise-robustness eval (interpolative latent corruption). + # Skips t=0.0 since clean reconstruction is already covered by val/depth_mae. + _NOISE_LEVELS: tuple[float, ...] = (0.05, 0.10, 0.15, 0.20) + + @staticmethod + def _encoder_input(network, data_batch, input_key) -> torch.Tensor: + """Build the encoder input exactly as ``TransformerVAE.forward`` does. + + For ``mask_as_input`` nets the encoder expects a 2-channel + ``[depth, mask]`` tensor, but that concat lives in ``forward`` -- NOT in + ``encode`` -- so any callback that re-encodes (``encode(x)`` directly) + must replicate it, else the patch-embed conv (in_channels=2) gets a + 1-channel input and raises. Prefers the dataloader's explicit + ``loss_mask`` (correct under per-row norm), falls back to the same + ``depth > min+eps`` derivation ``forward`` uses. + """ + x = data_batch[input_key].float() + if getattr(network, "mask_as_input", False): + vm = data_batch.get("loss_mask", None) + if vm is not None: + valid = vm.to(x.dtype) + else: + valid = ( + x[:, :1] + > (network.mask_input_min_value + network.mask_input_eps) + ).to(x.dtype) + x = torch.cat([x, valid], dim=1) + return x + + @torch.no_grad() + def _render_utonia_pca(self, network, data_batch, input_key, output_batch) -> dict: + """PCA-RGB viz of the frozen Utonia teacher (the VF-loss alignment target). + + Logs (first val sample only, rank0): + * ``val/utonia_pca`` -- per-pixel teacher features PCA'd to RGB at the + FULL range resolution (reads like a semantic map). + * ``val/utonia_pca_recon`` -- [teacher(GT) | teacher(recon)] at FULL + resolution, SAME GT PCA basis/std (color-comparable), so divergence + shows where the recon loses foundation-model-perceived structure. + * ``val/utonia_align`` -- [pooled teacher | projected latent z'] at the + LATENT grid, SAME PCA basis (z' lives in the teacher's feature space + via the linear ``utonia_proj``), so aligned features share colors. + + No-op for non-utonia nets; best-effort (any failure -> warning). + """ + media: dict = {} + if not getattr(network, "utonia_align", False): + return media + try: + x = data_batch[input_key].float()[:1] # first sample only + if x.ndim == 4: + x = x.unsqueeze(2) + depth = x[:, :1] # (1, 1, T, H, W) + teacher = network.utonia(depth) # (1, D, T, H, W) + if teacher.ndim == 4: + teacher = teacher.unsqueeze(2) + feat = teacher[0] # (D, T, H, W) + valid_full = feat.abs().sum(0) > 0 # (T, H, W) + fv = feat.permute(1, 2, 3, 0)[valid_full] # (M, D) + if fv.shape[0] < 3: + return media + mean, V = _fit_pca_basis(fv) + rgb_full, full_std = _apply_pca_rgb(feat, valid_full, mean, V) + media["val/utonia_pca"] = wandb_rgb_media(rgb_full) + + # Teacher run on the RECONSTRUCTED output, PCA'd with the SAME GT + # basis (mean/V/std) so colors are directly comparable. Shows whether + # the recon preserves the foundation-model-perceived structure. + recon = output_batch.get(PREDICTION, None) + if recon is not None: + recon = recon.float()[:1] + if recon.ndim == 4: + recon = recon.unsqueeze(2) + recon_depth = recon[:, :1].clamp(-1, 1) # (1, 1, T, H, W) + teacher_r = network.utonia(recon_depth) + if teacher_r.ndim == 4: + teacher_r = teacher_r.unsqueeze(2) + feat_r = teacher_r[0] # (D, T, H, W) + valid_r = feat_r.abs().sum(0) > 0 + rgb_recon, _ = _apply_pca_rgb(feat_r, valid_r, mean, V, std3=full_std) + sbs_full = np.concatenate([rgb_full, rgb_recon], axis=2) # along W + media["val/utonia_pca_recon"] = wandb_rgb_media(sbs_full) + + # Alignment view at the latent grid: pooled teacher vs projected z'. + sample = output_batch.get("latent", None) + if sample is not None and hasattr(network, "utonia_proj"): + sample = sample[:1].float() # (1, z, Tz, Hz, Wz) + Tz, Hz, Wz = sample.shape[2], sample.shape[3], sample.shape[4] + tvalid = (feat.abs().sum(0, keepdim=True) > 0).to(feat.dtype)[None] + num = F.adaptive_avg_pool3d(teacher * tvalid, (Tz, Hz, Wz)) + den = F.adaptive_avg_pool3d(tvalid, (Tz, Hz, Wz)) + f_grid = (num / den.clamp_min(1e-6))[0] # (D, Tz, Hz, Wz) + vgrid = den[0, 0] > 0 # (Tz, Hz, Wz) + # z' = utonia_proj(sample), per-frame (Conv2d). B=1 -> fold T. + z2 = sample[0].permute(1, 0, 2, 3) # (Tz, z, Hz, Wz) + z_proj = network.utonia_proj(z2).permute(1, 0, 2, 3) # (D, Tz, Hz, Wz) + gv = f_grid.permute(1, 2, 3, 0)[vgrid] + if gv.shape[0] >= 3: + gmean, gV = _fit_pca_basis(gv) + t_rgb, gstd = _apply_pca_rgb(f_grid, vgrid, gmean, gV) + z_rgb, _ = _apply_pca_rgb(z_proj, vgrid, gmean, gV, std3=gstd) + sbs = np.concatenate([t_rgb, z_rgb], axis=2) # along W + media["val/utonia_align"] = wandb_rgb_media(_upsample_nn_rgb(sbs, 4)) + except Exception as e: # noqa: BLE001 + log.warning(f"utonia PCA viz failed: {e}") + return media + + def _compute_noise_robust_metrics( + self, + network, + data_batch: dict[str, torch.Tensor], + input_key: str, + target_images_unnorm: torch.Tensor, + valid_mask_target: torch.Tensor, + unnorm_args: dict, + dataset_config: dict, + render_media: bool = True, + ) -> tuple[dict[str, float], dict[str, object]]: + """Per-noise-level reconstruction + auto-consistency for decoder finetune runs. + + For each t in _NOISE_LEVELS, in normalized latent space: + z_t = (1 - t) * z_0 + t * gamma * eps + then: + depth_mae_t = MAE(unnormalize(decode(z_t, [t])), GT) + consistency_l2_t = RMS(encode(decode(z_t, [t]))_norm - z_0_norm) + and renders a side-by-side GT-vs-recon point cloud for visual inspection. + + Returns ({}, {}) when the network has no loaded latent_stats + (i.e. non-finetune networks), so this is a no-op there. + """ + if not getattr(network, "has_latent_stats", False): + return {}, {} + + # LTX networks route t into AdaLN-modulated decoder; plain VAE does not. + has_ltx = float(getattr(network, "denoising_t_max", 0.0)) > 0.0 + # gamma matches training-time noise scale (sigma_data for LTX, latent_norm_noise_sigma else). + gamma = ( + float(getattr(network, "sigma_data", 1.0)) + if has_ltx + else float(getattr(network, "latent_norm_noise_sigma", 1.0)) + ) + + metrics: dict[str, float] = {} + media: dict[str, object] = {} + x = self._encoder_input(network, data_batch, input_key) + T_input = x.shape[2] + + with torch.no_grad(): + z0, _ = network.encode(x) # sets network._input_T = T_input + latent_mean = network.latent_mean.to(z0) + latent_std = network.latent_std.to(z0) + z0_norm = (z0 - latent_mean) / latent_std + + try: + for t_val in self._NOISE_LEVELS: + B = z0_norm.shape[0] + t_view = torch.full( + (B,) + (1,) * (z0_norm.dim() - 1), + t_val, + device=z0.device, + dtype=z0.dtype, + ) + eps = torch.randn_like(z0_norm) * gamma + zt_norm = (1.0 - t_view) * z0_norm + t_view * eps + zt = zt_norm * latent_std + latent_mean + + # Restore _input_T (the consistency re-encode below mutates it). + network._input_T = T_input + if has_ltx: + t_scalar = torch.full( + (B,), t_val, device=z0.device, dtype=z0.dtype + ) + xt_hat_raw = network.decode(zt, t=t_scalar) + else: + xt_hat_raw = network.decode(zt) + + # Auto-consistency: re-encode the raw decode output (encoder + # expects pre-clamp / pre-undo_repeat (B,C,T,H,W) format). + zt_recon, _ = network.encode(xt_hat_raw) + zt_recon_norm = (zt_recon - latent_mean) / latent_std + consistency = ( + (zt_recon_norm - z0_norm).pow(2).mean().sqrt().item() + ) + metrics[f"val/consistency_l2_t{t_val:.2f}"] = consistency + + # Depth metric: mirror the existing unnormalize pipeline. + xt_hat = torch.clamp(xt_hat_raw.float(), -1, 1) + xt_hat = undo_row_col_temporal_repeat( + xt_hat, + dataset_config["repeat_row"], + dataset_config["repeat_col"], + dataset_config["repeat_temporal"], + ) + xt_unnorm_result = unnormalize_and_reduce_channels( + xt_hat, **unnorm_args + ) + if isinstance(xt_unnorm_result, tuple): + xt_unnorm = xt_unnorm_result[0] + valid_mask_t = xt_unnorm_result[1] + else: + xt_unnorm = xt_unnorm_result + valid_mask_t = valid_mask_target + valid = valid_mask_target & valid_mask_t + metrics[f"val/depth_mae_t{t_val:.2f}"] = ( + torch.abs(target_images_unnorm[valid] - xt_unnorm[valid]) + .mean() + .item() + ) + + # Side-by-side point cloud render for visual inspection + # (mirrors the clean recon path in on_validation_step_end). + if render_media and target_images_unnorm.ndim == 3: + media[f"val/range_map_t{t_val:.2f}"] = wandb_range_image( + target_images_unnorm, xt_unnorm + ) + elif render_media and target_images_unnorm.ndim == 4: + media[f"val/range_map_t{t_val:.2f}"] = wandb_range_video( + target_images_unnorm, xt_unnorm + ) + finally: + network._input_T = T_input + + return metrics, media + + @torch.no_grad() + def _accumulate_spectral_stats(self, network, data_batch, input_key) -> None: + """Encode the batch and accumulate SSVAE-style latent spectral + statistics into ``self._val_cache``. Best-effort: any failure is + swallowed so it can never break validation.""" + # A single spectral tensor cannot aggregate native sensor grids with + # different latent H/W. Avoid silently reporting only the first sensor; + # cross-dataset runs use the per-sensor reconstruction diagnostics. + if getattr(network, "uses_sensor_metadata", False): + return + try: + x = self._encoder_input(network, data_batch, input_key) + prev_T = getattr(network, "_input_T", None) + z, _ = network.encode(x) # (B, C, T, H, W); mutates _input_T + if prev_T is not None: + network._input_T = prev_T + + # Per-frame tokenizers (e.g. copilot4d) fold time into batch and + # return a 4D latent (B, C, H, W). Treat that as a single latent + # frame (T=1) so the analysis below logs instead of silently + # skipping on the 5D unpack. + if z.ndim == 4: + z = z.unsqueeze(2) + + # Per-channel standardize (SSVAE preprocessing): use loaded stats + # when available, else this batch's per-channel moments. + if getattr(network, "has_latent_stats", False): + zc = (z - network.latent_mean.to(z)) / network.latent_std.to(z) + else: + m = z.mean(dim=(0, 2, 3, 4), keepdim=True) + s = z.std(dim=(0, 2, 3, 4), keepdim=True).clamp_min(1e-6) + zc = (z - m) / s + zc = zc.float() + B, C, T, H, W = zc.shape + dev = zc.device + + # 3D-DCT energy (cache the per-axis basis matrices by latent shape). + if getattr(self, "_dct_cache_key", None) != (T, H, W): + self._dct_mt = _dct_matrix(T, dev, torch.float32) + self._dct_mh = _dct_matrix(H, dev, torch.float32) + self._dct_mw = _dct_matrix(W, dev, torch.float32) + self._dct_cache_key = (T, H, W) + e = _dct3d_energy(zc, self._dct_mt, self._dct_mh, self._dct_mw) + + c = self._val_cache + if c["spec_energy"] is None: + c["spec_energy"] = torch.zeros_like(e, dtype=torch.float64) + c["spec_sum_xx"] = torch.zeros(C, C, dtype=torch.float64, device=dev) + c["spec_energy"] += e.double() + v = zc.permute(0, 2, 3, 4, 1).reshape(-1, C).double() + c["spec_sum_xx"] += v.t() @ v + c["spec_n"] += v.shape[0] + + # Local correlation (size-2 windows; crop to divisible dims). + Tc = 1 + 2 * ((T - 1) // 2) if T > 1 else 1 + Hc, Wc = 2 * (H // 2), 2 * (W // 2) + if Hc >= 2 and Wc >= 2: + lf, lv, la = _windowed_localcorr(zc[:, :, :Tc, :Hc, :Wc]) + c["lc_sum"][0] += lf.double() + c["lc_sum"][1] += lv.double() if lv is not None else 0.0 + c["lc_sum"][2] += la.double() + c["lc_n"] += 1.0 + except Exception as exc: # noqa: BLE001 + log.warning(f"spectral-stats accumulation skipped: {exc}") + + def _get_viz_ray_dirs(self, dataset_config): + """Cached (H, W, 3) ray-direction override for the point-cloud viz. + + ``None`` for the default Pandar128 geometry; the sensor's measured + elevation/azimuth tables for the NCore backends (the viz renderer + otherwise asserts on the 128-row Pandar128 table vs Waymo's 64 / nuScenes' + 32 rows).""" + if getattr(self, "_viz_ray_dirs_cached", False): + return self._viz_ray_dirs + self._viz_ray_dirs = None + _backend = dataset_config.get("dataset_backend", "radym") + if _backend == "waymo_ncore": + from tokenizer.training.datasets.lidar_datasets.waymo_ncore import ( + load_waymo_ray_directions, + ) + self._viz_ray_dirs = load_waymo_ray_directions( + root_path=dataset_config["root_path"], + filter_list_path=dataset_config.get("filter_list_path", None), + lidar_id=dataset_config.get("lidar_id", "lidar_top"), + resample_width=dataset_config.get("resample_width", -1), + ) + elif _backend == "nuscenes_ncore": + from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import ( + load_nuscenes_ray_directions, + ) + self._viz_ray_dirs = load_nuscenes_ray_directions( + root_path=dataset_config["root_path"], + filter_list_path=dataset_config.get("filter_list_path", None), + lidar_id=dataset_config.get("lidar_id", "lidar_top"), + resample_width=dataset_config.get("resample_width", -1), + center_vehicle_forward=dataset_config.get( + "center_vehicle_forward", False + ), + ) + self._viz_ray_dirs_cached = True + return self._viz_ray_dirs + + def on_validation_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: # Collect the validation batch and aggregate the overall loss. + # Get data config + sensor_names = data_batch.get("sensor_dataset_name") + if sensor_names is not None: + if len(set(sensor_names)) != 1: + raise ValueError( + "Cross-dataset validation batches must be sensor-homogeneous" + ) + dataset_name = sensor_names[0] + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + extra_config = OmegaConf.create( + self.config.dataloader_val.dataset.shared_overrides + ) + per_dataset_overrides = self.config.dataloader_val.dataset.get( + "per_dataset_overrides", {} + ) + extra_config = OmegaConf.merge( + extra_config, per_dataset_overrides.get(dataset_name, {}) + ) + else: + dataset_name = self.config.dataloader_val.dataset.dataset_name + dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name]) + extra_config = OmegaConf.create(self.config.dataloader_val.dataset) + dataset_config = OmegaConf.merge(dataset_config, extra_config) + dataset_config = OmegaConf.to_container(dataset_config, resolve=True) + if sensor_names is None: + dataset_tag = "default" + val_prefix = "val" + else: + dataset_tag = ( + "pandaset" + if "pandaset" in dataset_name + else "nuscenes" + if "nuscenes" in dataset_name + else "waymo" + if "waymo" in dataset_name + else "pandar" + ) + val_prefix = f"val/{dataset_tag}" + # Geometry override for the point-cloud viz (None = Pandar128 default). + sensor_rays = data_batch.get("sensor_ray_directions") + viz_ray_dirs = ( + sensor_rays[0].detach().cpu() + if sensor_rays is not None + else self._get_viz_ray_dirs(dataset_config) + ) + + # Collect the validation batch and aggregate the overall loss. + _input_key = model.get_input_key(data_batch) + batch_size = data_batch[_input_key].shape[0] + self._val_cache["loss"] += loss * batch_size + self._val_cache["sample_size"] += batch_size + + # Cross-dataset validation renders the first batch from each sensor. + # Metrics / spectral stats below still run every batch. + render_media = ( + dataset_tag not in self._val_cache["media_logged_datasets"] + ) + + # Use recon_target as reference for consistency with loss (side-by-side and lidar metrics) + target_images = data_batch["recon_target"].float() # shape: [N, C, H, W] or [N, C, T, H, W] + output_images = output_batch[PREDICTION].float() + + if dataset_config.get("intensity_only", False): + # An intensity-only VAE has no depth channel to unproject. Evaluate + # only on the explicit depth-derived return mask and avoid reporting + # misleading depth/point-cloud metrics from intensity channel 0. + valid = data_batch.get("loss_mask") + if valid is None: + raise ValueError( + "intensity-only validation requires an explicit loss_mask" + ) + valid = valid[:, :1].to(torch.bool) + target_intensity = target_images[:, :1].clamp(-1, 1) + output_intensity = output_images[:, :1].clamp(-1, 1) + selected = valid.expand_as(target_intensity) + selected_f = selected.to(target_intensity.dtype) + count = selected_f.sum().clamp_min(1.0) + normalized_error = output_intensity - target_intensity + normalized_mae = ( + normalized_error.abs() * selected_f + ).sum() / count + normalized_rmse = torch.sqrt( + (normalized_error.square() * selected_f).sum() / count + ) + + if dataset_config.get("intensity_transform", "legacy") == "log1p": + scale = target_intensity.new_tensor(np.log(2.0)) + target_linear = torch.expm1( + (target_intensity + 1.0) * 0.5 * scale + ) + output_linear = torch.expm1( + (output_intensity + 1.0) * 0.5 * scale + ) + else: + target_linear = (target_intensity + 1.0) * 0.5 + output_linear = (output_intensity + 1.0) * 0.5 + linear_error = output_linear - target_linear + linear_mae = (linear_error.abs() * selected_f).sum() / count + linear_rmse = torch.sqrt( + (linear_error.square() * selected_f).sum() / count + ) + + scalar_metrics: dict[str, Any] = { + "loss": loss, + "intensity_normalized_mae": normalized_mae, + "intensity_normalized_rmse": normalized_rmse, + "intensity_mae": linear_mae, + "intensity_rmse": linear_rmse, + } + scalar_metrics.update(output_batch.get("loss", {})) + if sensor_names is not None: + self._accumulate_dataset_metrics( + dataset_tag, scalar_metrics, batch_size + ) + elif wandb.run is not None: + wandb.log( + { + f"{val_prefix}/{key}": value + for key, value in scalar_metrics.items() + }, + step=iteration, + ) + + if render_media and wandb.run is not None: + target_viz = torch.where( + valid, target_linear, torch.zeros_like(target_linear) + ) + output_viz = torch.where( + valid, output_linear, torch.zeros_like(output_linear) + ) + if target_viz.ndim == 5: + media = wandb_intensity_video( + target_viz[:1, 0], output_viz[:1, 0] + ) + else: + media = wandb_intensity_image( + target_viz[:1, 0], output_viz[:1, 0] + ) + wandb.log( + {f"{val_prefix}/intensity_reconstruction": [media]}, + step=iteration, + ) + self._val_cache["media_logged_datasets"].add(dataset_tag) + return + + # Invert per-row z-score back to [-1, 1] space so all downstream viz / + # metrics / clamps below operate in the dataset's native normalized + # space (no-op when per-row norm is disabled). + _per_row_normalizer = get_per_row_normalizer( + dataset_config.get("per_row_normalize", False), + dataset_config.get("per_row_stats_path", ""), + min_range=dataset_config["min_range"], + max_range=dataset_config["max_range"], + min_value=dataset_config["min_value"], + smooth_sigma=dataset_config.get("per_row_smooth_sigma", 5.0), + log_depth=False, + ) + target_images = invert_per_row_norm(target_images, _per_row_normalizer) + output_images = invert_per_row_norm(output_images, _per_row_normalizer) + + result_image = torch.cat((target_images, output_images), dim=-1) + n_channels = result_image.shape[1] + + n_channels = result_image.shape[1] + wandb_media = None + + # Raw channel visualization only works for 1 or 3 channels (mono/repeat). + # Dual-channel (range+intensity) is visualized properly below via colormapped images. + if render_media and dataset_config["process_output"] != "band" and n_channels in (1, 3): + + if result_image.ndim == 5 and result_image.shape[2] > 1: + wandb_media = wandb_video(result_image, iteration) + elif result_image.ndim == 5 and result_image.shape[2] == 1: + wandb_media = wandb_image(result_image[:, :, 0, ...], iteration) + else: + wandb_media = wandb_image(result_image, iteration) + + # Masked reconstruction range-image: same [GT | recon] layout as + # val/lidar_reconstruction, but the recon panel has its predicted + # no-return pixels (sigmoid(validity_logit) < 0.5) set to the no-return + # clamp (min_value) -- i.e. what the model would actually emit at + # inference. Only for validity-head nets (predict_validity=True). + # Built from the pre-de-repeat tensors so it aligns with wandb_media. + wandb_mask_recon_media = None + _validity_logits = output_batch.get("validity_logits", None) + if ( + render_media + and _validity_logits is not None + and dataset_config["process_output"] != "band" + and n_channels in (1, 3) + ): + _pred_keep = torch.sigmoid(_validity_logits.float())[:, :1] >= 0.5 + _masked_out = torch.where( + _pred_keep, output_images, torch.full_like(output_images, dataset_config["min_value"]) + ) + _result_masked = torch.cat((target_images, _masked_out), dim=-1) + if _result_masked.ndim == 5 and _result_masked.shape[2] > 1: + wandb_mask_recon_media = wandb_video(_result_masked, iteration) + elif _result_masked.ndim == 5 and _result_masked.shape[2] == 1: + wandb_mask_recon_media = wandb_image(_result_masked[:, :, 0, ...], iteration) + else: + wandb_mask_recon_media = wandb_image(_result_masked, iteration) + + # get the range_map + is_lidar = data_batch["data_type"][0] == "lidar" + has_intensity = dataset_config.get("load_intensity", False) + # Predicted-validity-mask media (only populated when the network has a + # validity head, i.e. predict_validity=True). Init here so the + # logging block never hits an undefined name. + wandb_mask_media = None + wandb_pcd_masked_media = None + wandb_range_map_media = None + wandb_multilidar_media = None + wandb_multilidar_pcd_media = None + wandb_multilidar_range_media = None + utonia_media: dict = {} + assert dataset_config["min_value"] == -1 + if is_lidar: + # target_images is recon_target (set above); unnormalize for range-map metrics + intensity_transform = dataset_config.get( + "intensity_transform", "legacy" + ) + target_images = torch.clamp(target_images, -1, 1) + output_images = torch.clamp(output_images, -1, 1) + + # reduce row and col repeat + target_images = undo_row_col_temporal_repeat( + target_images, + dataset_config["repeat_row"], + dataset_config["repeat_col"], + dataset_config["repeat_temporal"], + ) + output_images = undo_row_col_temporal_repeat( + output_images, + dataset_config["repeat_row"], + dataset_config["repeat_col"], + dataset_config["repeat_temporal"], + ) + # Cross-dataset batches carry true rays on the repeated model + # grid. Validation media is rendered after undoing those repeats, + # so reduce the ray grid in lockstep with the range map. + if viz_ray_dirs is not None: + map_hw = tuple(target_images.shape[-2:]) + ray_hw = tuple(viz_ray_dirs.shape[:2]) + repeat_row = int(dataset_config["repeat_row"]) + repeat_col = int(dataset_config["repeat_col"]) + repeated_hw = ( + map_hw[0] * repeat_row, + map_hw[1] * repeat_col, + ) + if ray_hw == repeated_hw: + viz_ray_dirs = viz_ray_dirs[ + ::repeat_row, ::repeat_col + ] + log_intensity_target = ( + target_images[:, -1] + if has_intensity and intensity_transform == "log1p" + else None + ) + log_intensity_recon = ( + output_images[:, -1] + if has_intensity and intensity_transform == "log1p" + else None + ) + + process_output = dataset_config["process_output"] + unnorm_args = dict( + max_range=dataset_config["max_range"], + min_range=dataset_config["min_range"], + min_value=dataset_config["min_value"], + inverse_depth=dataset_config["inverse_depth"], + process_output=process_output, + near_buffer=0.5, + far_buffer=0.5, + inv_depth_threshold=dataset_config["inv_depth_threshold"], + num_bands=dataset_config.get("num_bands", 3), + has_intensity=has_intensity, + intensity_transform=intensity_transform, + ) + + target_unnorm_result = unnormalize_and_reduce_channels(target_images, **unnorm_args) + output_unnorm_result = unnormalize_and_reduce_channels(output_images, **unnorm_args) + + if has_intensity: + target_images_unnorm, valid_mask_target, intensity_target = target_unnorm_result + output_images_unnorm, valid_mask_recon, intensity_recon = output_unnorm_result + else: + target_images_unnorm, valid_mask_target = target_unnorm_result + output_images_unnorm, valid_mask_recon = output_unnorm_result + + valid_mask = valid_mask_target & valid_mask_recon + + # --- depth point cloud visualization (original: fixed colors) --- + if render_media: + if target_images_unnorm.ndim == 3: + wandb_range_map_media = wandb_range_image(target_images_unnorm, output_images_unnorm, ray_directions=viz_ray_dirs) + elif target_images_unnorm.ndim == 4: + wandb_range_map_media = wandb_range_video(target_images_unnorm, output_images_unnorm, ray_directions=viz_ray_dirs) + + # --- multi-lidar (blind-spot) reconstruction viz --- + # Overlay the extra lidars (each a distinct color) with the top lidar + # (gray) in ONE scene, GT | recon. Perspective PCD + BEV/side panels + # + per-laser range/mask. VIDEO: one frame per temporal step (sample + # 0), packed into an mp4; single-frame -> one image. + _extra_recon = output_batch.get("extra_recon_points", None) + if render_media and _extra_recon is not None and viz_ray_dirs is not None: + _rd = np.asarray(viz_ray_dirs, dtype=np.float32) # (H, W, 3) + _is_video_ml = target_images_unnorm.ndim == 4 + T_ml = target_images_unnorm.shape[1] if _is_video_ml else 1 + + # Top-lidar range (sample 0, all frames) -> np. + _tgt = target_images_unnorm[0] # (T,H,W) video / (H,W) image + _rec = output_images_unnorm[0] + if torch.is_tensor(_tgt): + _tgt = _tgt.detach().cpu().numpy() + if torch.is_tensor(_rec): + _rec = _rec.detach().cpu().numpy() + # Predicted validity (sample 0, all frames) to mask the top recon + # (matches val/lidar_reconstruction_mask). Falls back to range>0. + _pp = None + _vlog = output_batch.get("validity_logits", None) + if _vlog is not None: + _v = undo_row_col_temporal_repeat( + _vlog.float(), + dataset_config["repeat_row"], + dataset_config["repeat_col"], + dataset_config["repeat_temporal"], + ) + _v = torch.sigmoid(_v)[:, 0] # (N, [T,] H, W) + _pp = _v[0].detach().cpu().numpy() # (T,H,W) / (H,W) + + _laser_t = data_batch.get("extra_laser", None) + _op_t = output_batch.get("extra_recon_opacity", None) + _row_t = data_batch.get("extra_row", None) + _col_t = data_batch.get("extra_col", None) + _hw_t = data_batch.get("extra_laser_hw", None) + _origin_t = data_batch.get("extra_ray_origin", None) + _have_range = _row_t is not None and _hw_t is not None and _origin_t is not None + _laser_hw = _hw_t[0].cpu().numpy() if _have_range else None # (L,2) clip-const + + def _top_pts(t): + tgt = _tgt[t] if _is_video_ml else _tgt + rec = _rec[t] if _is_video_ml else _rec + tm = tgt > 0 + rmask = rec > 0 + if _pp is not None: + pp = _pp[t] if _is_video_ml else _pp + rmask = rmask & (pp >= 0.5) + return ( + (_rd[tm] * tgt[tm][:, None]).astype(np.float32), + (_rd[rmask] * rec[rmask][:, None]).astype(np.float32), + ) + + def _extra_at(t): + # output_batch extras are (B*T, K, ...); sample 0 occupies + # rows 0..T-1, so frame t == row t. data_batch extras are + # (B, T, K, ...) -> [0, t]. + ex_gt = output_batch["extra_gt_points"][t].float().cpu().numpy() + ex_rec = _extra_recon[t].float().cpu().numpy() + ex_val = output_batch["extra_valid_points"][t].float().cpu().numpy() + ex_laser = ( + _laser_t[0, t].reshape(-1).cpu().numpy() + if _laser_t is not None + else np.zeros(ex_val.shape[0], dtype=np.int64) + ) + ex_keep = (_op_t[t].float().cpu().numpy() >= 0.5) if _op_t is not None else None + return ex_gt, ex_rec, ex_val, ex_laser, ex_keep + + per_frame = [(_top_pts(t), _extra_at(t)) for t in range(T_ml)] + + # Fixed BEV zoom across frames (stable video): union of GT extras. + _all_xy = [ + ex_gt[ex_val.astype(bool)][:, :2] + for (_, (ex_gt, _, ex_val, _, _)) in per_frame + if ex_val.astype(bool).any() + ] + if _all_xy: + _R_ml = float(np.clip(np.percentile(np.abs(np.concatenate(_all_xy, 0)), 99) * 1.3, 15.0, 80.0)) + else: + _R_ml = 40.0 + + pcd_frames, bev_frames, range_frames = [], [], [] + for t, ((top_gt_pts, top_rec_pts), (ex_gt, ex_rec, ex_val, ex_laser, ex_keep)) in enumerate(per_frame): + pcd_frames.append(_multilidar_pcd_frame( + top_gt_pts, top_rec_pts, ex_gt, ex_rec, ex_val, ex_laser, ex_keep=ex_keep, + )) + bev_frames.append(_multilidar_bev_frame( + top_gt_pts, top_rec_pts, ex_gt, ex_rec, ex_val, ex_laser, ex_keep=ex_keep, R=_R_ml, + )) + if _have_range: + ex_row = _row_t[0, t].reshape(-1).cpu().numpy() + ex_col = _col_t[0, t].reshape(-1).cpu().numpy() + origin_t = _origin_t[0, t].reshape(-1, 3).float().cpu().numpy() # (K,3) + gt_depth = data_batch["extra_gt_range"][0, t].reshape(-1).float().cpu().numpy() + recon_depth = np.linalg.norm(ex_rec - origin_t, axis=1) + pred_valid = ex_keep if ex_keep is not None else ex_val.astype(bool) + range_frames.append(_multilidar_range_frame( + gt_depth, recon_depth, pred_valid, + ex_laser, ex_row, ex_col, _laser_hw, + max_range=float(dataset_config["max_range"]), + )) + + wandb_multilidar_pcd_media = _frames_to_media(pcd_frames) + wandb_multilidar_media = _frames_to_media(bev_frames) + if range_frames: + wandb_multilidar_range_media = _frames_to_media(range_frames) + + # --- depth metrics --- + # For validity-head nets, evaluate depth ONLY over GT valid returns + # (valid_mask_target) -- the region the depth loss is trained on + # (mask_invalid_depth). The recon's depth at no-return pixels is + # unsupervised garbage; intersecting with recon-in-range + # (valid_mask) would optimistically drop the recon's worst + # out-of-range pixels. Non-validity nets keep the prior region. + has_validity_head = output_batch.get("validity_logits", None) is not None + depth_metric_mask = valid_mask_target if has_validity_head else valid_mask + range_map_target = target_images_unnorm[depth_metric_mask] + range_map_recon = output_images_unnorm[depth_metric_mask] + + mae = torch.abs(range_map_target - range_map_recon).mean().item() + rmse = torch.sqrt(torch.mean((range_map_target - range_map_recon) ** 2)).item() + relative_error = (torch.abs(range_map_target - range_map_recon) / (range_map_target + 1e-6)).mean().item() + + # --- noise-robustness metrics (only for decoder finetune runs) --- + network = ( + model.network + if not isinstance(model.network, torch_OptimizedModule) + else model.network._orig_mod + ) + noise_metrics, noise_media = self._compute_noise_robust_metrics( + network=network, + data_batch=data_batch, + input_key=_input_key, + target_images_unnorm=target_images_unnorm, + valid_mask_target=valid_mask_target, + unnorm_args=unnorm_args, + dataset_config=dataset_config, + render_media=render_media, + ) + + # SSVAE-style latent spectral diagnostics (accumulated across + # val batches, reduced + logged in on_validation_end). + self._accumulate_spectral_stats(network, data_batch, _input_key) + + # Utonia (PTv3) teacher PCA-RGB viz (VF-loss alignment target). + # rank0 + first batch only (one extra frozen PTv3 forward). + if render_media and distributed.is_rank0(): + utonia_media = self._render_utonia_pca( + network, data_batch, _input_key, output_batch + ) + + # --- predicted validity (raydrop) mask + mask-filtered points --- + # Present only when the network has a validity head + # (predict_validity=True). `validity_logits` are at full output + # resolution, so apply the SAME row/col/temporal de-repeat used + # for the range maps before comparing / filtering. + validity_logits = output_batch.get("validity_logits", None) + pred_prob = None # set below when a validity head is present + if render_media and validity_logits is not None: + vlog = undo_row_col_temporal_repeat( + validity_logits.float(), + dataset_config["repeat_row"], + dataset_config["repeat_col"], + dataset_config["repeat_temporal"], + ) + pred_prob = torch.sigmoid(vlog)[:, 0] # (N, [T,] H, W) + thr = dataset_config["min_value"] + 0.02 + # GT validity for the viz. Prefer the dataloader's explicit + # pre-per-row mask (per-row z-scoring breaks the depth>thr + # derivation); fall back to thresholding the (min-max) depth. + _explicit_valid = data_batch.get("loss_mask", None) + if _explicit_valid is not None: + _ev = undo_row_col_temporal_repeat( + _explicit_valid.float(), + dataset_config["repeat_row"], + dataset_config["repeat_col"], + dataset_config["repeat_temporal"], + ) + gt_valid = _ev[:, 0] # (N, [T,] H, W) + else: + gt_valid = (target_images[:, 0] > thr).float() # (N, [T,] H, W) + # Apply the predicted mask: drop points the decoder marks as + # no-return (prob < 0.5) before rendering the recon points. + output_masked = torch.where( + pred_prob >= 0.5, + output_images_unnorm, + torch.zeros_like(output_images_unnorm), + ) + if output_images_unnorm.ndim == 3: + wandb_mask_media = wandb_mask_image(gt_valid, pred_prob) + wandb_pcd_masked_media = wandb_range_image( + target_images_unnorm, output_masked, ray_directions=viz_ray_dirs + ) + elif output_images_unnorm.ndim == 4: + wandb_mask_media = wandb_mask_video(gt_valid, pred_prob) + wandb_pcd_masked_media = wandb_range_video( + target_images_unnorm, output_masked, ray_directions=viz_ray_dirs + ) + + # --- intensity visualizations and metrics --- + wandb_intensity_media = None + wandb_intensity_mask_media = None + wandb_pcd_intensity_media = None + wandb_pcd_intensity_mask_media = None + intensity_mae = None + intensity_rmse = None + intensity_log_mae = None + intensity_high_log_mae = None + if has_intensity: + int_gt = intensity_target + int_re = intensity_recon + int_gt_viz = int_gt + int_re_viz = int_re + + # intensity range image (colormapped side-by-side) + if render_media: + if int_gt.ndim == 3: + wandb_intensity_media = wandb_intensity_image( + int_gt_viz, int_re_viz + ) + elif int_gt.ndim == 4: + wandb_intensity_media = wandb_intensity_video( + int_gt_viz, int_re_viz + ) + + # Masked intensity recon: same [GT | recon] colormapped layout, + # but the recon panel's predicted no-return pixels + # (sigmoid(validity_logit) < 0.5) are zeroed -- the intensity + # counterpart of `val/lidar_reconstruction_mask` (depth). Shows + # whether the predicted raydrop mask lines up with intensity. + if pred_prob is not None: + int_re_masked = torch.where( + pred_prob >= 0.5, + int_re_viz, + torch.zeros_like(int_re_viz), + ) + if int_gt.ndim == 3: + wandb_intensity_mask_media = wandb_intensity_image( + int_gt_viz, int_re_masked + ) + elif int_gt.ndim == 4: + wandb_intensity_mask_media = wandb_intensity_video( + int_gt_viz, int_re_masked + ) + + # point cloud colored by intensity + tgt_np = target_images_unnorm.cpu().numpy() + out_np = output_images_unnorm.cpu().numpy() + int_gt_np = int_gt_viz.cpu().numpy() + int_re_np = int_re_viz.cpu().numpy() + if tgt_np.ndim == 3: + wandb_pcd_intensity_media = wandb_range_image_intensity( + tgt_np, out_np, int_gt_np, int_re_np, ray_directions=viz_ray_dirs + ) + elif tgt_np.ndim == 4: + wandb_pcd_intensity_media = wandb_range_video_intensity( + tgt_np, out_np, int_gt_np, int_re_np, ray_directions=viz_ray_dirs + ) + + # masked point cloud colored by intensity: recon points the + # decoder marks as no-return (prob < 0.5) are dropped via the + # zeroed `output_masked` depth (range 0 < min_range filters + # them out) and the matching `int_re_masked` coloring. The + # intensity counterpart of `val/range_map_masked`. + if pred_prob is not None: + out_masked_np = output_masked.cpu().numpy() + int_re_masked_np = int_re_masked.cpu().numpy() + if tgt_np.ndim == 3: + wandb_pcd_intensity_mask_media = wandb_range_image_intensity( + tgt_np, out_masked_np, int_gt_np, int_re_masked_np, ray_directions=viz_ray_dirs + ) + elif tgt_np.ndim == 4: + wandb_pcd_intensity_mask_media = wandb_range_video_intensity( + tgt_np, out_masked_np, int_gt_np, int_re_masked_np, ray_directions=viz_ray_dirs + ) + + # intensity metrics (on valid depth pixels; same region as the + # depth metrics -- GT valid returns for validity-head nets). + int_gt_valid = int_gt[depth_metric_mask] + int_re_valid = int_re[depth_metric_mask] + intensity_mae = torch.abs(int_gt_valid - int_re_valid).mean().item() + intensity_rmse = torch.sqrt(torch.mean((int_gt_valid - int_re_valid) ** 2)).item() + if intensity_transform == "log1p": + log_gt = log_intensity_target[depth_metric_mask] + log_re = log_intensity_recon[depth_metric_mask] + intensity_log_mae = torch.abs(log_gt - log_re).mean().item() + high_thr = torch.quantile(log_gt.float(), 0.95) + high = log_gt >= high_thr + intensity_high_log_mae = torch.abs( + log_gt[high] - log_re[high] + ).mean().item() + + else: + mae = None + wandb_range_map_media = None + has_intensity = False + noise_metrics = {} + noise_media: dict[str, object] = {} + + scalar_metrics: dict[str, Any] = {"loss": loss} + if mae is not None: + scalar_metrics.update( + depth_mae=mae, + depth_rmse=rmse, + depth_relative_error=relative_error, + ) + scalar_metrics.update( + { + key.removeprefix("val/"): value + for key, value in noise_metrics.items() + } + ) + if has_intensity and intensity_mae is not None: + scalar_metrics.update( + intensity_mae=intensity_mae, + intensity_rmse=intensity_rmse, + ) + if intensity_log_mae is not None: + scalar_metrics.update( + intensity_log_mae=intensity_log_mae, + intensity_high95_log_mae=intensity_high_log_mae, + ) + scalar_metrics.update(output_batch.get("loss", {})) + scalar_metrics.update( + { + metric_key.upper(): metric_val + for metric_key, metric_val in output_batch.get( + "metric", {} + ).items() + } + ) + if sensor_names is not None: + self._accumulate_dataset_metrics( + dataset_tag, scalar_metrics, batch_size + ) + + if wandb.run is not None: + if sensor_names is None: + wandb.log( + { + f"{val_prefix}/{key}": value + for key, value in scalar_metrics.items() + }, + step=iteration, + ) + for k, m in noise_media.items(): + scoped_key = f"{val_prefix}/{k.removeprefix('val/')}" + wandb.log({scoped_key: [m]}, step=iteration) + + if wandb_media is not None: + if is_lidar: + wandb.log( + {f"{val_prefix}/lidar_reconstruction": [wandb_media]}, + step=iteration, + ) + else: + wandb.log( + {f"{val_prefix}/rgb_reconstruction": [wandb_media]}, + step=iteration, + ) + + if wandb_range_map_media is not None: + wandb.log( + {f"{val_prefix}/range_map": [wandb_range_map_media]}, + step=iteration, + ) + + if wandb_multilidar_media is not None: + wandb.log( + {f"{val_prefix}/multilidar_bev": [wandb_multilidar_media]}, + step=iteration, + ) + if wandb_multilidar_pcd_media is not None: + wandb.log( + {f"{val_prefix}/multilidar_pcd": [wandb_multilidar_pcd_media]}, + step=iteration, + ) + if wandb_multilidar_range_media is not None: + wandb.log( + { + f"{val_prefix}/multilidar_range": [ + wandb_multilidar_range_media + ] + }, + step=iteration, + ) + + if wandb_intensity_media is not None: + wandb.log( + {f"{val_prefix}/intensity_map": [wandb_intensity_media]}, + step=iteration, + ) + if wandb_intensity_mask_media is not None: + wandb.log( + { + f"{val_prefix}/range_map_intensity_mask": [ + wandb_intensity_mask_media + ] + }, + step=iteration, + ) + if wandb_pcd_intensity_media is not None: + wandb.log( + {f"{val_prefix}/pcd_intensity": [wandb_pcd_intensity_media]}, + step=iteration, + ) + if wandb_pcd_intensity_mask_media is not None: + wandb.log( + { + f"{val_prefix}/pcd_intensity_masked": [ + wandb_pcd_intensity_mask_media + ] + }, + step=iteration, + ) + + if wandb_mask_media is not None: + wandb.log( + {f"{val_prefix}/validity_mask": [wandb_mask_media]}, + step=iteration, + ) + if wandb_pcd_masked_media is not None: + wandb.log( + {f"{val_prefix}/range_map_masked": [wandb_pcd_masked_media]}, + step=iteration, + ) + if wandb_mask_recon_media is not None: + wandb.log( + { + f"{val_prefix}/lidar_reconstruction_mask": [ + wandb_mask_recon_media + ] + }, + step=iteration, + ) + + for _k, _m in utonia_media.items(): + scoped_key = f"{val_prefix}/{_k.removeprefix('val/')}" + wandb.log({scoped_key: [_m]}, step=iteration) + + # Set on all ranks so every rank skips later media for this sensor. + if render_media: + self._val_cache["media_logged_datasets"].add(dataset_tag) + + def on_before_dataloading(self, iteration: int = 0) -> None: + if iteration % self.config.trainer.logging_iter == 0 and distributed.is_rank0(): + self.start_iteration_time = time.time() + + def on_validation_end(self, model: Model, iteration: int = 0) -> None: + # Compute the average validation loss across all devices. + dist.all_reduce(self._val_cache["loss"], op=dist.ReduceOp.SUM) + dist.all_reduce(self._val_cache["sample_size"], op=dist.ReduceOp.SUM) + loss = self._val_cache["loss"].item() / self._val_cache["sample_size"] + + # Reduce SSVAE-style latent spectral accumulators across ranks. The + # ``spec_energy is not None`` guard is symmetric across ranks (the run + # is lidar-or-not for all of them), so the collectives stay matched. + c = self._val_cache + spectral = None + if c.get("spec_energy") is not None: + dist.all_reduce(c["spec_energy"], op=dist.ReduceOp.SUM) + dist.all_reduce(c["spec_sum_xx"], op=dist.ReduceOp.SUM) + dist.all_reduce(c["spec_n"], op=dist.ReduceOp.SUM) + dist.all_reduce(c["lc_sum"], op=dist.ReduceOp.SUM) + dist.all_reduce(c["lc_n"], op=dist.ReduceOp.SUM) + centroid, bias_index, lf_frac = _spectral_centroid_lf(c["spec_energy"]) + autocorr = c["spec_sum_xx"] / c["spec_n"].clamp_min(1.0) + autocorr = 0.5 * (autocorr + autocorr.t()) + ev = torch.linalg.eigvalsh(autocorr).clamp_min(0.0) + p = ev / ev.sum().clamp_min(1e-12) + eff_rank = float(torch.exp(-(p * (p + 1e-12).log()).sum())) + lc = (c["lc_sum"] / c["lc_n"].clamp_min(1.0)).tolist() + spectral = { + "val/spectral_bias_index": bias_index, + "val/spectral_centroid": centroid, + "val/spectral_lf_energy_frac": lf_frac, + "val/latent_eff_rank": eff_rank, + "val/latent_lc_first": lc[0], + "val/latent_lc_video": lc[1], + "val/latent_lc_avg": lc[2], + } + + dataset_metrics = {} + for dataset_tag in sorted(c["dataset_metrics"]): + for metric_name in sorted(c["dataset_metrics"][dataset_tag]): + entry = c["dataset_metrics"][dataset_tag][metric_name] + dist.all_reduce(entry["sum"], op=dist.ReduceOp.SUM) + dist.all_reduce(entry["count"], op=dist.ReduceOp.SUM) + dataset_metrics[ + f"val/{dataset_tag}/{metric_name}" + ] = ( + entry["sum"] / entry["count"].clamp_min(1.0) + ).item() + + # Log data/stats of validation set to W&B. + if distributed.is_rank0(): + log.info(f"Validation loss (iteration {iteration}): {loss:4f}") + wandb.log({"val/loss": loss}, step=iteration) + if dataset_metrics: + wandb.log(dataset_metrics, step=iteration) + if spectral is not None: + wandb.log(spectral, step=iteration) + log.info( + f"Latent spectral (iter {iteration}): " + f"bias_index={spectral['val/spectral_bias_index']:.3f} " + f"eff_rank={spectral['val/latent_eff_rank']:.2f} " + f"lc_avg={spectral['val/latent_lc_avg']:.3f}" + ) + + def on_train_end(self, model: Model, iteration: int = 0) -> None: + wandb.finish() diff --git a/tokenizer/training/losses/__init__.py b/tokenizer/training/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f946d23712a17a93be7fc9668985dc7cf070b01c --- /dev/null +++ b/tokenizer/training/losses/__init__.py @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The loss reduction modes.""" + +from enum import Enum + +import torch + + +def _mean(recon: torch.Tensor) -> torch.Tensor: + return torch.mean(recon) + + +def _sum_per_frame(recon: torch.Tensor) -> torch.Tensor: + batch_size = recon.shape[0] * recon.shape[2] if recon.ndim == 5 else recon.shape[0] + return torch.sum(recon) / batch_size + + +def _sum(recon: torch.Tensor) -> torch.Tensor: + return torch.sum(recon) / recon.shape[0] + + +class ReduceMode(Enum): + MEAN = "MEAN" + SUM_PER_FRAME = "SUM_PER_FRAME" + SUM = "SUM" + + @property + def function(self): + if self == ReduceMode.MEAN: + return _mean + elif self == ReduceMode.SUM_PER_FRAME: + return _sum_per_frame + elif self == ReduceMode.SUM: + return _sum + else: + raise ValueError("Invalid ReduceMode") diff --git a/tokenizer/training/losses/continuous.py b/tokenizer/training/losses/continuous.py new file mode 100644 index 0000000000000000000000000000000000000000..71b663b09230b62d2b6614c187b12823c6f9f254 --- /dev/null +++ b/tokenizer/training/losses/continuous.py @@ -0,0 +1,1376 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The combined loss functions for continuous-space tokenizers training.""" +import einops +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +import torchvision.models.optical_flow as optical_flow + +from tokenizer.networks.utils import batch2time, time2batch +from tokenizer.training.datasets.utils import INPUT_KEY, LATENT_KEY, MASK_KEY, RECON_KEY, RECON_TARGET_KEY +from tokenizer.training.losses import ReduceMode +from tokenizer.training.losses.lpips import LPIPS +from utils.lazy_config import instantiate + +# NOTE: TokenizerLoss.forward double-adds the LAST module's loss (lines +# ~58-61). ``gradient`` is intentionally kept last to preserve that +# pre-existing behavior for ``_grad`` configs; new losses (temporal_diff, +# validity_bce, validity_lpips) must go BEFORE it so they are counted exactly once. +_VALID_LOSS_NAMES = ["color", "perceptual", "flow", "kl", "video_consistency", "point_loss", "local_chamfer", "normal", "eikonal", "temporal_diff", "intensity_tail_l1", "validity_bce", "invalid_depth_sentinel", "raydrop_mse", "validity_lpips", "surface_concentration", "voxel_occupancy_bce", "extra_lidar", "repa_align", "gradient"] +VIDEO_CONSISTENCY_LOSS = "video_consistency" +RECON_CONSISTENCY_KEY = f"{RECON_KEY}_consistency" +POINT_LOSS = "point_loss" + + +def _loss_enabled(node) -> bool: + """Whether a loss node should actually be instantiated. + + A loss whose inner ``config`` sets ``enabled=False`` is skipped ENTIRELY + (replaced by ``NullLoss``), not merely made a no-op in ``forward``. This + keeps disabled losses from constructing heavy backbones at __init__ time -- + ``ValidityLPIPSLoss``/``PerceptualLoss`` build a VGG and ``FlowLoss`` builds + RAFT, each of which downloads a checkpoint. Those downloads race/corrupt + across ranks on multi-node jobs, so a loss that's off by default must not + pull them in. Losses without an ``enabled`` flag (color/kl/perceptual) + default to enabled and are unaffected. + """ + inner = getattr(node, "config", None) + if inner is None: + return True + try: + return bool(getattr(inner, "enabled", True)) + except Exception: + return True + + +class TokenizerLoss(nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.config = config + _reduce = ReduceMode(config.reduce.upper()) if hasattr(config, "reduce") else None + self.reduce = _reduce.function + self.loss_modules = nn.ModuleDict() + for key in _VALID_LOSS_NAMES: + node = getattr(config, key) if hasattr(config, key) else None + # Gate on the inner config's ``enabled`` flag so a disabled loss is + # never instantiated (-> NullLoss), keeping its backbone/checkpoint + # from loading. NullLoss still occupies the dict key, so model.py / + # callbacks that index loss_modules[...] and guard on + # hasattr(., "enabled") stay correct, and the forward-loop ordering + # (gradient last, double-added) is unchanged. + is_valid = node is not None and _loss_enabled(node) + self.loss_modules[key] = instantiate(node) if is_valid else NullLoss() + # When enabled, the per-pixel MASK_KEY becomes the GT validity (return) + # mask instead of all-ones, so the depth losses skip no-return pixels. + self.mask_invalid_depth = getattr(config, "mask_invalid_depth", False) + self.mask_invalid_min_value = getattr(config, "mask_invalid_min_value", -1.0) + self.mask_invalid_raydrop_eps = getattr(config, "mask_invalid_raydrop_eps", 0.02) + # When True, the per-pixel validity mask comes from the dataloader + # (``loss_mask`` -> MASK_KEY, set in model.{training,validation}_step) + # rather than being derived from ``recon_target > min_value + eps``. + # Required under per-row normalization, where the depth sentinel is + # unrecoverable. The incoming [B,1,...] mask is broadcast to all + # channels for the depth losses; validity_bce/lpips read it as target. + self.mask_from_batch = getattr(config, "mask_from_batch", False) + + def forward(self, inputs, output_batch, iteration) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + loss = dict() + total_loss = 0.0 + + if self.mask_from_batch: + # Explicit per-pixel valid mask from the dataloader (already in + # MASK_KEY via model.{training,validation}_step). Broadcast the + # [B,1,...] mask to all channels; do NOT recompute from recon_target + # (per-row norm makes the depth sentinel unrecoverable). Left as the + # default all-ones if no loss_mask was provided. + _target = inputs[RECON_TARGET_KEY] + inputs[MASK_KEY] = inputs[MASK_KEY][:, :1].expand_as(_target) + elif self.mask_invalid_depth: + # GT validity (return) mask from the depth channel (channel 0), + # broadcast across all channels. 1 = valid return, 0 = no-return. + # Same threshold ValidityBCELoss uses, so depth supervision and the + # validity head are consistent. color/gradient read MASK_KEY + # directly; point_loss reshapes it to drop no-return points. + _target = inputs[RECON_TARGET_KEY] + _thr = self.mask_invalid_min_value + self.mask_invalid_raydrop_eps + _valid = (_target[:, :1] > _thr).to(_target.dtype) + inputs[MASK_KEY] = _valid.expand_as(_target) + else: + inputs[MASK_KEY] = torch.ones_like(inputs[RECON_TARGET_KEY]) + # Calculates reconstruction losses (`total_loss`). + for key, module in self.loss_modules.items(): + curr_loss = module(inputs, output_batch, iteration) + loss.update({k: torch.mean(v) for k, v in curr_loss.items()}) + total_loss += sum([self.reduce(v) if (v.dim() > 0) else v for v in curr_loss.values()]) + + loss.update({k: torch.mean(v) for k, v in curr_loss.items()}) + + # Computes the overall loss as sum of the reconstruction losses and the generator loss. + total_loss += sum([self.reduce(v) if (v.dim() > 0) else v for v in curr_loss.values()]) + return dict(loss=loss), total_loss + + +class WeightScheduler(torch.nn.Module): + def __init__(self, boundaries, values): + super().__init__() + self.boundaries = list(boundaries) + self.values = list(values) + + def forward(self, iteration): + for boundary, value in zip(self.boundaries, self.values): + if iteration < boundary: + return value + return self.values[-1] + + +class NullLoss(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward(self, inputs, output_batch, iteration) -> dict[dict, torch.Tensor]: + return dict() + + +class ColorLoss(torch.nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.normalize_by_valid_mask = getattr( + config, "normalize_by_valid_mask", False + ) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + reconstructions = output_batch[RECON_KEY] + weights = inputs[MASK_KEY] + if self.normalize_by_valid_mask: + weights = weights * ( + weights.numel() / weights.sum().clamp_min(1.0) + ) + recon_target = inputs[RECON_TARGET_KEY] + recon = weights * torch.abs(recon_target.contiguous() - reconstructions.contiguous()) + color_weighted = self.schedule(iteration) * recon + if torch.isnan(color_weighted).any(): + raise ValueError("[COLOR] NaN detected in loss") + return dict(color=color_weighted) + +class PointLoss(torch.nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.normalize_by_valid_mask = getattr( + config, "normalize_by_valid_mask", False + ) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled: + return dict() + + reconstructions = output_batch[f"{RECON_KEY}_points"].contiguous() + targets = output_batch[f"{RECON_TARGET_KEY}_points"].contiguous() + err = torch.abs(targets - reconstructions) # (B, F, H, W, 3) + # Drop no-return points using the same per-pixel validity mask the + # other depth losses use (MASK_KEY; all-ones when masking is disabled, + # so this is a no-op then). Reshape image-layout (B, C, [T,] H, W) to + # point layout (B, F, H, W, 1); skip if spatial dims don't line up + # (e.g. repeat_row/col > 1 -> points are de-repeated). + mask = inputs.get(MASK_KEY, None) + if mask is not None: + m = mask[:, 0].unsqueeze(-1) if mask.ndim == 5 else mask[:, :1].unsqueeze(-1) + if m.shape[-3:-1] == err.shape[-3:-1] and m.shape[1] in (1, err.shape[1]): + if self.normalize_by_valid_mask: + m = m * (m.numel() / m.sum().clamp_min(1.0)) + err = err * m + loss = err.mean(dim=1) + point_weighted = self.schedule(iteration) * loss + if torch.isnan(point_weighted).any(): + raise ValueError("[POINT] NaN detected in loss") + return dict(point=point_weighted) + + +class LocalChamferLoss(torch.nn.Module): + """One-sided, windowed Chamfer (recon -> nearest GT) -- the floater killer. + + For every reconstructed point we take the distance to the CLOSEST ground-truth + point inside a ``(2r+1) x (2r+1)`` range-image window centered on the same + pixel, and penalize that distance. A floater (a recon point hallucinated into + empty space, typically from edge-smearing) has every GT neighbor far away, so + it gets a large penalty and the decoder is pulled to snap it onto the nearest + real surface. A correctly-placed point (even on a sharp depth edge) sits on top + of a GT point, so its penalty is ~0 -- unlike ``gradient`` which lights up at + every edge regardless of whether the point is actually wrong. + + Cheap: instead of an all-pairs Chamfer it does a shift-loop with a running min + over the ``(2*radius_h+1) x (2*radius_w+1)`` window (azimuth W wraps circularly, + elevation H clamps), so cost is ``O(window * HW)`` with no N^2 distance matrix. + + Window anisotropy (``radius_h`` / ``radius_w``): each range-image ROW is one + laser ring, so an elevation (H) window lets a recon point match a GT point on + an ADJACENT ring -- the decoder is then not penalized for getting this ring's + depth wrong, which smears / merges rings (destroys the ring texture) at high + weight. Set ``radius_h=0`` (AZIMUTH-ONLY) to forbid cross-ring matching: it + keeps the edge-floater cleanup (a floater is off in range and has no nearby + same-row GT) while preserving per-ring depth. ``radius_h<0`` (default) mirrors + ``radius`` (isotropic) for backward compatibility. Pair an azimuth-only window + with ``point_loss`` (exact pixel correspondence = the ring anchor); Chamfer is + then the floater-cleanup term, not the sole geometry loss. + + Differentiable: ``best`` is the per-point min squared distance to a (detached) + GT point; ``torch.minimum`` routes the gradient through the selected neighbor, + so the decoder learns to move the point toward that surface. We use the + Charbonnier / pseudo-Huber form ``sqrt(best + eps)`` -- smooth at 0 (no + sqrt singularity) and METER-scaled, so it is a drop-in replacement for + ``point_loss`` (``radius=0`` reduces to the per-point Euclidean point error). + + Reads the de-repeated metric point maps the model stashes (same as PointLoss: + ``{recon,recon_target}_points``, shape ``(B, F, H, W, 3)``); no-op if absent. + Candidates are restricted to VALID GT returns (via MASK_KEY) so floaters can + only snap to real surfaces, and only valid recon positions are scored. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.radius_w = int(config.radius) # azimuth window half-size + # Elevation window half-size: <0 mirrors radius (isotropic, backward + # compatible); 0 = azimuth-only (no cross-ring matching). + _rh = int(getattr(config, "radius_h", -1)) + self.radius_h = self.radius_w if _rh < 0 else _rh + self.eps = float(config.eps) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled: + return dict() + recon = output_batch.get(f"{RECON_KEY}_points", None) + target = output_batch.get(f"{RECON_TARGET_KEY}_points", None) + if recon is None or target is None: + return dict() + recon = recon.contiguous() + target = target.detach().contiguous() # GT is fixed; gradient flows to recon + B, F, H, W, _ = recon.shape + + # Per-point valid mask (B, F, H, W) from MASK_KEY, matched to point layout + # like PointLoss; None (skip masking) if spatial dims don't line up. + mask = inputs.get(MASK_KEY, None) + valid = None + if mask is not None: + m = mask[:, 0] if mask.ndim == 5 else mask[:, 0:1] # (B,T,H,W) | (B,1,H,W) + if m.shape[-2:] == (H, W) and m.shape[1] in (1, F): + if m.shape[1] == 1 and F != 1: + m = m.expand(B, F, H, W) + valid = m > 0.5 + + INF = recon.new_tensor(1.0e9) + best = recon.new_full((B, F, H, W), 1.0e9) + hb = torch.arange(H, device=recon.device) + wb = torch.arange(W, device=recon.device) + for dh in range(-self.radius_h, self.radius_h + 1): + h_idx = (hb + dh).clamp_(0, H - 1) # elevation: clamp at edges + for dw in range(-self.radius_w, self.radius_w + 1): + w_idx = (wb + dw) % W # azimuth: circular wrap + gt = target.index_select(2, h_idx).index_select(3, w_idx) # (B,F,H,W,3) + d = ((recon - gt) ** 2).sum(-1) # squared dist (B,F,H,W) + if valid is not None: + vshift = valid.index_select(2, h_idx).index_select(3, w_idx) + d = torch.where(vshift, d, INF) # only real surfaces are candidates + best = torch.minimum(best, d) + + dist = torch.sqrt(best + self.eps) # Charbonnier ~ meters + sel = best < (1.0e9 * 0.5) # had >=1 valid GT candidate + if valid is not None: + sel = sel & valid # score only valid recon points + if sel.any(): + loss = dist[sel].mean() + else: + loss = recon.sum() * 0.0 + chamfer_weighted = self.schedule(iteration) * loss + if torch.isnan(chamfer_weighted).any(): + raise ValueError("[LOCAL_CHAMFER] NaN detected in loss") + return dict(local_chamfer=chamfer_weighted) + + +class NormalLoss(torch.nn.Module): + """Surface-normal consistency (Sensor2Sensor L_normals, arXiv:2605.22809). + + Per-pixel normals are finite-differenced from the projected 3D points in + range-view (``ComputeNormals`` in the paper): + ``n = normalize(cross(p_right - p_left, p_down - p_up))``. The recon normals + are supervised against the GT normals on valid returns. Unlike depth L1 / + point_loss (which only constrain absolute range), this constrains the spatial + derivative of the surface, so it directly flattens locally-planar regions -- + the ground in particular. + + Reuses the de-repeated metric point maps the model already stashes for + point_loss (``{recon,recon_target}_points``, shape ``(N, T, H, W, 3)``); + no-op if absent (point_loss / normal not enabled -> points not computed). + De-repeated points are required: repeated rows would give zero diffs. + + Sensor2Sensor wraps this in LPIPS; we use a cheaper pixel-space consistency + (cosine distance by default, ``mode="l1"`` for L1 on the normal vectors), + which is the more direct smoothness signal. An LPIPS-on-normals variant can + be added later like ``ValidityLPIPSLoss`` if perceptual matching is wanted. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.mode = getattr(config, "mode", "cosine") # "cosine" | "l1" + # No-returns are clamped to the near plane by geo_converter, so GT point + # range == min_range there; range in (min_range+eps, max_range-eps) + # selects valid surface returns. Match the dataset's depth_min/max. + self.min_range = config.min_range + self.max_range = config.max_range + self.valid_eps = config.valid_eps + + @staticmethod + def _normals(points: torch.Tensor) -> torch.Tensor: + # points: (N, T, H, W, 3) -> unit normals (N, T, H-2, W-2, 3). + pu = points[..., :-2, 1:-1, :] + pd = points[..., 2:, 1:-1, :] + pl = points[..., 1:-1, :-2, :] + pr = points[..., 1:-1, 2:, :] + n = torch.cross(pr - pl, pd - pu, dim=-1) + return n / (n.norm(dim=-1, keepdim=True) + 1e-6) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + rp = output_batch.get(f"{RECON_KEY}_points", None) + tp = output_batch.get(f"{RECON_TARGET_KEY}_points", None) + if rp is None or tp is None: + return dict() + n_re = self._normals(rp.contiguous()) + n_gt = self._normals(tp.contiguous()) + # Validity from GT point range (self-contained; aligned to the + # de-repeated point resolution, unlike the full-res MASK_KEY). + r = tp.norm(dim=-1) # (N, T, H, W) + v = ((r > self.min_range + self.valid_eps) & (r < self.max_range - self.valid_eps)).to(n_gt.dtype) + # Require all 4 neighbors used by the cross product to be valid. + vn = v[..., :-2, 1:-1] * v[..., 2:, 1:-1] * v[..., 1:-1, :-2] * v[..., 1:-1, 2:] + if self.mode == "l1": + err = (n_re - n_gt).abs().sum(dim=-1) + else: + err = 1.0 - (n_re * n_gt).sum(dim=-1) # cosine distance in [0, 2] + loss = (err * vn).sum() / vn.sum().clamp_min(1.0) + normal_weighted = self.schedule(iteration) * loss + if torch.isnan(normal_weighted).any(): + raise ValueError("[NORMAL] NaN detected in loss") + return dict(normal=normal_weighted) + + +class EikonalLoss(torch.nn.Module): + """Eikonal regularizer (IGR/SIREN; LODE ``grad_constraint``, arXiv:2302.14052). + + Pushes the decoded SDF volume toward ``||grad phi|| = 1`` so phi becomes a + true *metric* signed-distance field. A unit-gradient field has a clean, + consistent normal field (``grad phi / ||grad phi||``) and a smooth zero + level-set, which removes spurious zero-crossings (floaters) and yields good + normals *without* supervising on (noisy) GT LiDAR normals -- the surface + location is anchored by the existing render/point losses, exactly the IGR + recipe. Targets smooth ground as a by-product of the field being distance-like. + + Reads the ``(B*T, n_z, Y, X)`` volume + metric voxel sizes the decomp-BEV + SDF network stashes (``sdf_density`` / ``sdf_voxel_size``); no-op if absent + (only that tokenizer provides them; meaningless unless ``use_sdf=True``). + Gradients are central finite differences scaled by metric voxel size. + ``num_samples>0`` evaluates the constraint at that many random interior + voxels per item (memory-frugal at full BEV resolution); ``0`` = whole volume. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.num_samples = config.num_samples + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + phi = output_batch.get("sdf_density", None) + vsize = output_batch.get("sdf_voxel_size", None) + if phi is None or vsize is None: + return dict() + vz, vy, vx = (float(v) for v in vsize) + B, Z, Y, X = phi.shape + interior = max(Z - 2, 0) * max(Y - 2, 0) * max(X - 2, 0) + if interior == 0: + return dict() + if self.num_samples and 0 < self.num_samples < interior: + n = self.num_samples + zc = torch.randint(1, Z - 1, (B, n), device=phi.device) + yc = torch.randint(1, Y - 1, (B, n), device=phi.device) + xc = torch.randint(1, X - 1, (B, n), device=phi.device) + b = torch.arange(B, device=phi.device)[:, None].expand(B, n) + gz = (phi[b, zc + 1, yc, xc] - phi[b, zc - 1, yc, xc]) / (2 * vz) + gy = (phi[b, zc, yc + 1, xc] - phi[b, zc, yc - 1, xc]) / (2 * vy) + gx = (phi[b, zc, yc, xc + 1] - phi[b, zc, yc, xc - 1]) / (2 * vx) + else: + gz = (phi[:, 2:, 1:-1, 1:-1] - phi[:, :-2, 1:-1, 1:-1]) / (2 * vz) + gy = (phi[:, 1:-1, 2:, 1:-1] - phi[:, 1:-1, :-2, 1:-1]) / (2 * vy) + gx = (phi[:, 1:-1, 1:-1, 2:] - phi[:, 1:-1, 1:-1, :-2]) / (2 * vx) + grad_norm = torch.sqrt(gx * gx + gy * gy + gz * gz + 1e-12) + loss = (grad_norm - 1.0).abs().mean() + eik_weighted = self.schedule(iteration) * loss + if torch.isnan(eik_weighted).any(): + raise ValueError("[EIKONAL] NaN detected in loss") + return dict(eikonal=eik_weighted) + + +class GradientLoss(torch.nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled: + return dict() + + reconstructions = output_batch[RECON_KEY] + targets = inputs[RECON_TARGET_KEY] + loss = self.multi_scale_grad_loss(reconstructions, targets, inputs[MASK_KEY]) + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[GRADIENT] NaN detected in loss") + return dict(gradient=loss_weighted) + + def multi_scale_grad_loss(self, prediction, target, mask): + total = 0 + for scale in range(4): + step = pow(2, scale) + total += self.grad_loss( + prediction[..., ::step, ::step], + target[..., ::step, ::step], + mask[..., ::step, ::step], + ) + return total + + def grad_loss(self, prediction, target, mask, beta=1.0): + """Huber gradient loss along the last two dims (H, W). + + Works for (B, C, H, W) and (B, C, T, H, W) inputs. + """ + M = torch.sum(mask, dim=(-2, -1)) + diff = prediction - target + diff = mask * diff + # W-direction (last dim) + grad_w = F.smooth_l1_loss(diff[..., :, 1:], diff[..., :, :-1], reduction="none", beta=beta) + mask_w = mask[..., :, 1:] * mask[..., :, :-1] + grad_w = mask_w * grad_w + # H-direction (second-to-last dim) + grad_h = F.smooth_l1_loss(diff[..., 1:, :], diff[..., :-1, :], reduction="none", beta=beta) + mask_h = mask[..., 1:, :] * mask[..., :-1, :] + grad_h = mask_h * grad_h + + image_loss = torch.sum(grad_w, dim=(-2, -1)) + torch.sum(grad_h, dim=(-2, -1)) + return torch.sum(image_loss) / torch.sum(M).clamp(min=1) + + +class TemporalDiffLoss(torch.nn.Module): + """PV-VAE-style matched temporal-difference loss (motion-aware). + + Penalizes ``(x_hat[t] - x_hat[t-1]) - (x[t] - x[t-1])`` so the recon's + frame-to-frame change matches GT's. Because it is a *matched* + difference, constant ego motion appears in both terms and cancels -- + no ego warp / pose plumbing needed -- while temporally-incoherent + jitter (recon oscillating where GT is smooth) is penalized directly. + + Two lidar-specific knobs: + * ``raydrop_eps``: a depth pixel at the no-return clamp value + (``min_value`` in normalized space) flickers frame-to-frame; both + endpoints of a pair must sit above ``min_value + raydrop_eps`` for + the pair to count. This drops the raydrop / tree-foliage flicker + that would otherwise dominate the loss. + * ``tau_ramp``: when the network exposes the per-sample interpolative + noise level ``noise_tau``, scale this loss per-sample by + ``tau ** tau_ramp_power``. Clean samples (tau=0) get ~zero weight + so crisp motion is preserved at low noise, and the smoothness + constraint ramps in exactly where the noisy decode would otherwise + oscillate. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.min_value = config.min_value + self.raydrop_eps = config.raydrop_eps + self.tau_ramp = config.tau_ramp + self.tau_ramp_power = config.tau_ramp_power + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + + recon = output_batch[RECON_KEY] + target = inputs[RECON_TARGET_KEY] + if recon.ndim != 5 or recon.shape[2] < 2: + # Needs (B, C, T, H, W) with T >= 2. + return dict() + + d_recon = recon[:, :, 1:] - recon[:, :, :-1] + d_target = target[:, :, 1:] - target[:, :, :-1] + err = torch.abs(d_recon - d_target) # (B, C, T-1, H, W) + + # Raydrop / no-return gate on the depth channel (channel 0): a pair + # counts only if BOTH endpoints are valid returns in BOTH gt and + # recon. Broadcasts over the channel dim. + thr = self.min_value + self.raydrop_eps + valid = (target[:, :1] > thr) & (recon[:, :1] > thr) # (B, 1, T, H, W) + valid_pair = (valid[:, :, 1:] & valid[:, :, :-1]).to(err.dtype) + + # Per-sample tau ramp: ~0 weight on clean samples, full on noisy. + if self.tau_ramp and "noise_tau" in output_batch: + tau = output_batch["noise_tau"].detach().clamp(min=0.0) + w_tau = tau.pow(self.tau_ramp_power).reshape(-1, 1, 1, 1, 1) + err = err * w_tau + + err = err * valid_pair + denom = valid_pair.sum().clamp(min=1.0) * err.shape[1] # × C (mean over channels) + loss = err.sum() / denom + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[TEMPORAL_DIFF] NaN detected in loss") + return dict(temporal_diff=loss_weighted) + + +class ValidityBCELoss(torch.nn.Module): + """Binary cross-entropy on a predicted per-pixel validity (raydrop) mask. + + Matches ``L^BCE_validity`` in Sensor2Sensor (arXiv:2605.22809, Eq. 4): + the decoder emits one extra channel of validity logits, and the target is + the binary return mask (1 = valid return, 0 = no return). For our lidar + range maps a no-return / raydrop pixel is clamped to ``min_value`` in the + normalized range channel (channel 0), so the GT mask is simply + ``range > min_value + raydrop_eps``. (Intensity / elongation terms from + the paper are intentionally omitted.) + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.min_value = config.min_value + self.raydrop_eps = config.raydrop_eps + # Read the GT validity from the dataloader-provided MASK_KEY instead of + # thresholding recon_target (per-row norm breaks the depth sentinel). + self.mask_from_batch = getattr(config, "mask_from_batch", False) + self.invalid_class_weight = getattr( + config, "invalid_class_weight", None + ) + if self.invalid_class_weight is not None and not ( + 0.0 <= self.invalid_class_weight <= 1.0 + ): + raise ValueError( + "validity_bce.invalid_class_weight must be in [0, 1], got " + f"{self.invalid_class_weight}" + ) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + logits = output_batch.get("validity_logits", None) + if logits is None: + return dict() + + if self.mask_from_batch: + valid = inputs[MASK_KEY][:, :1].to(logits.dtype) # 1=return + else: + target = inputs[RECON_TARGET_KEY] + thr = self.min_value + self.raydrop_eps + valid = (target[:, :1] > thr).to(logits.dtype) # (B, 1, [T,] H, W) 1=return + loss_map = F.binary_cross_entropy_with_logits(logits, valid, reduction="none") + # Deterministic near-plane no-returns are culled geometrically (depth < + # depth_min), so don't supervise the head there -- skip those pixels. + near = output_batch.get("validity_near_mask", None) + keep = ( + ~near.bool() + if near is not None + else torch.ones_like(valid, dtype=torch.bool) + ) + if self.invalid_class_weight is not None: + invalid_mask = keep & (valid < 0.5) + valid_mask = keep & (valid >= 0.5) + invalid_count = invalid_mask.sum() + valid_count = valid_mask.sum() + invalid_loss = ( + loss_map * invalid_mask.to(loss_map.dtype) + ).sum() / invalid_count.clamp_min(1) + valid_loss = ( + loss_map * valid_mask.to(loss_map.dtype) + ).sum() / valid_count.clamp_min(1) + invalid_weight = self.invalid_class_weight + valid_weight = 1.0 - invalid_weight + present_weight = ( + invalid_weight * (invalid_count > 0).to(loss_map.dtype) + + valid_weight * (valid_count > 0).to(loss_map.dtype) + ) + loss = ( + invalid_weight * invalid_loss + valid_weight * valid_loss + ) / present_weight.clamp_min(torch.finfo(loss_map.dtype).eps) + else: + keep_float = keep.to(loss_map.dtype) + loss = (loss_map * keep_float).sum() / keep_float.sum().clamp_min( + 1.0 + ) + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[VALIDITY_BCE] NaN detected in loss") + return dict(validity_bce=loss_weighted) + + +class InvalidDepthSentinelLoss(torch.nn.Module): + """Weakly anchor no-return depth pixels to the normalized sentinel.""" + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler( + boundaries=config.boundaries, values=config.values + ) + self.enabled = config.enabled + self.sentinel = float(config.sentinel) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + reconstruction = output_batch[RECON_KEY][:, :1] + valid = inputs[MASK_KEY][:, :1].to(reconstruction.dtype) + invalid = 1.0 - valid + error = torch.abs(reconstruction - self.sentinel) + loss = (error * invalid).sum() / invalid.sum().clamp_min(1.0) + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[INVALID_DEPTH_SENTINEL] NaN detected in loss") + return dict(invalid_depth_sentinel=loss_weighted) + + +class RaydropMSELoss(torch.nn.Module): + """MSE on the predicted raydrop PROBABILITY (OmniGen L_r). + + OmniGen (arXiv:2512.14225) renders a raydrop probability and supervises it + with MSE against the binary return mask (1=return, 0=no-return), unlike the + BCE head. We keep the network emitting a validity LOGIT (so inference / + callbacks / near-plane culling are unchanged) and apply ``sigmoid`` here, + then MSE -- identical target derivation as ``ValidityBCELoss``. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.min_value = config.min_value + self.raydrop_eps = config.raydrop_eps + self.mask_from_batch = getattr(config, "mask_from_batch", False) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + logits = output_batch.get("validity_logits", None) + if logits is None: + return dict() + + if self.mask_from_batch: + valid = inputs[MASK_KEY][:, :1].to(logits.dtype) # 1=return + else: + target = inputs[RECON_TARGET_KEY] + thr = self.min_value + self.raydrop_eps + valid = (target[:, :1] > thr).to(logits.dtype) + prob = torch.sigmoid(logits) + loss_map = (prob - valid) ** 2 + near = output_batch.get("validity_near_mask", None) + if near is not None: + keep = (~near.bool()).to(loss_map.dtype) + loss = (loss_map * keep).sum() / keep.sum().clamp_min(1.0) + else: + loss = loss_map.mean() + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[RAYDROP_MSE] NaN detected in loss") + return dict(raydrop_mse=loss_weighted) + + +class SurfaceConcentrationLoss(torch.nn.Module): + """Force the renderer's per-ray weight distribution onto the GT surface. + + The differentiable depth raycast outputs, per ray, a set of sample weights + ``w_s`` (alpha-compositing) over discrete depths ``d_s``. The rendered depth + is the mean ``E[d]=Σ w_s d_s``; when the weights are diffuse/multimodal the + mean lands in empty space between lumps -> "floaters". This loss penalizes + the opacity-normalized variance of that depth distribution about the GT + range, i.e. the (normalized) spread ``Σ w_s (d_s - d_gt)^2 / Σ w_s``. Driving + it to 0 collapses the weights onto the true surface, so ``E[d]`` is clean + (no eval-time median-depth hack needed) and rays terminate at the surface. + + Reads the renderer outputs the BEV models stash in ``output_batch`` + (``render_weights`` (N,R,S), ``render_sample_depths`` (S,), ``render_gt_depth`` + (N,R), ``render_valid`` (N,R)). Applied only to valid (return) rays -- + no-return rays have no surface and are left to the validity head. Squared + distance is normalized by ``depth_scale``^2 to keep the loss O(1). + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.depth_scale = config.depth_scale + # "variance": opacity-normalized E[(d-d_gt)^2] (smooth proxy). + # "surface_indicator": the EXACT Copilot4D Eq.5 middle term + # Σ_i 1(|h_i - D_gt| > eps) * w_i (suppress weight farther than eps + # meters from the GT surface -> free-space + beyond-surface in one). + self.mode = getattr(config, "mode", "variance") + self.epsilon = getattr(config, "epsilon", 0.1) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + w = output_batch.get("render_weights", None) # (N, R, S) + s = output_batch.get("render_sample_depths", None) # (S,) + d = output_batch.get("render_gt_depth", None) # (N, R) + m = output_batch.get("render_valid", None) # (N, R) + if w is None or s is None or d is None or m is None: + return dict() + m = m.to(w.dtype) + if self.mode == "surface_indicator": + far = (torch.abs(s.view(1, 1, -1) - d.unsqueeze(-1)) > self.epsilon).to(w.dtype) + per_ray = (w * far).sum(-1) # (N, R) weight off-surface + else: + sq = ((s.view(1, 1, -1) - d.unsqueeze(-1)) / self.depth_scale) ** 2 # (N,R,S) + opacity = w.sum(-1).clamp_min(1e-6) + per_ray = (w * sq).sum(-1) / opacity # (N, R) normalized spread + loss = (per_ray * m).sum() / m.sum().clamp_min(1.0) + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[SURFACE_CONCENTRATION] NaN detected in loss") + return dict(surface_concentration=loss_weighted) + + +class VoxelOccupancyBCELoss(torch.nn.Module): + """Direct occupancy supervision on the decoder's 3D binary voxel logits. + + This is the genuinely-faithful Copilot4D signal: the input point cloud is + voxelized into a binary occupancy grid, and the decoder's coarse voxel-logit + head (used for empty-space skipping at inference) is supervised against it + with BCE. Unlike the implicit render-only path, this gives the latent a + direct geometric target, so occupancy isn't learned only through the + depth/opacity of a few hundred ray samples. + + Reads ``voxel_logits`` and ``voxel_occupancy_target`` (both (N, Z, Hv, Wv)) + from the network's training output dict. ``pos_weight`` upweights the rare + occupied voxels (occupancy is sparse -> BCE is otherwise dominated by empty + space). No-op for nets that don't emit these keys. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.pos_weight = config.pos_weight + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + logits = output_batch.get("voxel_logits", None) + target = output_batch.get("voxel_occupancy_target", None) + if logits is None or target is None: + return dict() + pw = logits.new_tensor(self.pos_weight) if self.pos_weight > 0 else None + loss = F.binary_cross_entropy_with_logits(logits, target.to(logits.dtype), pos_weight=pw) + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[VOXEL_OCCUPANCY_BCE] NaN detected in loss") + return dict(voxel_occupancy_bce=loss_weighted) + + +class ExtraLidarDepthLoss(torch.nn.Module): + """Multi-lidar reconstruction: depth L1 on the extra (blind-spot) lidars. + + The BEV occupancy tokenizer renders the dumped blind-spot lasers' rays (each + with its own origin/direction in the top-sensor frame) through the SAME + decoded occupancy volume as the top lidar. This loss supervises those rays' + rendered depth against the measured range (both in the network's normalized + depth space), masked to real returns (padding excluded). No-op for nets that + don't emit these keys (e.g. at validation / non-multi-lidar runs). + + Reads ``extra_depth`` (N, K), ``extra_gt_depth`` (N, K), ``extra_valid`` + (N, K) from the network's training output dict. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + pred = output_batch.get("extra_depth", None) # (N, K) + gt = output_batch.get("extra_gt_depth", None) # (N, K) + m = output_batch.get("extra_valid", None) # (N, K) + if pred is None or gt is None or m is None: + return dict() + m = m.to(pred.dtype) + err = torch.abs(pred - gt) * m + loss = err.sum() / m.sum().clamp_min(1.0) + loss_weighted = self.schedule(iteration) * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[EXTRA_LIDAR] NaN detected in loss") + return dict(extra_lidar=loss_weighted) + + +class ValidityLPIPSLoss(LPIPS): + """LPIPS perceptual loss on the predicted validity (raydrop) mask + (Sensor2Sensor, arXiv:2605.22809 ``L^LPIPS_validity``). + + The single-channel mask is replicated to 3 channels and mapped from + [0, 1] to [-1, 1] before the (frozen VGG) LPIPS backbone. GT target is + the binary return mask ``range > min_value + raydrop_eps``; prediction is + ``sigmoid(validity_logits)``. No-op when disabled / weight 0 / logits + absent. Loads its own VGG (the standard ``perceptual`` LPIPS is a + separate instance; for this experiment it is disabled, so this is the + only LPIPS backbone resident). + """ + + def __init__(self, config) -> None: + super().__init__(config.checkpoint_activations) + self.net = self.net.eval() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.min_value = config.min_value + self.raydrop_eps = config.raydrop_eps + self.mask_from_batch = getattr(config, "mask_from_batch", False) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + logits = output_batch.get("validity_logits", None) + if logits is None: + return dict() + + if self.mask_from_batch: + gt = inputs[MASK_KEY][:, :1].to(logits.dtype) # (B, 1, [T,] H, W) + else: + target = inputs[RECON_TARGET_KEY] + thr = self.min_value + self.raydrop_eps + gt = (target[:, :1] > thr).to(logits.dtype) # (B, 1, [T,] H, W) + pred = torch.sigmoid(logits) # (B, 1, [T,] H, W) + # Fold time into batch so the 2D VGG sees per-frame maps. + if pred.ndim == 5: + pred, _ = time2batch(pred) + gt, _ = time2batch(gt) + # [0,1] -> [-1,1], replicate mono -> RGB for the VGG backbone. + pred3 = (pred * 2.0 - 1.0).repeat(1, 3, 1, 1) + gt3 = (gt * 2.0 - 1.0).repeat(1, 3, 1, 1) + val = super().forward(pred3, gt3) # (N, 1, 1, 1) summed over layers + loss_weighted = self.schedule(iteration) * val.mean() + if torch.isnan(loss_weighted).any(): + raise ValueError("[VALIDITY_LPIPS] NaN detected in loss") + return dict(validity_lpips=loss_weighted) + + +class IntensityTailL1Loss(torch.nn.Module): + """Extra valid-return L1 supervision for each sensor's bright tail. + + Thresholds are specified on the raw linear [0, 1] intensity scale and + selected by ``sensor_dataset_id``. The reconstruction error remains in the + model's normalized intensity space. Normalizing by the number of selected + pixels prevents the rare tail's gradient from vanishing with its frequency. + """ + + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.intensity_channel = config.intensity_channel + self.linear_thresholds = list(config.linear_thresholds) + self.intensity_transform = config.intensity_transform + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + weight = self.schedule(iteration) + if not self.enabled or weight == 0.0: + return dict() + + target = inputs[RECON_TARGET_KEY] + pred = output_batch[RECON_KEY] + if target.shape[1] <= self.intensity_channel: + raise ValueError( + f"[INTENSITY_TAIL_L1] Missing intensity channel {self.intensity_channel} " + f"in target shape {tuple(target.shape)}" + ) + + thresholds = target.new_tensor(self.linear_thresholds) + dataset_ids = inputs.get("sensor_dataset_id") + if dataset_ids is None and thresholds.numel() == 1: + dataset_ids = torch.zeros( + target.shape[0], device=target.device, dtype=torch.long + ) + elif dataset_ids is None: + raise ValueError( + "[INTENSITY_TAIL_L1] sensor_dataset_id is required when " + "multiple thresholds are configured" + ) + else: + dataset_ids = torch.as_tensor( + dataset_ids, device=target.device, dtype=torch.long + ).reshape(-1) + if dataset_ids.numel() == 1 and target.shape[0] > 1: + dataset_ids = dataset_ids.expand(target.shape[0]) + if dataset_ids.numel() != target.shape[0]: + raise ValueError( + f"[INTENSITY_TAIL_L1] Expected {target.shape[0]} dataset IDs, " + f"got {dataset_ids.numel()}" + ) + + if ( + dataset_ids.min().item() < 0 + or dataset_ids.max().item() >= thresholds.numel() + ): + raise ValueError( + f"[INTENSITY_TAIL_L1] Dataset IDs {dataset_ids.tolist()} exceed " + f"{thresholds.numel()} configured thresholds" + ) + threshold = thresholds[dataset_ids] + if self.intensity_transform == "log1p": + threshold = 2.0 * torch.log1p(threshold) / torch.log( + threshold.new_tensor(2.0) + ) - 1.0 + elif self.intensity_transform == "linear": + threshold = 2.0 * threshold - 1.0 + else: + raise ValueError( + f"[INTENSITY_TAIL_L1] Unsupported transform: {self.intensity_transform}" + ) + + target_intensity = target[:, self.intensity_channel] + pred_intensity = pred[:, self.intensity_channel] + threshold = threshold.reshape( + target.shape[0], *([1] * (target_intensity.ndim - 1)) + ) + valid = inputs[MASK_KEY][:, 0].to(torch.bool) + tail = valid & (target_intensity >= threshold) + tail_f = tail.to(pred_intensity.dtype) + loss = ( + torch.abs(pred_intensity - target_intensity) * tail_f + ).sum() / tail_f.sum().clamp_min(1.0) + loss_weighted = weight * loss + if torch.isnan(loss_weighted).any(): + raise ValueError("[INTENSITY_TAIL_L1] NaN detected in loss") + return dict(intensity_tail_l1=loss_weighted) + + +class RepaAlignLoss(torch.nn.Module): + """REPA / Volt-style conv-teacher alignment. The network already computes + the masked cosine distance between the projected latent and the frozen + Utonia (PTv3) BEV teacher features and stashes it as a scalar in the output + dict (``repa_align``); here we just apply the weight schedule. No-op when + the network didn't produce it (disabled / eval / non-UniPAD net).""" + + def __init__(self, config) -> None: + super().__init__() + self.enabled = config.enabled + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + val = output_batch.get("repa_align", None) if isinstance(output_batch, dict) else None + if not self.enabled or val is None: + return dict() + return dict(repa_align=self.schedule(iteration) * val) + + +class KLLoss(torch.nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + + def kl(self, mean, logvar): + _dims = [idx for idx in range(1, mean.ndim)] + var = torch.exp(logvar) + return 0.5 * (torch.pow(mean, 2) + var - 1.0 - logvar) + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if "posteriors" not in output_batch: # No KL loss for discrete tokens. + return dict() + mean, logvar = output_batch["posteriors"] + if mean.ndim == 1: # No KL if the mean is a scalar. + return dict() + kl = self.kl(mean, logvar) + kl_weighted = self.schedule(iteration) * kl + if torch.isnan(kl_weighted).any(): + raise ValueError("[KL] NaN detected in loss") + return dict(kl=kl_weighted) + + +class PerceptualLoss(LPIPS): + """Relevant changes that're internal to us: + + - Remove linear projection layers, simply use the raw pre-normalized features. + - Use pyramid-layer weights: [1.0 / 2.6, 1.0 / 4.8, 1.0 / 3.7, 1.0 / 5.6, 10.0 / 1.5]. + - Accepts pixel-wise masks and modulates the features before norm calculation. + - Implements gram-matrix and correlation losses. + """ + + def __init__(self, config): + super(PerceptualLoss, self).__init__(config.checkpoint_activations) + self.net = self.net.eval() + self.gram_enabled = config.gram_enabled + self.corr_enabled = config.corr_enabled + self.layer_weights = list(config.layer_weights) + self.lpips_schedule = WeightScheduler(config.lpips_boundaries, config.lpips_values) + self.gram_schedule = WeightScheduler(config.gram_boundaries, config.gram_values) + self.corr_schedule = WeightScheduler(config.corr_boundaries, config.corr_values) + self.checkpoint_activations = config.checkpoint_activations + + def _temporal_gram_matrix(self, x, batch_size=None): + x = batch2time(x, batch_size) + c, t, h, w = x.shape[-4], x.shape[-3], x.shape[-2], x.shape[-1] + reshaped_x = torch.reshape(x, [-1, c, t * h * w]) + return torch.matmul(reshaped_x, reshaped_x.transpose(1, 2)) / float(t * h * w) + + def _gram_matrix(self, x, batch_size=None): + if batch_size is not None and x.shape[0] != batch_size: + return self._temporal_gram_matrix(x, batch_size) + c, h, w = x.shape[-3], x.shape[-2], x.shape[-1] + reshaped_x = torch.reshape(x, [-1, c, h * w]) + return torch.matmul(reshaped_x, reshaped_x.transpose(1, 2)) / float(h * w) + + def forward(self, inputs, output_batch, iteration): + output_dict = dict() + reconstructions = output_batch[RECON_KEY] + weights = inputs[MASK_KEY] + input_images = inputs[INPUT_KEY] + + if input_images.ndim == 5: + input_images, batch_size = time2batch(input_images) + reconstructions, _ = time2batch(reconstructions) + weights, _ = time2batch(weights) + else: + batch_size = input_images.shape[0] + + in0_input, in1_input = (self.scaling_layer(input_images), self.scaling_layer(reconstructions)) + outs0, outs1 = self.net(in0_input), self.net(in1_input) + + _layer_weights = self.layer_weights + weights_map, res, diffs = {}, {}, {} + for kk in range(len(self.chns)): + weights_map[kk] = torch.nn.functional.interpolate(weights[:, :1, ...], outs0[kk].shape[-2:]) + diffs[kk] = weights_map[kk] * torch.abs(outs0[kk] - outs1[kk]) + res[kk] = _layer_weights[kk] * diffs[kk].mean([1, 2, 3], keepdim=True) + + val = res[0] + for ll in range(1, len(self.chns)): + val += res[ll] + # Scale by number of pixels to match pixel-wise losses. + val = val.expand(-1, input_images.shape[-3], input_images.shape[-2], input_images.shape[-1]) + if batch_size != input_images.shape[0]: + val = batch2time(val, batch_size) + if torch.isnan(val).any(): + raise ValueError("[LPIPS] NaN detected in loss") + output_dict["lpips"] = self.lpips_schedule(iteration) * val + + if self.gram_enabled and self.gram_schedule(iteration) > 0.0: + num_chans = len(self.chns) + grams0 = [self._gram_matrix(weights_map[kk] * outs0[kk], batch_size) for kk in range(num_chans)] + grams1 = [self._gram_matrix(weights_map[kk] * outs1[kk], batch_size) for kk in range(num_chans)] + gram_diffs = [(grams0[kk] - grams1[kk]) ** 2 for kk in range(num_chans)] + grams_res = [_layer_weights[kk] * gram_diffs[kk].mean([1, 2], keepdim=True) for kk in range(num_chans)] + gram_val = grams_res[0] + for ll in range(1, len(self.chns)): + gram_val += grams_res[ll] + + # Scale by number of total pixels to match pixel-wise losses. + gram_val = gram_val.unsqueeze(1).expand( + -1, input_images.shape[-3], input_images.shape[-2], input_images.shape[-1] + ) + if batch_size != input_images.shape[0]: + gram_val = batch2time(gram_val, batch_size) + if torch.isnan(gram_val).any(): + raise ValueError("[GRAM] NaN detected in loss") + output_dict["gram"] = self.gram_schedule(iteration) * gram_val + return output_dict + + def torch_compile(self): + """ + This method invokes torch.compile() on this loss + """ + # cuda-graphs crash after 1k iterations + self.net = torch.compile(self.net, dynamic=False) + + +class FlowLoss(torch.nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(config.boundaries, config.values) + self.scale = config.scale + self.dtype = getattr(torch, config.dtype) + self.checkpoint_activations = config.checkpoint_activations + self.enabled = config.enabled + + current_device = torch.device(torch.cuda.current_device()) + + # In order to be able to run model in bf16 we need to change make_coords_grid() + # to allow it to return arbitrary type provided by us in argument + # the line from orginal implementation that caused results to be only fp32 is commented + # Additionally I've changed that function to run on GPU instead of CPU, which results in + # less graph breaks when torch.compile() is used + # This function is copied from + # https://github.com/pytorch/vision/blob/main/torchvision/models/optical_flow/_utils.py#L22 + # commit: b06ea39d5f0adbe949d08257837bda912339e415 + def make_coords_grid( + batch_size: int, h: int, w: int, device: torch.device = current_device, dtype: torch.dtype = self.dtype + ): + # Original: def make_coords_grid(batch_size: int, h: int, w: int, device: str = "cpu"): + device = torch.device(device) + coords = torch.meshgrid(torch.arange(h, device=device), torch.arange(w, device=device), indexing="ij") + coords = torch.stack(coords[::-1], dim=0).to(dtype) + # Original: coords = torch.stack(coords[::-1], dim=0).float() + return coords[None].repeat(batch_size, 1, 1, 1) + + # We also need to specify output dtype of torch.linspace() in index_pyramid() + # method of CorrBlock, otherwise it uses default fp32 dtype as output. + # Additionally I've changed that function to run on GPU instead of CPU, which results in + # less graph breaks when torch.compile() is used + # This function is copied from + # https://github.com/pytorch/vision/blob/main/torchvision/models/optical_flow/raft.py#L394 + # commit: b06ea39d5f0adbe949d08257837bda912339e415 + def index_pyramid( + self, centroids_coords, dtype: torch.dtype = self.dtype, device: torch.device = current_device + ): + # Original: def index_pyramid(self, centroids_coords): + """Return correlation features by indexing from the pyramid.""" + neighborhood_side_len = 2 * self.radius + 1 # see note in __init__ about out_channels + di = torch.linspace(-self.radius, self.radius, neighborhood_side_len, dtype=dtype, device=device) + dj = torch.linspace(-self.radius, self.radius, neighborhood_side_len, dtype=dtype, device=device) + # Original: di = torch.linspace(-self.radius, self.radius, neighborhood_side_len) + # Original: dj = torch.linspace(-self.radius, self.radius, neighborhood_side_len) + delta = torch.stack(torch.meshgrid(di, dj, indexing="ij"), dim=-1).to(centroids_coords.device) + delta = delta.view(1, neighborhood_side_len, neighborhood_side_len, 2) + + batch_size, _, h, w = centroids_coords.shape # _ = 2 + centroids_coords = centroids_coords.permute(0, 2, 3, 1).reshape(batch_size * h * w, 1, 1, 2) + + indexed_pyramid = [] + for corr_volume in self.corr_pyramid: + sampling_coords = centroids_coords + delta # end shape is (batch_size * h * w, side_len, side_len, 2) + indexed_corr_volume = optical_flow.raft.grid_sample( + corr_volume, sampling_coords, align_corners=True, mode="bilinear" + ).view(batch_size, h, w, -1) + indexed_pyramid.append(indexed_corr_volume) + centroids_coords = centroids_coords / 2 + + corr_features = torch.cat(indexed_pyramid, dim=-1).permute(0, 3, 1, 2).contiguous() + + expected_output_shape = (batch_size, self.out_channels, h, w) + if corr_features.shape != expected_output_shape: + raise ValueError( + f"Output shape of index pyramid is incorrect. Should be {expected_output_shape}, got {corr_features.shape}" + ) + + return corr_features + + optical_flow.raft.make_coords_grid = make_coords_grid + optical_flow.raft.CorrBlock.index_pyramid = index_pyramid + + flow_model = optical_flow.raft_large(pretrained=True, progress=False) + flow_model.requires_grad_(False) + flow_model.eval() + flow_model = flow_model.to(self.dtype) + + self.flow_model = flow_model + + def _run_model(self, input1: torch.Tensor, input2: torch.Tensor) -> torch.Tensor: + """Runs flow_model in the forward mode on explicit dtype=float32. + + Args: + input1: First video frames batch, layout (T, C, H, W), bfloat16. + input2: Next video frames batch, layout (T, C, H, W), bfloat16. + + Returns: + Forward optical flow, (T, 2, H, W), bfloat16. + """ + input_dtype = input1.dtype + flow_output = self.flow_model.to(self.dtype)(input1.to(self.dtype), input2.to(self.dtype))[-1] + return flow_output.to(input_dtype) + + def _run_model_fwd(self, input_video: torch.Tensor) -> torch.Tensor: + """Runs foward flow on a batch of videos, one batch at a time. + Args: + input_video: The input batch of videos, layout (B, T, C, H, W). + + Returns: + Forward optical flow, layout (B, 2, T-1, H, W). + """ + output_list = list() + for fwd_input_frames in input_video: + fwd_input_frames = fwd_input_frames.transpose(1, 0) + fwd_flow_output = self._run_model(fwd_input_frames[:-1], fwd_input_frames[1:]) + output_list.append(fwd_flow_output.transpose(1, 0)) + return torch.stack(output_list, dim=0) + + def _bidirectional_flow(self, input_video: torch.Tensor) -> torch.Tensor: + """The bidirectional optical flow on a batch of videos. + + The forward and backward flows are averaged to get the bidirectional flow. + To reduce memory pressure, the input video is scaled down by a factor of `self.scale`, + and rescaled back to match other pixel-wise losses. + + Args: + input_video: The input batch of videos, layout (B, T, C, H, W). + + Returns: + Biderectinoal flow, layout (B, 2, T-1, H, W). + """ + # scale down the input video to reduce memory pressure. + t, h, w = input_video.shape[-3:] + input_video_scaled = F.interpolate(input_video, (t, h // self.scale, w // self.scale), mode="trilinear") + + # forward flow. + if self.checkpoint_activations: + fwd_flow_output = checkpoint.checkpoint(self._run_model_fwd, input_video_scaled, use_reentrant=False) + else: + fwd_flow_output = self._run_model_fwd(input_video_scaled) + + # backward flow. + input_video_scaled = input_video_scaled.flip([2]) + if self.checkpoint_activations: + bwd_flow_output = checkpoint.checkpoint(self._run_model_fwd, input_video_scaled, use_reentrant=False) + else: + bwd_flow_output = self._run_model_fwd(input_video_scaled) + bwd_flow_output = bwd_flow_output.flip([2]) + + # bidirectional flow, concat fwd and bwd along temporal axis. + flow_input = torch.cat([fwd_flow_output, bwd_flow_output], dim=2) + return self.scale * F.interpolate(flow_input, (2 * (t - 1), h, w), mode="trilinear") + + def forward( + self, inputs: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor], iteration: int + ) -> dict[str, torch.Tensor]: + input_images = inputs[INPUT_KEY] + if input_images.ndim == 4 or input_images.shape[2] == 1: + return dict() + if not self.enabled or self.schedule(iteration) == 0.0: + return dict() + + # Biderectional flow (B, 2, 2*(T-1), H, W) + flow_input = self._bidirectional_flow(input_images) + flow_recon = self._bidirectional_flow(output_batch[RECON_KEY]) + + # L1 loss on the flow. (B, 1, 2*(T-1), H, W) + flow_loss = torch.abs(flow_input - flow_recon).mean(dim=1, keepdim=True) + + flow_loss_weighted = self.schedule(iteration) * flow_loss + if torch.isnan(flow_loss_weighted).any(): + raise ValueError("[FLOW] NaN detected in loss") + return dict(flow=flow_loss_weighted) + + def torch_compile(self): + """ + This method invokes torch.compile() on this loss + """ + self.flow_model = torch.compile(self.flow_model, dynamic=False) + + +class VideoConsistencyLoss(torch.nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.schedule = WeightScheduler(boundaries=config.boundaries, values=config.values) + self.enabled = config.enabled + self.num_frames = config.num_frames + self.step = config.step + self.num_windows = None + + def shuffle(self, inputs: torch.Tensor) -> torch.Tensor: + """ + For input video of [B, 3, T, H, W], this function will reshape the video to + the shape of [B*(T-num_frames+1)//step, 3, num_frames, H, W] using a sliding window + This function is used to compute the temporal consistency between overlapped frames + to enable temporal consistency + """ + assert len(inputs.shape) == 5, f"inputs shape should be [B, 3, T, H, W]. currently {inputs.shape}" + B, C, T, H, W = inputs.shape + assert T >= self.num_frames, f"inputs {T} should be greater than {self.num_frames}" + + # [B, C, num_windows, H, W, num_frames] + outputs = inputs.unfold(dimension=2, size=self.num_frames, step=self.step) + self.num_windows = outputs.shape[2] + outputs = einops.rearrange(outputs, "b c m h w n -> (b m) c n h w") + + return outputs + + def forward(self, inputs, output_batch, iteration) -> dict[str, torch.Tensor]: + if not self.enabled or self.num_windows is None: + return dict() + if self.schedule(iteration) == 0.0: + return dict() + # reshape output_batch to compute loss between overlapped frames + reconstructions = output_batch[RECON_CONSISTENCY_KEY] + B, C, T, H, W = reconstructions.shape + + assert T == self.num_frames, f"reconstruction shape invalid (shape[2] should be {self.num_frames})" + assert ( + B % self.num_windows == 0 + ), f"reconstruction shape invalid (shape[0]={B} not dividable by {self.num_windows})" + + B = B // self.num_windows + videos = reconstructions.view(B, self.num_windows, C, self.num_frames, H, W) + + # Compute the L1 distance between overlapped frames for all windows at once + diff = torch.mean(torch.abs(videos[:, :-1, :, self.step :, :, :] - videos[:, 1:, :, : -self.step, :, :])) + diff_weighted = self.schedule(iteration) * diff + + if LATENT_KEY not in output_batch: + return dict(frame_consistency=diff_weighted) + + B_latent, C_latent, T_latent, H_latent, W_latent = output_batch["latent"].shape + assert B_latent % self.num_windows == 0, f"latent batches should be divisible by {self.num_windows}" + + latents = output_batch[LATENT_KEY].view( + B_latent // self.num_windows, self.num_windows, C_latent, T_latent, H_latent, W_latent + ) + temporal_rate = self.num_frames // T_latent + spatial_rate = (H // H_latent) * (W // W_latent) + step_latent = self.step // temporal_rate + latent_diff = torch.mean( + torch.abs(latents[:, :-1, :, step_latent:, :, :] - latents[:, 1:, :, :-step_latent, :, :]) + ) + latent_diff_weighted = self.schedule(iteration) * latent_diff * (C * temporal_rate * spatial_rate) / (C_latent) + return dict(frame_consistency=diff_weighted, latent_consistency=latent_diff_weighted) + + def unshuffle(self, inputs: torch.Tensor) -> torch.Tensor: + """ + For input video of [B*num_windows, 3, num_frames, H, W], this function will + undo the shuffle to a tensor of shape [B, 3, T, H, W] + """ + assert len(inputs.shape) == 5, f"inputs shape should be [B, 3, T, H, W]. currently {inputs.shape}" + B, C, T, H, W = inputs.shape + assert T == self.num_frames, f"inputs shape invalid (shape[2] should be {self.num_frames})" + assert B % self.num_windows == 0, f"inputs shape invalid (shape[0]={B} not dividable by {self.num_windows})" + + B = B // self.num_windows + videos = inputs.view(B, self.num_windows, C, self.num_frames, H, W) + + T = self.num_frames + (self.num_windows - 1) * self.step + current_device = torch.device(torch.cuda.current_device()) + outputs = torch.zeros(B, C, T, H, W).to(inputs.dtype).to(current_device) + counter = torch.zeros_like(outputs) + for i in range(self.num_windows): + outputs[:, :, i * self.step : i * self.step + self.num_frames, :, :] += videos[:, i, :, :, :, :] + counter[:, :, i * self.step : i * self.step + self.num_frames, :, :] += 1 + outputs = outputs / counter + + return outputs diff --git a/tokenizer/training/losses/lpips.py b/tokenizer/training/losses/lpips.py new file mode 100644 index 0000000000000000000000000000000000000000..a7664a34d92f81048cce1eb46f31feb8a50a48e7 --- /dev/null +++ b/tokenizer/training/losses/lpips.py @@ -0,0 +1,195 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""LPIPS loss. + +Adapted from: github.com/CompVis/stable-diffusion/ldm/modules/losses/contperceptual.py. +""" + +import hashlib +import os +from collections import namedtuple + +import requests +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.utils.checkpoint as checkpoint +from loguru import logger as logging +from torchvision import models +from tqdm import tqdm + +from utils.distributed import is_rank0 + +_URL_MAP = {"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"} +_CKPT_MAP = {"vgg_lpips": "vgg.pth"} +_MD5_MAP = {"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"} + + +def _download(url, local_path, chunk_size=1024): + os.makedirs(os.path.split(local_path)[0], exist_ok=True) + with requests.get(url, stream=True) as r: + total_size = int(r.headers.get("content-length", 0)) + with tqdm(total=total_size, unit="B", unit_scale=True) as pbar: + with open(local_path, "wb") as f: + for data in r.iter_content(chunk_size=chunk_size): + if data: + f.write(data) + pbar.update(chunk_size) + + +def _md5_hash(path): + with open(path, "rb") as f: + content = f.read() + return hashlib.md5(content).hexdigest() + + +def _get_ckpt_path(name, root, check=False): + assert name in _URL_MAP + path = os.path.join(root, _CKPT_MAP[name]) + if not os.path.exists(path) or (check and not _md5_hash(path) == _MD5_MAP[name]): + logging.info("Downloading {} model from {} to {}".format(name, _URL_MAP[name], path)) + _download(_URL_MAP[name], path) + md5 = _md5_hash(path) + assert md5 == _MD5_MAP[name], md5 + return path + + +class LPIPS(nn.Module): + def __init__(self, checkpoint_activations: bool = False): + super().__init__() + self.scaling_layer = ScalingLayer() + self.chns = [64, 128, 256, 512, 512] # vg16 features + + # Download pretrained weights on rank 0 first, then load on all ranks + # to avoid file corruption from concurrent downloads to shared cache. + if dist.is_initialized() and is_rank0(): + self.net = vgg16(pretrained=True, requires_grad=False, checkpoint_activations=checkpoint_activations) + self.load_from_pretrained() + dist.barrier() + elif dist.is_initialized(): + dist.barrier() + self.net = vgg16(pretrained=True, requires_grad=False, checkpoint_activations=checkpoint_activations) + self.load_from_pretrained() + else: + self.net = vgg16(pretrained=True, requires_grad=False, checkpoint_activations=checkpoint_activations) + self.load_from_pretrained() + + for param in self.parameters(): + param.requires_grad = False + + def load_from_pretrained(self, name="vgg_lpips"): + ckpt = _get_ckpt_path(name, os.path.join(torch.hub.get_dir(), "checkpoints")) + self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False) + logging.info("Loaded pretrained LPIPS loss from {}".format(ckpt)) + + @classmethod + def from_pretrained(cls, name="vgg_lpips"): + if name != "vgg_lpips": + raise NotImplementedError + model = cls() + ckpt = _get_ckpt_path(name) + model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False) + return model + + def forward(self, input, target): + in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target)) + outs0, outs1 = self.net(in0_input), self.net(in1_input) + feats0, feats1, diffs = {}, {}, {} + for kk in range(len(self.chns)): + feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk]) + diffs[kk] = (feats0[kk] - feats1[kk]) ** 2 + + res = [diffs[kk].mean([1, 2, 3], keepdim=True) for kk in range(len(self.chns))] + val = res[0] + for l in range(1, len(self.chns)): + val += res[l] + return val + + +class ScalingLayer(nn.Module): + def __init__(self): + super(ScalingLayer, self).__init__() + self.register_buffer("shift", torch.Tensor([-0.030, -0.088, -0.188])[None, :, None, None], persistent=False) + self.register_buffer("scale", torch.Tensor([0.458, 0.448, 0.450])[None, :, None, None], persistent=False) + + def forward(self, inp): + return (inp - self.shift) / self.scale + + +def normalize_tensor(x, eps=1e-10): + norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True)) + return x / (norm_factor + eps) + + +class vgg16(torch.nn.Module): + def __init__(self, requires_grad=False, pretrained=True, checkpoint_activations: bool = False): + super(vgg16, self).__init__() + vgg_pretrained_features = models.vgg16(pretrained=pretrained).features + self.checkpoint_activations = checkpoint_activations + self.slice1 = torch.nn.Sequential() + self.slice2 = torch.nn.Sequential() + self.slice3 = torch.nn.Sequential() + self.slice4 = torch.nn.Sequential() + self.slice5 = torch.nn.Sequential() + self.N_slices = 5 + for x in range(4): + self.slice1.add_module(str(x), vgg_pretrained_features[x]) + for x in range(4, 9): + self.slice2.add_module(str(x), vgg_pretrained_features[x]) + for x in range(9, 16): + self.slice3.add_module(str(x), vgg_pretrained_features[x]) + for x in range(16, 23): + self.slice4.add_module(str(x), vgg_pretrained_features[x]) + for x in range(23, 30): + self.slice5.add_module(str(x), vgg_pretrained_features[x]) + if not requires_grad: + for param in self.parameters(): + param.requires_grad = False + + def forward(self, X): + if self.checkpoint_activations: + h = checkpoint.checkpoint(self.slice1, X, use_reentrant=False) + else: + h = self.slice1(X) + h_relu1_2 = h + + if self.checkpoint_activations: + h = checkpoint.checkpoint(self.slice2, h, use_reentrant=False) + else: + h = self.slice2(h) + h_relu2_2 = h + + if self.checkpoint_activations: + h = checkpoint.checkpoint(self.slice3, h, use_reentrant=False) + else: + h = self.slice3(h) + h_relu3_3 = h + + if self.checkpoint_activations: + h = checkpoint.checkpoint(self.slice4, h, use_reentrant=False) + else: + h = self.slice4(h) + h_relu4_3 = h + + if self.checkpoint_activations: + h = checkpoint.checkpoint(self.slice5, h, use_reentrant=False) + else: + h = self.slice5(h) + h_relu5_3 = h + + vgg_outputs = namedtuple("VggOutputs", ["relu1_2", "relu2_2", "relu3_3", "relu4_3", "relu5_3"]) + out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3) + return out diff --git a/tokenizer/training/metrics.py b/tokenizer/training/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..d08050a336a5ba12d2a44d99c04041cd78613cc6 --- /dev/null +++ b/tokenizer/training/metrics.py @@ -0,0 +1,139 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The combined loss functions for continuous-space tokenizers training.""" + +import numpy as np +import torch +import torch.nn as nn +from skimage.metrics import structural_similarity as ssim + +from tokenizer.networks.utils import time2batch +from utils.lazy_config import instantiate + +_VALID_METRIC_NAMES = ["PSNR", "SSIM", "CodeUsage"] +_UINT8_MAX_F = float(torch.iinfo(torch.uint8).max) +_FLOAT32_EPS = torch.finfo(torch.float32).eps +_RECONSTRUCTION = "reconstructions" +_QUANT_INFO = "quant_info" + + +class TokenizerMetric(nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.config = config + self.metric_modules = nn.ModuleDict() + for key in _VALID_METRIC_NAMES: + self.metric_modules[key] = instantiate(getattr(config, key)) if hasattr(config, key) else NULLMetric() + + def forward( + self, inputs: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor], iteration: int + ) -> dict[str, torch.Tensor]: + metric = dict() + for _, module in self.metric_modules.items(): + metric.update(module(inputs, output_batch, iteration)) + return dict(metric=metric) + + +class NULLMetric(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward( + self, inputs: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor], iteration: int + ) -> dict[str, torch.Tensor]: + return dict() + + +class PSNRMetric(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward( + self, inputs: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor], iteration: int + ) -> dict[str, torch.Tensor]: + reconstructions = output_batch[_RECONSTRUCTION] + if inputs.ndim == 5: + inputs, _ = time2batch(inputs) + reconstructions, _ = time2batch(reconstructions) + + # Normalize to uint8 [0..255] range. + true_image = (inputs.to(torch.float32) + 1) / 2 + pred_image = (reconstructions.to(torch.float32) + 1) / 2 + true_image = (true_image * _UINT8_MAX_F + 0.5).to(torch.uint8) + pred_image = (pred_image * _UINT8_MAX_F + 0.5).to(torch.uint8) + + # Calculate PNSR, based on Mean Squared Error (MSE) + true_image = true_image.to(torch.float32) + pred_image = pred_image.to(torch.float32) + mse = torch.mean((true_image - pred_image) ** 2, dim=(1, 2, 3)) + psnr = 10 * torch.log10(_UINT8_MAX_F**2 / (mse + _FLOAT32_EPS)) + return dict(PSNR=torch.mean(psnr)) + + +class SSIMMetric(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward( + self, inputs: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor], iteration: int + ) -> dict[str, torch.Tensor]: + reconstructions = output_batch[_RECONSTRUCTION] + if inputs.ndim == 5: + inputs, _ = time2batch(inputs) + reconstructions, _ = time2batch(reconstructions) + + # Normalize to uint8 [0..255] range. + true_image = (inputs.to(torch.float32) + 1) / 2 + pred_image = (reconstructions.to(torch.float32) + 1) / 2 + true_image = (true_image * _UINT8_MAX_F + 0.5).to(torch.uint8) + pred_image = (pred_image * _UINT8_MAX_F + 0.5).to(torch.uint8) + + # Move tensors to CPU and convert to numpy arrays + true_image_np = true_image.permute(0, 2, 3, 1).cpu().numpy() + pred_image_np = pred_image.permute(0, 2, 3, 1).cpu().numpy() + + # Calculate SSIM for each image in the batch and average over the batch + ssim_values = [] + for true_image_i, pred_image_i in zip(true_image_np, pred_image_np): + ssim_value = ssim(true_image_i, pred_image_i, data_range=_UINT8_MAX_F, multichannel=True, channel_axis=-1) + ssim_values.append(ssim_value) + ssim_mean = np.mean(ssim_values) + return dict(SSIM=torch.tensor(ssim_mean, dtype=torch.float32, device=inputs.device)) + + +class CodeUsageMetric(torch.nn.Module): + """ + Calculate the perplexity of codebook usage (only for discrete tokenizers) + + :param codebook_indices: Tensor of codebook indices (quant_info) + :param codebook_size: The total number of codebook entries + :return: Perplexity of the codebook usage + """ + + def __init__(self, codebook_size: int) -> None: + super().__init__() + self.codebook_size = codebook_size + + def forward( + self, inputs: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor], iteration: int + ) -> dict[str, torch.Tensor]: + code_indices = output_batch[_QUANT_INFO] + usage_counts = torch.bincount(code_indices.flatten().int(), minlength=self.codebook_size) + total_usage = usage_counts.sum().float() + usage_probs = usage_counts.float() / total_usage + entropy = -torch.sum(usage_probs * torch.log(usage_probs + _FLOAT32_EPS)) + perplexity = torch.exp(entropy) + return dict(CodeUsage=torch.tensor(perplexity, dtype=torch.float32, device=code_indices.device)) diff --git a/tokenizer/training/model.py b/tokenizer/training/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4be8445984fdc79f4f57e434f2106e2185577fa7 --- /dev/null +++ b/tokenizer/training/model.py @@ -0,0 +1,404 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implements the forward op for training, validation, and inference.""" + +from typing import Any + +import torch +from einops import rearrange +from tokenizer.training.datasets.utils import IMAGE_KEY, INPUT_KEY, MASK_KEY, RECON_KEY, RECON_TARGET_KEY, VIDEO_KEY +from tokenizer.training.losses.continuous import RECON_CONSISTENCY_KEY, VIDEO_CONSISTENCY_LOSS, POINT_LOSS +from tokenizer.training.geo_converter import GeoConverter +from utils import ema, log +from utils.lazy_config import LazyDict, instantiate +from utils.model import Model + +PREDICTION = "prediction" +EMA_PREDICTION = "ema_prediction" + + +class TokenizerModel(Model): + def __init__(self, config) -> None: + super().__init__() + self.config = config + self.network = instantiate(config.network) + self.disc = instantiate(config.disc) if config.disc else config.disc + self.loss = instantiate(config.loss) + self.metric = instantiate(config.metric) + self.precision = getattr(torch, config.precision) + if self.config.ema.enabled: + self.ema = ema.EMAModelTracker( + self, + beta=self.config.ema.beta, + torch_compile_buffer_renaming=self.config.ema.torch_compile_buffer_renaming, + ) + self.init_input_keys() + + assert hasattr(self.config, "data_config"), "data_config is required for geo_converter" + self.geo_converter = GeoConverter(self.config.data_config) + + def init_input_keys(self): + self.image_key = IMAGE_KEY + self.video_key = VIDEO_KEY + + def get_input_key(self, data_batch: dict[str, torch.Tensor]) -> str: + if self.image_key in data_batch: + return self.image_key + elif self.video_key in data_batch: + return self.video_key + else: + raise ValueError("Input key not found in data_batch.") + + def init_optimizer_scheduler( + self, optimizer_config: LazyDict, scheduler_config: LazyDict + ) -> tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler]: + """Creates the optimizer and scheduler for the network. + + Args: + optimizer_config: The optimizer config for the net. + scheduler_config: The scheduler config for the net. + + Returns: + optimizer (torch.optim.Optimizer): The net optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The net optimization scheduler. + """ + # Only pass trainable parameters to the optimizer. This makes + # decoder-only fine-tuning work cleanly: frozen encoder params + # don't waste optimizer state and don't trip DDP gradient checks. + optimizer_config.params = [p for p in self.network.parameters() if p.requires_grad] + optimizer = instantiate(optimizer_config) + scheduler_config.optimizer = optimizer + scheduler = instantiate(scheduler_config) + + return optimizer, scheduler + + def on_train_start(self, memory_format: torch.memory_format = torch.preserve_format) -> None: + if self.config.ema.enabled: + self.ema.to(dtype=torch.float32) + self.network = self.network.to(dtype=self.precision, memory_format=memory_format) + self.loss = self.loss.to(dtype=self.precision, memory_format=memory_format) + + def on_before_zero_grad( + self, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + iteration: int, + ) -> None: + if self.config.ema.enabled: + self.ema.update_average(self, iteration=iteration) + + def state_dict( + self, destination: dict[str, Any] = None, prefix: str = "", keep_vars: bool = False + ) -> dict[str, Any]: + original_state_dict = super(TokenizerModel, self).state_dict(destination, prefix, keep_vars) + + # Filter out '.loss' and 'ema.loss-' keys from the state dict. + filtered_state_dict = {k: v for k, v in original_state_dict.items() if not k.startswith("loss.")} + filtered_state_dict = {k: v for k, v in filtered_state_dict.items() if not k.startswith("ema.loss-")} + filtered_state_dict = { + k: v for k, v in filtered_state_dict.items() if not k.startswith("network.encoder.patcher") + } + filtered_state_dict = { + k: v for k, v in filtered_state_dict.items() if not k.startswith("network.decoder.unpatcher") + } + + return filtered_state_dict + + def load_state_dict(self, state_dict: Any, strict: bool = True) -> None: + if state_dict and all(key.startswith("network.") for key in state_dict): + # Release exports contain the materialized EMA network, not a trainer EMA. + result = self.network.load_state_dict( + {key[len("network."):]: value for key, value in state_dict.items()}, strict=strict + ) + if self.config.ema.enabled: + beta = self.ema.beta + try: + self.ema.beta = 0.0 + self.ema.update_average(self) + finally: + self.ema.beta = beta + log.info(f"Loaded tokenizer release network and initialized training EMA: {result}") + return + own_state = self.state_dict() + filtered_state_dict = {k: v for k, v in state_dict.items() if k in own_state} + + # Auto-prefix bare keys with "network." when loading pretrained VAE checkpoints + if not filtered_state_dict: + prefixed = {f"network.{k}": v for k, v in state_dict.items()} + filtered_state_dict = {k: v for k, v in prefixed.items() if k in own_state} + + adapted_keys = [] + for key, value in tuple(filtered_state_dict.items()): + if not hasattr(value, "shape") or own_state[key].shape == value.shape: + continue + adapted = self.adapt_warmstart_tensor(key, value, own_state[key]) + if adapted is not None: + if adapted.shape != own_state[key].shape: + raise ValueError( + f"Warm-start adapter returned {adapted.shape} for {key}; " + f"expected {own_state[key].shape}" + ) + filtered_state_dict[key] = adapted + adapted_keys.append(key) + if adapted_keys: + log.info( + f"Channel-surgery adapted {len(adapted_keys)} checkpoint tensor(s): " + f"{sorted(adapted_keys)}" + ) + + # Drop shape-mismatched tensors: torch's ``load_state_dict(strict=False)`` + # tolerates missing/unexpected keys but STILL hard-errors on size + # mismatch. For a warm-start (``strict_resume=False``) we want the + # compatible backbone to load and the incompatible layers to re-init + # (e.g. AE->VAE head doubling z_factor, or a channel-count change), so we + # skip mismatched keys here; they fall into ``missing_keys`` below and + # raise only when ``strict``. + shape_mismatch = [ + k for k, v in filtered_state_dict.items() + if hasattr(v, "shape") and own_state[k].shape != v.shape + ] + if shape_mismatch: + log.warning( + f"Skipping {len(shape_mismatch)} shape-mismatched key(s) when loading " + f"state_dict (will re-init): {sorted(shape_mismatch)}" + ) + filtered_state_dict = {k: v for k, v in filtered_state_dict.items() if k not in shape_mismatch} + + # Load only filtered state dict. + super(TokenizerModel, self).load_state_dict(filtered_state_dict, strict=False) + + # If strict is True, ensure all parameters are loaded (except the excluded ones) + missing_keys = set(own_state.keys()) - set(filtered_state_dict.keys()) + if missing_keys and strict: + raise KeyError(f"Missing keys in state_dict: {missing_keys}") + + def adapt_warmstart_tensor( + self, + name: str, + source: torch.Tensor, + target: torch.Tensor, + ) -> torch.Tensor | None: + """Delegate opt-in checkpoint surgery to the tokenizer network.""" + if name.startswith("ema.network-"): + network_name = name[len("ema.") :].replace("-", ".") + elif name.startswith("network."): + network_name = name + else: + return None + adapter = getattr(self.network, "adapt_warmstart_tensor", None) + if adapter is None: + return None + return adapter(network_name, source, target) + + def _on_before_network_forward(self, data_batch: dict[str, torch.Tensor]) -> None: + consistency_loss = self.loss.loss_modules[VIDEO_CONSISTENCY_LOSS] + if hasattr(consistency_loss, "enabled") and consistency_loss.enabled: + _input_key = self.get_input_key(data_batch) + if _input_key is self.video_key: + data_batch[_input_key] = consistency_loss.shuffle(data_batch[_input_key]) + return + + def _on_after_network_forward( + self, data_batch: dict[str, torch.Tensor], output_batch: dict[str, torch.Tensor] + ) -> None: + consistency_loss = self.loss.loss_modules[VIDEO_CONSISTENCY_LOSS] + if hasattr(consistency_loss, "enabled") and consistency_loss.enabled: + _input_key = self.get_input_key(data_batch) + if _input_key is self.video_key: + data_batch[_input_key] = consistency_loss.unshuffle(data_batch[_input_key]) + output_batch[RECON_CONSISTENCY_KEY] = torch.ones_like(output_batch[RECON_KEY]) * output_batch[RECON_KEY] + output_batch[RECON_KEY] = consistency_loss.unshuffle(output_batch[RECON_KEY]) + + # Compute the de-repeated metric point maps when point_loss OR normal + # loss is enabled (NormalLoss finite-differences these into normals). + point_loss = self.loss.loss_modules[POINT_LOSS] + normal_loss = self.loss.loss_modules["normal"] if "normal" in self.loss.loss_modules else None + chamfer_loss = self.loss.loss_modules["local_chamfer"] if "local_chamfer" in self.loss.loss_modules else None + needs_points = ( + (hasattr(point_loss, "enabled") and point_loss.enabled) + or (normal_loss is not None and getattr(normal_loss, "enabled", False)) + or (chamfer_loss is not None and getattr(chamfer_loss, "enabled", False)) + ) + if needs_points: + geometry_kwargs = {} + if data_batch.get("sensor_ray_directions") is not None: + geometry_kwargs = { + "ray_directions": data_batch["sensor_ray_directions"], + "depth_bounds": data_batch["sensor_depth_bounds"], + } + output_batch[f"{RECON_KEY}_points"] = self.geo_converter( + output_batch[RECON_KEY], **geometry_kwargs + ) + output_batch[f"{RECON_TARGET_KEY}_points"] = self.geo_converter( + data_batch[RECON_TARGET_KEY], **geometry_kwargs + ) + return + + def _network_forward(self, data_batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + # A callback proxy to modify the input before the forward pass. + if self.get_input_key(data_batch) == "images": + if data_batch["images"].ndim == 5: # input should be [B, C, H, W] + data_batch["images"] = rearrange(data_batch["images"], "B C T H W -> (B T) C H W") + if "recon_target" in data_batch: + data_batch["recon_target"] = rearrange(data_batch["recon_target"], "B C T H W -> (B T) C H W") + # Keep the explicit valid mask in lockstep with recon_target so + # MASK_KEY and the mask_as_input concat align in image mode. + if data_batch.get("loss_mask") is not None and data_batch["loss_mask"].ndim == 5: + data_batch["loss_mask"] = rearrange(data_batch["loss_mask"], "B C T H W -> (B T) C H W") + + elif self.get_input_key(data_batch) == "video": # the model takes as input (B, C, T, H, W) + if data_batch["video"].size(2) == 3: + data_batch["video"] = data_batch["video"].permute(0, 2, 1, 3, 4) + + self._on_before_network_forward(data_batch) + + # Do the forward pass. + tensor_batch = data_batch[self.get_input_key(data_batch)] + # Pass the hdmap conditioning tensor through as a kwarg ONLY when + # both: (a) the dataloader provides one (datasets with + # custom_fields=["lidar", "hdmap"] populate sample["lidar_hdmap"]; + # see rangemap_sampler.py), and (b) the network advertises that + # it consumes hdmap (``uses_hdmap=True`` on the unwrapped module, + # set by the hdmap-injection variants of TransformerVAE in their + # __init__). Other networks (TransformerVAELTX, plain + # TransformerVAE without the injection flags) keep their original + # ``forward(x)`` signature and don't get the unexpected kwarg. + forward_kwargs = {} + unwrapped = getattr(self.network, "module", self.network) + if ( + getattr(unwrapped, "uses_hdmap", False) + and "lidar_hdmap" in data_batch + and data_batch["lidar_hdmap"] is not None + ): + forward_kwargs["hdmap"] = data_batch["lidar_hdmap"] + # Explicit per-pixel validity mask (computed by the dataloader BEFORE + # per-row normalization). Threaded only when the network advertises it + # consumes one (``uses_valid_mask`` -> mask_as_input nets) and the + # dataloader populated ``loss_mask``. Used for the mask_as_input concat + # in place of the (per-row-broken) depth>thr derivation. + if ( + getattr(unwrapped, "uses_valid_mask", False) + and "loss_mask" in data_batch + and data_batch["loss_mask"] is not None + ): + forward_kwargs["valid_mask"] = data_batch["loss_mask"] + if getattr(unwrapped, "uses_sensor_metadata", False): + if data_batch.get("sensor_ray_directions") is None: + raise KeyError( + "Cross-dataset tokenizer requires sensor_ray_directions" + ) + forward_kwargs["sensor_ray_directions"] = data_batch[ + "sensor_ray_directions" + ] + if getattr(unwrapped, "uses_dataset_id", False): + if data_batch.get("sensor_dataset_id") is None: + raise KeyError( + "Dataset-embedding tokenizer requires sensor_dataset_id" + ) + forward_kwargs["sensor_dataset_id"] = data_batch[ + "sensor_dataset_id" + ] + # Ego poses (lidar->world per frame) for the static/dynamic + # decomposition network's ego warp. Threaded only when the network + # advertises it consumes poses (``uses_pose`` -> decompose=True) and + # the dataloader populated ``lidar_to_world`` (rangemap_sampler). + if ( + getattr(unwrapped, "uses_pose", False) + and "lidar_to_world" in data_batch + and data_batch["lidar_to_world"] is not None + ): + forward_kwargs["pose"] = data_batch["lidar_to_world"] + output_batch = self.network(tensor_batch, **forward_kwargs) + output_batch = output_batch if self.network.training else output_batch._asdict() + + # A callback proxy to modify the output after the forward pass. + self._on_after_network_forward(data_batch, output_batch) + return output_batch + + def training_step( + self, + data_batch: dict[str, torch.Tensor], + iteration: int, + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + _input_key = self.get_input_key(data_batch) + output_dict = self._network_forward(data_batch) + input_images, recon_images, recon_target = ( + data_batch[_input_key], + output_dict[RECON_KEY], + data_batch["recon_target"] + ) + + # pass loss_mask and recon_target (always present) + inputs = { + INPUT_KEY: input_images, + MASK_KEY: data_batch.get("loss_mask", torch.ones_like(recon_target)), + RECON_TARGET_KEY: recon_target, + } + if data_batch.get("sensor_dataset_id") is not None: + inputs["sensor_dataset_id"] = data_batch["sensor_dataset_id"] + + loss_dict, loss_value = self.loss(inputs, output_dict, iteration) + return dict({PREDICTION: recon_images, **loss_dict}), loss_value + + @torch.no_grad() + def validation_step( + self, + data_batch: dict[str, torch.Tensor], + iteration: int, + ema_model: bool = False, + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + _input_key = self.get_input_key(data_batch) + output_dict = self._network_forward(data_batch) + input_images, recon_images, recon_target = ( + data_batch[_input_key], + output_dict[RECON_KEY], + data_batch["recon_target"] + ) + + # pass loss_mask and recon_target (always present) + inputs = { + INPUT_KEY: input_images, + MASK_KEY: data_batch.get("loss_mask", torch.ones_like(recon_target)), + RECON_TARGET_KEY: recon_target, + } + if data_batch.get("sensor_dataset_id") is not None: + inputs["sensor_dataset_id"] = data_batch["sensor_dataset_id"] + + loss_dict, loss_value = self.loss(inputs, output_dict, iteration) + metric_dict = self.metric(recon_target, output_dict, iteration) + loss_dict.update(metric_dict) + prediction_key = EMA_PREDICTION if ema_model else PREDICTION + result = dict({prediction_key: recon_images, **loss_dict}) + # Surface predicted validity logits (predict_validity networks) so the + # callback can visualize the mask + mask-filtered point cloud. + if output_dict.get("validity_logits") is not None: + result["validity_logits"] = output_dict["validity_logits"] + # Surface multi-lidar (blind-spot) reconstruction for the BEV viz panel. + for _k in ( + "extra_recon_points", + "extra_gt_points", + "extra_valid_points", + "extra_recon_opacity", + ): + if output_dict.get(_k) is not None: + result[_k] = output_dict[_k] + return result, loss_value + + @torch.inference_mode() + def forward(self, data_batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + _input_key = self.get_input_key(data_batch) + output_dict = self._network_forward(data_batch) + return dict({PREDICTION: output_dict[RECON_KEY]}) diff --git a/tokenizer/training/train.py b/tokenizer/training/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e10b858f29ec5a82367a27bf57057359e0f08a --- /dev/null +++ b/tokenizer/training/train.py @@ -0,0 +1,96 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import importlib +import os +from copy import deepcopy + +from loguru import logger as logging +from omegaconf import OmegaConf + +from utils.config import Config, pretty_print_overrides +from utils.config_helper import get_config_module, override +from utils.lazy_config import instantiate +from utils.lazy_config.lazy import LazyConfig + + +@logging.catch(reraise=True) +def launch(config: Config, args: argparse.Namespace) -> None: + # Check that the config is valid + config.validate() + # Save a copy of train/val data config into config.model for reproducibility (e.g. logging, checkpointing). + try: + from utils.processed_pai import build_loader + if config.dataloader_train.get("_target_") in (build_loader, "utils.processed_pai.build_loader"): + train_data_config = OmegaConf.create(dict(uses_sensor_metadata=True, + shared_overrides=dict(process_input="mono", process_output="mono", load_intensity=False, + min_range=2.5, max_range=100., repeat_row=1, repeat_col=1))) + else: + train_data_config = OmegaConf.create(deepcopy(config.dataloader_train.dataset)) + OmegaConf.update(config.model.config, "data_config", train_data_config, merge=False, force_add=True) + except Exception as e: + logging.warning(f"Could not copy train/val data config into model config: {e}") + # Freeze the config so developers don't change it during training. + config.freeze() # type: ignore + trainer = config.trainer.type(config) + # Create the model + model = instantiate(config.model) + model.on_model_init_end() + dataloader_train = instantiate(config.dataloader_train) + dataloader_val = instantiate(config.dataloader_val) + # Start training + trainer.train( + model, + dataloader_train, + dataloader_val, + ) + + +if __name__ == "__main__": + # Usage: torchrun --nproc_per_node=1 -m scripts.train --config=projects/tutorials/mnist/config.py + + # Get the config file from the input arguments. + parser = argparse.ArgumentParser(description="Training") + parser.add_argument("--config", help="Path to the config file", required=True) + parser.add_argument( + "opts", + help=""" +Modify config options at the end of the command. For Yacs configs, use +space-separated "PATH.KEY VALUE" pairs. +For python-based LazyConfig, use "path.key=value". + """.strip(), + default=None, + nargs=argparse.REMAINDER, + ) + parser.add_argument( + "--dryrun", + action="store_true", + help="Do a dry run without training. Useful for debugging the config.", + ) + args = parser.parse_args() + config_module = get_config_module(args.config) + config = importlib.import_module(config_module).make_config() + config = override(config, args.opts) + if args.dryrun: + logging.info( + "Config:\n" + config.pretty_print(use_color=True) + "\n" + pretty_print_overrides(args.opts, use_color=True) + ) + os.makedirs(config.job.path_local, exist_ok=True) + LazyConfig.save_yaml(config, f"{config.job.path_local}/config.yaml") + print(f"{config.job.path_local}/config.yaml") + else: + # Launch the training job. + launch(config, args) diff --git a/tokenizer/training/trainer.py b/tokenizer/training/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2536a63c6f31582b6ef9c2da92f5651e1dc286ed --- /dev/null +++ b/tokenizer/training/trainer.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.utils.data + +from tokenizer.training.checkpointer import TokenizerCheckpointer +from utils import ema, misc +from utils.model import Model +from utils.trainer import Trainer + + +class TokenizerTrainer(Trainer): + """The tokenizers traine, extended from Trainer. + + It extends model training functionality. + + Attributes: + checkpointer (Checkpointer): checkpointer object to save/load model weights and optimizer states. + training_timer (misc.Timer): Timer object to time code blocks and functions. + """ + + def __init__(self, config): + super(TokenizerTrainer, self).__init__(config) + self.model_config = config.model.config + self.checkpointer = TokenizerCheckpointer(config.checkpoint, config.job, callbacks=self.callbacks) + + @torch.no_grad() + def validate(self, model: Model, dataloader_val: torch.utils.data.DataLoader, iteration: int = 0) -> None: + """Validate on the full validation dataset. + + Args: + model (Model): The PyTorch model. + dataloader_val (torch.utils.data.DataLoader): The validation data loader. + iteration (int): Current iteration number. + """ + self.callbacks.on_validation_start(model, dataloader_val, iteration=iteration) + model.eval() + # Evaluate only the deployment weights: EMA when enabled, regular + # weights otherwise. Keep callbacks inside the scope because some + # validation diagnostics call the network directly. + with ema.ema_scope(model, enabled=model.config.ema.enabled): + for val_iter, data_batch in enumerate(dataloader_val): + if self.config.trainer.max_val_iter is not None and val_iter >= self.config.trainer.max_val_iter: + break + data_batch = misc.to(data_batch, device="cuda") + self.callbacks.on_validation_step_start(model, data_batch, iteration=iteration) + output_batch, loss = model.validation_step(data_batch, iteration) + self.callbacks.on_validation_step_end( + model, data_batch, output_batch, loss, iteration=iteration + ) + self.callbacks.on_validation_end(model, iteration=iteration) diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dac9a4d7496eb38831f1f3c820a90d50e25e2a7e --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/utils/atomic_save.py b/utils/atomic_save.py new file mode 100644 index 0000000000000000000000000000000000000000..c9afc9ce8a382968ce0aac0400f69f59bf4bde9f --- /dev/null +++ b/utils/atomic_save.py @@ -0,0 +1,212 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Atomic, crash-safe helpers for writing checkpoints. + +The default ``torch.save(obj, path)`` writes incrementally to ``path``. If the +process is killed (SIGTERM/SIGKILL/OOM/wall-time) while the write is in +progress, the file at ``path`` is left torn — typically with a header but no +zip central directory at the tail — and the next ``torch.load(path)`` blows +up with ``PytorchStreamReader failed reading zip archive: failed finding +central directory``. The previous good copy at ``path`` is also lost because +``torch.save`` overwrote it in place. + +The functions in this module fix that pattern by: + +* Writing first to a temporary sibling file ``.tmp.``, +* fsync()-ing that file so its bytes are durable on disk, +* Atomically renaming it onto ``path`` with ``os.replace`` (POSIX guarantees + the rename is atomic on the same filesystem, so a concurrent reader either + sees the old complete file or the new complete file — never a torn one), +* Optionally fsync()-ing the parent directory so the new directory entry is + durable across kernel-level crashes (cheap; off by default since our + failure mode is process-level, not power-loss). + +After every successful write we also lightly **validate** the file (check +that ``torch.save`` actually produced a well-formed zip), turning silent +corruption into a loud, immediate failure that the caller can retry. +""" + +from __future__ import annotations + +import os +import zipfile +from typing import Any + +import torch + + +class CorruptCheckpointError(RuntimeError): + """Raised when a freshly-written .pt file fails post-save validation.""" + + +def _tmp_path(path: str) -> str: + """Sibling path used while a write is in flight.""" + return f"{path}.tmp.{os.getpid()}" + + +def _fsync_file(path: str) -> None: + """Force ``path``'s bytes to disk. No-op if the file no longer exists.""" + try: + fd = os.open(path, os.O_RDONLY) + except FileNotFoundError: + return + try: + os.fsync(fd) + finally: + os.close(fd) + + +def _fsync_dir(path: str) -> None: + """Force the *directory entry* of ``path``'s parent to disk. + + Needed for full crash-safety of the rename: without it, an OS crash + immediately after ``os.replace`` may roll the directory back to a state + that no longer references the new inode. + """ + parent = os.path.dirname(os.path.abspath(path)) or "." + try: + fd = os.open(parent, os.O_RDONLY) + except (FileNotFoundError, NotADirectoryError): + return + try: + os.fsync(fd) + except OSError: + # Some filesystems (e.g. some FUSE/NFS configs) don't support + # fsync() on directories. The atomic rename is still the strongest + # safety we can provide there; swallow rather than fail the save. + pass + finally: + os.close(fd) + + +def validate_pt_file(path: str) -> None: + """Verify ``path`` is a structurally valid PyTorch .pt zip archive. + + ``torch.save`` writes a zip; if the zip's central directory at the tail + is missing or malformed, ``torch.load`` will fail with ``PytorchStream + Reader failed reading zip archive: failed finding central directory``. + ``zipfile.is_zipfile`` does the cheap end-of-archive check that catches + exactly that failure mode (and is O(1) regardless of file size). + + Raises: + CorruptCheckpointError: if the file is missing or not a valid zip. + """ + if not os.path.exists(path): + raise CorruptCheckpointError(f"validation: file does not exist: {path}") + if os.path.getsize(path) == 0: + raise CorruptCheckpointError(f"validation: file is empty: {path}") + if not zipfile.is_zipfile(path): + raise CorruptCheckpointError( + f"validation: not a valid zip archive (likely a torn write): {path}" + ) + + +def atomic_torch_save( + obj: Any, + path: str, + *, + validate: bool = True, + fsync_dir: bool = False, + **torch_save_kwargs: Any, +) -> None: + """Save ``obj`` to ``path`` atomically using ``torch.save`` + rename. + + A SIGTERM/SIGKILL during the write leaves only the throwaway + ``.tmp.`` partially written; ``path`` itself either keeps the + previous-iteration's complete file or doesn't exist yet — never a torn + zip. By the time this function returns successfully, ``path`` is the + fully-written, validated checkpoint. + + Args: + obj: object to pickle (any ``torch.save``-compatible value). + path: final destination path (typically ``...iter_NNNNNN.pt``). + validate: if True (default), verify the written file is a valid + zip before renaming it into place; raise on failure. + fsync_dir: if True, also fsync the parent directory after rename + so the directory entry survives a kernel-level crash. Off by + default (the rename alone is sufficient for process-level + kills like SIGTERM/SIGKILL/OOM). + **torch_save_kwargs: forwarded to ``torch.save``. + """ + tmp = _tmp_path(path) + # Make sure no stale tmp from a previous, killed save is in the way. + try: + os.remove(tmp) + except FileNotFoundError: + pass + + torch.save(obj, tmp, **torch_save_kwargs) + _fsync_file(tmp) + + if validate: + try: + validate_pt_file(tmp) + except CorruptCheckpointError: + try: + os.remove(tmp) + except FileNotFoundError: + pass + raise + + os.replace(tmp, path) + if fsync_dir: + _fsync_dir(path) + + +def atomic_torch_jit_save( + jit_module: torch.jit.ScriptModule, + path: str, + *, + validate: bool = True, + fsync_dir: bool = False, +) -> None: + """``torch.jit.save`` analog of :func:`atomic_torch_save`. + + TorchScript files are also zip archives, so the same tmp+rename and + zip-validity check apply. + """ + tmp = _tmp_path(path) + try: + os.remove(tmp) + except FileNotFoundError: + pass + + torch.jit.save(jit_module, tmp) + _fsync_file(tmp) + + if validate: + try: + validate_pt_file(tmp) + except CorruptCheckpointError: + try: + os.remove(tmp) + except FileNotFoundError: + pass + raise + + os.replace(tmp, path) + if fsync_dir: + _fsync_dir(path) + + +def atomic_write_text(path: str, content: str, *, fsync_dir: bool = False) -> None: + """Write ``content`` to ``path`` atomically. + + Used for tiny pointer files like ``latest_checkpoint.txt`` where a torn + write (e.g. a 0-byte file because the process died between + ``open(..., "w")`` and ``write``) silently breaks resume. + """ + tmp = _tmp_path(path) + try: + os.remove(tmp) + except FileNotFoundError: + pass + + with open(tmp, "w") as f: + f.write(content) + f.flush() + os.fsync(f.fileno()) + + os.replace(tmp, path) + if fsync_dir: + _fsync_dir(path) diff --git a/utils/callback.py b/utils/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..4f576eba70eccfa129c2a4741c19c52601f534d5 --- /dev/null +++ b/utils/callback.py @@ -0,0 +1,403 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import time +import warnings +from typing import TYPE_CHECKING, Any, Callable, Optional + +import omegaconf +import torch +import torch.utils.data +import tqdm + +from utils import distributed, log +from utils.lazy_config import instantiate +from utils.misc import get_local_tensor_if_DTensor + +if TYPE_CHECKING: + from utils.config import Config + from utils.model import Model + from utils.trainer import Trainer + + +class CallBackGroup: + """A class for hosting a collection of callback objects. + + It is used to execute callback functions of multiple callback objects with the same method name. + When callbackgroup.func(args) is executed, internally it loops through the objects in self._callbacks and runs + self._callbacks[0].func(args), self._callbacks[1].func(args), etc. The method name and arguments should match. + + Attributes: + _callbacks (list[Callback]): List of callback objects. + """ + + def __init__(self, config: Config, trainer: Trainer) -> None: + """Initializes the list of callback objects. + + Args: + config (Config): The config object for the codebase. + trainer (Trainer): The main trainer. + """ + self._callbacks = [] + callback_configs = config.trainer.callbacks + if callback_configs: + if isinstance(callback_configs, list) or isinstance(callback_configs, omegaconf.listconfig.ListConfig): + warnings.warn( + "The 'config.trainer.callbacks' parameter should be a dict instead of a list. " + "Please update your code", + DeprecationWarning, + stacklevel=2, + ) + callback_configs = {f"callback_{i}": v for i, v in enumerate(callback_configs)} + for callback_name, current_callback_cfg in callback_configs.items(): + if "_target_" not in current_callback_cfg: + log.critical( + f"Callback {callback_name} is missing the '_target_' field. \n SKip {current_callback_cfg}" + ) + continue + log.critical(f"Instantiating callback {callback_name}: {current_callback_cfg}") + _callback = instantiate(current_callback_cfg) + assert isinstance(_callback, Callback), f"{current_callback_cfg} is not a valid callback." + _callback.config = config + _callback.trainer = trainer + self._callbacks.append(_callback) + + def __getattr__(self, method_name: str) -> Callable: + """Loops through the callback objects to call the corresponding callback function. + + Args: + method_name (str): Callback method name. + """ + + def multi_callback_wrapper(*args, **kwargs) -> None: + for callback in self._callbacks: + assert hasattr(callback, method_name) + method = getattr(callback, method_name) + assert callable(method) + _ = method(*args, **kwargs) + + return multi_callback_wrapper + + +class Callback: + """The base class for all callbacks. + + All callbacks should inherit from this class and adhere to the established method names and signatures. + """ + + def __init__(self, config: Optional["Config"] = None, trainer: Optional["Trainer"] = None): + """Initializes a Callback object. + + Args: + config (Optional[Config]): The configuration object for the codebase, if available. + trainer (Optional[Trainer]): The main trainer handling the training loop, if available. + + Notes: + The config and trainer parameters are optional to maintain backward compatibility. + In future releases, these parameters will be removed. Upon using these parameters, a deprecation + warning will be issued. + + """ + if config is not None or trainer is not None: + warnings.warn( + "The 'config' and 'trainer' parameters are deprecated and will be removed in a future release. " + "Please update your code to create Callback instances without these parameters.", + DeprecationWarning, + stacklevel=2, + ) + del config, trainer + + def on_train_start(self, model: Model, iteration: int = 0) -> None: + pass + + def on_training_step_start(self, model: Model, data: dict[str, torch.Tensor], iteration: int = 0) -> None: + pass + + def on_before_forward(self, iteration: int = 0) -> None: + pass + + def on_after_forward(self, iteration: int = 0) -> None: + pass + + def on_before_backward( + self, model_ddp: distributed.DistributedDataParallel, loss: torch.Tensor, iteration: int = 0 + ) -> None: + pass + + def on_after_backward(self, model_ddp: distributed.DistributedDataParallel, iteration: int = 0) -> None: + pass + + def on_before_dataloading(self, iteration: int = 0) -> None: + pass + + def on_after_dataloading(self, iteration: int = 0) -> None: + pass + + def on_optimizer_init_start(self) -> None: + pass + + def on_optimizer_init_end(self) -> None: + pass + + def on_before_optimizer_step( + self, + model_ddp: distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int = 0, + ) -> None: + pass + + def on_before_zero_grad( + self, + model_ddp: distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + iteration: int = 0, + ) -> None: + pass + + def on_training_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: + pass + + def on_validation_start( + self, model: Model, dataloader_val: torch.utils.data.DataLoader, iteration: int = 0 + ) -> None: + pass + + def on_validation_step_start(self, model: Model, data: dict[str, torch.Tensor], iteration: int = 0) -> None: + pass + + def on_validation_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: + pass + + def on_validation_end(self, model: Model, iteration: int = 0) -> None: + pass + + def on_load_checkpoint_start(self, model: Model) -> None: + pass + + def on_load_checkpoint_end(self, model: Model) -> None: + pass + + def on_load_checkpoint(self, model: Model, state_dict: dict[Any]) -> None: + pass + + def on_save_checkpoint_start(self, model: Model, iteration: int = 0) -> None: + pass + + def on_save_checkpoint_end(self, model: Model, iteration: int = 0) -> None: + pass + + def on_save_checkpoint_success(self, iteration: int = 0) -> None: + pass + + def on_save_checkpoint(self, model: Model, state_dict: dict[Any]) -> None: + pass + + def on_train_end(self, model: Model, iteration: int = 0) -> None: + pass + + def on_app_end(self) -> None: + pass + + +class EMAModelCallback(Callback): + """The callback class for tracking EMA model weights.""" + + def on_train_start(self, model: Model, iteration: int = 0) -> None: + # Set up the EMA model weight tracker. + if model.config.ema.enabled: + assert hasattr(model, "ema"), "EMA should be initialized from Model" + # EMA model must be kept in FP32 precision. + model.ema = model.ema.to(dtype=torch.float32) + else: + assert not hasattr(model, "ema"), "There should be no EMA initialized." + + def on_training_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: + # Update the EMA model with the new regular weights. + if model.config.ema.enabled: + model.ema.update_average(model, iteration) + + +class ProgressBarCallback(Callback): + """The callback class for visualizing the training/validation progress bar in the console.""" + + @distributed.rank0_only + def on_train_start(self, model: Model, iteration: int = 0) -> None: + self.train_pbar = tqdm.trange(self.config.trainer.max_iter, initial=iteration, desc="Training") + + @distributed.rank0_only + def on_training_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: + self.train_pbar.update() + + @distributed.rank0_only + def on_validation_start( + self, model: Model, dataloader_val: torch.utils.data.DataLoader, iteration: int = 0 + ) -> None: + if self.config.trainer.max_val_iter is not None: + num_iter = self.config.trainer.max_val_iter + else: + num_iter = len(dataloader_val) + assert num_iter is not None and num_iter > 0, f"Invalid number of validation iterations: {num_iter}" + self.val_pbar = tqdm.trange(num_iter, desc="Validating", position=1, leave=False) + + @distributed.rank0_only + def on_validation_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: + self.val_pbar.update() + + @distributed.rank0_only + def on_validation_end(self, model: Model, iteration: int = 0) -> None: + self.val_pbar.close() + + @distributed.rank0_only + def on_train_end(self, model: Model, iteration: int = 0) -> None: + self.trainer.checkpointer.finalize() + self.train_pbar.close() + + +class IterationLoggerCallback(Callback): + """The callback class for visualizing the training/validation progress bar in the console.""" + + @distributed.rank0_only + def on_train_start(self, model: Model, iteration: int = 0) -> None: + # self.train_pbar = tqdm.trange(self.config.trainer.max_iter, initial=iteration, desc="Training") + self.start_iteration_time = time.time() + self.elapsed_iteration_time = 0 + + @distributed.rank0_only + def on_training_step_start(self, model: Model, data: dict[str, torch.Tensor], iteration: int = 0) -> None: + self.start_iteration_time = time.time() + + @distributed.rank0_only + def on_training_step_end( + self, + model: Model, + data_batch: dict[str, torch.Tensor], + output_batch: dict[str, torch.Tensor], + loss: torch.Tensor, + iteration: int = 0, + ) -> None: + self.elapsed_iteration_time += time.time() - self.start_iteration_time + + if iteration % self.config.trainer.logging_iter == 0: + avg_time = self.elapsed_iteration_time / self.config.trainer.logging_iter + log.info(f"Iteration: {iteration}, average iter time: {avg_time:2f}, total loss {loss.item():4f}") + + self.elapsed_iteration_time = 0 + + +class GradClipCallback(Callback): + """The callback class for gradient clipping.""" + + def __init__( + self, + config: Optional["Config"] = None, + trainer: Optional["Trainer"] = None, + grad_clip_norm: float = 1.0, + ): + super().__init__(config, trainer) + self.grad_clip_norm = grad_clip_norm + + def on_before_optimizer_step( + self, + model_ddp: distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int = 0, + ) -> None: + grad_scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model_ddp.module.parameters(), max_norm=self.grad_clip_norm) + + +class LowPrecisionCallback(Callback): + """The callback class handling low precision training""" + + def __init__(self, update_iter: int, config: Optional["Config"] = None, trainer: Optional["Trainer"] = None): + super().__init__(config, trainer) + self.update_iter = update_iter + + def on_train_start(self, model: Model, iteration: int = 0) -> None: + assert model.precision in [ + torch.bfloat16, + torch.float16, + torch.half, + ], "LowPrecisionCallback must use a low precision dtype." + self.precision_type = model.precision + + def on_training_step_start(self, model: Model, data: dict[str, torch.Tensor], iteration: int = 0) -> None: + for k, v in data.items(): + if isinstance(v, torch.Tensor) and torch.is_floating_point(data[k]): + data[k] = v.to(dtype=self.precision_type) + + def on_validation_step_start(self, model: Model, data: dict[str, torch.Tensor], iteration: int = 0) -> None: + for k, v in data.items(): + if isinstance(v, torch.Tensor) and torch.is_floating_point(data[k]): + data[k] = v.to(dtype=self.precision_type) + + def on_before_zero_grad( + self, + model_ddp: distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + iteration: int = 0, + ) -> None: + if iteration % self.update_iter == 0: + if getattr(optimizer, "master_weights", False): + params, master_params = [], [] + for group, group_master in zip(optimizer.param_groups, optimizer.param_groups_master): + for p, p_master in zip(group["params"], group_master["params"]): + params.append(get_local_tensor_if_DTensor(p.data)) + master_params.append(p_master.data) + torch._foreach_copy_(params, master_params) diff --git a/utils/camera/base.py b/utils/camera/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e0855153638c553b1bdca217a73fa48b37086331 --- /dev/null +++ b/utils/camera/base.py @@ -0,0 +1,680 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch +import numpy as np +import cv2 +from utils.misc import make_sure_numpy, make_sure_torch +from typing import List, Tuple, Union +from abc import ABC, abstractmethod + +DEPTH_MAX = 122.5 + +def interpolate_polyline_to_points(polyline, voxel_size=0.025): + """ + polyline: + numpy.ndarray, shape (N, 3) or list of points + + Returns: + points: numpy array, shape (interpolate_num*N, 3) + """ + def interpolate_points(previous_vertex, vertex): + """ + Args: + previous_vertex: (x, y, z) + vertex: (x, y, z) + + Returns: + points: numpy array, shape (interpolate_num, 3) + """ + interpolate_num = int(np.linalg.norm(np.array(vertex) - np.array(previous_vertex)) / voxel_size) + interpolate_num = max(interpolate_num, 2) + + # interpolate between previous_vertex and vertex + x = np.linspace(previous_vertex[0], vertex[0], num=interpolate_num) + y = np.linspace(previous_vertex[1], vertex[1], num=interpolate_num) + z = np.linspace(previous_vertex[2], vertex[2], num=interpolate_num) + return np.stack([x, y, z], axis=1) + + points = [] + previous_vertex = None + for idx, vertex in enumerate(polyline): + if idx == 0: + previous_vertex = vertex + continue + else: + points.extend(interpolate_points(previous_vertex, vertex)) + previous_vertex = vertex + + return np.array(points) + + +class CameraBase: + def __init__(self): + pass + + @abstractmethod + def ray2pixel_torch(self, rays: torch.Tensor) -> torch.Tensor: + raise NotImplementedError + + @abstractmethod + def ray2pixel_np(self, rays: np.ndarray) -> np.ndarray: + raise NotImplementedError + + @abstractmethod + def _get_rays(self) -> torch.Tensor: + raise NotImplementedError + + def transform_points_torch(self, points: torch.Tensor, tfm: torch.Tensor) -> torch.Tensor: + """ + Args: + points: (M, 3) + tfm: (4, 4) + Returns: + points_transformed: (M, 3) + """ + transformed_points = tfm[:3, :3] @ points.T + tfm[:3, 3].unsqueeze(-1) + return transformed_points.T + + def transform_points_np(self, points: np.ndarray, tfm: np.ndarray) -> np.ndarray: + """ + Args: + points: (M, 3) + tfm: (4, 4) + Returns: + points_transformed: (M, 3) + """ + transformed_points = tfm[:3, :3] @ points.T + tfm[:3, 3].reshape(-1, 1) + return transformed_points.T + + def _get_rays_posed(self, camera_poses: torch.Tensor): + """ + Args: + camera_poses: (N, 4, 4) + Returns: + ray_o: (N, H, W, 3), camera origin + ray_d: (N, H, W, 3), camera rays + """ + rays_in_cam = self._get_rays() # shape (H, W, 3) + rays_d_in_world = torch.einsum('bij,hwj->bhwi', camera_poses[:, :3, :3], rays_in_cam) # shape (N, H, W, 3) + rays_o_in_world = camera_poses[:, :3, 3].unsqueeze(-2).unsqueeze(-2).expand_as(rays_d_in_world) # shape (N, H, W, 3) + + return rays_o_in_world, rays_d_in_world + + def _clip_polyline_to_image_plane(self, points_in_cam: np.ndarray) -> np.ndarray: + """ + Args: + points_in_cam: np.ndarray + shape: (M, 3), a polyline, they are connected. + Returns: + points: np.ndarray + shape: (M', 3), a polyline, but we clip the points to positive z if the points are behind the camera. + """ + depth = points_in_cam[:, 2] + # go through all the edges of the polyline. + eps = 1e-1 + cam_coords_cliped = [] + for i in range(len(points_in_cam) - 1): + pt1 = points_in_cam[i] + pt2 = points_in_cam[i+1] + + if depth[i] >= 0 and depth[i+1] >= 0: + cam_coords_cliped.append(pt1) + elif depth[i] < 0 and depth[i+1] < 0: + continue + else: + # clip the line to the image boundary + if depth[i] >= 0: + # add the first point + cam_coords_cliped.append(pt1) + + # calculate the intersection point and add it + t = (- pt2[2]) / (pt1[2] - pt2[2]) + eps + inter_pt = pt2 + t * (pt1 - pt2) + cam_coords_cliped.append(inter_pt) + else: + # calculate the intersection point and add it + t = (- pt1[2]) / (pt2[2] - pt1[2]) + eps + inter_pt = pt1 + t * (pt2 - pt1) + cam_coords_cliped.append(inter_pt) + + # handle the last point, if its depth > 0 and not already added + if depth[-1] >= 0: + cam_coords_cliped.append(points_in_cam[-1]) + + cam_coords_cliped = np.stack(cam_coords_cliped, axis=0) # shape (M', 3) + + return cam_coords_cliped + + """ + Projection related functions + """ + def distance_to_zbuffer(self, distance_map: Union[torch.Tensor, np.ndarray]) -> Union[torch.Tensor, np.ndarray]: + """ + Args: + distance_map: (N, H, W) or (H, W), distance to the camera + Returns: + zbuffer_map: (N, H, W) or (H, W), 0 means no depth value + """ + rays = self._get_rays() # normalized camera rays, shape (H, W, 3) + + return distance_map * rays[..., 2].expand_as(distance_map) + + + def zbuffer_to_distance(self, zbuffer_map: Union[torch.Tensor, np.ndarray]) -> Union[torch.Tensor, np.ndarray]: + """ + Args: + zbuffer_map: (N, H, W) or (H, W), depth value + Returns: + distance_map: (N, H, W) or (H, W), distance to the camera + """ + rays = self._get_rays() + + return zbuffer_map / rays[..., 2].expand_as(zbuffer_map) + + def get_zbuffer_map_from_points(self, camera_poses: Union[torch.Tensor, np.ndarray], points: Union[torch.Tensor, np.ndarray]) -> Union[torch.Tensor, np.ndarray]: + if isinstance(camera_poses, np.ndarray): + return self.get_zbuffer_map_from_points_np(camera_poses, points) + else: + return self.get_zbuffer_map_from_points_torch(camera_poses, points) + + def get_zbuffer_map_from_points_torch(self, camera_poses: torch.Tensor, points: torch.Tensor) -> torch.Tensor: + """ + Args: + camera_pose: (N, 4, 4) or (4, 4) + points: (M, 3), in world coordinate + Returns: + zbuffer_map: (N, H, W) or (H, W), 0 means no depth value + """ + depth_images = [] + camera_poses = make_sure_torch(camera_poses).to(self.device).to(self.dtype) + points = make_sure_torch(points).to(self.device).to(self.dtype) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses.unsqueeze(0) + + for camera_to_world in camera_poses: + points_in_cam = self.transform_points_torch(points, torch.inverse(camera_to_world)) + uv_coords = self.ray2pixel_torch(points_in_cam) + depth = points_in_cam[:, 2] + valid_depth_mask = depth > 0 + + u_round = torch.round(uv_coords[:, 0]).long() + v_round = torch.round(uv_coords[:, 1]).long() + + valid_uv_mask = (u_round >= 0) & (u_round < self.width) & (v_round >= 0) & (v_round < self.height) + valid_mask = valid_depth_mask & valid_uv_mask + + u_valid = u_round[valid_mask] + v_valid = v_round[valid_mask] + z_valid = depth[valid_mask] + + indices = v_valid * self.width + u_valid + + depth_image = torch.full((self.height, self.width), float('inf')).to(depth).flatten() + depth_image = depth_image.scatter_reduce_(0, indices, z_valid, "amin") + depth_image = depth_image.view(self.height, self.width) + depth_mask = torch.isfinite(depth_image) + + # change inf to 0 + depth_image[~depth_mask] = 0 + + depth_images.append(depth_image) + + depth_images = torch.stack(depth_images, dim=0) + + if depth_images.shape[0] == 1: + depth_images = depth_images.squeeze(0) + + return depth_images + + + def get_zbuffer_map_from_points_np(self, camera_poses: np.ndarray, points: np.ndarray) -> np.ndarray: + """ + Args: + camera_pose: (N, 4, 4) or (4, 4) + points: (M, 3), in world coordinate + Returns: + zbuffer_map: (N, H, W) or (H, W), 0 means no depth value + """ + depth_images = [] + camera_poses = make_sure_numpy(camera_poses) + points = make_sure_numpy(points) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses[np.newaxis, ...] + + for camera_to_world in camera_poses: + points_in_cam = self.transform_points_np(points, np.linalg.inv(camera_to_world)) + uv_coords = self.ray2pixel_np(points_in_cam) + depth = points_in_cam[:, 2] + valid_depth_mask = depth > 0 + + u_round = np.round(uv_coords[:, 0]).astype(np.int32) + v_round = np.round(uv_coords[:, 1]).astype(np.int32) + + valid_uv_mask = (u_round >= 0) & (u_round < self.width) & (v_round >= 0) & (v_round < self.height) + valid_mask = valid_depth_mask & valid_uv_mask + + u_valid = u_round[valid_mask] + v_valid = v_round[valid_mask] + z_valid = depth[valid_mask] + + depth_image = np.zeros((self.height, self.width)) + # use np.minimum.at to update the depth image + np.minimum.at(depth_image, (v_valid, u_valid), z_valid) + + depth_images.append(depth_image) + + depth_images = np.stack(depth_images, axis=0) + + if depth_images.shape[0] == 1: + depth_images = depth_images[0] + + return depth_images + + + def get_distance_map_from_points(self, camera_poses: torch.Tensor, points: torch.Tensor) -> torch.Tensor: + """ + Args: + camera_pose: (N, 4, 4) or (4, 4) + points: (M, 3), in world coordinate + Returns: + distance_map: (N, H, W) or (H, W), 0 means no depth value + """ + depth_map = self.get_zbuffer_map_from_points(camera_poses, points) # shape (N, H, W) or (H, W) + return self.zbuffer_to_distance(depth_map) + + + def get_distance_map_from_voxel(self, camera_poses: torch.Tensor, voxel_grid) -> torch.Tensor: + """ + Args: + camera_pose: (N, 4, 4) or (4, 4) + voxel_grid: fvdb.GridBatch + + Returns: + distance_map: (N, H, W) or (H, W), 0 means no depth value + """ + camera_poses = make_sure_torch(camera_poses).to(self.device).to(self.dtype) + voxel_grid = voxel_grid.to(self.device).to(self.dtype) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses.unsqueeze(0) + + rays_o, rays_d = self._get_rays_posed(camera_poses) + N, H, W = rays_o.shape[:3] + + segment = voxel_grid.segments_along_rays(rays_o.reshape(-1, 3), rays_d.reshape(-1, 3), 1, eps=1e-1) + pixel_hit = segment.joffsets[1:] - segment.joffsets[:-1] + pixel_hit = pixel_hit.view(N, H, W).float() + distance = segment.jdata[:, 0] # [N_hit,] + + distance_map = torch.zeros((N, H, W)).to(distance.device) + distance_map[pixel_hit > 0] = distance + + if N == 1: + distance_map = distance_map.squeeze(0) + + return distance_map + + def get_zbuffer_map_from_voxel(self, camera_poses: torch.Tensor, voxel_grid) -> torch.Tensor: + """ + Args: + camera_pose: (N, 4, 4) or (4, 4) + voxel_grid: fvdb.GridBatch + + Returns: + zbuffer_map: (N, H, W) or (H, W), 0 means no depth value + """ + distance_map = self.get_distance_map_from_voxel(camera_poses, voxel_grid) + return self.distance_to_zbuffer(distance_map) + + + def get_semantic_map_from_voxel(self, camera_poses: torch.Tensor, voxel_grid, voxel_semantic: torch.Tensor, background_semantic: int = 0) -> torch.Tensor: + """ + Args: + camera_pose: (N, 4, 4) or (4, 4) + voxel_grid: fvdb.GridBatch + voxel_semantic: torch.Tensor, (#voxel, ) + + Returns: + semantic_map: (N, H, W) or (H, W) + """ + camera_poses = make_sure_torch(camera_poses).to(self.device).to(self.dtype) + voxel_grid = voxel_grid.to(self.device) + voxel_semantic = voxel_semantic.to(self.device) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses.unsqueeze(0) + + rays_o, rays_d = self._get_rays_posed(camera_poses) + N, H, W = rays_o.shape[:3] + + vox, times = voxel_grid.voxels_along_rays(rays_o.reshape(-1, 3), rays_d.reshape(-1, 3), 1, eps=1e-1, return_ijk=False) + + pixel_hit = times.joffsets[1:] - times.joffsets[:-1] + pixel_hit = pixel_hit.view(N, H, W).bool() # (N, H, W) 0,1 mask + + # semantic + hit_voxel_semantic = voxel_semantic[vox.jdata] # [N_hit, C] + + # fill the semantic to the image plane. 0 refers to UNDEFINED, which is the sky / background. + semantic_rasterize = torch.full((N, H, W), background_semantic).to(hit_voxel_semantic) + semantic_rasterize[pixel_hit] = hit_voxel_semantic + + if N == 1: + semantic_rasterize = semantic_rasterize.squeeze(0) # (H, W) + + return semantic_rasterize + + """ + Drawing related functions + """ + def draw_points( + self, + camera_poses: Union[torch.Tensor, np.ndarray], + points: Union[torch.Tensor, np.ndarray], + colors: Union[torch.Tensor, np.ndarray, None] = None, + radius: int = 1, + fast_impl_when_radius_gt_1: bool = True + ) -> np.ndarray: + """ + Args: + camera_poses: torch.Tensor or np.ndarray + shape: (N, 4, 4) or (4, 4) + points: torch.Tensor or np.ndarray + shape: (M, 3) + colors: torch.Tensor or np.ndarray or None + shape: (M, 3) in uint8 + radius: int, + radius of the point + fast_impl_when_radius_gt_1: bool, + if True, use cv2.circle to draw the point when radius > 1 + Returns: + canvas: np.ndarray + shape: (N, H, W, 3) or (H, W, 3) + dtype: np.uint8 + """ + draw_images = [] + camera_poses = make_sure_numpy(camera_poses) + points = make_sure_numpy(points) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses[np.newaxis, ...] + + if colors is not None: + colors = make_sure_numpy(colors) + else: + colors = np.tile([[255, 0, 0]], (points.shape[0], 1)) + + for camera_to_world in camera_poses: + points_in_cam = self.transform_points_np(points, np.linalg.inv(camera_to_world)) + uv_coords = self.ray2pixel_np(points_in_cam) + depth = points_in_cam[:, 2] + valid_depth_mask = depth > 0 + + u_round = np.round(uv_coords[:, 0]).astype(np.int32) + v_round = np.round(uv_coords[:, 1]).astype(np.int32) + + valid_uv_mask = (u_round >= 0) & (u_round < self.width) & (v_round >= 0) & (v_round < self.height) + valid_mask = valid_depth_mask & valid_uv_mask + + u_valid = u_round[valid_mask] + v_valid = v_round[valid_mask] + z_valid = depth[valid_mask] + colors_valid = colors[valid_mask] + + sorted_indices = np.argsort(z_valid, axis=0)[::-1] + u_valid = u_valid[sorted_indices] + v_valid = v_valid[sorted_indices] + colors_valid = colors_valid[sorted_indices] + + if radius > 1 and fast_impl_when_radius_gt_1 is False: + canvas = np.zeros((self.height, self.width, 3), dtype=np.uint8) + for u, v, color in zip(u_valid, v_valid, colors_valid): + cv2.circle(canvas, (u.item(), v.item()), radius, color.tolist(), -1) + canvas = np.array(canvas, dtype=np.uint8) + + # radius = 1 or we want fast impl + else: + canvas = np.zeros((self.height, self.width, 3), dtype=np.uint8) + canvas[v_valid, u_valid] = colors_valid # fill from the farthest point to the nearest point + + # use fast impl when radius > 1 + if radius > 1: + canvas_accum = np.zeros_like(canvas) + i_shifts = np.arange(-radius//2, radius//2+1) + j_shifts = np.arange(-radius//2, radius//2+1) + for i in i_shifts: + for j in j_shifts: + # use torch.roll to shift the canvas + canvas_shifted = np.roll(canvas, shift=(i, j), axis=(0, 1)) + canvas_accum = np.maximum(canvas_accum, canvas_shifted) + canvas = canvas_accum + + draw_images.append(canvas) + + draw_images = np.stack(draw_images, axis=0) + + if draw_images.shape[0] == 1: + draw_images = draw_images[0] + + return draw_images + + def draw_line_depth( + self, + camera_poses: Union[torch.Tensor, np.ndarray], + polylines: List, + radius: int = 8, + colors: np.ndarray = None, + segment_interval: float = 0, + ) -> np.ndarray: + """ + draw lines on the image, and the drawed pixel value is related to the depth of the points. + The polyline can be out of boundary, use cv2.clipLine to clip the line to the image boundary, or abandon the line. + Then use cv2.line to draw the line. + + Args: + camera_poses: torch.Tensor or np.ndarray + shape: (N, 4, 4) or (4, 4) + polylines: list of list of points, + each point is in 3D (x, y, z) + radius: int, + radius of the drawn circle + colors: np.ndarray, + shape: (3, ), dtype: np.uint8 + segment_interval: float, + if > 0, the polyline is segmented into segments with the interval + + Returns: + draw_images: np.ndarray + shape: (N, H, W, 3) or (H, W, 3) + dtype: np.uint8 + """ + draw_images = [] + camera_poses = make_sure_numpy(camera_poses) + + if colors is None: + colors = np.array([255, 255, 255]) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses[np.newaxis, ...] + + for camera_to_world in camera_poses: + canvas = np.zeros((self.height, self.width, 3), dtype=np.uint8) + H, W = canvas.shape[:2] + + for polyline in polylines: + if len(polyline) < 2: + continue + if isinstance(polyline, list): + polyline = np.array(polyline) + + if segment_interval > 0: + polyline = interpolate_polyline_to_points(polyline, segment_interval) + + points_in_cam = self.transform_points_np(polyline, np.linalg.inv(camera_to_world)) + uv_coords = self.ray2pixel_np(points_in_cam) + depth = points_in_cam[:, 2] + + u_round = np.round(uv_coords[:, 0]).astype(np.int32) + v_round = np.round(uv_coords[:, 1]).astype(np.int32) + valid_uv_mask = (u_round >= 0) & (u_round < W) & (v_round >= 0) & (v_round < H) + + # filter out the polyline if all points are out of the image boundary + if (~valid_uv_mask).all(): + continue + + # if depth all greater than DEPTH_MAX, skip + if depth.min() > DEPTH_MAX: + continue + + for i in range(len(u_round) - 1): + if depth[i] < 0 and depth[i+1] < 0: + continue + + if depth[i] * depth[i+1] < 0: + # if the two points are on different sides of the camera, we first clip the 3d point in the back to the camera plane + epsilon + # and then reproject it to the image plane, calculate the uv coordinate + pt1 = points_in_cam[i] + pt2 = points_in_cam[i+1] + + # make sure pt1 is in front of the camera, pt2 is behind the camera + if depth[i] < 0: + pt1, pt2 = pt2, pt1 + + # clip the line to the image boundary + eps = 2e-1 + t = (- pt2[2]) / (pt1[2] - pt2[2]) + eps + pt2 = t * pt1 + (1 - t) * pt2 + + # project the point to the image plane + pt1_norm = pt1[:3] / pt1[2] + pt2_norm = pt2[:3] / pt2[2] + + pixel1 = self.ray2pixel_np(pt1_norm)[0] + pixel2 = self.ray2pixel_np(pt2_norm)[0] + else: + pixel1 = np.array([u_round[i], v_round[i]]) + pixel2 = np.array([u_round[i+1], v_round[i+1]]) + + try: + clipped, pixel1, pixel2 = \ + cv2.clipLine((0, 0, W, H), pixel1.astype(np.int32), pixel2.astype(np.int32)) + except: + breakpoint() + + depth_mean = (depth[i] + depth[i+1]) / 2 + depth_mean = np.clip(depth_mean, 0, DEPTH_MAX) + fill_weight = (2 * (DEPTH_MAX - depth_mean)) / 255 + fill_value = (fill_weight * colors).astype(np.uint8).tolist() + + cv2.line(canvas, tuple(pixel1), tuple(pixel2), fill_value, radius) + + draw_images.append(canvas) + + draw_images = np.stack(draw_images, axis=0) + + if draw_images.shape[0] == 1 and len(draw_images.shape) == 3: + draw_images = draw_images[0] + + return draw_images + + + def draw_hull_depth( + self, + camera_poses: Union[torch.Tensor, np.ndarray], + hulls: List, + colors: np.ndarray = None + ) -> torch.Tensor: + """ + draw hulls on the image, and the drawed pixel value is related to the depth of the points. + The hull can be out of boundary, use cv2.clipLine to clip the line to the image boundary, or abandon the line. + Then use cv2.line to draw the line. + + Args: + camera_poses: torch.Tensor or np.ndarray + shape: (N, 4, 4) or (4, 4) + hulls: list of list of points, + each point is in 3D (x, y, z) + colors: np.ndarray, + shape: (3, ), dtype: np.uint8 + + Returns: + draw_images: (N, H, W, 3) or (H, W, 3), image with hulls drawn + """ + draw_images = [] + camera_poses = make_sure_numpy(camera_poses) + + if len(camera_poses.shape) == 2: + camera_poses = camera_poses[np.newaxis, ...] + + for camera_to_world in camera_poses: + canvas = np.zeros((self.height, self.width, 3), dtype=np.uint8) + H, W = canvas.shape[:2] + + for hull in hulls: + if len(hull) < 3: + continue + + points_in_cam = self.transform_points_np(hull, np.linalg.inv(camera_to_world)) + uv_coords = self.ray2pixel_np(points_in_cam).astype(np.int32) + depth = points_in_cam[:, 2] + valid_depth_mask = depth > 0 + + u_round = uv_coords[:, 0] + v_round = uv_coords[:, 1] + valid_uv_mask = (u_round >= 0) & (u_round < W) & (v_round >= 0) & (v_round < H) + valid_mask = valid_depth_mask & valid_uv_mask + + # filter out the polyline if all points are out of the image boundary + if not valid_mask.any(): + continue + + # if depth all greater than DEPTH_MAX, skip + if depth.min() > DEPTH_MAX: + continue + + # project again with clipped points + points_in_cam_clipped = self._clip_polyline_to_image_plane(points_in_cam) + uv_coords = self.ray2pixel_np(points_in_cam_clipped).astype(np.int32) + depth_mean = points_in_cam_clipped[:, 2].mean() + + # cv2.clipLine to limit the points to the image boundary + uv_coords_line_clipped = [] + for i in range(len(uv_coords) - 1): + pixel1 = uv_coords[i] + pixel2 = uv_coords[i+1] + clipped, pixel1, pixel2 = cv2.clipLine((0, 0, W, H), pixel1, pixel2) + uv_coords_line_clipped.append(pixel1) + uv_coords_line_clipped.append(pixel2) + + hull_in_uv = np.array(uv_coords_line_clipped).astype(np.int32) + + # create convex hull and draw on the image + convex_hull_in_uv = cv2.convexHull(hull_in_uv.astype(np.int32)) # shape (N, 1, 2) + fill_weight = (2 * (DEPTH_MAX - depth_mean)) / 255 + fill_value = (fill_weight * colors).astype(np.uint8).tolist() + cv2.fillPoly(canvas, [convex_hull_in_uv], fill_value) + + draw_images.append(canvas) + + draw_images = np.stack(draw_images, axis=0) + + if draw_images.shape[0] == 1 and len(draw_images.shape) == 3: + draw_images = draw_images[0] + + return draw_images \ No newline at end of file diff --git a/utils/camera/ftheta.py b/utils/camera/ftheta.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf761aafc6ce6a8bbfd9b3689edbaa478b9770e --- /dev/null +++ b/utils/camera/ftheta.py @@ -0,0 +1,778 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import math +from typing import Any, Dict, Tuple, TypeVar, Union + +import numpy as np +import torch +from numpy.polynomial.polynomial import Polynomial +from scipy.optimize import curve_fit +from utils.camera.base import CameraBase + +CropParams = TypeVar("CropParams") +ScaleParams = TypeVar("ScaleParams") + +def compute_max_distance_to_border(image_size_component: float, principal_point_component: float) -> float: + """Given an image size component (x or y) and corresponding principal point component (x or y), + returns the maximum distance (in image domain units) from the principal point to either image boundary.""" + + center = 0.5 * image_size_component + if principal_point_component > center: + return principal_point_component + else: + return image_size_component - principal_point_component + + +def compute_max_radius(image_size: np.ndarray, principal_point: np.ndarray) -> float: + """Compute the maximum radius from the principal point to the image boundaries.""" + + max_diag = np.array( + [ + compute_max_distance_to_border(image_size[0], principal_point[0]), + compute_max_distance_to_border(image_size[1], principal_point[1]), + ] + ) + return np.linalg.norm(max_diag).item() + + +def compute_ftheta_fw_mapping_max_angle(fwpoly: np.ndarray, max_radius_pixels: float): + """ + Best guess of the valid domain of a forward mapping (ray to pixel). + + Args: + fw_mapping (callable): Forward mapping function that maps angle to pixel radius. + max_radius_pixels (float): Maximum radius in pixels. + + Returns: + float: Maximum angle in radians. + """ + + # Constants + MAX_ANGLE = np.pi # Try up to 180 degrees (covers 360 degrees FOV if principal point is in the middle) + DOMAIN_SAMPLE_COUNT = 2000 # Enough steps to get a fine enough resolution + STEP_SIZE = MAX_ANGLE / DOMAIN_SAMPLE_COUNT + + angle = 0.0 + for i in range(1, DOMAIN_SAMPLE_COUNT + 1): + next_angle = i * STEP_SIZE + next_r = eval_polynomial( + np.asarray(next_angle).reshape(1), fwpoly + ).item() # Forward polynomial maps angle to pixel radius + + # Compute the derivative at the next angle + d_next_r = eval_polynomial_derivative(np.asarray(next_angle).reshape(1), fwpoly).item() + + if d_next_r <= 0.0: + # Polynomial is monotonically increasing in valid domain, so derivative must be positive. + # At this point, this is not the case -> stop + break + + angle = next_angle + if next_r > max_radius_pixels: + # Now we're outside of the image pixels -> stop + break + + return angle + + +def eval_polynomial(xs: np.ndarray, coeffs: np.ndarray) -> np.ndarray: + """Evaluates polynomial coeffs [D,] at given points [N,] using Horner scheme""" + ret = np.zeros(len(xs), dtype=xs.dtype) + + for coeff in reversed(coeffs): + ret = ret * xs + coeff + + return ret + + +def eval_polynomial_derivative(xs: np.ndarray, coeffs: np.ndarray) -> np.ndarray: + """Evaluates the derivative of polynomial coeffs [D,] at given points [N,] using Horner scheme""" + ret = np.zeros(len(xs), dtype=xs.dtype) + + for i, coeff in enumerate(reversed(coeffs[:-1])): + ret = ret * xs + coeff * (len(coeffs) - 1 - i) + + return ret + + +def approximate_polynomial_inverse(coeffs: np.ndarray, range_min: float, range_max: float) -> np.ndarray: + """ + Computes an approximate inverse polynomial in the provided range, fixing the first coefficient to zero. + + The fitting is performed via least squares on inverted sampled points (y, x) of the provided polynomial. + + Parameters: + ----------- + coeffs : np.ndarray + Coefficients of the polynomial to be inverted. + range_min : float + Minimum value of the range for sampling. + range_max : float + Maximum value of the range for sampling. + + Returns: + -------- + np.ndarray + Coefficients of the approximate inverse polynomial. + + Raises: + ------- + ValueError + If the polynomial degree is not supported (i.e., not 4 or 5). + """ + + def f4(x, b, x1, x2, x3, x4): + """4th degree polynomial.""" + return b + x * (x1 + x * (x2 + x * (x3 + x * x4))) + + def f5(x, b, x1, x2, x3, x4, x5): + """5th degree polynomial.""" + return b + x * (x1 + x * (x2 + x * (x3 + x * (x4 + x * x5)))) + + SAMPLE_COUNT = 500 + samples_y = np.linspace(range_min, range_max, SAMPLE_COUNT) + samples_x = eval_polynomial(samples_y, coeffs.astype(np.float64)) # use high-precision estimation + + # The constant term in the polynomial should be zero, so add the `bounds` condition + if (poly_degree := len(coeffs) - 1) == 4: + # Fit a 4th degree polynomial + bounds = ( + [0, -np.inf, -np.inf, -np.inf, -np.inf], + [np.finfo(np.float64).eps, np.inf, np.inf, np.inf, np.inf], + ) + inv_coeffs, _ = curve_fit(f4, samples_x, samples_y, bounds=bounds) + elif poly_degree == 5: + # Fit a 5th degree polynomial + bounds = ( + [0, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf], + [np.finfo(np.float64).eps, np.inf, np.inf, np.inf, np.inf, np.inf], + ) + inv_coeffs, _ = curve_fit(f5, samples_x, samples_y, bounds=bounds) + else: + raise ValueError(f"Unsupported polynomial degree {poly_degree}") + + return np.array([np.float32(val) if i > 0 else 0 for i, val in enumerate(inv_coeffs)], dtype=np.float32) + + +class FThetaCamera(CameraBase): + """Defines an FTheta camera model.""" + + @classmethod + def from_rig(cls, rig_file: str, sensor_name: str): + """Helper method to initialize a new object using a rig file and the sensor's name. + + Args: + rig_file (str): the rig file path. + sensor_name (str): the name of the sensor. usually available sensors are: + - camera:front:wide:120fov + - camera:cross:left:120fov + - camera:cross:right:120fov + - camera:rear:left:70fov + - camera:rear:right:70fov + - camera:rear:tele:30fov + Returns: + FThetaCamera: the newly created object. + """ + with open(rig_file, "r") as fp: + rig = json.load(fp) + + # Parse the properties from the rig file + sensors = rig["rig"]["sensors"] + sensor = None + sensor_found = False + + for sensor in sensors: + if sensor["name"] == sensor_name: + sensor_found = True + break + + if not sensor_found: + raise ValueError(f"The camera '{sensor_name}' was not found in the rig!") + + return cls.from_dict(sensor) + + @classmethod + def from_dict(cls, rig_dict: Dict[str, Any]): + """Helper method to initialize a new object using a dictionary of the rig. + + Args: + rig_dict (dict): the sensor dictionary to initialize with. + + Returns: + FThetaCamera: the newly created object. + """ + cx, cy, width, height, bw_poly = FThetaCamera.get_ftheta_parameters_from_json( + rig_dict + ) + return cls(cx, cy, width, height, bw_poly) + + @classmethod + def from_numpy(cls, intrinsics: np.ndarray, device=None): + """Helper method to initialize a new object using an array of intrinsics. + + Args: + intrinsics (np.ndarray): the intrinsics array. The ordering is expected to be + "cx, cy, width, height, poly (more coefficients), is_bw_poly". This is the same ordering as the `intrinsics` + property of this class. + + Returns: + FThetaCaamera: the newly created object. + """ + return cls( + cx=intrinsics[0], + cy=intrinsics[1], + width=intrinsics[2], + height=intrinsics[3], + is_bw_poly=intrinsics[-1] > 0, + poly=intrinsics[4:-1], + device=device + ) + + def __init__( + self, + cx: float, + cy: float, + width: int, + height: int, + poly: np.ndarray = None, + is_bw_poly: bool = True, + dtype=torch.float32, + device=None + ): + """The __init__ method. + + Args: + cx (float): optical center x. + cy (float): optical center y. + width (int): the width of the image. + height (int): the height of the image. + is_bw_poly (bool): whether the poly is bw poly + poly (np.ndarray): the polynomial of the FTheta model. Usually 5 coefficients. + """ + self._rescale_width: int | None = None + self._rescale_height: int | None = None + self._center = np.asarray([cx, cy], dtype=np.float32) + self._width = int(width) + self._height = int(height) + + if is_bw_poly: + self._bw_poly = Polynomial(poly) + self._fw_poly = self._compute_fw_poly() + else: + self._fw_poly = Polynomial(poly) + self._bw_poly = self._compute_bw_poly() + + # Other properties that need to be computed + self._horizontal_fov = None + self._vertical_fov = None + self._max_angle = None + self._max_ray_angle = None + + # Populate the array of intrinsics + self._intrinsics = np.array([cx, cy, width, height, *poly, 1 if is_bw_poly else 0], dtype=np.float32) + + self._update_calibrated_camera() + + if device is None: + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.device = device + self.dtype = dtype + + @property + def is_rescaled(self): + return self._rescale_width is not None and self._rescale_height is not None + + def rescale(self, width: int, height: int): + self._rescale_width = width + self._rescale_height = height + + @staticmethod + def get_ftheta_parameters_from_json(rig_dict: Dict[str, Any]) -> Tuple[Any]: + """Helper method for obtaining FTheta camera model parameters from a rig dict. + + Args: + rig_dict (Dict[str, Any]): the rig dictionary to parse. + + Raises: + ValueError: if the provided rig is not supported. + AssertionError: if the provided model is supported, but cannot be parsed properly. + + Returns: + Tuple[Any]: the values `cx`, `cy`, `width`, `height` and `bw_poly` that were parsed. + """ + props = rig_dict["properties"] + + if props["Model"] != "ftheta": + raise ValueError("The given camera is not an FTheta camera") + + cx = float(props["cx"]) + cy = float(props["cy"]) + width = int(props["width"]) + height = int(props["height"]) + + if "bw-poly" in props: # Is this a regular rig? + poly = props["bw-poly"] + elif "polynomial" in props: # Is this a VT rig? + # VT rigs have a slightly different format, so need to handle these + # specifically. Refer to the following thread for more details: + # https://nvidia.slack.com/archives/C017LLEG763/p1633304770105300 + poly_type = props["polynomial-type"] + assert poly_type == "pixeldistance-to-angle", ( + "Encountered an unsupported VT rig. Only `pixeldistance-to-angle` " + f"polynomials are supported (got {poly_type}). Rig:\n{rig_dict}" + ) + + linear_c = float(props["linear-c"]) if "linear-c" in props else None + linear_d = float(props["linear-d"]) if "linear-d" in props else None + linear_e = float(props["linear-e"]) if "linear-e" in props else None + + # If we had all the terms present, sanity check to make sure they are [1, 0, 0] + if linear_c is not None and linear_d is not None and linear_e is not None: + assert ( + linear_c == 1.0 + ), f"Expected `linear-c` term to be 1.0 (got {linear_c}. Rig:\n{rig_dict})" + assert ( + linear_d == 0.0 + ), f"Expected `linear-d` term to be 0.0 (got {linear_d}. Rig:\n{rig_dict})" + assert ( + linear_e == 0.0 + ), f"Expected `linear-e` term to be 0.0 (got {linear_e}. Rig:\n{rig_dict})" + + # If we're here, then it means we can parse the rig successfully. + poly = props["polynomial"] + else: + raise ValueError( + f"Unable to parse the rig. Only FTheta rigs are supported! Rig:\n{rig_dict}" + ) + + bw_poly = [np.float32(val) for val in poly.split()] + return cx, cy, width, height, bw_poly + + @property + def fov(self) -> tuple: + """Returns a tuple of horizontal and vertical fov of the sensor.""" + if self._vertical_fov is None or self._horizontal_fov is None: + self._compute_fov() + return self._horizontal_fov, self._vertical_fov + + @property + def width(self) -> int: + """Returns the width of the sensor.""" + return self._width if not self.is_rescaled else self._rescale_width + + @property + def height(self) -> int: + """Returns the height of the sensor.""" + return self._height if not self.is_rescaled else self._rescale_height + + @property + def center(self) -> np.ndarray: + """Returns the center of the sensor.""" + assert not self.is_rescaled + return self._center + + @property + def intrinsics(self) -> np.ndarray: + """Obtain an array of the intrinsics of this camera model. + + Returns: + np.ndarray: an array of intrinsics. The ordering is "cx, cy, width, height, poly, is_bw_poly". + dtype is np.float32. + """ + assert not self.is_rescaled + return self._intrinsics + + def __str__(self): + """Returns a string representation of this object.""" + return ( + f"FTheta camera model:\n\t{self._bw_poly}\n\t" + f"center={self._center}\n\twidth={self._width}\n\theight={self._height}\n\t" + f"h_fov={np.degrees(self._horizontal_fov)}\n\tv_fov={np.degrees(self._vertical_fov)}" + ) + + def _update_calibrated_camera(self): + """Updates the internals of this object after calulating various properties.""" + self._compute_fov() + self._max_ray_angle = (self._max_angle).copy() + is_fw_poly_slope_negative_in_domain = False + ray_angle = (np.float32(self._max_ray_angle)).copy() + deg2rad = np.pi / 180.0 + while ray_angle >= np.float32(0.0): + temp_dval = self._fw_poly.deriv()(self._max_ray_angle).item() + if temp_dval < 0: + is_fw_poly_slope_negative_in_domain = True + ray_angle -= deg2rad * np.float32(1.0) + + if is_fw_poly_slope_negative_in_domain: + ray_angle = (np.float32(self._max_ray_angle)).copy() + while ray_angle >= np.float32(0.0): + ray_angle -= deg2rad * np.float32(1.0) + raise ArithmeticError( + "FThetaCamera: derivative of distortion within image interior is negative" + ) + + # Evaluate the forward polynomial at point (self._max_ray_angle, 0) + # Also evaluate its derivative at the same point + val = self._fw_poly(self._max_ray_angle).item() + dval = self._fw_poly.deriv()(self._max_ray_angle).item() + + if dval < 0: + raise ArithmeticError( + "FThetaCamera: derivative of distortion at edge of image is negative" + ) + + self._max_ray_distortion = np.asarray([val, dval], dtype=np.float32) + + def _compute_fw_poly(self): + """Computes the forward polynomial for this camera. + + This function is a replication of the logic in the following file from the DW repo: + src/dw/calibration/cameramodel/CameraModels.cpp + """ + max_value = compute_max_radius([self._width, self._height], self._center) + coeffs = approximate_polynomial_inverse(self._bw_poly.coef, 0, max_value) + + # Return the polynomial and hardcode the bias value to 0 + return Polynomial( + [np.float32(val) if i > 0 else 0 for i, val in enumerate(coeffs)] + ) + + + def _compute_bw_poly(self): + """Computes the backward polynomial for this camera. + """ + max_pixel_radius = compute_max_radius([self._width, self._height], self._center) + max_value = compute_ftheta_fw_mapping_max_angle(self._fw_poly.coef, max_pixel_radius) + coeffs = approximate_polynomial_inverse(self._fw_poly.coef, 0, max_value) + return Polynomial( + [np.float32(val) if i > 0 else 0 for i, val in enumerate(coeffs)] + ) + + def _get_rays(self) -> torch.Tensor: + """ + Returns: + rays: (H, W, 3), normalized camera rays in opencv convention + + z (front) + / + o ------> x (right) + | + v y (down) + """ + u = torch.arange(self.width, dtype=torch.int32, device=self.device) + v = torch.arange(self.height, dtype=torch.int32, device=self.device) + u, v = torch.meshgrid(u, v, indexing='xy') # must pass indexing='xy' + uv_coords = torch.stack([u, v], dim=-1).reshape(-1, 2) # shape (H, W, 2) + + # call pixel2ray to get the rays + rays = self.pixel2ray(uv_coords.cpu().numpy())[0] + rays = torch.tensor(rays, device=self.device, dtype=self.dtype).reshape(self.height, self.width, 3) + return rays + + + def pixel2ray(self, x: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """Backproject 2D pixels into 3D rays. + + Args: + x (np.ndarray): the pixels to backproject. Size of (n_points, 2), where the first + column contains the `x` values, and the second column contains the `y` values. + + Returns: + rays (np.ndarray): the backprojected 3D rays. Size of (n_points, 3). + valid (np.ndarray): bool flag indicating the validity of each backprojected pixel. + """ + # Make sure x is n x 2 + if np.ndim(x) == 1: + x = x[np.newaxis, :] + + if self.is_rescaled: + x = x * np.array( + [self._width / self._rescale_width, self._height / self._rescale_height] + ).astype(np.float32) + + # Fix the type + x = x.astype(np.float32) + xd = x - self._center + xd_norm = np.linalg.norm(xd, axis=1, keepdims=True) + alpha = self._bw_poly(xd_norm) + sin_alpha = np.sin(alpha) + + rx = sin_alpha * xd[:, 0:1] / xd_norm + ry = sin_alpha * xd[:, 1:] / xd_norm + rz = np.cos(alpha) + + rays = np.hstack((rx, ry, rz)) + # special case: ray is perpendicular to image plane normal + valid = (xd_norm > np.finfo(np.float32).eps).squeeze() + rays[~valid, :] = (0, 0, 1) # This is what DW sets these rays to + + # note: + # if constant coefficient of bwPoly is non-zero, + # the resulting ray might not be normalized. + return rays, valid + + def ray2pixel(self, rays: np.ndarray) -> np.ndarray: + """Project 3D rays to 2D pixel coordinates. + + Args: + rays (np.ndarray): the rays. shape: (M, 3) + + Returns: + result (np.ndarray): the projected pixel coordinates. shape: (M, 2) + """ + # Make sure the input shape is (n_points, 3) + if np.ndim(rays) == 1: + rays = rays[np.newaxis, :] + + # Fix the type + rays = rays.astype(np.float32) + # TODO(restes) combine 2 and 3 column norm for rays? + xy_norm = np.linalg.norm(rays[:, :2], axis=1, keepdims=True) + cos_alpha = rays[:, 2:] / np.linalg.norm(rays, axis=1, keepdims=True) + + alpha = np.empty_like(cos_alpha) + cos_alpha_condition = np.logical_and( + cos_alpha > np.float32(-1.0), cos_alpha < np.float32(1.0) + ).squeeze() + alpha[cos_alpha_condition] = np.arccos(cos_alpha[cos_alpha_condition]) + alpha[~cos_alpha_condition] = xy_norm[~cos_alpha_condition] + + delta = np.empty_like(cos_alpha) + alpha_cond = alpha <= self._max_ray_angle + delta[alpha_cond] = self._fw_poly(alpha[alpha_cond]) + # For outside the model (which need to do linear extrapolation) + delta[~alpha_cond] = ( + self._max_ray_distortion[0] + + (alpha[~alpha_cond] - self._max_ray_angle) * self._max_ray_distortion[1] + ) + + # Determine the bad points with a norm of zero, and avoid division by zero + bad_norm = xy_norm <= 0 + xy_norm[bad_norm] = 1 + delta[bad_norm] = 0 + # compute pixel relative to center + scale = delta / xy_norm + pixel = scale * rays + + # Handle the edge cases (ray along image plane normal) + edge_case_cond = (xy_norm <= np.float32(0.0)).squeeze() + pixel[edge_case_cond, :] = rays[edge_case_cond, :] + result = pixel[:, :2] + self._center + + if self.is_rescaled: + result = result * np.array( + [self._rescale_width / self._width, self._rescale_height / self._height] + ).astype(np.float32) + + return result + + def ray2pixel_np(self, rays: np.ndarray) -> np.ndarray: + # call ray2pixel + return self.ray2pixel(rays) + + def ray2pixel_torch(self, rays: torch.Tensor) -> torch.Tensor: + device = rays.device + dtype = rays.dtype + return torch.tensor(self.ray2pixel(rays.cpu().numpy()), device=device, dtype=dtype) + + def _get_pixel_fov(self, pt: np.ndarray) -> float: + """Gets the FOV for a given point. Used internally for FOV computation. + + Args: + pt (np.ndarray): 2D pixel. + + Returns: + fov (float): the FOV of the pixel. + """ + ray, _ = self.pixel2ray(pt) + fov = np.arctan2(np.linalg.norm(ray[:, :2], axis=1), ray[:, 2]) + return fov + + def _compute_fov(self): + """Computes the FOV of this camera model.""" + max_x = self._width - 1 + max_y = self._height - 1 + + point_left = np.asarray([0, self._center[1]], dtype=np.float32) + point_right = np.asarray([max_x, self._center[1]], dtype=np.float32) + point_top = np.asarray([self._center[0], 0], dtype=np.float32) + point_bottom = np.asarray([self._center[0], max_y], dtype=np.float32) + + fov_left = self._get_pixel_fov(point_left) + fov_right = self._get_pixel_fov(point_right) + fov_top = self._get_pixel_fov(point_top) + fov_bottom = self._get_pixel_fov(point_bottom) + + self._vertical_fov = fov_top + fov_bottom + self._horizontal_fov = fov_left + fov_right + self._compute_max_angle() + + def _compute_max_angle(self): + """Computes the maximum ray angle for this camera.""" + max_x = self._width - 1 + max_y = self._height - 1 + + p = np.asarray( + [[0, 0], [max_x, 0], [0, max_y], [max_x, max_y]], dtype=np.float32 + ) + + self._max_angle = max( + max(self._get_pixel_fov(p[0, ...]), self._get_pixel_fov(p[1, ...])), + max(self._get_pixel_fov(p[2, ...]), self._get_pixel_fov(p[3, ...])), + ) + + def is_ray_inside_fov(self, ray: np.ndarray) -> bool: + """Determines whether a given ray is inside the FOV of this camera. + + Args: + ray (np.ndarray): the 3D ray. + + Returns: + bool: whether the ray is inside the FOV. + """ + if np.ndim(ray) == 1: + ray = ray[np.newaxis, :] + + ray_angle = np.arctan2(np.linalg.norm(ray[:, :2], axis=1), ray[:, 2]) + return ray_angle <= self._max_angle + + + +def rays_to_pixels_batch( + rays: torch.Tensor, cam_intrinsic: torch.Tensor +) -> torch.Tensor: + """Project 3D rays to 2D pixel coordinates. + + Computes image projection for 3D points in an + F-theta camera. + More information about the projection is in the below link: + https://confluence.nvidia.com/display/DS/Camera+intrinsic+models + Args: + rays (torch.Tensor): 3D rays tensor with size (B, H, W, 3, N). + where N is the number of vertices. + cam_intrinsic (torch.Tensor): camera intrinsic. tensor with size 9. + In particular, the element 0 is img_cx, 1 is img_cy, + 2 is img_width, 3 is img_height, 4:9 is img_bw_poly. + + Returns: + pixels (torch.Tensor): the projected pixel coordinates. + Tensor is of size (B, H, W, 2, N). + """ + cam_intrinsic = cam_intrinsic.cpu().detach().numpy() + img_cx = cam_intrinsic[0] + img_cy = cam_intrinsic[1] + img_width = cam_intrinsic[2] + img_height = cam_intrinsic[3] + img_bw_poly = cam_intrinsic[4:] + ftheta_model = FThetaCamera(img_cx, img_cy, img_width, img_height, img_bw_poly) + # Computes the forward polynomial for this camera + fw_poly = list(ftheta_model._compute_fw_poly()) + device = rays.device + max_ray_angle = torch.tensor(ftheta_model._max_ray_angle, device=device) + max_ray_distortion = torch.tensor(ftheta_model._max_ray_distortion, device=device) + + ray_x = rays[:, :, :, 0, :] + ray_y = rays[:, :, :, 1, :] + ray_z = rays[:, :, :, 2, :] + ray_xy_norm = torch.linalg.norm(torch.stack([ray_x, ray_y], dim=3), dim=3) + # Compute the angle of ray with the optical axis + alpha = (math.pi / 2.0) - torch.atan2(ray_z, ray_xy_norm) + + delta_valid = ( + fw_poly[0] + + fw_poly[1] * alpha + + fw_poly[2] * alpha**2 + + fw_poly[3] * alpha**3 + + fw_poly[4] * alpha**4 + ) + # For outside the model (which need to do linear extrapolation) + delta_invalid = ( + max_ray_distortion[0] + (alpha - max_ray_angle) * max_ray_distortion[1] + ) + delta = torch.where(alpha <= max_ray_angle, delta_valid, delta_invalid) + + # Determine the bad points with a norm of zero, and avoid division by zero + delta = torch.where(ray_xy_norm > 0.0, delta, torch.tensor(0.0, device=device)) + ray_xy_norm = torch.where( + ray_xy_norm > 0.0, ray_xy_norm, torch.tensor(1.0, device=device) + ) + + # compute pixel relative to center + scale = delta / ray_xy_norm + + pixel_x = img_cx + scale * ray_x + pixel_y = img_cy + scale * ray_y + pixels = torch.stack([pixel_x, pixel_y], dim=3) + + return pixels + + +def convert_to_2d_camera_model( + xyz: np.ndarray, ft_camera: FThetaCamera +) -> Tuple[np.ndarray, np.ndarray]: + """Converts a series of points in xyz to 2D camera coordinates. + + Args: + xyz: Batch of points [x, 3] in shape. + ft_camera: The camera model to use for the conversion to 2D coordinates. + + Returns: + Points in camera uv coordinates. + """ + P = np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0]]) + flu = P @ xyz.T + uv = ft_camera.ray2pixel(flu.T) + return uv + + +def unit_test_downsample(): + cx = 1931.257881559029 + cy = 1509.477889795519 + height = 2160 + width = 3840 + + # front wide 120's bw poly + bw_poly = [0, 0.0005280342432281367, 3.440655735426777e-09, -5.025598287293601e-12, 5.143362581269205e-15, 0] + ftheta_camera = FThetaCamera(cx, cy, width, height, bw_poly) + print(ftheta_camera._fw_poly) + + # downsample 2x + bw_poly_downsample = [p * 2**i for i, p in enumerate(bw_poly)] + ftheta_camera_downsample = FThetaCamera(cx / 2, cy / 2, width / 2, height / 2, bw_poly_downsample) + print(ftheta_camera_downsample._fw_poly) + + +def unit_test_bw_poly_inverse(): + cx = 1931.257881559029 + cy = 1509.477889795519 + height = 2160 + width = 3840 + + # front wide 120's bw poly + bw_poly = [0, 0.0005280342432281367, 3.440655735426777e-09, -5.025598287293601e-12, 5.143362581269205e-15, 0] + ftheta_camera = FThetaCamera(cx, cy, width, height, bw_poly) + fw_poly = ftheta_camera._fw_poly.coef + print(fw_poly) + + # use fw_poly to compute the inverse + ftheta_camera_fw_input = FThetaCamera(cx, cy, width, height, fw_poly, is_bw_poly=False) + bw_poly = ftheta_camera_fw_input._bw_poly.coef + print(bw_poly) + + +if __name__ == "__main__": + unit_test_downsample() \ No newline at end of file diff --git a/utils/checkpointer.py b/utils/checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..c21cb568f9a99f61ed1ff5d1bb292caef98d42d4 --- /dev/null +++ b/utils/checkpointer.py @@ -0,0 +1,279 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import threading +from typing import TYPE_CHECKING + +import torch + +from utils import callback, distributed, ema, log, misc +from utils.atomic_save import atomic_torch_save, atomic_write_text +from utils.model import Model + +if TYPE_CHECKING: + from utils.config import CheckpointConfig, JobConfig + + +class Checkpointer: + """The checkpointer class. Supports checkpoint saving/loading to local disk.""" + + def __init__(self, config_checkpoint: CheckpointConfig, config_job: JobConfig, callbacks: callback.CallBackGroup): + """Constructor of the checkpointer. + + Args: + config_checkpoint (CheckpointConfig): The config object for the checkpointer. + """ + # Set the callback functions. + self.callbacks = callbacks + self.checkpoint_dir_local = f"{config_job.path_local}/checkpoints" + self.strict_resume = config_checkpoint.strict_resume + self.load_path = config_checkpoint.load_path or None + self.load_training_state = config_checkpoint.load_training_state + self.only_load_scheduler_state = config_checkpoint.only_load_scheduler_state + self.load_ema_to_reg = config_checkpoint.load_ema_to_reg + self.save_thread = None + + def save( + self, + model: Model, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int, + ) -> None: + """Save network weights, optimizer parameters, scheduler parameters to a checkpoint. + + Args: + model (Model): The PyTorch model. + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + grad_scaler (torch.amp.GradScaler): The gradient scaler (for mixed precision training). + iteration (int): Current iteration number. + """ + self.callbacks.on_save_checkpoint_start(model, iteration) + + checkpoint_file = f"ckpt.pt" + + if distributed.get_rank() == 0: + state_dict = dict( + model=model.state_dict(), + optimizer=optimizer.state_dict(), + scheduler=scheduler.state_dict(), + grad_scaler=grad_scaler.state_dict(), + iteration=iteration, + ) + state_dict = misc.to(state_dict, device="cpu") + self.callbacks.on_save_checkpoint(model, state_dict=state_dict) + # Wait for previous saver thread to end. + if self.save_thread: + self.save_thread.join() + # Run the checkpoint saver in a separate thread. + self.save_thread = threading.Thread( + target=self._save_worker_local, + daemon=False, + args=(state_dict, checkpoint_file, distributed.get_rank()), + ) + self.save_thread.start() + + # Note: Checkpoints are saved on a separate thread and this callback is not accurate. + # Please check logs from on_save_checkpoint_success() for better accuracy + self.callbacks.on_save_checkpoint_end(model=None, iteration=iteration) + + @misc.timer("checkpoint saving (local)") + def _save_worker_local(self, state_dict: dict[str, torch.Tensor], checkpoint_file: str, rank: int = 0) -> None: + """Worker to save checkpoint to local disk, spawned with a child thread (runs in parallel with the training). + + Args: + state_dict (dict[str, torch.Tensor]): The state dict of the model/optimizer/scheduler. + checkpoint_file (str): The file name of the model checkpoint. + rank (int): GPU device (default: 0). + """ + checkpoint_path = os.path.join(self.checkpoint_dir_local, checkpoint_file) + os.makedirs(self.checkpoint_dir_local, exist_ok=True) + try: + # tmp+fsync+rename, with zip-validity check, so a SIGTERM/SIGKILL + # mid-write can't leave a torn .pt file that breaks resume. + atomic_torch_save(state_dict, checkpoint_path) + if rank == 0: + self._write_latest_checkpoint_file(checkpoint_file) + log.success(f"Saved checkpoint (local): {checkpoint_path}") + iteration = int(checkpoint_file.replace("iter_", "").replace(".pt", "")) + self.callbacks.on_save_checkpoint_success(iteration=iteration) + except Exception as e: # noqa: BLE001 + log.exception(f"Checkpoint failed to save (local): {e}") + + @misc.timer("checkpoint loading") + def load( + self, + model: Model, + optimizer: torch.optim.Optimizer | None = None, + scheduler: torch.optim.lr_scheduler.LRScheduler | None = None, + grad_scaler: torch.amp.GradScaler | None = None, + ) -> int: + """Load network weights and optimizer states from a checkpoint in a single process. + + The priority of the checkpoint loading logic is: + 1. Attempt to resume training if possible by looking for latest_checkpoint.txt under the same name. + 2. If no latest checkpoint were found, it loads the model weights specified by config_checkpoint.path. + - This is typically used for inference mode. + - If config_checkpoint.load_optimizer_state is True, then also load the optimizer and scheduler states. + 3. If none of the above, randomly initialize the model parameters and train from scratch. + + Args: + model (Model): The PyTorch model. + optimizer (torch.optim.Optimizer | None): The model optimizer (default: None). + scheduler (torch.optim.lr_scheduler.LRScheduler | None): The optimization scheduler (default: None). + grad_scaler (torch.amp.GradScaler | None): The gradient scaler (for mixed precision training). + + Returns: + iteration (int): the iteration number to start/resume from. + """ + self.callbacks.on_load_checkpoint_start(model) + + latest_checkpoint_file = self._read_latest_checkpoint_file() + if latest_checkpoint_file is not None: + # 1. Resume training from latest_checkpoint.txt under the same name. + checkpoint_dir = self.checkpoint_dir_local + checkpoint_path = os.path.join(checkpoint_dir, latest_checkpoint_file) + resume = True + only_resume_scheduler = True + else: + if self.load_path: + # 2. Load the module weights specified by config_checkpoint.path. + checkpoint_path = self.load_path + resume = self.load_training_state + only_resume_scheduler = self.only_load_scheduler_state + else: + # 3. Randomly initialize the model parameters and train from scratch. + checkpoint_path = None + resume = False + only_resume_scheduler = False + # Load checkpoint. + if checkpoint_path is not None: + self._check_checkpoint_exists(checkpoint_path) + log.info(f"Loading checkpoint (local): {checkpoint_path}") + state_dict = torch.load(checkpoint_path, map_location=lambda storage, loc: storage, weights_only=False) + log.success(f"Complete loading checkpoint (local): {checkpoint_path}") + self.callbacks.on_load_checkpoint(model, state_dict=state_dict) + if self.load_ema_to_reg: + self._copy_ema_weights_to_regular_model(model, state_dict) + # Load the state dicts. + log.info("- Loading the model...") + if "model" in state_dict: + model.load_state_dict(state_dict["model"], strict=self.strict_resume) + else: + model.load_state_dict(state_dict, strict=self.strict_resume) + if resume or only_resume_scheduler: + iteration = state_dict["iteration"] + assert scheduler + log.info("- Loading the scheduler...") + scheduler.load_state_dict(state_dict["scheduler"]) + scheduler.last_epoch = iteration + else: + iteration = 0 + if resume: + assert optimizer + log.info("- Loading the optimizer...") + optimizer.load_state_dict(state_dict["optimizer"]) + log.info("- Loading the gradient scaler...") + grad_scaler.load_state_dict(state_dict["grad_scaler"]) + log.success(f"Done with loading the checkpoint (iteration {iteration}).") + else: + log.success("Done with loading the checkpoint.") + else: + # Checkpoint not found and not specified. We will train everything from scratch. + iteration = 0 + log.info("Training from scratch.") + torch.cuda.empty_cache() + + self.callbacks.on_load_checkpoint_end(model) + + return iteration + + @staticmethod + def _copy_ema_weights_to_regular_model(model: Model, state_dict: dict) -> None: + model_state = state_dict.get("model", state_dict) + compile_renaming = getattr( + getattr(model, "ema", None), + "torch_compile_buffer_renaming", + False, + ) + copied = 0 + adapted = 0 + for name, parameter in model.named_parameters(): + ema_key = f"ema.{ema.get_buffer_name(name, compile_renaming)}" + ema_weight = model_state.get(ema_key) + if ema_weight is None: + continue + if ema_weight.shape != parameter.shape: + adapter = getattr(model, "adapt_warmstart_tensor", None) + ema_weight = ( + adapter(name, ema_weight, parameter) + if adapter is not None + else None + ) + if ema_weight is None: + continue + adapted += 1 + model_state[name] = ema_weight + copied += 1 + if copied == 0: + raise ValueError( + "checkpoint.load_ema_to_reg=True, but no compatible EMA " + "parameters were found in the checkpoint" + ) + log.info( + f"Initialized {copied} regular model parameters from EMA weights " + f"({adapted} channel-surgery adapted)." + ) + + def _read_latest_checkpoint_file(self) -> str | None: + """Get the file name of the latest saved checkpoint. If it doesn't exist, return None. + + Returns: + checkpoint_file (str | None): file name of the latest saved checkpoint. + """ + checkpoint_file = None + latest_path = os.path.join(self.checkpoint_dir_local, "latest_checkpoint.txt") + if os.path.isfile(latest_path): + checkpoint_file = open(latest_path).read().strip() + return checkpoint_file + + def _write_latest_checkpoint_file(self, checkpoint_file: str) -> None: + """Track the file name of the latest saved checkpoint. + + Args: + checkpoint_file (str): file name of the latest saved checkpoint. + """ + content = f"{checkpoint_file}\n" + latest_path = os.path.join(self.checkpoint_dir_local, "latest_checkpoint.txt") + atomic_write_text(latest_path, content) + + def _check_checkpoint_exists(self, checkpoint_path: str) -> None: + """If the file checkpoint_path does not exist, raise an error. + + Args: + checkpoint_path (str): full path to the checkpoint. + """ + if not os.path.exists(checkpoint_path): + raise FileNotFoundError(f"File not found (local): {checkpoint_path}") + + def finalize(self) -> None: + """Finalize the checkpointer.""" + if self.save_thread: + self.save_thread.join() diff --git a/utils/config.py b/utils/config.py new file mode 100644 index 0000000000000000000000000000000000000000..cb91367c36642274fa02a5f04421973e74c7d29e --- /dev/null +++ b/utils/config.py @@ -0,0 +1,342 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +from typing import Any, Dict, Optional, Type, TypeVar, Union + +import attrs +import torch +from megatron.core import ModelParallelConfig + +from utils import callback +from utils.lazy_config import LazyCall as L +from utils.lazy_config import LazyDict +from utils.misc import Color + +T = TypeVar("T") + + +def _is_attrs_instance(obj: object) -> bool: + """ + Helper function to check if an object is an instance of an attrs-defined class. + + Args: + obj: The object to check. + + Returns: + bool: True if the object is an instance of an attrs-defined class, False otherwise. + """ + return hasattr(obj, "__attrs_attrs__") + + +def make_freezable(cls: T) -> T: + """ + A decorator that adds the capability to freeze instances of an attrs-defined class. + + NOTE: This requires the wrapped attrs to be defined with attrs.define(slots=False) because we need + to hack on a "_is_frozen" attribute. + + This decorator enhances an attrs-defined class with the ability to be "frozen" at runtime. + Once an instance is frozen, its attributes cannot be changed. It also recursively freezes + any attrs-defined objects that are attributes of the class. + + Usage: + @make_freezable + @attrs.define(slots=False) + class MyClass: + attribute1: int + attribute2: str + + obj = MyClass(1, 'a') + obj.freeze() # Freeze the instance + obj.attribute1 = 2 # Raises AttributeError + + Args: + cls: The class to be decorated. + + Returns: + The decorated class with added freezing capability. + """ + + if not hasattr(cls, "__dict__"): + raise TypeError( + "make_freezable cannot be used with classes that do not define __dict__. Make sure that the wrapped " + "class was defined with `@attrs.define(slots=False)`" + ) + + original_setattr = cls.__setattr__ + + def setattr_override(self, key, value) -> None: # noqa: ANN001 + """ + Override __setattr__ to allow modifications during initialization + and prevent modifications once the instance is frozen. + """ + if hasattr(self, "_is_frozen") and self._is_frozen and key != "_is_frozen": + raise AttributeError("Cannot modify frozen instance") + original_setattr(self, key, value) # type: ignore + + cls.__setattr__ = setattr_override # type: ignore + + def freeze(self: object) -> None: + """ + Freeze the instance and all its attrs-defined attributes. + """ + for _, value in attrs.asdict(self, recurse=False).items(): + if _is_attrs_instance(value) and hasattr(value, "freeze"): + value.freeze() + self._is_frozen = True # type: ignore + + cls.freeze = freeze # type: ignore + + return cls + + +def _pretty_print_attrs_instance(obj: object, indent: int = 0, use_color: bool = False) -> str: + """ + Recursively pretty prints attrs objects with color. + """ + + assert attrs.has(obj.__class__) + + lines: list[str] = [] + for attribute in attrs.fields(obj.__class__): + value = getattr(obj, attribute.name) + if attrs.has(value.__class__): + if use_color: + lines.append(" " * indent + Color.cyan("* ") + Color.green(attribute.name) + ":") + else: + lines.append(" " * indent + "* " + attribute.name + ":") + lines.append(_pretty_print_attrs_instance(value, indent + 1, use_color)) + else: + if use_color: + lines.append( + " " * indent + Color.cyan("* ") + Color.green(attribute.name) + ": " + Color.yellow(value) + ) + else: + lines.append(" " * indent + "* " + attribute.name + ": " + str(value)) + return "\n".join(lines) + + +def pretty_print_overrides(overrides: Optional[list[str]] = None, use_color: bool = False) -> str: + """ + Pretty prints overrides. + """ + + lines: list[str] = [] + lines.append(Color.cyan("* ") + Color.green("overrides") + ": ") + for override in overrides: + if override == "--": + continue + attribute_name, attribute_value = override.split("=") + if use_color: + lines.append(" " + Color.cyan("* ") + Color.green(attribute_name) + ": " + Color.yellow(attribute_value)) + else: + lines.append(" " + "* " + attribute_name + ": " + str(attribute_value)) + + return "\n".join(lines) + + +@make_freezable +@attrs.define(slots=False) +class JobConfig: + # Project name. + project: str = "" + # Experiment name. + group: str = "" + # Run/job name. + name: str = "" + + wandb_mode: str = "online" + + @property + def path(self) -> str: + return f"{self.project}/{self.group}/{self.name}" + + @property + def path_local(self) -> str: + local_root = os.environ.get("OUTPUT_ROOT", "checkpoints") + return f"{local_root}/{self.path}" + + +@make_freezable +@attrs.define(slots=False) +class EMAConfig: + # Enable tracking a set of exponential moving average (EMA) weights. + enabled: bool = False + # EMA decay rate. + beta: float = 0.9999 + # Enable removing "_orig_mod-" from buffer names that is added by torch.compile + torch_compile_buffer_renaming: bool = False + + +@make_freezable +@attrs.define(slots=False) +class DDPConfig: + # Traverse the computation graph to find parameters that don't receive gradients. + find_unused_parameters: bool = False + # Set to True if the computation graph does not change during the whole training loop. + static_graph: bool = True + # Set to True if we want to synchronize buffers. Set to False if the sync is going to be handled elsewhere. + broadcast_buffers: bool = True + + +@make_freezable +@attrs.define(slots=False) +class CuDNNConfig: + # Set to True for better reproducibility of the results (only using deterministic cudnn functions). + deterministic: bool = False + # If set to True, cudnn will benchmark several algorithms and pick the fastest one. + benchmark: bool = True + + +@make_freezable +@attrs.define(slots=False) +class JITConfig: + # Enable exporting a JIT compiled model. + enabled: bool = False + # Input tensor shape, for example input. + input_shape: Union[list[int], None] = None + # Device to compile onto. + device: str = "cuda" + # # Data type to compile onto. + dtype: str = "bfloat16" + # Strict mode for PyTorch JIT. + strict: bool = True + + +@make_freezable +@attrs.define(slots=False) +class CheckpointConfig: + # possible checkpoint class + type: Optional[Dict] = None + # for dcp, whether to use async mode + dcp_async_mode_enabled: bool = False + # Save the checkpoint every N iterations. + save_iter: int = 999999999 + # Also save and retain checkpoints at these exact iterations. + save_at_iters: list[int] = [] + # Retain at most this many completed generations when supported. Non-positive disables pruning. + keep_last_checkpoints: int = 0 + # Path of model weights to resume the checkpoint from. + load_path: str = "" + # Whether to load the training states (optimizer/scheduler/grad-scaler) from the checkpoint path. + load_training_state: bool = False + # Whether to load the scheduler state only from the checkpoint path. If load_training_state is True, this will be ignored. + only_load_scheduler_state: bool = False + # Load state_dict to the models in strict mode. + strict_resume: bool = True + # Print detailed information during checkpoint saving/loading. + verbose: bool = True + # Configs for JIT compiling EMA model. + jit: JITConfig = attrs.field(factory=JITConfig) + # keys not to resume from the checkpoint, choices: ["model", "optim", "scheduler", "trainer"] + keys_not_to_resume: list[str] = [] + # Whether to use the local filesystem for broadcasting checkpoint data (used for Tensor Parallel Checkpointer). + broadcast_via_filesystem: bool = False + load_ema_to_reg: bool = False + async_saving: bool = True + + +@make_freezable +@attrs.define(slots=False) +class TrainerConfig: + from utils.trainer import Trainer + + type: Type[Trainer] = Trainer + # Set the callback class. + # Defaults to the callbacks below. + callbacks: LazyDict = LazyDict( + dict( + ema=L(callback.EMAModelCallback)(), + progress_bar=L(callback.ProgressBarCallback)(), + ) + ) + # distributed parallelism strategy + distributed_parallelism: str = "ddp" + # Distributed data parallel configs. + ddp: DDPConfig = attrs.field(factory=DDPConfig) + # cuDNN configs. + cudnn: CuDNNConfig = attrs.field(factory=CuDNNConfig) + # Set the random seed. + seed: int = 0 + # Gradient scaler arguments (for torch.amp.GradScaler). + grad_scaler_args: dict = attrs.field(factory=lambda: dict(enabled=False)) + # Maximum number of iterations to train the model. + max_iter: int = 999999999 + # Maximum number of iterations to validate the model. If None, validate on the entire dataset. + max_val_iter: int | None = None + # How often we log the training stats. + logging_iter: int = 100 + # Whether we want to run the validation routines. + run_validation: bool = True + # How often we evaluate on the validation set. + validation_iter: int = 999999999 + # Kill the process after N seconds since the last iteration (usually means dead job). + timeout_period: int = 999999999 + # Tensor memory organization format. + memory_format: torch.memory_format = torch.preserve_format + # Gradient accumulation (update step every N iteration). + grad_accum_iter: int = 1 + # # Profiling config + # profiling: Profiling = attrs.field(factory=Profiling) + + +@make_freezable +@attrs.define(slots=False) +class Config: + """Config for a job. + + See /README.md/Configuration System for more info. + """ + + # Model configs. + model: LazyDict + # Optimizer configs. + optimizer: LazyDict = LazyDict(dict(dummy=None)) + # Scheduler configs. + scheduler: LazyDict = LazyDict(dict(dummy=None)) + # Training data configs. + dataloader_train: LazyDict = LazyDict(dict(dummy=None)) + # Validation data configs. + dataloader_val: LazyDict = LazyDict(dict(dummy=None)) + + # Training job configs. + job: JobConfig = attrs.field(factory=JobConfig) + + # Trainer configs. + trainer: TrainerConfig = attrs.field(factory=TrainerConfig) + + # Megatron-Core configs + model_parallel: ModelParallelConfig = attrs.field(factory=ModelParallelConfig) + + # Checkpointer configs. + checkpoint: CheckpointConfig = attrs.field(factory=CheckpointConfig) + + def pretty_print(self, use_color: bool = False) -> str: + return _pretty_print_attrs_instance(self, 0, use_color) + + # Training job configs. + job: JobConfig = attrs.field(factory=JobConfig) + + def to_dict(self) -> dict[str, Any]: + return attrs.asdict(self) + + def validate(self) -> None: + """Validate that the config has all required fields.""" + assert self.job.project != "", "Project name is required." + assert self.job.group != "", "Group name is required." + assert self.job.name != "", "Job name is required." diff --git a/utils/config_helper.py b/utils/config_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..7846d0142f514e4b7dd151a0c64f548d8a8ef836 --- /dev/null +++ b/utils/config_helper.py @@ -0,0 +1,196 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import os +import pkgutil +import sys +from dataclasses import fields as dataclass_fields +from dataclasses import is_dataclass +from typing import Any, Dict, Optional + +import attr +import attrs +from hydra import compose, initialize +from hydra.core.config_store import ConfigStore +from omegaconf import DictConfig, OmegaConf + +from utils import log +from utils.config import Config + + +def is_attrs_or_dataclass(obj) -> bool: + """ + Check if the object is an instance of an attrs class or a dataclass. + + Args: + obj: The object to check. + + Returns: + bool: True if the object is an instance of an attrs class or a dataclass, False otherwise. + """ + return is_dataclass(obj) or attr.has(type(obj)) + + +def get_fields(obj): + """ + Get the fields of an attrs class or a dataclass. + + Args: + obj: The object to get fields from. Must be an instance of an attrs class or a dataclass. + + Returns: + list: A list of field names. + + Raises: + ValueError: If the object is neither an attrs class nor a dataclass. + """ + if is_dataclass(obj): + return [field.name for field in dataclass_fields(obj)] + elif attr.has(type(obj)): + return [field.name for field in attr.fields(type(obj))] + else: + raise ValueError("The object is neither an attrs class nor a dataclass.") + + +def override(config: Config, overrides: Optional[list[str]] = None) -> Config: + """ + :param config: the instance of class `Config` (usually from `make_config`) + :param overrides: list of overrides for config + :return: the composed instance of class `Config` + """ + # Store the class of the config for reconstruction after overriding. + # config_class = type(config) + + # Convert Config object to a DictConfig object + config_dict = attrs.asdict(config) + config_omegaconf = DictConfig(content=config_dict, flags={"allow_objects": True}) + # Enforce "--" separator between the script arguments and overriding configs. + if overrides: + if overrides[0] != "--": + raise ValueError('Hydra config overrides must be separated with a "--" token.') + overrides = overrides[1:] + # Use Hydra to handle overrides + cs = ConfigStore.instance() + cs.store(name="config", node=config_omegaconf) + with initialize(version_base=None): + config_omegaconf = compose(config_name="config", overrides=overrides) + OmegaConf.resolve(config_omegaconf) + + def config_from_dict(ref_instance: Any, kwargs: Any) -> Any: + """ + Construct an instance of the same type as ref_instance using the provided dictionary or data or unstructured data + + Args: + ref_instance: The reference instance to determine the type and fields when needed + kwargs: A dictionary of keyword arguments to use for constructing the new instance or primitive data or unstructured data + + Returns: + Any: A new instance of the same type as ref_instance constructed using the provided kwargs or the primitive data or unstructured data + + Raises: + AssertionError: If the fields do not match or if extra keys are found. + Exception: If there is an error constructing the new instance. + """ + is_type = is_attrs_or_dataclass(ref_instance) + if not is_type: + return kwargs + else: + ref_fields = set(get_fields(ref_instance)) + assert isinstance(kwargs, dict) or isinstance( + kwargs, DictConfig + ), "kwargs must be a dictionary or a DictConfig" + keys = set(kwargs.keys()) + + # ref_fields must equal to or include all keys + extra_keys = keys - ref_fields + assert ref_fields == keys or keys.issubset( + ref_fields + ), f"Fields mismatch: {ref_fields} != {keys}. Extra keys found: {extra_keys} \n \t when constructing {type(ref_instance)} with {keys}" + + resolved_kwargs: Dict[str, Any] = {} + for f in keys: + resolved_kwargs[f] = config_from_dict(getattr(ref_instance, f), kwargs[f]) + try: + new_instance = type(ref_instance)(**resolved_kwargs) + except Exception as e: + log.error(f"Error when constructing {type(ref_instance)} with {resolved_kwargs}") + log.error(e) + raise e + return new_instance + + config = config_from_dict(config, config_omegaconf) + + return config + + +def get_config_module(config_file: str) -> str: + if not config_file.endswith(".py"): + log.error("Config file cannot be specified as module.") + log.error("Please provide the path to the Python config file (relative to the Cosmos root).") + assert os.path.isfile(config_file), f"Cosmos config file ({config_file}) not found." + # Convert to importable module format. + config_module = config_file.replace("/", ".").replace(".py", "") + return config_module + + +def import_all_modules_from_package(package_path: str, reload: bool = False, skip_underscore: bool = True) -> None: + """ + Import all modules from the specified package path recursively. + + This function is typically used in conjunction with Hydra to ensure that all modules + within a specified package are imported, which is necessary for registering configurations. + + Example usage: + ```python + import_all_modules_from_package("diffusion.config.inference", reload=True, skip_underscore=False) + ``` + + Args: + package_path (str): The dotted path to the package from which to import all modules. + reload (bool): Flag to determine whether to reload modules if they're already imported. + skip_underscore (bool): If True, skips importing modules that start with an underscore. + """ + log.debug(f"{'Reloading' if reload else 'Importing'} all modules from package {package_path}") + package = importlib.import_module(package_path) + package_directory = package.__path__ + + def import_modules_recursively(directory: str, prefix: str) -> None: + """ + Recursively imports or reloads all modules in the given directory. + + Args: + directory (str): The file system path to the current package directory. + prefix (str): The module prefix (e.g., 'models.diffusion.config'). + """ + for _, module_name, is_pkg in pkgutil.iter_modules([directory]): + if skip_underscore and module_name.startswith("_"): + log.debug(f"Skipping module {module_name} as it starts with an underscore") + continue + + full_module_name = f"{prefix}.{module_name}" + log.debug(f"{'Reloading' if reload else 'Importing'} module {full_module_name}") + + if full_module_name in sys.modules and reload: + importlib.reload(sys.modules[full_module_name]) + else: + importlib.import_module(full_module_name) + + if is_pkg: + sub_package_directory = os.path.join(directory, module_name) + import_modules_recursively(sub_package_directory, full_module_name) + + for directory in package_directory: + import_modules_recursively(directory, package_path) diff --git a/utils/device.py b/utils/device.py new file mode 100644 index 0000000000000000000000000000000000000000..db486afabd4ae0bf11feb05d8a4efd96690ce64b --- /dev/null +++ b/utils/device.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import os + +import pynvml + + +class Device: + """A class to handle NVIDIA GPU device operations using NVML. + + This class provides an interface to access and manage NVIDIA GPU devices, + including retrieving device information and CPU affinity settings. + + Attributes: + _nvml_affinity_elements (int): Number of 64-bit elements needed to represent CPU affinity + """ + + _nvml_affinity_elements = math.ceil(os.cpu_count() / 64) # type: ignore + + def __init__(self, device_idx: int): + """Initialize a Device instance for a specific GPU. + + Args: + device_idx (int): Index of the GPU device to manage + + Raises: + NVMLError: If the device cannot be found or initialized + """ + super().__init__() + self.handle = pynvml.nvmlDeviceGetHandleByIndex(device_idx) + + def get_cpu_affinity(self) -> list[int]: + """Get the CPU affinity mask for this GPU device. + + Retrieves the CPU affinity mask indicating which CPU cores are assigned + to this GPU device. The affinity is returned as a list of CPU core indices. + + Returns: + list[int]: List of CPU core indices that have affinity with this GPU + + Raises: + NVMLError: If the CPU affinity information cannot be retrieved + + Example: + >>> device = Device(0) + >>> device.get_cpu_affinity() + [0, 1, 2, 3] # Shows this GPU has affinity with CPU cores 0-3 + """ + affinity_string = "" + for j in pynvml.nvmlDeviceGetCpuAffinity(self.handle, Device._nvml_affinity_elements): + # assume nvml returns list of 64 bit ints + affinity_string = "{:064b}".format(j) + affinity_string + affinity_list = [int(x) for x in affinity_string] + affinity_list.reverse() # so core 0 is in 0th element of list + return [i for i, e in enumerate(affinity_list) if e != 0] diff --git a/utils/distributed.py b/utils/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..4c20fe7619b7be069b9069bf35b0a9115e13b0b2 --- /dev/null +++ b/utils/distributed.py @@ -0,0 +1,449 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import collections +import collections.abc +import ctypes +import functools +import os +from contextlib import contextmanager +from datetime import timedelta +from typing import TYPE_CHECKING, Any, Callable, Container, Optional + +import torch +import torch.distributed as dist +from torch.distributed import get_process_group_ranks + +from utils import log + +try: + import pynvml + + from utils.device import Device +except ImportError: + pynvml = None + Device = None + +if TYPE_CHECKING: + from utils.config import DDPConfig + +if dist.is_available(): + from torch.distributed.distributed_c10d import _get_default_group + from torch.distributed.utils import _sync_module_states, _verify_param_shape_across_processes + + +try: + from megatron.core import parallel_state +except ImportError: + print("Megatron-core is not installed.") + + +def init() -> int | None: + """Initialize distributed training.""" + local_rank = int(os.getenv("LOCAL_RANK", 0)) + # CPU affinity is an optional topology optimization, not a CUDA requirement. + if pynvml is None or Device is None: + log.info("pynvml is unavailable; skipping GPU-local CPU affinity") + else: + try: + pynvml.nvmlInit() + device = Device(local_rank) + os.sched_setaffinity(0, device.get_cpu_affinity()) + except Exception as e: + log.info(f"Error setting CPU affinity: {e}") + # Set up NCCL communication. + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = "0" + os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "1" + if dist.is_available(): + if dist.is_initialized(): + return torch.cuda.current_device() + torch.cuda.set_device(local_rank) + # Get the timeout value from environment variable + timeout_seconds = os.getenv("TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC", 1800) + # Convert the timeout to an integer (if it isn't already) and then to a timedelta + timeout_timedelta = timedelta(seconds=int(timeout_seconds)) + dist.init_process_group(backend="nccl", init_method="env://", timeout=timeout_timedelta) + log.critical( + f"Initialized distributed program with local rank {local_rank} with timeout {timeout_seconds}", + rank0_only=False, + ) + # Increase the L2 fetch granularity for faster speed. + _libcudart = ctypes.CDLL("libcudart.so") + # Set device limit on the current device. + p_value = ctypes.cast((ctypes.c_int * 1)(), ctypes.POINTER(ctypes.c_int)) + _libcudart.cudaDeviceSetLimit(ctypes.c_int(0x05), ctypes.c_int(128)) + _libcudart.cudaDeviceGetLimit(p_value, ctypes.c_int(0x05)) + log.info(f"Running with {get_world_size()} GPUs.") + + +def get_rank(group: Optional[dist.ProcessGroup] = None) -> int: + """Get the rank (GPU device) of the worker. + + Returns: + rank (int): The rank of the worker. + """ + rank = 0 + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank(group) + return rank + + +def get_world_size(group: Optional[dist.ProcessGroup] = None) -> int: + """Get world size. How many GPUs are available in this job. + + Returns: + world_size (int): The total number of GPUs available in this job. + """ + world_size = 1 + if dist.is_available() and dist.is_initialized(): + world_size = dist.get_world_size(group) + return world_size + + +def is_rank0() -> bool: + """Check if current process is the master GPU. + + Returns: + (bool): True if this function is called from the master GPU, else False. + """ + return get_rank() == 0 + + +def is_local_rank0() -> bool: + """Check if current process is the local master GPU in the current node. + + Returns: + (bool): True if this function is called from the local master GPU, else False. + """ + return torch.cuda.current_device() == 0 + + +def rank0_only(func: Callable) -> Callable: + """Apply this function only to the master GPU. + + Example usage: + @rank0_only + def func(x): + return x + 3 + + Args: + func (Callable): a function. + + Returns: + (Callable): A function wrapper executing the function only on the master GPU. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): # noqa: ANN202 + if is_rank0(): + return func(*args, **kwargs) + else: + return None + + return wrapper + + +def barrier() -> None: + """Barrier for all GPUs.""" + if dist.is_available() and dist.is_initialized(): + dist.barrier() + + +def rank0_first(func: Callable) -> Callable: + """run the function on rank 0 first, then on other ranks.""" + + @functools.wraps(func) + def wrapper(*args, **kwargs): # noqa: ANN202 + if is_rank0(): + result = func(*args, **kwargs) + barrier() + if not is_rank0(): + result = func(*args, **kwargs) + return result + + return wrapper + + +def parallel_model_wrapper(config_ddp: DDPConfig, model: torch.nn.Module) -> torch.nn.Module | DistributedDataParallel: + """Wraps the model to enable data parallalism for training across multiple GPU devices. + + Args: + config_ddp (DDPConfig): The data parallel config. + model (torch.nn.Module): The PyTorch module. + + Returns: + model (torch.nn.Module | DistributedDataParallel): The data parallel model wrapper + if distributed environment is available, otherwise return the original model. + """ + if dist.is_available() and dist.is_initialized(): + local_rank = int(os.getenv("LOCAL_RANK", 0)) + try: + ddp_group = parallel_state.get_data_parallel_group(with_context_parallel=True) + except Exception as e: + log.info(e) + log.info("parallel_state not initialized, treating all GPUs equally for DDP") + ddp_group = None + + model = DistributedDataParallel( + model, + device_ids=[local_rank], + output_device=local_rank, + find_unused_parameters=config_ddp.find_unused_parameters, + static_graph=config_ddp.static_graph, + broadcast_buffers=config_ddp.broadcast_buffers, + process_group=ddp_group, + ) + return model + + +class DistributedDataParallel(torch.nn.parallel.DistributedDataParallel): + """This extends torch.nn.parallel.DistributedDataParallel with .training_step(). + + This borrows the concept of `forward-redirection` from Pytorch lightning. It wraps an coreModel such that + model.training_step() would be executed when calling self.training_step(), while preserving the behavior of calling + model() for Pytorch modules. Internally, this is a double rerouting mechanism (training_step -> forward -> + training_step), allowing us to preserve the function names and signatures. + """ + + def __init__(self, model: torch.nn.Module, *args, **kwargs): + super().__init__(model, *args, **kwargs) + self.show_sync_grad_static_graph_warning = True + + def training_step(self, *args, **kwargs) -> Any: + # Cache the original model.forward() method. + original_forward = self.module.forward + + def wrapped_training_step(*_args, **_kwargs): # noqa: ANN202 + # Unpatch immediately before calling training_step() because itself may want to call the real forward. + self.module.forward = original_forward + # The actual .training_step(). + return self.module.training_step(*_args, **_kwargs) + + # Patch the original_module's forward so we can redirect the arguments back to the real method. + self.module.forward = wrapped_training_step + # Call self, which implicitly calls self.forward() --> model.forward(), which is now model.training_step(). + # Without calling self.forward() or model.forward() explciitly, implicit hooks are also executed. + return self(*args, **kwargs) + + +@contextmanager +def ddp_sync_grad(model, enabled): + r""" + Context manager to enable/disable gradient synchronizations across DDP processes for DDP model. + Modified from: + https://pytorch.org/docs/stable/_modules/torch/nn/parallel/distributed.html#DistributedDataParallel.no_sync + Note that this is incompatible with static_graph=True and will be an no-op if static_graph=True. + + Within this context, gradients will be accumulated on module + variables, which will later be synchronized in the first + forward-backward pass exiting the context. + + .. warning:: + The forward pass should be included inside the context manager, or + else gradients will still be synchronized. + """ + assert isinstance(model, torch.nn.Module) + if isinstance(model, DistributedDataParallel): + old_require_backward_grad_sync = model.require_backward_grad_sync + if model.static_graph and model.require_backward_grad_sync != enabled: + if model.show_sync_grad_static_graph_warning: + log.warning("DDP static_graph=True is incompatible with sync_grad(). Performance will be reduced.") + model.show_sync_grad_static_graph_warning = False + else: + model.require_backward_grad_sync = enabled + try: + yield + finally: + if isinstance(model, DistributedDataParallel): + model.require_backward_grad_sync = old_require_backward_grad_sync + + +def collate_batches(data_batches: list[dict[str, torch.Tensor]]) -> torch.Tensor | dict[str, torch.Tensor]: + """Aggregate the list of data batches from all devices and process the results. + + This is used for gathering validation data batches with utils.dataloader.DistributedEvalSampler. + It will return the data/output of the entire validation set in its original index order. The sizes of data_batches + in different ranks may differ by 1 (if dataset size is not evenly divisible), in which case a dummy sample will be + created before calling dis.all_gather(). + + Args: + data_batches (list[dict[str, torch.Tensor]]): List of tensors or (hierarchical) dictionary where + leaf entries are tensors. + + Returns: + data_gather (torch.Tensor | dict[str, torch.Tensor]): tensors or (hierarchical) dictionary where + leaf entries are concatenated tensors. + """ + if isinstance(data_batches[0], torch.Tensor): + # Concatenate the local data batches. + data_concat = torch.cat(data_batches, dim=0) # type: ignore + # Get the largest number of local samples from all ranks to determine whether to dummy-pad on this rank. + max_num_local_samples = torch.tensor(len(data_concat), device="cuda") + dist.all_reduce(max_num_local_samples, op=dist.ReduceOp.MAX) + if len(data_concat) < max_num_local_samples: + assert len(data_concat) + 1 == max_num_local_samples + dummy = torch.empty_like(data_concat[:1]) + data_concat = torch.cat([data_concat, dummy], dim=0) + dummy_count = torch.tensor(1, device="cuda") + else: + dummy_count = torch.tensor(0, device="cuda") + # Get all concatenated batches from all ranks and concatenate again. + dist.all_reduce(dummy_count, op=dist.ReduceOp.SUM) + data_concat = all_gather_tensor(data_concat.contiguous()) + data_collate = torch.stack(data_concat, dim=1).flatten(start_dim=0, end_dim=1) + # Remove the dummy samples. + if dummy_count > 0: + data_collate = data_collate[:-dummy_count] + elif isinstance(data_batches[0], collections.abc.Mapping): + data_collate = dict() + for key in data_batches[0].keys(): + data_collate[key] = collate_batches([data[key] for data in data_batches]) # type: ignore + else: + raise TypeError + return data_collate + + +@torch.no_grad() +def all_gather_tensor(tensor: torch.Tensor) -> list[torch.Tensor]: + """Gather the corresponding tensor from all GPU devices to a list. + + Args: + tensor (torch.Tensor): Pytorch tensor. + + Returns: + tensor_list (list[torch.Tensor]): A list of Pytorch tensors gathered from all GPU devices. + """ + tensor_list = [torch.zeros_like(tensor) for _ in range(get_world_size())] + dist.all_gather(tensor_list, tensor) + return tensor_list + + +def broadcast(tensor, src, group=None, async_op=False): + world_size = get_world_size() + if world_size < 2: + return tensor + dist.broadcast(tensor, src=src, group=group, async_op=async_op) + + +def sync_model_states( + model: torch.nn.Module, + process_group: Optional[dist.ProcessGroup] = None, + src: int = 0, + params_and_buffers_to_ignore: Optional[Container[str]] = None, + broadcast_buffers: bool = True, +): + """ + Modify based on DDP source code + Synchronizes the parameters and buffers of a model across different processes in a distributed setting. + + This function ensures that all processes in the specified process group have the same initial parameters and + buffers from the source rank, typically rank 0. It is useful when different processes start with different model + states and a synchronization is required to ensure consistency across all ranks. + + Args: + model (nn.Module): The model whose parameters and buffers are to be synchronized. + process_group (dist.ProcessGroup, optional): The process group for communication. If None, + the default group is used. Defaults to None. + src (int, optional): The source rank from which parameters and buffers will be broadcasted. + Defaults to 0. + params_and_buffers_to_ignore (Optional[Container[str]], optional): A container of parameter and buffer + names to exclude from synchronization. Defaults to None, which means all parameters and buffers are + included. + broadcast_buffers (bool, optional): Whether to broadcast buffers or not. Defaults to True. + + Side Effects: + This function modifies the state of the model in-place to synchronize it with the source rank's model state. + + Raises: + RuntimeError: If the shapes of parameters across processes do not match, a runtime error will be raised. + + Examples: + >>> # downloading duplicated model weights from s3 in each rank and save network bandwidth + >>> # useful and save our time when model weights are huge + >>> if dist.get_rank == 0: + >>> model.load_state_dict(network_bound_weights_download_fn(s3_weights_path)) + >>> dist.barrir() + >>> sync_model_states(model) # sync rank0 weights to other ranks + """ + if process_group is None: + process_group = _get_default_group() + if not params_and_buffers_to_ignore: + params_and_buffers_to_ignore = set() + + log.info( + f"Synchronizing model states from rank {src} to all ranks in process group {get_process_group_ranks(process_group)}." + ) + + # Build tuple of (module, parameter) for all parameters that require grads. + modules_and_parameters = [ + (module, parameter) + for module_name, module in model.named_modules() + for parameter in [ + param + # Note that we access module.named_parameters instead of + # parameters(module). parameters(module) is only needed in the + # single-process multi device case, where it accesses replicated + # parameters through _former_parameters. + for param_name, param in module.named_parameters(recurse=False) + if f"{module_name}.{param_name}" not in params_and_buffers_to_ignore + # if param.requires_grad + # and f"{module_name}.{param_name}" not in params_and_buffers_to_ignore + ] + ] + + # Deduplicate any parameters that might be shared across child modules. + memo = set() + modules_and_parameters = [ + # "p not in memo" is the deduplication check. + # "not memo.add(p)" is always True, and it's only there to cause "add(p)" if needed. + (m, p) + for m, p in modules_and_parameters + if p not in memo and not memo.add(p) # type: ignore[func-returns-value] + ] + + # Build list of parameters. + parameters = [parameter for _, parameter in modules_and_parameters] + if len(parameters) == 0: + return + + _verify_param_shape_across_processes(process_group, parameters) + + _sync_module_states( + module=model, + process_group=process_group, + broadcast_bucket_size=int(250 * 1024 * 1024), + src=src, + params_and_buffers_to_ignore=params_and_buffers_to_ignore, + broadcast_buffers=broadcast_buffers, + ) + + +def dist_reduce_tensor(tensor, rank=0, reduce="mean"): + r"""Reduce to rank 0""" + world_size = get_world_size() + if world_size < 2: + return tensor + with torch.no_grad(): + dist.reduce(tensor, dst=rank) + if get_rank() == rank: + if reduce == "mean": + tensor /= world_size + elif reduce == "sum": + pass + else: + raise NotImplementedError + return tensor diff --git a/utils/easy_io/__init__.py b/utils/easy_io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3159bfe65645499015bd92609b99d476d69544e9 --- /dev/null +++ b/utils/easy_io/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/utils/easy_io/backends/__init__.py b/utils/easy_io/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b598e88a9318ecaf97f0af32da1a7b3907a81f80 --- /dev/null +++ b/utils/easy_io/backends/__init__.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from utils.easy_io.backends.base_backend import BaseStorageBackend +from utils.easy_io.backends.http_backend import HTTPBackend +from utils.easy_io.backends.local_backend import LocalBackend +from utils.easy_io.backends.registry_utils import backends, prefix_to_backends, register_backend + +__all__ = [ + "BaseStorageBackend", + "LocalBackend", + "HTTPBackend", + "register_backend", + "backends", + "prefix_to_backends", +] diff --git a/utils/easy_io/backends/base_backend.py b/utils/easy_io/backends/base_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..2db3b921f0b6fdb3aaea867c0bb3cafdb5e59888 --- /dev/null +++ b/utils/easy_io/backends/base_backend.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import os.path as osp +from abc import ABCMeta, abstractmethod + + +def mkdir_or_exist(dir_name, mode=0o777): + if dir_name == "": + return + dir_name = osp.expanduser(dir_name) + os.makedirs(dir_name, mode=mode, exist_ok=True) + + +def has_method(obj, method): + return hasattr(obj, method) and callable(getattr(obj, method)) + + +class BaseStorageBackend(metaclass=ABCMeta): + """Abstract class of storage backends. + + All backends need to implement two apis: :meth:`get()` and + :meth:`get_text()`. + + - :meth:`get()` reads the file as a byte stream. + - :meth:`get_text()` reads the file as texts. + """ + + # a flag to indicate whether the backend can create a symlink for a file + # This attribute will be deprecated in future. + _allow_symlink = False + + @property + def allow_symlink(self): + return self._allow_symlink + + @property + def name(self): + return self.__class__.__name__ + + @abstractmethod + def get(self, filepath): + pass + + @abstractmethod + def get_text(self, filepath): + pass diff --git a/utils/easy_io/backends/http_backend.py b/utils/easy_io/backends/http_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..26f4921c38ce2a7c393b1d7ebe5e3b676792bd2f --- /dev/null +++ b/utils/easy_io/backends/http_backend.py @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import tempfile +from contextlib import contextmanager +from pathlib import Path +from typing import Generator, Union +from urllib.request import urlopen + +from utils.easy_io.backends.base_backend import BaseStorageBackend + + +class HTTPBackend(BaseStorageBackend): + """HTTP and HTTPS storage bachend.""" + + def get(self, filepath: str) -> bytes: + """Read bytes from a given ``filepath``. + + Args: + filepath (str): Path to read data. + + Returns: + bytes: Expected bytes object. + + Examples: + >>> backend = HTTPBackend() + >>> backend.get('http://path/of/file') + b'hello world' + """ + return urlopen(filepath).read() + + def get_text(self, filepath, encoding="utf-8") -> str: + """Read text from a given ``filepath``. + + Args: + filepath (str): Path to read data. + encoding (str): The encoding format used to open the ``filepath``. + Defaults to 'utf-8'. + + Returns: + str: Expected text reading from ``filepath``. + + Examples: + >>> backend = HTTPBackend() + >>> backend.get_text('http://path/of/file') + 'hello world' + """ + return urlopen(filepath).read().decode(encoding) + + @contextmanager + def get_local_path(self, filepath: str) -> Generator[Union[str, Path], None, None]: + """Download a file from ``filepath`` to a local temporary directory, + and return the temporary path. + + ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It + can be called with ``with`` statement, and when exists from the + ``with`` statement, the temporary path will be released. + + Args: + filepath (str): Download a file from ``filepath``. + + Yields: + Iterable[str]: Only yield one temporary path. + + Examples: + >>> backend = HTTPBackend() + >>> # After existing from the ``with`` clause, + >>> # the path will be removed + >>> with backend.get_local_path('http://path/of/file') as path: + ... # do something here + """ + try: + f = tempfile.NamedTemporaryFile(delete=False) + f.write(self.get(filepath)) + f.close() + yield f.name + finally: + os.remove(f.name) diff --git a/utils/easy_io/backends/local_backend.py b/utils/easy_io/backends/local_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..8a07f29bdd3687da24a4b7bbe9c6c680ab9d164a --- /dev/null +++ b/utils/easy_io/backends/local_backend.py @@ -0,0 +1,550 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import io +import os +import os.path as osp +import shutil +from contextlib import contextmanager +from pathlib import Path +from typing import Generator, Iterator, Optional, Tuple, Union + +from utils.easy_io.backends.base_backend import BaseStorageBackend, mkdir_or_exist + + +class LocalBackend(BaseStorageBackend): + """Raw local storage backend.""" + + _allow_symlink = True + + def get(self, filepath: Union[str, Path]) -> bytes: + """Read bytes from a given ``filepath`` with 'rb' mode. + + Args: + filepath (str or Path): Path to read data. + + Returns: + bytes: Expected bytes object. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.get(filepath) + b'hello world' + """ + with open(filepath, "rb") as f: + value = f.read() + return value + + def get_text(self, filepath: Union[str, Path], encoding: str = "utf-8") -> str: + """Read text from a given ``filepath`` with 'r' mode. + + Args: + filepath (str or Path): Path to read data. + encoding (str): The encoding format used to open the ``filepath``. + Defaults to 'utf-8'. + + Returns: + str: Expected text reading from ``filepath``. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.get_text(filepath) + 'hello world' + """ + with open(filepath, encoding=encoding) as f: + text = f.read() + return text + + def put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path]) -> None: + """Write bytes to a given ``filepath`` with 'wb' mode. + + Note: + ``put`` will create a directory if the directory of + ``filepath`` does not exist. + + Args: + obj (bytes): Data to be written. + filepath (str or Path): Path to write data. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.put(b'hello world', filepath) + """ + mkdir_or_exist(osp.dirname(filepath)) + if isinstance(obj, io.BytesIO): + obj.seek(0) + obj = obj.getvalue() + with open(filepath, "wb") as f: + f.write(obj) + + def put_text(self, obj: str, filepath: Union[str, Path], encoding: str = "utf-8") -> None: + """Write text to a given ``filepath`` with 'w' mode. + + Note: + ``put_text`` will create a directory if the directory of + ``filepath`` does not exist. + + Args: + obj (str): Data to be written. + filepath (str or Path): Path to write data. + encoding (str): The encoding format used to open the ``filepath``. + Defaults to 'utf-8'. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.put_text('hello world', filepath) + """ + mkdir_or_exist(osp.dirname(filepath)) + with open(filepath, "w", encoding=encoding) as f: + f.write(obj) + + def exists(self, filepath: Union[str, Path]) -> bool: + """Check whether a file path exists. + + Args: + filepath (str or Path): Path to be checked whether exists. + + Returns: + bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.exists(filepath) + True + """ + return osp.exists(filepath) + + def isdir(self, filepath: Union[str, Path]) -> bool: + """Check whether a file path is a directory. + + Args: + filepath (str or Path): Path to be checked whether it is a + directory. + + Returns: + bool: Return ``True`` if ``filepath`` points to a directory, + ``False`` otherwise. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/dir' + >>> backend.isdir(filepath) + True + """ + return osp.isdir(filepath) + + def isfile(self, filepath: Union[str, Path]) -> bool: + """Check whether a file path is a file. + + Args: + filepath (str or Path): Path to be checked whether it is a file. + + Returns: + bool: Return ``True`` if ``filepath`` points to a file, ``False`` + otherwise. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.isfile(filepath) + True + """ + return osp.isfile(filepath) + + def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str: + r"""Concatenate all file paths. + + Join one or more filepath components intelligently. The return value + is the concatenation of filepath and any members of \*filepaths. + + Args: + filepath (str or Path): Path to be concatenated. + + Returns: + str: The result of concatenation. + + Examples: + >>> backend = LocalBackend() + >>> filepath1 = '/path/of/dir1' + >>> filepath2 = 'dir2' + >>> filepath3 = 'path/of/file' + >>> backend.join_path(filepath1, filepath2, filepath3) + '/path/of/dir/dir2/path/of/file' + """ + return osp.join(filepath, *filepaths) + + @contextmanager + def get_local_path( + self, + filepath: Union[str, Path], + ) -> Generator[Union[str, Path], None, None]: + """Only for unified API and does nothing. + + Args: + filepath (str or Path): Path to be read data. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Examples: + >>> backend = LocalBackend() + >>> with backend.get_local_path('abc/def.jpg') as path: + ... # do something here + """ + yield filepath + + def copyfile( + self, + src: Union[str, Path], + dst: Union[str, Path], + ) -> str: + """Copy a file src to dst and return the destination file. + + src and dst should have the same prefix. If dst specifies a directory, + the file will be copied into dst using the base filename from src. If + dst specifies a file that already exists, it will be replaced. + + Args: + src (str or Path): A file to be copied. + dst (str or Path): Copy file to dst. + + Returns: + str: The destination file. + + Raises: + SameFileError: If src and dst are the same file, a SameFileError + will be raised. + + Examples: + >>> backend = LocalBackend() + >>> # dst is a file + >>> src = '/path/of/file' + >>> dst = '/path1/of/file1' + >>> # src will be copied to '/path1/of/file1' + >>> backend.copyfile(src, dst) + '/path1/of/file1' + + >>> # dst is a directory + >>> dst = '/path1/of/dir' + >>> # src will be copied to '/path1/of/dir/file' + >>> backend.copyfile(src, dst) + '/path1/of/dir/file' + """ + return shutil.copy(src, dst) + + def copytree( + self, + src: Union[str, Path], + dst: Union[str, Path], + ) -> str: + """Recursively copy an entire directory tree rooted at src to a + directory named dst and return the destination directory. + + src and dst should have the same prefix and dst must not already exist. + + + Args: + src (str or Path): A directory to be copied. + dst (str or Path): Copy directory to dst. + + Returns: + str: The destination directory. + + Raises: + FileExistsError: If dst had already existed, a FileExistsError will + be raised. + + Examples: + >>> backend = LocalBackend() + >>> src = '/path/of/dir1' + >>> dst = '/path/of/dir2' + >>> backend.copytree(src, dst) + '/path/of/dir2' + """ + return shutil.copytree(src, dst) + + def copyfile_from_local( + self, + src: Union[str, Path], + dst: Union[str, Path], + ) -> str: + """Copy a local file src to dst and return the destination file. Same + as :meth:`copyfile`. + + Args: + src (str or Path): A local file to be copied. + dst (str or Path): Copy file to dst. + + Returns: + str: If dst specifies a directory, the file will be copied into dst + using the base filename from src. + + Raises: + SameFileError: If src and dst are the same file, a SameFileError + will be raised. + + Examples: + >>> backend = LocalBackend() + >>> # dst is a file + >>> src = '/path/of/file' + >>> dst = '/path1/of/file1' + >>> # src will be copied to '/path1/of/file1' + >>> backend.copyfile_from_local(src, dst) + '/path1/of/file1' + + >>> # dst is a directory + >>> dst = '/path1/of/dir' + >>> # src will be copied to + >>> backend.copyfile_from_local(src, dst) + '/path1/of/dir/file' + """ + return self.copyfile(src, dst) + + def copytree_from_local( + self, + src: Union[str, Path], + dst: Union[str, Path], + ) -> str: + """Recursively copy an entire directory tree rooted at src to a + directory named dst and return the destination directory. Same as + :meth:`copytree`. + + Args: + src (str or Path): A local directory to be copied. + dst (str or Path): Copy directory to dst. + + Returns: + str: The destination directory. + + Examples: + >>> backend = LocalBackend() + >>> src = '/path/of/dir1' + >>> dst = '/path/of/dir2' + >>> backend.copytree_from_local(src, dst) + '/path/of/dir2' + """ + return self.copytree(src, dst) + + def copyfile_to_local( + self, + src: Union[str, Path], + dst: Union[str, Path], + dst_type: Optional[str] = None, + ) -> str: + """Copy the file src to local dst and return the destination file. Same + as :meth:`copyfile`. + + If dst specifies a directory, the file will be copied into dst using + the base filename from src. If dst specifies a file that already + exists, it will be replaced. + + Args: + src (str or Path): A file to be copied. + dst (str or Path): Copy file to to local dst. + + Returns: + str: If dst specifies a directory, the file will be copied into dst + using the base filename from src. + + Examples: + >>> backend = LocalBackend() + >>> # dst is a file + >>> src = '/path/of/file' + >>> dst = '/path1/of/file1' + >>> # src will be copied to '/path1/of/file1' + >>> backend.copyfile_to_local(src, dst) + '/path1/of/file1' + + >>> # dst is a directory + >>> dst = '/path1/of/dir' + >>> # src will be copied to + >>> backend.copyfile_to_local(src, dst) + '/path1/of/dir/file' + """ + return self.copyfile(src, dst) + + def copytree_to_local( + self, + src: Union[str, Path], + dst: Union[str, Path], + ) -> str: + """Recursively copy an entire directory tree rooted at src to a local + directory named dst and return the destination directory. + + Args: + src (str or Path): A directory to be copied. + dst (str or Path): Copy directory to local dst. + backend_args (dict, optional): Arguments to instantiate the + prefix of uri corresponding backend. Defaults to None. + + Returns: + str: The destination directory. + + Examples: + >>> backend = LocalBackend() + >>> src = '/path/of/dir1' + >>> dst = '/path/of/dir2' + >>> backend.copytree_from_local(src, dst) + '/path/of/dir2' + """ + return self.copytree(src, dst) + + def remove(self, filepath: Union[str, Path]) -> None: + """Remove a file. + + Args: + filepath (str or Path): Path to be removed. + + Raises: + IsADirectoryError: If filepath is a directory, an IsADirectoryError + will be raised. + FileNotFoundError: If filepath does not exist, an FileNotFoundError + will be raised. + + Examples: + >>> backend = LocalBackend() + >>> filepath = '/path/of/file' + >>> backend.remove(filepath) + """ + if not self.exists(filepath): + raise FileNotFoundError(f"filepath {filepath} does not exist") + + if self.isdir(filepath): + raise IsADirectoryError("filepath should be a file") + + os.remove(filepath) + + def rmtree(self, dir_path: Union[str, Path]) -> None: + """Recursively delete a directory tree. + + Args: + dir_path (str or Path): A directory to be removed. + + Examples: + >>> dir_path = '/path/of/dir' + >>> backend.rmtree(dir_path) + """ + shutil.rmtree(dir_path) + + def copy_if_symlink_fails( + self, + src: Union[str, Path], + dst: Union[str, Path], + ) -> bool: + """Create a symbolic link pointing to src named dst. + + If failed to create a symbolic link pointing to src, directly copy src + to dst instead. + + Args: + src (str or Path): Create a symbolic link pointing to src. + dst (str or Path): Create a symbolic link named dst. + + Returns: + bool: Return True if successfully create a symbolic link pointing + to src. Otherwise, return False. + + Examples: + >>> backend = LocalBackend() + >>> src = '/path/of/file' + >>> dst = '/path1/of/file1' + >>> backend.copy_if_symlink_fails(src, dst) + True + >>> src = '/path/of/dir' + >>> dst = '/path1/of/dir1' + >>> backend.copy_if_symlink_fails(src, dst) + True + """ + try: + os.symlink(src, dst) + return True + except Exception: + if self.isfile(src): + self.copyfile(src, dst) + else: + self.copytree(src, dst) + return False + + def list_dir_or_file( + self, + dir_path: Union[str, Path], + list_dir: bool = True, + list_file: bool = True, + suffix: Optional[Union[str, Tuple[str]]] = None, + recursive: bool = False, + ) -> Iterator[str]: + """Scan a directory to find the interested directories or files in + arbitrary order. + + Note: + :meth:`list_dir_or_file` returns the path relative to ``dir_path``. + + Args: + dir_path (str or Path): Path of the directory. + list_dir (bool): List the directories. Defaults to True. + list_file (bool): List the path of files. Defaults to True. + suffix (str or tuple[str], optional): File suffix that we are + interested in. Defaults to None. + recursive (bool): If set to True, recursively scan the directory. + Defaults to False. + + Yields: + Iterable[str]: A relative path to ``dir_path``. + + Examples: + >>> backend = LocalBackend() + >>> dir_path = '/path/of/dir' + >>> # list those files and directories in current directory + >>> for file_path in backend.list_dir_or_file(dir_path): + ... print(file_path) + >>> # only list files + >>> for file_path in backend.list_dir_or_file(dir_path, list_dir=False): + ... print(file_path) + >>> # only list directories + >>> for file_path in backend.list_dir_or_file(dir_path, list_file=False): + ... print(file_path) + >>> # only list files ending with specified suffixes + >>> for file_path in backend.list_dir_or_file(dir_path, suffix='.txt'): + ... print(file_path) + >>> # list all files and directory recursively + >>> for file_path in backend.list_dir_or_file(dir_path, recursive=True): + ... print(file_path) + """ # noqa: E501 + if list_dir and suffix is not None: + raise TypeError("`suffix` should be None when `list_dir` is True") + + if (suffix is not None) and not isinstance(suffix, (str, tuple)): + raise TypeError("`suffix` must be a string or tuple of strings") + + root = dir_path + + def _list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive): + for entry in os.scandir(dir_path): + if not entry.name.startswith(".") and entry.is_file(): + rel_path = osp.relpath(entry.path, root) + if (suffix is None or rel_path.endswith(suffix)) and list_file: + yield rel_path + elif osp.isdir(entry.path): + if list_dir: + rel_dir = osp.relpath(entry.path, root) + yield rel_dir + if recursive: + yield from _list_dir_or_file(entry.path, list_dir, list_file, suffix, recursive) + + return _list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive) diff --git a/utils/easy_io/backends/registry_utils.py b/utils/easy_io/backends/registry_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8c302fedba781e8e091e031d7ab5193ad8309d4f --- /dev/null +++ b/utils/easy_io/backends/registry_utils.py @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +from typing import Optional, Type, Union + +from utils.easy_io.backends.base_backend import BaseStorageBackend +from utils.easy_io.backends.http_backend import HTTPBackend +from utils.easy_io.backends.local_backend import LocalBackend + +backends: dict = {} +prefix_to_backends: dict = {} + + +def _register_backend( + name: str, + backend: Type[BaseStorageBackend], + force: bool = False, + prefixes: Union[str, list, tuple, None] = None, +): + """Register a backend. + + Args: + name (str): The name of the registered backend. + backend (BaseStorageBackend): The backend class to be registered, + which must be a subclass of :class:`BaseStorageBackend`. + force (bool): Whether to override the backend if the name has already + been registered. Defaults to False. + prefixes (str or list[str] or tuple[str], optional): The prefix + of the registered storage backend. Defaults to None. + """ + global backends, prefix_to_backends + + if not isinstance(name, str): + raise TypeError("the backend name should be a string, " f"but got {type(name)}") + + if not inspect.isclass(backend): + raise TypeError(f"backend should be a class, but got {type(backend)}") + if not issubclass(backend, BaseStorageBackend): + raise TypeError(f"backend {backend} is not a subclass of BaseStorageBackend") + + if name in backends and not force: + raise ValueError( + f"{name} is already registered as a storage backend, " 'add "force=True" if you want to override it' + ) + backends[name] = backend + + if prefixes is not None: + if isinstance(prefixes, str): + prefixes = [prefixes] + else: + assert isinstance(prefixes, (list, tuple)) + + for prefix in prefixes: + if prefix in prefix_to_backends and not force: + raise ValueError( + f"{prefix} is already registered as a storage backend," + ' add "force=True" if you want to override it' + ) + + prefix_to_backends[prefix] = backend + + +def register_backend( + name: str, + backend: Optional[Type[BaseStorageBackend]] = None, + force: bool = False, + prefixes: Union[str, list, tuple, None] = None, +): + """Register a backend. + + Args: + name (str): The name of the registered backend. + backend (class, optional): The backend class to be registered, + which must be a subclass of :class:`BaseStorageBackend`. + When this method is used as a decorator, backend is None. + Defaults to None. + force (bool): Whether to override the backend if the name has already + been registered. Defaults to False. + prefixes (str or list[str] or tuple[str], optional): The prefix + of the registered storage backend. Defaults to None. + + This method can be used as a normal method or a decorator. + + Examples: + + >>> class NewBackend(BaseStorageBackend): + ... def get(self, filepath): + ... return filepath + ... + ... def get_text(self, filepath): + ... return filepath + >>> register_backend('new', NewBackend) + + >>> @register_backend('new') + ... class NewBackend(BaseStorageBackend): + ... def get(self, filepath): + ... return filepath + ... + ... def get_text(self, filepath): + ... return filepath + """ + if backend is not None: + _register_backend(name, backend, force=force, prefixes=prefixes) + return + + def _register(backend_cls): + _register_backend(name, backend_cls, force=force, prefixes=prefixes) + return backend_cls + + return _register + + +register_backend("local", LocalBackend, prefixes="") +register_backend("http", HTTPBackend, prefixes=["http", "https"]) diff --git a/utils/easy_io/easy_io.py b/utils/easy_io/easy_io.py new file mode 100644 index 0000000000000000000000000000000000000000..a31d26e5307a32da6c8b0d3fb0265d2f11b4950f --- /dev/null +++ b/utils/easy_io/easy_io.py @@ -0,0 +1,1066 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import warnings +from contextlib import contextmanager +from io import BytesIO, StringIO +from pathlib import Path +from typing import IO, Any, Generator, Iterator, Optional, Tuple, Union + +from utils.easy_io.backends import backends, prefix_to_backends +from utils.easy_io.file_client import FileClient +from utils.easy_io.handlers import file_handlers + +backend_instances: dict = {} + + +def is_filepath(filepath): + return isinstance(filepath, (str, Path)) + + +def _parse_uri_prefix(uri: Union[str, Path]) -> str: + """Parse the prefix of uri. + + Args: + uri (str or Path): Uri to be parsed that contains the file prefix. + + Examples: + >>> _parse_uri_prefix('/home/path/of/your/file') + '' + >>> _parse_uri_prefix('s3://path/of/your/file') + 's3' + >>> _parse_uri_prefix('clusterName:s3://path/of/your/file') + 's3' + + Returns: + str: Return the prefix of uri if the uri contains '://'. Otherwise, + return ''. + """ + assert is_filepath(uri) + uri = str(uri) + # if uri does not contains '://', the uri will be handled by + # LocalBackend by default + if "://" not in uri: + return "" + else: + prefix, _ = uri.split("://") + if ":" in prefix: + _, prefix = prefix.split(":") + return prefix + + +def _get_file_backend(prefix: str, backend_args: dict): + """Return a file backend based on the prefix or backend_args. + + Args: + prefix (str): Prefix of uri. + backend_args (dict): Arguments to instantiate the corresponding + backend. + """ + # backend name has a higher priority + if "backend" in backend_args: + # backend_args should not be modified + backend_args_bak = backend_args.copy() + backend_name = backend_args_bak.pop("backend") + backend = backends[backend_name](**backend_args_bak) + else: + backend = prefix_to_backends[prefix](**backend_args) + return backend + + +def get_file_backend( + uri: Union[str, Path, None] = None, + *, + backend_args: Optional[dict] = None, + enable_singleton: bool = False, + backend_key: Optional[str] = None, +): + """Return a file backend based on the prefix of uri or backend_args. + + Args: + uri (str or Path): Uri to be parsed that contains the file prefix. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + enable_singleton (bool): Whether to enable the singleton pattern. + If it is True, the backend created will be reused if the + signature is same with the previous one. Defaults to False. + backend_key: str: The key to register the backend. Defaults to None. + + Returns: + BaseStorageBackend: Instantiated Backend object. + + Examples: + >>> # get file backend based on the prefix of uri + >>> uri = 's3://path/of/your/file' + >>> backend = get_file_backend(uri) + >>> # get file backend based on the backend_args + >>> backend = get_file_backend(backend_args={'backend': 's3'}) + >>> # backend name has a higher priority if 'backend' in backend_args + >>> backend = get_file_backend(uri, backend_args={'backend': 's3'}) + """ + global backend_instances + if backend_key is not None: + if backend_key in backend_instances: + return backend_instances[backend_key] + + if backend_args is None: + backend_args = {} + + if uri is None and "backend" not in backend_args and backend_key is None: + raise ValueError( + 'uri should not be None when "backend" does not exist in ' "backend_args and backend_key is None" + ) + + if uri is not None: + prefix = _parse_uri_prefix(uri) + else: + prefix = "" + + if enable_singleton: + unique_key = f"{prefix}:{json.dumps(backend_args)}" + if unique_key in backend_instances: + return backend_instances[unique_key] + + backend = _get_file_backend(prefix, backend_args) + backend_instances[unique_key] = backend + if backend_key is not None: + backend_instances[backend_key] = backend + return backend + else: + backend = _get_file_backend(prefix, backend_args) + return backend + + +def get( + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> bytes: + """Read bytes from a given ``filepath`` with 'rb' mode. + + Args: + filepath (str or Path): Path to read data. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + bytes: Expected bytes object. + + Examples: + >>> filepath = '/path/of/file' + >>> get(filepath) + b'hello world' + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + return backend.get(filepath) + + +def get_text( + filepath: Union[str, Path], + encoding="utf-8", + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> str: + """Read text from a given ``filepath`` with 'r' mode. + + Args: + filepath (str or Path): Path to read data. + encoding (str): The encoding format used to open the ``filepath``. + Defaults to 'utf-8'. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + str: Expected text reading from ``filepath``. + + Examples: + >>> filepath = '/path/of/file' + >>> get_text(filepath) + 'hello world' + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + return backend.get_text(filepath, encoding) + + +def put( + obj: bytes, + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> None: + """Write bytes to a given ``filepath`` with 'wb' mode. + + Note: + ``put`` should create a directory if the directory of + ``filepath`` does not exist. + + Args: + obj (bytes): Data to be written. + filepath (str or Path): Path to write data. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Examples: + >>> filepath = '/path/of/file' + >>> put(b'hello world', filepath) + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + backend.put(obj, filepath) + + +def put_text( + obj: str, + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> None: + """Write text to a given ``filepath`` with 'w' mode. + + Note: + ``put_text`` should create a directory if the directory of + ``filepath`` does not exist. + + Args: + obj (str): Data to be written. + filepath (str or Path): Path to write data. + encoding (str, optional): The encoding format used to open the + ``filepath``. Defaults to 'utf-8'. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Examples: + >>> filepath = '/path/of/file' + >>> put_text('hello world', filepath) + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + backend.put_text(obj, filepath) + + +def exists( + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> bool: + """Check whether a file path exists. + + Args: + filepath (str or Path): Path to be checked whether exists. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. + + Examples: + >>> filepath = '/path/of/file' + >>> exists(filepath) + True + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + return backend.exists(filepath) + + +def isdir( + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> bool: + """Check whether a file path is a directory. + + Args: + filepath (str or Path): Path to be checked whether it is a + directory. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + bool: Return ``True`` if ``filepath`` points to a directory, + ``False`` otherwise. + + Examples: + >>> filepath = '/path/of/dir' + >>> isdir(filepath) + True + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + return backend.isdir(filepath) + + +def isfile( + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> bool: + """Check whether a file path is a file. + + Args: + filepath (str or Path): Path to be checked whether it is a file. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + bool: Return ``True`` if ``filepath`` points to a file, ``False`` + otherwise. + + Examples: + >>> filepath = '/path/of/file' + >>> isfile(filepath) + True + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + return backend.isfile(filepath) + + +def join_path( + filepath: Union[str, Path], + *filepaths: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + r"""Concatenate all file paths. + + Join one or more filepath components intelligently. The return value + is the concatenation of filepath and any members of \*filepaths. + + Args: + filepath (str or Path): Path to be concatenated. + *filepaths (str or Path): Other paths to be concatenated. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + str: The result of concatenation. + + Examples: + >>> filepath1 = '/path/of/dir1' + >>> filepath2 = 'dir2' + >>> filepath3 = 'path/of/file' + >>> join_path(filepath1, filepath2, filepath3) + '/path/of/dir/dir2/path/of/file' + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + return backend.join_path(filepath, *filepaths) + + +@contextmanager +def get_local_path( + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Generator[Union[str, Path], None, None]: + """Download data from ``filepath`` and write the data to local path. + + ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It + can be called with ``with`` statement, and when exists from the + ``with`` statement, the temporary path will be released. + + Note: + If the ``filepath`` is a local path, just return itself and it will + not be released (removed). + + Args: + filepath (str or Path): Path to be read data. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Yields: + Iterable[str]: Only yield one path. + + Examples: + >>> with get_local_path('abc/def.jpg') as path: + ... # do something here + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + with backend.get_local_path(str(filepath)) as local_path: + yield local_path + + +def copyfile( + src: Union[str, Path], + dst: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + """Copy a file src to dst and return the destination file. + + src and dst should have the same prefix. If dst specifies a directory, + the file will be copied into dst using the base filename from src. If + dst specifies a file that already exists, it will be replaced. + + Args: + src (str or Path): A file to be copied. + dst (str or Path): Copy file to dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + str: The destination file. + + Raises: + SameFileError: If src and dst are the same file, a SameFileError will + be raised. + + Examples: + >>> # dst is a file + >>> src = '/path/of/file' + >>> dst = '/path1/of/file1' + >>> # src will be copied to '/path1/of/file1' + >>> copyfile(src, dst) + '/path1/of/file1' + + >>> # dst is a directory + >>> dst = '/path1/of/dir' + >>> # src will be copied to '/path1/of/dir/file' + >>> copyfile(src, dst) + '/path1/of/dir/file' + """ + backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copyfile(src, dst) + + +def copytree( + src: Union[str, Path], + dst: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + """Recursively copy an entire directory tree rooted at src to a directory + named dst and return the destination directory. + + src and dst should have the same prefix and dst must not already exist. + + Args: + src (str or Path): A directory to be copied. + dst (str or Path): Copy directory to dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + backend_key (str, optional): The key to get the backend from register. + + Returns: + str: The destination directory. + + Raises: + FileExistsError: If dst had already existed, a FileExistsError will be + raised. + + Examples: + >>> src = '/path/of/dir1' + >>> dst = '/path/of/dir2' + >>> copytree(src, dst) + '/path/of/dir2' + """ + backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copytree(src, dst) + + +def copyfile_from_local( + src: Union[str, Path], + dst: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + """Copy a local file src to dst and return the destination file. + + Note: + If the backend is the instance of LocalBackend, it does the same + thing with :func:`copyfile`. + + Args: + src (str or Path): A local file to be copied. + dst (str or Path): Copy file to dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + str: If dst specifies a directory, the file will be copied into dst + using the base filename from src. + + Examples: + >>> # dst is a file + >>> src = '/path/of/file' + >>> dst = 's3://openmmlab/mmengine/file1' + >>> # src will be copied to 's3://openmmlab/mmengine/file1' + >>> copyfile_from_local(src, dst) + s3://openmmlab/mmengine/file1 + + >>> # dst is a directory + >>> dst = 's3://openmmlab/mmengine' + >>> # src will be copied to 's3://openmmlab/mmengine/file'' + >>> copyfile_from_local(src, dst) + 's3://openmmlab/mmengine/file' + """ + backend = get_file_backend(dst, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copyfile_from_local(src, dst) + + +def copytree_from_local( + src: Union[str, Path], + dst: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + """Recursively copy an entire directory tree rooted at src to a directory + named dst and return the destination directory. + + Note: + If the backend is the instance of LocalBackend, it does the same + thing with :func:`copytree`. + + Args: + src (str or Path): A local directory to be copied. + dst (str or Path): Copy directory to dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + str: The destination directory. + + Examples: + >>> src = '/path/of/dir' + >>> dst = 's3://openmmlab/mmengine/dir' + >>> copyfile_from_local(src, dst) + 's3://openmmlab/mmengine/dir' + """ + backend = get_file_backend(dst, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copytree_from_local(src, dst) + + +def copyfile_to_local( + src: Union[str, Path], + dst: Union[str, Path], + dst_type: str, # Choose from ["file", "dir"] + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + """Copy the file src to local dst and return the destination file. + + If dst specifies a directory, the file will be copied into dst using + the base filename from src. If dst specifies a file that already + exists, it will be replaced. + + Note: + If the backend is the instance of LocalBackend, it does the same + thing with :func:`copyfile`. + + Args: + src (str or Path): A file to be copied. + dst (str or Path): Copy file to to local dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + str: If dst specifies a directory, the file will be copied into dst + using the base filename from src. + + Examples: + >>> # dst is a file + >>> src = 's3://openmmlab/mmengine/file' + >>> dst = '/path/of/file' + >>> # src will be copied to '/path/of/file' + >>> copyfile_to_local(src, dst) + '/path/of/file' + + >>> # dst is a directory + >>> dst = '/path/of/dir' + >>> # src will be copied to '/path/of/dir/file' + >>> copyfile_to_local(src, dst) + '/path/of/dir/file' + """ + assert dst_type in ["file", "dir"] + Path(dst).parent.mkdir(parents=True, exist_ok=True) + backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copyfile_to_local(src, dst, dst_type=dst_type) + + +def copytree_to_local( + src: Union[str, Path], + dst: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Union[str, Path]: + """Recursively copy an entire directory tree rooted at src to a local + directory named dst and return the destination directory. + + Note: + If the backend is the instance of LocalBackend, it does the same + thing with :func:`copytree`. + + Args: + src (str or Path): A directory to be copied. + dst (str or Path): Copy directory to local dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + str: The destination directory. + + Examples: + >>> src = 's3://openmmlab/mmengine/dir' + >>> dst = '/path/of/dir' + >>> copytree_to_local(src, dst) + '/path/of/dir' + """ + Path(dst).parent.mkdir(parents=True, exist_ok=True) + backend = get_file_backend(dst, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copytree_to_local(src, dst) + + +def remove( + filepath: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> None: + """Remove a file. + + Args: + filepath (str, Path): Path to be removed. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Raises: + FileNotFoundError: If filepath does not exist, an FileNotFoundError + will be raised. + IsADirectoryError: If filepath is a directory, an IsADirectoryError + will be raised. + + Examples: + >>> filepath = '/path/of/file' + >>> remove(filepath) + """ + backend = get_file_backend( + filepath, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + backend.remove(filepath) + + +def rmtree( + dir_path: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> None: + """Recursively delete a directory tree. + + Args: + dir_path (str or Path): A directory to be removed. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Examples: + >>> dir_path = '/path/of/dir' + >>> rmtree(dir_path) + """ + backend = get_file_backend( + dir_path, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + backend.rmtree(dir_path) + + +def copy_if_symlink_fails( + src: Union[str, Path], + dst: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> bool: + """Create a symbolic link pointing to src named dst. + + If failed to create a symbolic link pointing to src, directory copy src to + dst instead. + + Args: + src (str or Path): Create a symbolic link pointing to src. + dst (str or Path): Create a symbolic link named dst. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + bool: Return True if successfully create a symbolic link pointing to + src. Otherwise, return False. + + Examples: + >>> src = '/path/of/file' + >>> dst = '/path1/of/file1' + >>> copy_if_symlink_fails(src, dst) + True + >>> src = '/path/of/dir' + >>> dst = '/path1/of/dir1' + >>> copy_if_symlink_fails(src, dst) + True + """ + backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.copy_if_symlink_fails(src, dst) + + +def list_dir( + dir_path: Union[str, Path], + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +): + """List all folders in an S3 bucket with a given prefix. + + Args: + dir_path (str | Path): Path of the directory. + + Examples: + >>> dir_path = '/path/of/dir' + >>> for file_path in list_dir(dir_path): + ... print(file_path) + """ + if not dir_path.endswith("/"): + dir_path += "/" + backend = get_file_backend( + dir_path, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + + return backend.list_dir(dir_path) + + +def list_dir_or_file( + dir_path: Union[str, Path], + list_dir: bool = True, + list_file: bool = True, + suffix: Optional[Union[str, Tuple[str]]] = None, + recursive: bool = False, + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> Iterator[str]: + """Scan a directory to find the interested directories or files in + arbitrary order. + + Note: + :meth:`list_dir_or_file` returns the path relative to ``dir_path``. + + Args: + dir_path (str or Path): Path of the directory. + list_dir (bool): List the directories. Defaults to True. + list_file (bool): List the path of files. Defaults to True. + suffix (str or tuple[str], optional): File suffix that we are + interested in. Defaults to None. + recursive (bool): If set to True, recursively scan the directory. + Defaults to False. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Yields: + Iterable[str]: A relative path to ``dir_path``. + + Examples: + >>> dir_path = '/path/of/dir' + >>> for file_path in list_dir_or_file(dir_path): + ... print(file_path) + >>> # list those files and directories in current directory + >>> for file_path in list_dir_or_file(dir_path): + ... print(file_path) + >>> # only list files + >>> for file_path in list_dir_or_file(dir_path, list_dir=False): + ... print(file_path) + >>> # only list directories + >>> for file_path in list_dir_or_file(dir_path, list_file=False): + ... print(file_path) + >>> # only list files ending with specified suffixes + >>> for file_path in list_dir_or_file(dir_path, suffix='.txt'): + ... print(file_path) + >>> # list all files and directory recursively + >>> for file_path in list_dir_or_file(dir_path, recursive=True): + ... print(file_path) + """ + backend = get_file_backend( + dir_path, + backend_args=backend_args, + enable_singleton=True, + backend_key=backend_key, + ) + yield from backend.list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive) + + +def generate_presigned_url( + url: str, + client_method: str = "get_object", + expires_in: int = 3600, + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> str: + """Generate the presigned url of video stream which can be passed to + mmcv.VideoReader. Now only work on s3 backend. + + Note: + Now only work on s3 backend. + + Args: + url (str): Url of video stream. + client_method (str): Method of client, 'get_object' or + 'put_object'. Defaults to 'get_object'. + expires_in (int): expires, in seconds. Defaults to 3600. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + + Returns: + str: Generated presigned url. + """ + backend = get_file_backend(url, backend_args=backend_args, enable_singleton=True, backend_key=backend_key) + return backend.generate_presigned_url(url, client_method, expires_in) + + +def load( + file: Union[str, Path, IO[Any]], + file_format: Optional[str] = None, + file_client_args: Optional[dict] = None, + fast_backend: bool = False, + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, + **kwargs, +): + """Load data from json/yaml/pickle files (pickle is deprecated). + + This method provides a unified api for loading data from serialized files. + + ``load`` supports loading data from serialized files those can be storaged + in different backends. + + Args: + file (str or :obj:`Path` or file-like object): Filename or a file-like + object. + file_format (str, optional): If not specified, the file format will be + inferred from the file extension, otherwise use the specified one. + Currently supported formats include "json", "yaml/yml" and + "pickle/pkl". + file_client_args (dict, optional): Arguments to instantiate a + FileClient. See :class:`mmengine.fileio.FileClient` for details. + Defaults to None. It will be deprecated in future. Please use + ``backend_args`` instead. + fast_backend: bool: Whether to use multiprocess. Defaults to False. + backend_args (dict, optional): Arguments to instantiate the + prefix of uri corresponding backend. Defaults to None. + New in v0.2.0. + + Examples: + >>> load('/path/of/your/file') # file is storaged in disk + >>> load('https://path/of/your/file') # file is storaged in Internet + >>> load('s3://path/of/your/file') # file is storaged in s3 + + Returns: + The content from the file. + """ + if isinstance(file, Path): + file = str(file) + if file_format is None and isinstance(file, str): + file_format = file.split(".")[-1] + # convert file_format to lower case + file_format = file_format.lower() + if file_format not in file_handlers: + raise TypeError(f"Unsupported format: {file_format}") + + if file_client_args is not None: + warnings.warn( + '"file_client_args" will be deprecated in future. ' 'Please use "backend_args" instead', + DeprecationWarning, + ) + if backend_args is not None: + raise ValueError('"file_client_args and "backend_args" cannot be set at the ' "same time.") + + handler = file_handlers[file_format] + if isinstance(file, str): + if file_client_args is not None: + file_client = FileClient.infer_client(file_client_args, file) + file_backend = file_client + else: + file_backend = get_file_backend( + file, + backend_args=backend_args, + backend_key=backend_key, + enable_singleton=True, + ) + + if handler.str_like: + with StringIO(file_backend.get_text(file)) as f: + obj = handler.load_from_fileobj(f, **kwargs) + else: + if fast_backend: + if hasattr(file_backend, "fast_get"): + with BytesIO(file_backend.fast_get(file)) as f: + obj = handler.load_from_fileobj(f, **kwargs) + else: + warnings.warn( + f"fast_backend is not supported by the backend, type {type(file_backend)} fallback to normal get" + ) + with BytesIO(file_backend.get(file)) as f: + obj = handler.load_from_fileobj(f, **kwargs) + else: + with BytesIO(file_backend.get(file)) as f: + obj = handler.load_from_fileobj(f, **kwargs) + elif hasattr(file, "read"): + obj = handler.load_from_fileobj(file, **kwargs) + else: + raise TypeError('"file" must be a filepath str or a file-object') + return obj + + +def dump( + obj: Any, + file: Union[str, Path, IO[Any], None] = None, + file_format: Optional[str] = None, + file_client_args: Optional[dict] = None, + fast_backend: bool = False, + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, + **kwargs, +): + """Dump data to json/yaml strings or files (pickle is deprecated). + + This method provides a unified api for dumping data as strings or to files, + and also supports custom arguments for each file format. + + ``dump`` supports dumping data as strings or to files which is saved to + different backends. + + Args: + obj (any): The python object to be dumped. + file (str or :obj:`Path` or file-like object, optional): If not + specified, then the object is dumped to a str, otherwise to a file + specified by the filename or file-like object. + file_format (str, optional): Same as :func:`load`. + file_client_args (dict, optional): Arguments to instantiate a + FileClient. See :class:`mmengine.fileio.FileClient` for details. + Defaults to None. It will be deprecated in future. Please use + ``backend_args`` instead. + fast_backend: bool: Whether to use multiprocess. Defaults to False. + backend_args (dict, optional): Arguments to instantiate the + prefix of uri corresponding backend. Defaults to None. + New in v0.2.0. + backend_key: str: The key to register the backend. Defaults to None. + + Examples: + >>> dump('hello world', '/path/of/your/file') # disk + >>> dump('hello world', 's3://path/of/your/file') # ceph or s3 + + Returns: + bool: True for success, False otherwise. + """ + if isinstance(file, Path): + file = str(file) + if file_format is None: + if isinstance(file, str): + file_format = file.split(".")[-1] + elif file is None: + raise ValueError("file_format must be specified since file is None") + # convert file_format to lower case + file_format = file_format.lower() + if file_format not in file_handlers: + raise TypeError(f"Unsupported format: {file_format}") + + if file_client_args is not None: + warnings.warn( + '"file_client_args" will be deprecated in future. ' 'Please use "backend_args" instead', + DeprecationWarning, + ) + if backend_args is not None: + raise ValueError('"file_client_args" and "backend_args" cannot be set at the ' "same time.") + + handler = file_handlers[file_format] + if file is None: + return handler.dump_to_str(obj, **kwargs) + elif isinstance(file, str): + if file_client_args is not None: + file_client = FileClient.infer_client(file_client_args, file) + file_backend = file_client + else: + file_backend = get_file_backend( + file, + backend_args=backend_args, + backend_key=backend_key, + enable_singleton=True, + ) + + if handler.str_like: + with StringIO() as f: + handler.dump_to_fileobj(obj, f, **kwargs) + file_backend.put_text(f.getvalue(), file) + else: + with BytesIO() as f: + handler.dump_to_fileobj(obj, f, **kwargs) + if fast_backend: + if hasattr(file_backend, "fast_put"): + file_backend.fast_put(f, file) + else: + warnings.warn("fast_backend is not supported by the backend, fallback to normal put") + file_backend.put(f, file) + else: + file_backend.put(f, file) + elif hasattr(file, "write"): + handler.dump_to_fileobj(obj, file, **kwargs) + else: + raise TypeError('"file" must be a filename str or a file-object') diff --git a/utils/easy_io/file_client.py b/utils/easy_io/file_client.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8a76dd2052b00b20e14f6917277d0070771a47 --- /dev/null +++ b/utils/easy_io/file_client.py @@ -0,0 +1,450 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Generator, Iterator, Optional, Tuple, Union + +from utils.easy_io.backends import BaseStorageBackend, HTTPBackend, LocalBackend + + +def is_filepath(filepath): + return isinstance(filepath, (str, Path)) + + +class HardDiskBackend(LocalBackend): + """Raw hard disks storage backend.""" + + @property + def name(self): + return self.__class__.__name__ + + +class FileClient: + """A general file client to access files in different backends. + + The client loads a file or text in a specified backend from its path + and returns it as a binary or text file. There are two ways to choose a + backend, the name of backend and the prefix of path. Although both of them + can be used to choose a storage backend, ``backend`` has a higher priority + that is if they are all set, the storage backend will be chosen by the + backend argument. If they are all `None`, the disk backend will be chosen. + Note that It can also register other backend accessor with a given name, + prefixes, and backend class. In addition, We use the singleton pattern to + avoid repeated object creation. If the arguments are the same, the same + object will be returned. + + Warning: + `FileClient` will be deprecated in future. Please use io functions + in https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io + + Args: + backend (str, optional): The storage backend type. Options are "disk", + "memcached", "lmdb", "http" and "s3". Defaults to None. + prefix (str, optional): The prefix of the registered storage backend. + Options are "s3", "http", "https". Defaults to None. + + Examples: + >>> # only set backend + >>> file_client = FileClient(backend='s3') + >>> # only set prefix + >>> file_client = FileClient(prefix='s3') + >>> # set both backend and prefix but use backend to choose client + >>> file_client = FileClient(backend='s3', prefix='s3') + >>> # if the arguments are the same, the same object is returned + >>> file_client1 = FileClient(backend='s3') + >>> file_client1 is file_client + True + + Attributes: + client (:obj:`BaseStorageBackend`): The backend object. + """ + + _backends = { + "disk": HardDiskBackend, + "http": HTTPBackend, + } + + _prefix_to_backends: dict = { + "http": HTTPBackend, + "https": HTTPBackend, + } + + _instances: dict = {} + + client: Any + + def __new__(cls, backend=None, prefix=None, **kwargs): + if backend is None and prefix is None: + backend = "disk" + if backend is not None and backend not in cls._backends: + raise ValueError( + f"Backend {backend} is not supported. Currently supported ones" f" are {list(cls._backends.keys())}" + ) + if prefix is not None and prefix not in cls._prefix_to_backends: + raise ValueError( + f"prefix {prefix} is not supported. Currently supported ones " + f"are {list(cls._prefix_to_backends.keys())}" + ) + + # concatenate the arguments to a unique key for determining whether + # objects with the same arguments were created + arg_key = f"{backend}:{prefix}" + for key, value in kwargs.items(): + arg_key += f":{key}:{value}" + + # if a backend was overridden, it will create a new object + if arg_key in cls._instances: + _instance = cls._instances[arg_key] + else: + # create a new object and put it to _instance + _instance = super().__new__(cls) + if backend is not None: + _instance.client = cls._backends[backend](**kwargs) + else: + _instance.client = cls._prefix_to_backends[prefix](**kwargs) + + cls._instances[arg_key] = _instance + + return _instance + + @property + def name(self): + return self.client.name + + @property + def allow_symlink(self): + return self.client.allow_symlink + + @staticmethod + def parse_uri_prefix(uri: Union[str, Path]) -> Optional[str]: + """Parse the prefix of a uri. + + Args: + uri (str | Path): Uri to be parsed that contains the file prefix. + + Examples: + >>> FileClient.parse_uri_prefix('s3://path/of/your/file') + 's3' + + Returns: + str | None: Return the prefix of uri if the uri contains '://' else + ``None``. + """ + assert is_filepath(uri) + uri = str(uri) + if "://" not in uri: + return None + else: + prefix, _ = uri.split("://") + if ":" in prefix: + _, prefix = prefix.split(":") + return prefix + + @classmethod + def infer_client( + cls, + file_client_args: Optional[dict] = None, + uri: Optional[Union[str, Path]] = None, + ) -> "FileClient": + """Infer a suitable file client based on the URI and arguments. + + Args: + file_client_args (dict, optional): Arguments to instantiate a + FileClient. Defaults to None. + uri (str | Path, optional): Uri to be parsed that contains the file + prefix. Defaults to None. + + Examples: + >>> uri = 's3://path/of/your/file' + >>> file_client = FileClient.infer_client(uri=uri) + >>> file_client_args = {'backend': 's3'} + >>> file_client = FileClient.infer_client(file_client_args) + + Returns: + FileClient: Instantiated FileClient object. + """ + assert file_client_args is not None or uri is not None + if file_client_args is None: + file_prefix = cls.parse_uri_prefix(uri) # type: ignore + return cls(prefix=file_prefix) + else: + return cls(**file_client_args) + + @classmethod + def _register_backend(cls, name, backend, force=False, prefixes=None): + if not isinstance(name, str): + raise TypeError("the backend name should be a string, " f"but got {type(name)}") + if not inspect.isclass(backend): + raise TypeError(f"backend should be a class but got {type(backend)}") + if not issubclass(backend, BaseStorageBackend): + raise TypeError(f"backend {backend} is not a subclass of BaseStorageBackend") + if not force and name in cls._backends: + raise KeyError( + f"{name} is already registered as a storage backend, " 'add "force=True" if you want to override it' + ) + + if name in cls._backends and force: + for arg_key, instance in list(cls._instances.items()): + if isinstance(instance.client, cls._backends[name]): + cls._instances.pop(arg_key) + cls._backends[name] = backend + + if prefixes is not None: + if isinstance(prefixes, str): + prefixes = [prefixes] + else: + assert isinstance(prefixes, (list, tuple)) + for prefix in prefixes: + if prefix not in cls._prefix_to_backends: + cls._prefix_to_backends[prefix] = backend + elif (prefix in cls._prefix_to_backends) and force: + overridden_backend = cls._prefix_to_backends[prefix] + for arg_key, instance in list(cls._instances.items()): + if isinstance(instance.client, overridden_backend): + cls._instances.pop(arg_key) + else: + raise KeyError( + f"{prefix} is already registered as a storage backend," + ' add "force=True" if you want to override it' + ) + + @classmethod + def register_backend(cls, name, backend=None, force=False, prefixes=None): + """Register a backend to FileClient. + + This method can be used as a normal class method or a decorator. + + .. code-block:: python + + class NewBackend(BaseStorageBackend): + + def get(self, filepath): + return filepath + + def get_text(self, filepath): + return filepath + + FileClient.register_backend('new', NewBackend) + + or + + .. code-block:: python + + @FileClient.register_backend('new') + class NewBackend(BaseStorageBackend): + + def get(self, filepath): + return filepath + + def get_text(self, filepath): + return filepath + + Args: + name (str): The name of the registered backend. + backend (class, optional): The backend class to be registered, + which must be a subclass of :class:`BaseStorageBackend`. + When this method is used as a decorator, backend is None. + Defaults to None. + force (bool, optional): Whether to override the backend if the name + has already been registered. Defaults to False. + prefixes (str or list[str] or tuple[str], optional): The prefixes + of the registered storage backend. Defaults to None. + `New in version 1.3.15.` + """ + if backend is not None: + cls._register_backend(name, backend, force=force, prefixes=prefixes) + return + + def _register(backend_cls): + cls._register_backend(name, backend_cls, force=force, prefixes=prefixes) + return backend_cls + + return _register + + def get(self, filepath: Union[str, Path]) -> Union[bytes, memoryview]: + """Read data from a given ``filepath`` with 'rb' mode. + + Note: + There are two types of return values for ``get``, one is ``bytes`` + and the other is ``memoryview``. The advantage of using memoryview + is that you can avoid copying, and if you want to convert it to + ``bytes``, you can use ``.tobytes()``. + + Args: + filepath (str or Path): Path to read data. + + Returns: + bytes | memoryview: Expected bytes object or a memory view of the + bytes object. + """ + return self.client.get(filepath) + + def get_text(self, filepath: Union[str, Path], encoding="utf-8") -> str: + """Read data from a given ``filepath`` with 'r' mode. + + Args: + filepath (str or Path): Path to read data. + encoding (str): The encoding format used to open the ``filepath``. + Defaults to 'utf-8'. + + Returns: + str: Expected text reading from ``filepath``. + """ + return self.client.get_text(filepath, encoding) + + def put(self, obj: bytes, filepath: Union[str, Path]) -> None: + """Write data to a given ``filepath`` with 'wb' mode. + + Note: + ``put`` should create a directory if the directory of ``filepath`` + does not exist. + + Args: + obj (bytes): Data to be written. + filepath (str or Path): Path to write data. + """ + self.client.put(obj, filepath) + + def put_text(self, obj: str, filepath: Union[str, Path]) -> None: + """Write data to a given ``filepath`` with 'w' mode. + + Note: + ``put_text`` should create a directory if the directory of + ``filepath`` does not exist. + + Args: + obj (str): Data to be written. + filepath (str or Path): Path to write data. + encoding (str, optional): The encoding format used to open the + `filepath`. Defaults to 'utf-8'. + """ + self.client.put_text(obj, filepath) + + def remove(self, filepath: Union[str, Path]) -> None: + """Remove a file. + + Args: + filepath (str, Path): Path to be removed. + """ + self.client.remove(filepath) + + def exists(self, filepath: Union[str, Path]) -> bool: + """Check whether a file path exists. + + Args: + filepath (str or Path): Path to be checked whether exists. + + Returns: + bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. + """ + return self.client.exists(filepath) + + def isdir(self, filepath: Union[str, Path]) -> bool: + """Check whether a file path is a directory. + + Args: + filepath (str or Path): Path to be checked whether it is a + directory. + + Returns: + bool: Return ``True`` if ``filepath`` points to a directory, + ``False`` otherwise. + """ + return self.client.isdir(filepath) + + def isfile(self, filepath: Union[str, Path]) -> bool: + """Check whether a file path is a file. + + Args: + filepath (str or Path): Path to be checked whether it is a file. + + Returns: + bool: Return ``True`` if ``filepath`` points to a file, ``False`` + otherwise. + """ + return self.client.isfile(filepath) + + def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str: + r"""Concatenate all file paths. + + Join one or more filepath components intelligently. The return value + is the concatenation of filepath and any members of \*filepaths. + + Args: + filepath (str or Path): Path to be concatenated. + + Returns: + str: The result of concatenation. + """ + return self.client.join_path(filepath, *filepaths) + + @contextmanager + def get_local_path(self, filepath: Union[str, Path]) -> Generator[Union[str, Path], None, None]: + """Download data from ``filepath`` and write the data to local path. + + ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It + can be called with ``with`` statement, and when exists from the + ``with`` statement, the temporary path will be released. + + Note: + If the ``filepath`` is a local path, just return itself. + + .. warning:: + ``get_local_path`` is an experimental interface that may change in + the future. + + Args: + filepath (str or Path): Path to be read data. + + Examples: + >>> file_client = FileClient(prefix='s3') + >>> with file_client.get_local_path('s3://bucket/abc.jpg') as path: + ... # do something here + + Yields: + Iterable[str]: Only yield one path. + """ + with self.client.get_local_path(str(filepath)) as local_path: + yield local_path + + def list_dir_or_file( # pylint: disable=too-many-arguments + self, + dir_path: Union[str, Path], + list_dir: bool = True, + list_file: bool = True, + suffix: Optional[Union[str, Tuple[str]]] = None, + recursive: bool = False, + ) -> Iterator[str]: + """Scan a directory to find the interested directories or files in + arbitrary order. + + Note: + :meth:`list_dir_or_file` returns the path relative to ``dir_path``. + + Args: + dir_path (str | Path): Path of the directory. + list_dir (bool): List the directories. Defaults to True. + list_file (bool): List the path of files. Defaults to True. + suffix (str or tuple[str], optional): File suffix + that we are interested in. Defaults to None. + recursive (bool): If set to True, recursively scan the + directory. Defaults to False. + + Yields: + Iterable[str]: A relative path to ``dir_path``. + """ + yield from self.client.list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive) diff --git a/utils/easy_io/handlers/__init__.py b/utils/easy_io/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca987814d7aad2a64b9912f61538a0cfd8efa4ea --- /dev/null +++ b/utils/easy_io/handlers/__init__.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from utils.easy_io.handlers.base import BaseFileHandler +from utils.easy_io.handlers.json_handler import JsonHandler +from utils.easy_io.handlers.pickle_handler import PickleHandler +from utils.easy_io.handlers.registry_utils import file_handlers, register_handler +from utils.easy_io.handlers.yaml_handler import YamlHandler + +__all__ = [ + "BaseFileHandler", + "JsonHandler", + "PickleHandler", + "YamlHandler", + "register_handler", + "file_handlers", +] diff --git a/utils/easy_io/handlers/base.py b/utils/easy_io/handlers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5dcbcabc40807706eeb43d1a598571c51922a8 --- /dev/null +++ b/utils/easy_io/handlers/base.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABCMeta, abstractmethod + + +class BaseFileHandler(metaclass=ABCMeta): + # `str_like` is a flag to indicate whether the type of file object is + # str-like object or bytes-like object. Pickle only processes bytes-like + # objects but json only processes str-like object. If it is str-like + # object, `StringIO` will be used to process the buffer. + str_like = True + + @abstractmethod + def load_from_fileobj(self, file, **kwargs): + pass + + @abstractmethod + def dump_to_fileobj(self, obj, file, **kwargs): + pass + + @abstractmethod + def dump_to_str(self, obj, **kwargs): + pass + + def load_from_path(self, filepath, mode="r", **kwargs): + with open(filepath, mode) as f: + return self.load_from_fileobj(f, **kwargs) + + def dump_to_path(self, obj, filepath, mode="w", **kwargs): + with open(filepath, mode) as f: + self.dump_to_fileobj(obj, f, **kwargs) diff --git a/utils/easy_io/handlers/csv_handler.py b/utils/easy_io/handlers/csv_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..c042033d4efa55076c6eed3a0cde0e60ef8f7935 --- /dev/null +++ b/utils/easy_io/handlers/csv_handler.py @@ -0,0 +1,42 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import csv +from io import StringIO + +from utils.easy_io.handlers.base import BaseFileHandler + + +class CsvHandler(BaseFileHandler): + def load_from_fileobj(self, file, **kwargs): + del kwargs + reader = csv.reader(file) + return list(reader) + + def dump_to_fileobj(self, obj, file, **kwargs): + del kwargs + writer = csv.writer(file) + if not all(isinstance(row, list) for row in obj): + raise ValueError("Each row must be a list") + writer.writerows(obj) + + def dump_to_str(self, obj, **kwargs): + del kwargs + output = StringIO() + writer = csv.writer(output) + if not all(isinstance(row, list) for row in obj): + raise ValueError("Each row must be a list") + writer.writerows(obj) + return output.getvalue() diff --git a/utils/easy_io/handlers/gzip_handler.py b/utils/easy_io/handlers/gzip_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..8766cdbc30ea3be5c8df61c3609e77a86e7ab0f0 --- /dev/null +++ b/utils/easy_io/handlers/gzip_handler.py @@ -0,0 +1,45 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gzip +import warnings +from io import BytesIO +from typing import Any + +from utils.easy_io.handlers.pickle_handler import PickleHandler, _import_pickle + +_GZ_LOAD_WARNING = ( + "Loading gzip-compressed pickle is deprecated due to security concerns. " + "Consider converting .gz files to a safer format." +) + +_GZ_DUMP_WARNING = ( + "Writing gzip-compressed pickle is deprecated. " + "This will become an error in a future release." +) + + +class GzipHandler(PickleHandler): + str_like = False + + def load_from_fileobj(self, file: BytesIO, **kwargs): + warnings.warn(_GZ_LOAD_WARNING, DeprecationWarning, stacklevel=3) + with gzip.GzipFile(fileobj=file, mode="rb") as f: + return _import_pickle().load(f) + + def dump_to_fileobj(self, obj: Any, file: BytesIO, **kwargs): + warnings.warn(_GZ_DUMP_WARNING, DeprecationWarning, stacklevel=3) + with gzip.GzipFile(fileobj=file, mode="wb") as f: + _import_pickle().dump(obj, f) diff --git a/utils/easy_io/handlers/imageio_video_handler.py b/utils/easy_io/handlers/imageio_video_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..3809496611bb9233ba5a458a3f7c99c53891d013 --- /dev/null +++ b/utils/easy_io/handlers/imageio_video_handler.py @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import IO + +import numpy as np +import torch + +from utils.easy_io.handlers.base import BaseFileHandler + +try: + import imageio +except ImportError: + imageio = None + + +class ImageioVideoHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file: IO[bytes], format: str = "mp4", mode: str = "rgb", **kwargs): + """ + Load video from a file-like object using imageio with specified format and color mode. + + Parameters: + file (IO[bytes]): A file-like object containing video data. + format (str): Format of the video file (default 'mp4'). + mode (str): Color mode of the video, 'rgb' or 'gray' (default 'rgb'). + + Returns: + tuple: A tuple containing an array of video frames and metadata about the video. + """ + file.seek(0) + video_reader = imageio.get_reader(file, format, **kwargs) + + video_frames = [] + for frame in video_reader: + if mode == "gray": + import cv2 # Convert frame to grayscale if mode is gray + + frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) + frame = np.expand_dims(frame, axis=2) # Keep frame dimensions consistent + video_frames.append(frame) + + return np.array(video_frames), video_reader.get_meta_data() + + def dump_to_fileobj( + self, + obj: np.ndarray | torch.Tensor, + file: IO[bytes], + format: str = "mp4", # pylint: disable=redefined-builtin + fps: int = 17, + quality: int = 5, + **kwargs, + ): + """ + Save an array of video frames to a file-like object using imageio. + + Parameters: + obj (np.ndarray): An array of frames to be saved as video. + file (IO[bytes]): A file-like object to which the video data will be written. + format (str): Format of the video file (default 'mp4'). + fps (int): Frames per second of the output video (default 30). + + """ + if isinstance(obj, torch.Tensor): + assert obj.dtype == torch.uint8 + obj = obj.cpu().numpy() + h, w = obj.shape[1:-1] + kwargs = { + "fps": fps, + "quality": quality, + "macro_block_size": 1, + "ffmpeg_params": ["-s", f"{w}x{h}"], + "output_params": ["-f", "mp4"], + } + imageio.mimsave(file, obj, format, **kwargs) + + def dump_to_str(self, obj, **kwargs): + raise NotImplementedError diff --git a/utils/easy_io/handlers/json_handler.py b/utils/easy_io/handlers/json_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a82ffb08071912f2e95a0c5752e6687d7daa41 --- /dev/null +++ b/utils/easy_io/handlers/json_handler.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json + +import numpy as np + +from utils.easy_io.handlers.base import BaseFileHandler + + +def set_default(obj): + """Set default json values for non-serializable values. + + It helps convert ``set``, ``range`` and ``np.ndarray`` data types to list. + It also converts ``np.generic`` (including ``np.int32``, ``np.float32``, + etc.) into plain numbers of plain python built-in types. + """ + if isinstance(obj, (set, range)): + return list(obj) + elif isinstance(obj, np.ndarray): + return obj.tolist() + elif isinstance(obj, np.generic): + return obj.item() + raise TypeError(f"{type(obj)} is unsupported for json dump") + + +class JsonHandler(BaseFileHandler): + def load_from_fileobj(self, file): + return json.load(file) + + def dump_to_fileobj(self, obj, file, **kwargs): + kwargs.setdefault("default", set_default) + json.dump(obj, file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + kwargs.setdefault("default", set_default) + return json.dumps(obj, **kwargs) diff --git a/utils/easy_io/handlers/jsonl_handler.py b/utils/easy_io/handlers/jsonl_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..20cdd52091f3ad42274e902392ea0aeff7d74c3b --- /dev/null +++ b/utils/easy_io/handlers/jsonl_handler.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from typing import IO + +import numpy as np + +from utils.easy_io.handlers.base import BaseFileHandler + + +def set_default(obj): + """Set default json values for non-serializable values. + + It helps convert ``set``, ``range`` and ``np.ndarray`` data types to list. + It also converts ``np.generic`` (including ``np.int32``, ``np.float32``, + etc.) into plain numbers of plain python built-in types. + """ + if isinstance(obj, (set, range)): + return list(obj) + elif isinstance(obj, np.ndarray): + return obj.tolist() + elif isinstance(obj, np.generic): + return obj.item() + raise TypeError(f"{type(obj)} is unsupported for json dump") + + +class JsonlHandler(BaseFileHandler): + """Handler for JSON lines (JSONL) files.""" + + def load_from_fileobj(self, file: IO[bytes]): + """Load JSON objects from a newline-delimited JSON (JSONL) file object. + + Returns: + A list of Python objects loaded from each JSON line. + """ + data = [] + for line in file: + line = line.strip() + if not line: + continue # skip empty lines if any + data.append(json.loads(line)) + return data + + def dump_to_fileobj(self, obj: IO[bytes], file, **kwargs): + """Dump a list of objects to a newline-delimited JSON (JSONL) file object. + + Args: + obj: A list (or iterable) of objects to dump line by line. + """ + kwargs.setdefault("default", set_default) + for item in obj: + file.write(json.dumps(item, **kwargs) + "\n") + + def dump_to_str(self, obj, **kwargs): + """Dump a list of objects to a newline-delimited JSON (JSONL) string.""" + kwargs.setdefault("default", set_default) + lines = [json.dumps(item, **kwargs) for item in obj] + return "\n".join(lines) + + +if __name__ == "__main__": + from utils.easy_io import easy_io + + easy_io.dump([1, 2, 3], "test.jsonl", file_format="jsonl") + print(easy_io.load("test.jsonl")) + easy_io.dump([{"key1": 1, "key2": 2}, {"key1": 3, "key2": 4}], "test.jsonl", file_format="jsonl") + print(easy_io.load("test.jsonl")) diff --git a/utils/easy_io/handlers/np_handler.py b/utils/easy_io/handlers/np_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..930f0fc8ab13aa1174d2c456c545f2f1817f6edf --- /dev/null +++ b/utils/easy_io/handlers/np_handler.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from io import BytesIO +from typing import IO, Any + +import numpy as np + +from utils.easy_io.handlers.base import BaseFileHandler + + +class NumpyHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file: IO[bytes], **kwargs) -> Any: + """ + Load a NumPy array from a file-like object. + + Parameters: + file (IO[bytes]): The file-like object containing the NumPy array data. + **kwargs: Additional keyword arguments passed to `np.load`. + + Returns: + numpy.ndarray: The loaded NumPy array. + """ + return np.load(file, **kwargs) + + def load_from_path(self, filepath: str, **kwargs) -> Any: + """ + Load a NumPy array from a file path. + + Parameters: + filepath (str): The path to the file to load. + **kwargs: Additional keyword arguments passed to `np.load`. + + Returns: + numpy.ndarray: The loaded NumPy array. + """ + return super().load_from_path(filepath, mode="rb", **kwargs) + + def dump_to_str(self, obj: np.ndarray, **kwargs) -> str: + """ + Serialize a NumPy array to a string in binary format. + + Parameters: + obj (np.ndarray): The NumPy array to serialize. + **kwargs: Additional keyword arguments passed to `np.save`. + + Returns: + str: The serialized NumPy array as a string. + """ + with BytesIO() as f: + np.save(f, obj, **kwargs) + return f.getvalue() + + def dump_to_fileobj(self, obj: np.ndarray, file: IO[bytes], **kwargs): + """ + Dump a NumPy array to a file-like object. + + Parameters: + obj (np.ndarray): The NumPy array to dump. + file (IO[bytes]): The file-like object to which the array is dumped. + **kwargs: Additional keyword arguments passed to `np.save`. + """ + np.save(file, obj, **kwargs) + + def dump_to_path(self, obj: np.ndarray, filepath: str, **kwargs): + """ + Dump a NumPy array to a file path. + + Parameters: + obj (np.ndarray): The NumPy array to dump. + filepath (str): The file path where the array should be saved. + **kwargs: Additional keyword arguments passed to `np.save`. + """ + with open(filepath, "wb") as f: + np.save(f, obj, **kwargs) diff --git a/utils/easy_io/handlers/pandas_handler.py b/utils/easy_io/handlers/pandas_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..f84d23ed75c0102fc6c55fc215452226f313f33a --- /dev/null +++ b/utils/easy_io/handlers/pandas_handler.py @@ -0,0 +1,42 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pandas is only needed by the two CSV methods below, but this handler is +# instantiated eagerly in the easy_io handler registry (imported by utils.misc, +# i.e. almost the entire codebase). Importing pandas at module load crashes the +# whole utils stack on numpy-ABI-mismatched containers ("numpy.dtype size +# changed"). Guard it so unrelated code (viz, inference) keeps working; the CSV +# methods raise a clear error only if actually used. +try: + import pandas as pd +except Exception: # noqa: BLE001 + pd = None + +from utils.easy_io.handlers.base import BaseFileHandler # isort:skip + + +class PandasHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file, **kwargs): + if pd is None: + raise ImportError("pandas failed to import (see pandas_handler.py); cannot read CSV") + return pd.read_csv(file, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + obj.to_csv(file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + raise NotImplementedError("PandasHandler does not support dumping to str") diff --git a/utils/easy_io/handlers/pickle_handler.py b/utils/easy_io/handlers/pickle_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..ab6001677d8ed224c54e4367bb0a0bffc26a0b4f --- /dev/null +++ b/utils/easy_io/handlers/pickle_handler.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from io import BytesIO +from typing import Any + +from utils.easy_io.handlers.base import BaseFileHandler + +_LOAD_WARNING = ( + "Loading data via pickle is deprecated due to security concerns " + "(arbitrary code execution). Consider converting .pkl files to " + ".yaml, .json, or .pt format." +) + +_DUMP_WARNING = ( + "Writing data via pickle is deprecated. Use .yaml, .json, or .pt " + "format instead. This will become an error in a future release." +) + + +def _import_pickle(): + import pickle as _pickle + return _pickle + + +class PickleHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file: BytesIO, **kwargs): + warnings.warn(_LOAD_WARNING, DeprecationWarning, stacklevel=3) + return _import_pickle().load(file, **kwargs) + + def load_from_path(self, filepath, **kwargs): + return super().load_from_path(filepath, mode="rb", **kwargs) + + def dump_to_str(self, obj, **kwargs): + warnings.warn(_DUMP_WARNING, DeprecationWarning, stacklevel=3) + kwargs.setdefault("protocol", 2) + return _import_pickle().dumps(obj, **kwargs) + + def dump_to_fileobj(self, obj: Any, file: BytesIO, **kwargs): + warnings.warn(_DUMP_WARNING, DeprecationWarning, stacklevel=3) + kwargs.setdefault("protocol", 2) + _import_pickle().dump(obj, file, **kwargs) + + def dump_to_path(self, obj, filepath, **kwargs): + warnings.warn(_DUMP_WARNING, DeprecationWarning, stacklevel=3) + with open(filepath, "wb") as f: + _import_pickle().dump(obj, f, **kwargs) diff --git a/utils/easy_io/handlers/pil_handler.py b/utils/easy_io/handlers/pil_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..11535d210a242e55566010ff1e1b5621781b6de2 --- /dev/null +++ b/utils/easy_io/handlers/pil_handler.py @@ -0,0 +1,96 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import IO, Optional, Tuple, Union + +import numpy as np + +from utils.easy_io.handlers.base import BaseFileHandler + +try: + from PIL import Image +except ImportError: + Image = None + + +class PILHandler(BaseFileHandler): + format: str + str_like = False + + def load_from_fileobj( + self, + file: IO[bytes], + fmt: str = "pil", + size: Optional[Union[int, Tuple[int, int]]] = None, + **kwargs, + ): + """ + Load an image from a file-like object and return it in a specified format. + + Args: + file (IO[bytes]): A file-like object containing the image data. + fmt (str): The format to convert the image into. Options are \ + 'numpy', 'np', 'npy', 'type' (all return numpy arrays), \ + 'pil' (returns PIL Image), 'th', 'torch' (returns a torch tensor). + size (Optional[Union[int, Tuple[int, int]]]): The new size of the image as a single integer \ + or a tuple of (width, height). If specified, the image is resized accordingly. + **kwargs: Additional keyword arguments that can be passed to conversion functions. + + Returns: + Image data in the format specified by `fmt`. + + Raises: + IOError: If the image cannot be loaded or processed. + ValueError: If the specified format is unsupported. + """ + try: + img = Image.open(file) + img.load() # Explicitly load the image data + if size is not None: + if isinstance(size, int): + size = ( + size, + size, + ) # create a tuple if only one integer is provided + img = img.resize(size, Image.ANTIALIAS) + + # Return the image in the requested format + if fmt in ["numpy", "np", "npy"]: + return np.array(img, **kwargs) + if fmt == "pil": + return img + if fmt in ["th", "torch"]: + import torch + + # Convert to tensor + img_tensor = torch.from_numpy(np.array(img, **kwargs)) + # Convert image from HxWxC to CxHxW + if img_tensor.ndim == 3: + img_tensor = img_tensor.permute(2, 0, 1) + return img_tensor + raise ValueError( + "Unsupported format. Supported formats are 'numpy', 'np', 'npy', 'pil', 'th', and 'torch'." + ) + except Exception as e: + raise IOError(f"Unable to load image: {e}") from e + + def dump_to_fileobj(self, obj, file: IO[bytes], **kwargs): + if "format" not in kwargs: + kwargs["format"] = self.format + kwargs["format"] = "JPEG" if self.format.lower() == "jpg" else self.format.upper() + obj.save(file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + raise NotImplementedError diff --git a/utils/easy_io/handlers/registry_utils.py b/utils/easy_io/handlers/registry_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..db813ccf20e01a15d275f03533074f159d6e2c68 --- /dev/null +++ b/utils/easy_io/handlers/registry_utils.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from utils.easy_io.handlers.base import BaseFileHandler +from utils.easy_io.handlers.csv_handler import CsvHandler +from utils.easy_io.handlers.gzip_handler import GzipHandler +from utils.easy_io.handlers.imageio_video_handler import ImageioVideoHandler +from utils.easy_io.handlers.json_handler import JsonHandler +from utils.easy_io.handlers.jsonl_handler import JsonlHandler +from utils.easy_io.handlers.np_handler import NumpyHandler +from utils.easy_io.handlers.pandas_handler import PandasHandler +from utils.easy_io.handlers.pickle_handler import PickleHandler +from utils.easy_io.handlers.pil_handler import PILHandler +from utils.easy_io.handlers.tarfile_handler import TarHandler +from utils.easy_io.handlers.torch_handler import TorchHandler +from utils.easy_io.handlers.torchjit_handler import TorchJitHandler +from utils.easy_io.handlers.txt_handler import TxtHandler +from utils.easy_io.handlers.yaml_handler import YamlHandler + +file_handlers = { + "json": JsonHandler(), + "yaml": YamlHandler(), + "yml": YamlHandler(), + "pickle": PickleHandler(), + "pkl": PickleHandler(), + "tar": TarHandler(), + "jit": TorchJitHandler(), + "npy": NumpyHandler(), + "txt": TxtHandler(), + "csv": CsvHandler(), + "pandas": PandasHandler(), + "gz": GzipHandler(), + "jsonl": JsonlHandler(), +} + +for torch_type in ["pt", "pth", "ckpt"]: + file_handlers[torch_type] = TorchHandler() +for img_type in ["jpg", "jpeg", "png", "bmp", "gif"]: + file_handlers[img_type] = PILHandler() + file_handlers[img_type].format = img_type +for video_type in ["mp4", "avi", "mov", "webm", "flv", "wmv"]: + file_handlers[video_type] = ImageioVideoHandler() + + +def _register_handler(handler, file_formats): + """Register a handler for some file extensions. + + Args: + handler (:obj:`BaseFileHandler`): Handler to be registered. + file_formats (str or list[str]): File formats to be handled by this + handler. + """ + if not isinstance(handler, BaseFileHandler): + raise TypeError(f"handler must be a child of BaseFileHandler, not {type(handler)}") + if isinstance(file_formats, str): + file_formats = [file_formats] + if not all([isinstance(item, str) for item in file_formats]): + raise TypeError("file_formats must be a str or a list of str") + for ext in file_formats: + file_handlers[ext] = handler + + +def register_handler(file_formats, **kwargs): + def wrap(cls): + _register_handler(cls(**kwargs), file_formats) + return cls + + return wrap diff --git a/utils/easy_io/handlers/tarfile_handler.py b/utils/easy_io/handlers/tarfile_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..895f764859a82830bf54cce37fe40e5e59fe5679 --- /dev/null +++ b/utils/easy_io/handlers/tarfile_handler.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import tarfile + +from utils.easy_io.handlers.base import BaseFileHandler + + +class TarHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file, mode="r|*", **kwargs): + return tarfile.open(fileobj=file, mode=mode, **kwargs) + + def load_from_path(self, filepath, mode="r|*", **kwargs): + return tarfile.open(filepath, mode=mode, **kwargs) + + def dump_to_fileobj(self, obj, file, mode="w", **kwargs): + with tarfile.open(fileobj=file, mode=mode) as tar: + tar.add(obj, **kwargs) + + def dump_to_path(self, obj, filepath, mode="w", **kwargs): + with tarfile.open(filepath, mode=mode) as tar: + tar.add(obj, **kwargs) + + def dump_to_str(self, obj, **kwargs): + raise NotImplementedError diff --git a/utils/easy_io/handlers/torch_handler.py b/utils/easy_io/handlers/torch_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bc194fe3c80450ad14fa310cca720607f77044 --- /dev/null +++ b/utils/easy_io/handlers/torch_handler.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import torch +except ImportError: + torch = None + +from utils.easy_io.handlers.base import BaseFileHandler + + +class TorchHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file, **kwargs): + return torch.load(file, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + torch.save(obj, file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + raise NotImplementedError diff --git a/utils/easy_io/handlers/torchjit_handler.py b/utils/easy_io/handlers/torchjit_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..896cd546845ce3af09aa9a71317a860ee5604c5f --- /dev/null +++ b/utils/easy_io/handlers/torchjit_handler.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import torch +except ImportError: + torch = None + +from utils.easy_io.handlers.base import BaseFileHandler + + +class TorchJitHandler(BaseFileHandler): + str_like = False + + def load_from_fileobj(self, file, **kwargs): + return torch.jit.load(file, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + torch.jit.save(obj, file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + raise NotImplementedError diff --git a/utils/easy_io/handlers/txt_handler.py b/utils/easy_io/handlers/txt_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..49b0c71408f7c53e2d3ba76c454dfab10de80cb4 --- /dev/null +++ b/utils/easy_io/handlers/txt_handler.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from utils.easy_io.handlers.base import BaseFileHandler + + +class TxtHandler(BaseFileHandler): + def load_from_fileobj(self, file, **kwargs): + del kwargs + return file.read() + + def dump_to_fileobj(self, obj, file, **kwargs): + del kwargs + if not isinstance(obj, str): + obj = str(obj) + file.write(obj) + + def dump_to_str(self, obj, **kwargs): + del kwargs + if not isinstance(obj, str): + obj = str(obj) + return obj diff --git a/utils/easy_io/handlers/yaml_handler.py b/utils/easy_io/handlers/yaml_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..c97bab389457fda28c1bb4147b02582945b77817 --- /dev/null +++ b/utils/easy_io/handlers/yaml_handler.py @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import yaml + +try: + from yaml import CDumper as Dumper # type: ignore + from yaml import CLoader as Loader # type: ignore +except ImportError: + from yaml import Loader, Dumper # type: ignore + +from utils.easy_io.handlers.base import BaseFileHandler # isort:skip + + +class YamlHandler(BaseFileHandler): + def load_from_fileobj(self, file, **kwargs): + kwargs.setdefault("Loader", Loader) + return yaml.load(file, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + kwargs.setdefault("Dumper", Dumper) + yaml.dump(obj, file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + kwargs.setdefault("Dumper", Dumper) + return yaml.dump(obj, **kwargs) diff --git a/utils/ema.py b/utils/ema.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9347a48eb7589a724379e60cd37c6378b7347d --- /dev/null +++ b/utils/ema.py @@ -0,0 +1,327 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any, Generator, List, Optional, Union + +import numpy as np +import torch +from megatron.core import parallel_state + +from utils import distributed, log + +if TYPE_CHECKING: + from utils.model import Model + + +class FastEmaModelUpdater: + """ + This class is used to update target model~(EMA) given source model~(regular model) and beta. + The method interaface mimic :class:`EMAModelTracker` and :class:`PowerEMATracker`. + Different from two classes, this class does not maintain the EMA model weights as buffers. It expects the user to have two module with same architecture and weights shape. + The class is proposed to work with FSDP model where above two classes are not working as expected. Besides, it is strange to claim model weights as buffers and do unnecessary name changing in :class:`EMAModelTracker` and :class:`PowerEMATracker`. Moeving forward, we should use this class instead of above two classes. + """ + + def __init__(self): + # Flag to indicate whether the cache is taken or not. Useful to avoid cache overwrite + self.is_cached = False + + def update_average(self, src_model: torch.nn.Module, tgt_model: torch.nn.Module, beta: float = 0.9999) -> None: + target_list = [] + source_list = [] + for tgt_params, src_params in zip(tgt_model.parameters(), src_model.parameters()): + assert ( + tgt_params.dtype == torch.float32 + ), f"EMA model only works in FP32 dtype, got {tgt_params.dtype} instead." + target_list.append(tgt_params) + source_list.append(src_params.data) + torch._foreach_mul_(target_list, beta) + torch._foreach_add_(target_list, source_list, alpha=1.0 - beta) + + def copy_to(self, src_model: torch.nn.Module, tgt_model: torch.nn.Module) -> None: + for tgt_params, src_params in zip(tgt_model.parameters(), src_model.parameters()): + tgt_params.data.copy_(src_params.data) + + def cache(self, parameters: Any, is_cpu: bool = False) -> None: + """Save the current parameters for restoring later. + + Args: + parameters (iterable): Iterable of torch.nn.Parameter to be temporarily stored. + """ + assert self.is_cached is False, "EMA cache is already taken. Did you forget to restore it?" + device = "cpu" if is_cpu else "cuda" + self.collected_params = [param.clone().to(device) for param in parameters] + self.is_cached = True + + def restore(self, parameters: Any) -> None: + """Restore the parameters in self.collected_params. + + Useful to validate the model with EMA parameters without affecting the + original optimization process. Store the parameters before copy_to(). + After validation (or model saving), use this to restore the former parameters. + + Args: + parameters (iterable): Iterable of torch.nn.Parameter to be updated with the stored parameters. + """ + assert self.is_cached, "EMA cache is not taken yet." + for c_param, param in zip(self.collected_params, parameters, strict=False): + param.data.copy_(c_param.data.type_as(param.data)) + self.collected_params = [] + # Release the cache after we call restore + self.is_cached = False + + +def get_buffer_name(param_name: str, torch_compile_buffer_renaming: bool = False) -> str: + """ + This function creates buffer name used by EMA from parameter's name + + Args: + param_name (str): Model's parameter name + Returns: + buffer_name (str): buffer name to be used for given parameter name + """ + + buffer_name = param_name.replace(".", "-") + + if torch_compile_buffer_renaming: + # torch.compile() adds _orig_mod to state dict names, this way we get original name + buffer_name = buffer_name.replace("_orig_mod-", "") + + return buffer_name + + +class EMAModelTracker(torch.nn.Module): + """This is a class to track the EMA model weights. + + The EMA weights are registered as buffers, which are extractable as state dicts. The names follow those of the + regular weights, except all "." are replaced with "-" (limitation of register_buffer()). This is similar to SDXL's + implementation of EMA. There are no optimizable parameters. + + Attributes: + collected_params (list): temporarily stores the regular weights while in EMA mode. + beta (float): EMA decay rate. (default: 0.9999). + torch_compile_buffer_renaming (bool): whether to remove '_orig_mod-' from buffer names when torch.compile is used + """ + + def __init__(self, model: Model, beta: float = 0.9999, torch_compile_buffer_renaming: bool = False): + """Constructor of the EMA model weight tracker. + + Args: + model (Model): The PyTorch model. + beta (float): EMA decay rate. (default: 0.9999). + """ + super().__init__() + self.torch_compile_buffer_renaming: bool = torch_compile_buffer_renaming + if not 0.0 <= beta <= 1.0: + raise ValueError("Decay must be between 0 and 1") + self.beta = beta + for name, param in model.named_parameters(): + if param.requires_grad: + buffer_name = get_buffer_name(name, self.torch_compile_buffer_renaming) + self.register_buffer(buffer_name, param.clone().detach().data) + self.collected_params = [] + # Flag to indicate whether the cache is taken or not. Useful to avoid cache overwrite + self.is_cached = False + + @torch.no_grad() + def update_average(self, model: Model, iteration: Optional[int] = None) -> None: + del iteration + target_list = [] + source_list = [] + ema_buffers = self.state_dict() + for name, param in model.named_parameters(): + if param.requires_grad: + buffer_name = get_buffer_name(name, self.torch_compile_buffer_renaming) + buffer = ema_buffers[buffer_name] + assert buffer.dtype == torch.float32, f"EMA model only works in FP32 dtype, got {buffer.dtype} instead." + target_list.append(buffer) + source_list.append(param.data) + torch._foreach_mul_(target_list, self.beta) + torch._foreach_add_(target_list, source_list, alpha=1.0 - self.beta) + + def copy_to(self, model: Model) -> None: + ema_buffers = self.state_dict() + for name, param in model.named_parameters(): + if param.requires_grad: + buffer_name = get_buffer_name(name, self.torch_compile_buffer_renaming) + buffer = ema_buffers[buffer_name] + param.data.copy_(buffer.data) + + def cache(self, parameters: Any, is_cpu: bool = False) -> None: + """Save the current parameters for restoring later. + + Args: + parameters (iterable): Iterable of torch.nn.Parameter to be temporarily stored. + """ + assert self.is_cached is False, "EMA cache is already taken. Did you forget to restore it?" + device = "cpu" if is_cpu else "cuda" + self.collected_params = [param.clone().to(device) for param in parameters] + self.is_cached = True + + def restore(self, parameters: Any) -> None: + """Restore the parameters in self.collected_params. + + Useful to validate the model with EMA parameters without affecting the + original optimization process. Store the parameters before copy_to(). + After validation (or model saving), use this to restore the former parameters. + + Args: + parameters (iterable): Iterable of torch.nn.Parameter to be updated with the stored parameters. + """ + assert self.is_cached, "EMA cache is not taken yet." + for c_param, param in zip(self.collected_params, parameters, strict=False): + param.data.copy_(c_param.data.type_as(param.data)) + self.collected_params = [] + # Release the cache after we call restore + self.is_cached = False + + @classmethod + def initialize_multi_rank_ema( + cls, model: torch.nn.Module, rate: Union[float, List[float]], num: int = 1, enabled: bool = True + ) -> Optional[EMAModelTracker]: + """ + Class method to initialize per rank EMA Model Tracker with different rate. + Each rank will have a different rate based on the given configuration, resulting in different EMA weights. + + Args: + model (torch.nn.Module): The neural network model to be tracked. + rate (Union[float, List[float]]): The decay rate(s) for the EMA. If a list is provided, + it corresponds to rates for different ranks. + num (int, optional): The number of leading ranks to consider for different rates. + Defaults to 1. + enabled (bool, optional): Flag to enable or disable the creation of the tracker. + If False, returns None. Defaults to True. + + Returns: + Optional[EMAModelTracker]: An instance of EMAModelTracker if enabled, otherwise None. + + Example: + >>> model = torch.nn.Linear(10, 2) + >>> tracker = EMAModelTracker.initialize_ema_from_settings(model, rate=[0.1, 0.2], num=2) + >>> print(tracker) + + Notes: + If `rate` is a list and the current rank is less than `num`, the rate for the current rank + is used. If the current rank exceeds `num`, the first rate in the list is used by default. + """ + if not enabled: + return None + if parallel_state.is_initialized(): + cur_dp_rank = parallel_state.get_data_parallel_rank(with_context_parallel=True) + log.critical(f"using MCore parallel_state for EMA initialization. DP RANK: {cur_dp_rank}", rank0_only=False) + log.warning("It should not used together with FSDP!") + else: + cur_dp_rank = distributed.get_rank() + log.critical(f"using torch.distributed for EMA initialization. DP RANK: {cur_dp_rank}", rank0_only=False) + rate = rate if isinstance(rate, list) else [rate] + num = min(num, len(rate)) + rate = rate[cur_dp_rank] if cur_dp_rank < num else rate[0] + if cur_dp_rank < num: + print(f"EMAModelTracker: rank {cur_dp_rank}, rate {rate}") + return cls(model, rate) + + +class PowerEMATracker(EMAModelTracker): + def __init__(self, model: Model, s: float = 0.1, torch_compile_buffer_renaming: bool = False): + """Constructor of the EMA model weight tracker. + + Args: + model (Model): The PyTorch model. + s (float): EMA decay rate. See EDM2 paper + torch_compile_buffer_renaming (bool): whether to remove '_orig_mod-' from buffer names when torch.compile is used + """ + super().__init__(model=model, beta=0.0, torch_compile_buffer_renaming=torch_compile_buffer_renaming) + self.exp = np.roots([1, 7, 16 - s**-2, 12 - s**-2]).real.max() + + @torch.no_grad() + def update_average(self, model: Model, iteration: Optional[int] = None) -> None: + if iteration == 0: + beta = 0.0 + else: + i = iteration + 1 + beta = (1 - 1 / i) ** (self.exp + 1) + self.beta = beta + + super().update_average(model, iteration) + + @classmethod + def initialize_multi_rank_ema( + cls, model: torch.nn.Module, rate: float, num: int, enabled: bool = True + ) -> Optional[PowerEMATracker]: + """ + Class method to initialize per rank EMA Model Tracker with different rate. + Each rank will have a different rate based on the given configuration, resulting in different EMA weights. + + Args: + model (torch.nn.Module): The neural network model for which the EMA tracker is being set up. + num (int): The number of ranks for which the rate adjustment is applied. Beyond this, the rate remains unchanged. + rate (float): The base decay rate for the EMA calculation. + enabled (bool, optional): Flag to enable or disable the initialization of the tracker. If False, returns None. + Defaults to True. + + Returns: + Optional[PowerEMATracker]: An instance of PowerEMATracker with adjusted rate if enabled, otherwise None. + + Raises: + None + + Example: + >>> model = torch.nn.Linear(10, 2) + >>> tracker = PowerEMATracker.initialize_multi_rank_ema(model, num=3, rate=0.99) + >>> print(tracker) + + Notes: + The decay rate is modified by dividing it by 2 raised to the power of the rank for each rank less than `num`. + If the rank is greater than or equal to `num`, the base rate is used without modification. This approach + allows higher ranked processes to have a less aggressive decay, potentially reflecting their delayed synchronization + in a distributed training scenario. + """ + if not enabled: + return None + if parallel_state.is_initialized(): + cur_dp_rank = parallel_state.get_data_parallel_rank(with_context_parallel=True) + log.critical(f"using MCore parallel_state for EMA initialization. DP RANK: {cur_dp_rank}", rank0_only=False) + log.warning("It should not used together with FSDP!") + else: + cur_dp_rank = distributed.get_rank() + log.critical(f"using torch.distributed for EMA initialization. DP RANK: {cur_dp_rank}", rank0_only=False) + + divider = 2**cur_dp_rank if cur_dp_rank < num else 1 + if cur_dp_rank < num: + print(f"PowerEMATracker: rank {cur_dp_rank}, rate {rate / divider}") + return cls(model, rate / divider) + + +@contextmanager +def ema_scope(model: Model, enabled: bool = False) -> Generator[None, None, None]: + """Context manager for switching between regular and EMA model weights. + + Args: + model (Model): The PyTorch model. + enabled (bool): Whether switching to EMA weights is enabled (default: False). + """ + if enabled: + assert hasattr(model, "ema") and isinstance(model.ema, (FastEmaModelUpdater, EMAModelTracker, PowerEMATracker)) + model.ema.cache(model.parameters()) + model.ema.copy_to(model) + log.info("EMA: switched to EMA weights.") + try: + yield None + finally: + if enabled: + model.ema.restore(model.parameters()) + log.info("EMA: restored regular weights.") diff --git a/utils/fsdp_checkpointer.py b/utils/fsdp_checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..502decf64508e1ea5b5457d8eb1c6e708eb5a286 --- /dev/null +++ b/utils/fsdp_checkpointer.py @@ -0,0 +1,511 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import gc +import os +import re +import threading + +import torch +from torch.distributed.fsdp import FullOptimStateDictConfig, FullStateDictConfig +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import StateDictType + +from utils import callback, distributed, log, misc +from utils.atomic_save import atomic_torch_save, atomic_write_text +from utils.config import CheckpointConfig, JobConfig +from utils.easy_io import easy_io +from utils.fsdp_optim_fix import scatter_full_optim_state_dict +from utils.model import Model + + +class FSDPCheckpointer: + """The checkpointer class. Supports checkpoint saving/loading to local disk.""" + + _GENERATION_MARKER_RE = re.compile(r"^iter_(\d{9})\.pt$") + _GENERATION_FILE_RE = re.compile(r"^iter_(\d{9}).*\.pt$") + + def __init__(self, config_checkpoint: CheckpointConfig, config_job: JobConfig, callbacks: callback.CallBackGroup): + """Constructor of the checkpointer. + + Args: + config_checkpoint (CheckpointConfig): The config object for the checkpointer. + """ + # Set the callback functions. + self.callbacks = callbacks + self.checkpoint_dir_local = f"{config_job.path_local}/checkpoints" + self.strict_resume = config_checkpoint.strict_resume + self.load_path = config_checkpoint.load_path + self.load_training_state = config_checkpoint.load_training_state + self.save_thread = None + self.config_checkpoint = config_checkpoint + self.keep_last_checkpoints = int( + getattr(config_checkpoint, "keep_last_checkpoints", 0) + ) + self.save_at_iters = frozenset( + int(iteration) + for iteration in getattr(config_checkpoint, "save_at_iters", []) + ) + if self.keep_last_checkpoints < 0: + raise ValueError( + "checkpoint.keep_last_checkpoints must be non-negative, " + f"got {self.keep_last_checkpoints}" + ) + if any(iteration <= 0 for iteration in self.save_at_iters): + raise ValueError( + "checkpoint.save_at_iters must contain positive iterations, " + f"got {sorted(self.save_at_iters)}" + ) + + def _checkpoint_filename(self, iteration: int, postfix: str) -> str: + if self.keep_last_checkpoints > 0 or iteration in self.save_at_iters: + return f"iter_{iteration:09d}{postfix}.pt" + return f"ckpt_{postfix}.pt" + + def _prune_old_generations(self, current_iteration: int) -> None: + if self.keep_last_checkpoints == 0: + return + + filenames = os.listdir(self.checkpoint_dir_local) + completed_iterations = [] + for filename in filenames: + match = self._GENERATION_MARKER_RE.fullmatch(filename) + if match is not None: + iteration = int(match.group(1)) + if iteration <= current_iteration: + completed_iterations.append(iteration) + ordinary_iterations = sorted( + iteration + for iteration in completed_iterations + if iteration not in self.save_at_iters + ) + stale_iterations = set( + ordinary_iterations[: -self.keep_last_checkpoints] + ) + if not stale_iterations: + return + + removed_files = 0 + for filename in filenames: + match = self._GENERATION_FILE_RE.fullmatch(filename) + if match is None or int(match.group(1)) not in stale_iterations: + continue + os.remove(os.path.join(self.checkpoint_dir_local, filename)) + removed_files += 1 + log.info( + "Pruned checkpoint generations " + f"{sorted(stale_iterations)} ({removed_files} files); retained " + f"the latest {self.keep_last_checkpoints} non-target generations " + f"and target iterations {sorted(self.save_at_iters)}" + ) + + def _load_ckpt_file_during_init(self): + latest_checkpoint_file = self._read_latest_checkpoint_file() + if latest_checkpoint_file is not None: + # 1. Resume training from latest_checkpoint.txt under the same name. + checkpoint_dir = self.checkpoint_dir_local + checkpoint_path = os.path.join(checkpoint_dir, latest_checkpoint_file) + resume = True + log.critical(f"[Checkpoint] Found latest checkpoint file: {latest_checkpoint_file}") + log.critical(f"[Checkpoint] Loading from local path: {checkpoint_path}") + log.critical("[Checkpoint] Will resume full training state (model, optimizer, scheduler)") + else: + if self.load_path: + # 2. Load the module weights specified by config_checkpoint.path. + checkpoint_path = self.load_path + resume = self.load_training_state + log.critical(f"[Checkpoint] Using specified checkpoint path: {checkpoint_path}") + if resume: + log.critical("[Checkpoint] Will load complete training state (model, optimizer, scheduler)") + else: + log.critical("[Checkpoint] Will load model weights only (no optimizer/scheduler state)") + else: + # 3. Randomly initialize the model parameters and train from scratch. + checkpoint_path = None + resume = False + log.critical("[Checkpoint] No checkpoint path specified") + log.critical("[Checkpoint] Starting fresh training with random initialization") + return checkpoint_path, resume + + @misc.timer("FSDP.load_model_during_init") + def load_model_during_init(self, model, is_ema=False, ema_id: int = 0): + if ema_id > 0: + assert is_ema, "ema_id should be used with is_ema=True" + checkpoint_path, _ = self._load_ckpt_file_during_init() + if checkpoint_path is not None: + tag = "reg" if not is_ema else "ema" + default_checkpoint_path = checkpoint_path.replace(".pt", f"_{tag}_model.pt") + if not os.path.exists(default_checkpoint_path): + default_checkpoint_path = checkpoint_path # starting from the release checkpoint + log.warning(f"is_ema={is_ema} model is not found. Loading from {default_checkpoint_path}") + if tag == "ema" and ema_id > 0: + _checkpoint_path = checkpoint_path.replace(".pt", f"_RANK{ema_id}.pt") + _checkpoint_path = _checkpoint_path.replace(".pt", f"_{tag}_model.pt") + if self._check_checkpoint_exists(_checkpoint_path, is_raise=False): + default_checkpoint_path = _checkpoint_path + else: + print( + f"{distributed.get_rank()}: Checkpoint not found: {_checkpoint_path} " + f"(fallback to {default_checkpoint_path})" + ) + checkpoint_path = default_checkpoint_path + self._check_checkpoint_exists(checkpoint_path) + + log.info(f"Loading checkpoint (local): {checkpoint_path}") + state_dict = torch.load(checkpoint_path, map_location=lambda storage, loc: storage, weights_only=False) + if isinstance(state_dict, dict) and isinstance(state_dict.get("model"), dict): + state_dict = state_dict["model"] + log.success(f"Complete loading checkpoint (local): {checkpoint_path}") + log.info("- Loading the model...") + if self.strict_resume: + log.info(model.load_state_dict(state_dict, strict=self.strict_resume)) + else: + log.critical("\t Using non-strict model") + from diffusion.training.utils.checkpointer import non_strict_load_model + + log.info(non_strict_load_model(model, state_dict)) + log.info("-finish model loading") + else: + log.info(f"is_ema={is_ema} model is not found and loaded.") + + @misc.timer("FSDP.load_optim_scheduler_during_init") + def load_optim_scheduler_during_init(self, fsdp_model, optimizer, scheduler): + checkpoint_path, resume = self._load_ckpt_file_during_init() + log.critical(f"Loading optimizer and scheduler: {checkpoint_path} (resume: {resume}") + if checkpoint_path is not None: + if resume: + checkpoint_path = checkpoint_path.replace(".pt", "_optim.pt") + self._check_checkpoint_exists(checkpoint_path) + if distributed.get_rank() == 0: + log.info(f"Loading checkpoint (local): {checkpoint_path}") + state_dict = torch.load( + checkpoint_path, map_location=lambda storage, loc: storage, weights_only=False + ) + log.success(f"Complete loading checkpoint (local): {checkpoint_path}") + log.info("- Loading the optimizer (FSDP scatter)...") + else: + state_dict = { + "optimizer": None, + "scheduler": None, + } + distributed.barrier() + sharded_optimizer_state_dict = scatter_full_optim_state_dict( # <---- FSDP + state_dict["optimizer"], + fsdp_model, + ) + log.info("- Loading the optimizer (FSDP load_state_dict)...") + log.info(optimizer.load_state_dict(sharded_optimizer_state_dict)) + log.critical("Skip loading the scheduler...") + return + log.info("- Loading the scheduler...") + scheduler.load_state_dict(state_dict["scheduler"]) + + @misc.timer("FSDP get_optim_scheduler_state") + def get_optim_scheduler_state(self, optim, fsdp_model, scheduler): + with FSDP.state_dict_type( + fsdp_model, + StateDictType.FULL_STATE_DICT, + FullStateDictConfig(offload_to_cpu=True, rank0_only=True), + FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=True), + ): + optim_statedict = FSDP.full_optim_state_dict(fsdp_model, optim) + scheduler_statedict = scheduler.state_dict() + return { + "optimizer": optim_statedict, + "scheduler": scheduler_statedict, + } + + def save( + self, + model: Model, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + iteration: int, + async_saving: bool = True, + ) -> None: + """Save network weights, optimizer parameters, scheduler parameters to a checkpoint. + + Args: + model (Model): The PyTorch model. + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + grad_scaler (torch.amp.GradScaler): The gradient scaler (for mixed precision training). + iteration (int): Current iteration number. + """ + self.callbacks.on_save_checkpoint_start(model, iteration) + + model_state_dict = model.state_dict_model() + optim_scheduler_state_dict = self.get_optim_scheduler_state(optimizer, model.model, scheduler) + torch.cuda.empty_cache() + state_dict = dict( + iteration=iteration, + ) + self.callbacks.on_save_checkpoint(model, state_dict=state_dict) + + postfix, replicate_idx, shard_idx, total_ema_num = model.get_ckpt_postfix() + if replicate_idx == 0 and shard_idx == 0: + pass # save whole; it is rank0 + elif replicate_idx < total_ema_num and shard_idx == 0: + model_state_dict["model"] = None # only save ema + optim_scheduler_state_dict = None + state_dict = None + else: + return + + checkpoint_file = self._checkpoint_filename(iteration, postfix) + if async_saving: + # Wait for previous saver thread to end. + if self.save_thread: + self.save_thread.join() + # Run the checkpoint saver in a separate thread. + self.save_thread = threading.Thread( + target=self._save_worker_local, + daemon=False, + args=( + model_state_dict, + optim_scheduler_state_dict, + state_dict, + checkpoint_file, + distributed.get_rank(), + iteration, + ), + ) + self.save_thread.start() + log.info("checkpoint saving from an async thread") + else: + torch.cuda.empty_cache() + # Run the checkpoint saver in the current thread. + self._save_worker_local( + model_state_dict, + optim_scheduler_state_dict, + state_dict, + checkpoint_file, + distributed.get_rank(), + iteration, + ) + log.info("checkpoint saved within the main thread") + del model_state_dict, optim_scheduler_state_dict, state_dict + gc.collect() + torch.cuda.empty_cache() + self.callbacks.on_save_checkpoint_end(model=None, iteration=iteration) + + @misc.timer("checkpoint saving (local)") + def _save_worker_local( + self, + model_state_dict: dict[str, torch.Tensor], + optim_scheduler_state_dict: dict[str, torch.Tensor], + state_dict: dict[str, torch.Tensor], + checkpoint_file: str, + rank: int = 0, + iteration: int = 0, + ) -> None: + """Worker to save checkpoint to local disk, spawned with a child thread (runs in parallel with the training). + + Args: + state_dict (dict[str, torch.Tensor]): The state dict of the model/optimizer/scheduler. + checkpoint_file (str): The file name of the model checkpoint. + rank (int): GPU device (default: 0). + iteration (int): The completed optimizer iteration. + """ + checkpoint_path = os.path.join(self.checkpoint_dir_local, checkpoint_file) + os.makedirs(self.checkpoint_dir_local, exist_ok=True) + try: + model_state_dict, ema_model_state_dict = model_state_dict["model"], model_state_dict["ema"] + # Each save below writes to .tmp., fsyncs, validates + # the resulting zip, and only then atomically renames into place. + # A SIGTERM/SIGKILL/OOM/wall-time during any individual save + # leaves only the tmp file partially written; the canonical + # checkpoint paths keep the previous-iter's complete copies, so + # auto-resume can never hit the "failed finding central directory" + # torn-zip failure mode. + if model_state_dict is not None: + atomic_torch_save( + model_state_dict, checkpoint_path.replace(".pt", "_reg_model.pt") + ) + if ema_model_state_dict is not None: + atomic_torch_save( + ema_model_state_dict, checkpoint_path.replace(".pt", "_ema_model.pt") + ) + if optim_scheduler_state_dict is not None: + atomic_torch_save( + optim_scheduler_state_dict, checkpoint_path.replace(".pt", "_optim.pt") + ) + if state_dict is not None: + atomic_torch_save(state_dict, checkpoint_path) + # Only update the latest pointer once every shard above has been + # validated and renamed into place — never publish a half-written + # checkpoint as the resume target. + if rank == 0: + self._write_latest_checkpoint_file(checkpoint_file) + try: + # The new generation and resume pointer are already + # durable. Cleanup may leave extras if interrupted, but + # can never invalidate the published checkpoint. + self._prune_old_generations(iteration) + except Exception as cleanup_error: # noqa: BLE001 + log.warning( + "Checkpoint retention cleanup failed; keeping older " + f"generations: {cleanup_error!r}" + ) + log.success(f"Saved checkpoint (local): {checkpoint_path}") + self.callbacks.on_save_checkpoint_success(iteration=iteration) + except Exception as e: # noqa: BLE001 + log.exception(f"Checkpoint failed to save (local): {e}") + + @misc.timer("checkpoint loading") + def load( + self, + model: Model, + optimizer: torch.optim.Optimizer | None = None, + scheduler: torch.optim.lr_scheduler.LRScheduler | None = None, + grad_scaler: torch.amp.GradScaler | None = None, + ) -> int: + """Load network weights and optimizer states from a checkpoint in a single process. + + The priority of the checkpoint loading logic is: + 1. Attempt to resume training if possible by looking for latest_checkpoint.txt under the same name. + 2. If no latest checkpoint were found, it loads the model weights specified by config_checkpoint.path. + - This is typically used for inference mode. + - If config_checkpoint.load_optimizer_state is True, then also load the optimizer and scheduler states. + 3. If none of the above, randomly initialize the model parameters and train from scratch. + + Args: + model (FSDPDiffModle): The PyTorch model. + optimizer (torch.optim.Optimizer | None): The model optimizer (default: None). + scheduler (torch.optim.lr_scheduler.LRScheduler | None): The optimization scheduler (default: None). + grad_scaler (torch.amp.GradScaler | None): The gradient scaler (for mixed precision training). + + Returns: + iteration (int): the iteration number to start/resume from. + """ + self.callbacks.on_load_checkpoint_start(model) + + del optimizer, grad_scaler + checkpoint_path, resume = self._load_ckpt_file_during_init() + iteration = 0 + if checkpoint_path is not None: + self._check_checkpoint_exists(checkpoint_path) + log.info(f"Loading checkpoint (local): {checkpoint_path}") + state_dict = torch.load(checkpoint_path, map_location=lambda storage, loc: storage, weights_only=False) + log.success(f"Complete loading checkpoint (local): {checkpoint_path}") + self.callbacks.on_load_checkpoint(model, state_dict=state_dict) + if resume: + iteration = state_dict["iteration"] + log.success("Done with loading the checkpoint.") + else: + log.info("Training from scratch.") + torch.cuda.empty_cache() + + self.callbacks.on_load_checkpoint_end(model) + + if scheduler is not None: + scheduler.last_epoch = iteration + log.critical(f"resume scheduler from {iteration}", rank0_only=False) + + return iteration + + def _read_latest_checkpoint_file(self) -> str | None: + """Get the file name of the latest saved checkpoint. If it doesn't exist, return None. + + Returns: + checkpoint_file (str | None): file name of the latest saved checkpoint. + """ + checkpoint_file = None + latest_path = os.path.join(self.checkpoint_dir_local, "latest_checkpoint.txt") + if os.path.isfile(latest_path): + checkpoint_file = open(latest_path).read().strip() + if checkpoint_file is None: + log.warning(f"Latest ckpt file not found: {latest_path}") + else: + log.info(f"Found latest checkpoint: {checkpoint_file}") + return checkpoint_file + + def _write_latest_checkpoint_file(self, checkpoint_file: str) -> None: + """Track the file name of the latest saved checkpoint. + + Args: + checkpoint_file (str): file name of the latest saved checkpoint. + """ + content = f"{checkpoint_file}\n" + latest_path = os.path.join(self.checkpoint_dir_local, "latest_checkpoint.txt") + # Tmp+rename so a kill between open() and write() can't leave a + # 0-byte pointer file that breaks resume. + atomic_write_text(latest_path, content) + + def _check_checkpoint_exists(self, checkpoint_path: str, is_raise: bool = True) -> None: + """If the file checkpoint_path does not exist, raise an error. + + Args: + checkpoint_path (str): full path to the checkpoint. + """ + if not os.path.exists(checkpoint_path): + if is_raise: + raise FileNotFoundError(f"File not found (local): {checkpoint_path}") + return False + return True + + def finalize(self) -> None: + """Finalize the checkpointer.""" + if self.save_thread: + self.save_thread.join() + + +class FSDPInferenceCheckpointer: + def __init__( + self, + ckpt_path: str, + strict_resume: bool = True, + ): + self.ckpt_path = ckpt_path + self.strict_resume = strict_resume + + @misc.timer("FSDPInferenceCheckpointer.load_model_during_init") + def load_model_during_init(self, model, is_ema=False, ema_id: int = 0): + del ema_id + if is_ema: + log.warning("EMA model is not supported in inference mode.") + return + assert easy_io.exists(self.ckpt_path) + log.info(f"Loading from {self.ckpt_path}") + state_dict = torch.load(self.ckpt_path, map_location=lambda storage, loc: storage, weights_only=False) + if self.strict_resume: + log.info(model.load_state_dict(state_dict, strict=self.strict_resume)) + else: + log.critical("\t Using non-strict model") + from diffusion.training.utils.checkpointer import non_strict_load_model + + log.info(non_strict_load_model(model, state_dict)) + log.info("-finish model loading") + + def load_optim_scheduler_during_init(self, *args, **kwargs): + """ + We do not do load in inference mode. The function is here to maintain the same interface to avoid errors. + """ + pass + + def save(self, *args, **kwargs): + """ + We do not save anything in inference mode. The function is here to maintain the same interface to avoid errors. + """ + pass + + def load(self, *args, **kwargs): + """ + We do not do load in inference mode. The function is here to maintain the same interface to avoid errors. + """ + return 0 diff --git a/utils/fsdp_optim_fix.py b/utils/fsdp_optim_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..a08aa943828d4c9c385d25873528edae0a84ec24 --- /dev/null +++ b/utils/fsdp_optim_fix.py @@ -0,0 +1,351 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# flake8: noqa +# isort: skip_file + +""" +torch 2.2 has bugs in loading optimizer states for FSDP in hybrid mode +torch impl uses state.rank and dist.rank() inconsistently +The file fix the bugs. Verified it works for hybrid mode and fullly sharded mode +Please use the `scatter_full_optim_state_dict` in the code to replace the corresponding function in torch 2.2 +""" + +import copy +import warnings +from typing import Any, Dict, Iterable, List, Optional, Union + +import torch +import torch.distributed as dist +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel +from torch.distributed.fsdp._debug_utils import SimpleProfiler +from torch.distributed.fsdp._optim_utils import ( + _flatten_optim_state, + _FSDPState, + _get_fqn_to_fsdp_param_info, + _get_param_to_fqns, + _OptimStateKey, + _PosDimTensorInfo, + _shard_orig_param_state, + tree_map_only, +) +from torch.distributed.fsdp.fully_sharded_data_parallel import _rekey_sharded_optim_state_dict + + +def _broadcast_processed_state( + fsdp_state: _FSDPState, + optim_state: Dict[str, Any], + group: Optional[dist.ProcessGroup], +) -> Dict[str, Any]: + objects: List[Any] = [None] + if fsdp_state.rank == 0: + objects[0] = tree_map_only( + torch.Tensor, + lambda v: v.cpu() if v.dim() == 0 else _PosDimTensorInfo(v.shape, v.dtype), + optim_state, + ) + dist.broadcast_object_list(objects, src=0, group=group) + if dist.get_rank() == 0: + return optim_state + else: + return objects[0] + + +def _broadcast_state(fsdp_state: _FSDPState, state: Any, group: Optional[dist.ProcessGroup]) -> Any: + if dist.get_rank() == 0: + if not isinstance(state, torch.Tensor) or state.dim() == 0: + return state + tensor = state.to(fsdp_state.compute_device) + else: + if isinstance(state, torch.Tensor): + assert state.dim() == 0, ( + "For non-zero ranks, a tensor state should have zero dimension, " + "but got the state with shape {state.shape()}." + ) + return state + elif not isinstance(state, _PosDimTensorInfo): + return state + tensor = torch.zeros(state.shape, dtype=state.dtype, device=fsdp_state.compute_device) + dist.broadcast(tensor, src=0, group=group) + return tensor + + +def _flatten_optim_state_dict( + optim_state_dict: Dict[str, Any], + model: nn.Module, + use_orig_params: bool = False, + optim: Optional[torch.optim.Optimizer] = None, + rank0_only: bool = False, + group: Optional[dist.ProcessGroup] = None, +) -> Dict[str, Any]: + """ + Flattens the full optimizer state dict, still keying by unflattened parameter + names. + + If ``use_orig_params`` is True, each rank will have all FSDP-managed + parameters but some of these parameters may be empty due to the sharding. + For a regular optim.Optimizer, states for those empty parameters will + not be initialized. So, when aggregating the FQNs across ranks, no assert + will be raised on a rank even if it does not have all the states -- it is + valid and FSDP know how to aggregate them. However, FSDP has to ignore + handling those parameters that are not managed by FSDP and do not exist on + the local rank -- it is managed by other parallelism and FSDP does not + know ho to handle/aggregate them. + + Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to + flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require + all the states even if the corresponding parameters are empty. To this end, + ``optim`` will be used to to get the initial state of the empty parameters. + ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or + NamedOptimizer. + + Returns: + Dict[str, Any]: The flattened optimizer state dict. + """ + SimpleProfiler.reset() + + unflat_osd = optim_state_dict + if "state" not in unflat_osd and not rank0_only: + raise ValueError('`optim_state_dict` must have the keys "state"' "to be a valid optimizer state dict") + param_to_fqns = _get_param_to_fqns(model) + fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model) + fsdp_state = next(iter(fqn_to_fsdp_param_info.values())).state + + # Broadcast unflat_osd without non-scalar tensor if rank0_only is True. + if rank0_only: + unflat_osd = _broadcast_processed_state(fsdp_state, unflat_osd, group=group) + + # Construct the "state" part + flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {} + unflat_osd_state = unflat_osd["state"] + all_state_keys = set(unflat_osd_state.keys()) + + for param, fqns in param_to_fqns.items(): + fqn = fqns[0] + if fqn not in unflat_osd_state: + continue + all_state_keys.difference_update(fqns) + + if rank0_only: + for fqn in fqns: + if not unflat_osd_state[fqn]: + continue + for state_name in unflat_osd_state[fqn].keys(): + unflat_osd_state[fqn][state_name] = _broadcast_state( + fsdp_state, unflat_osd_state[fqn][state_name], group=group + ) + fqn = fqns[0] + if fqn in fqn_to_fsdp_param_info: + fsdp_param_info = fqn_to_fsdp_param_info[fqn] + if use_orig_params: + with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING): + flat_state = _shard_orig_param_state( + fsdp_param_info, + fqn, + unflat_osd_state[fqn], + ) + else: + flat_state = _flatten_optim_state( + fsdp_param_info, + unflat_osd_state, + fqns, + ) + key = _OptimStateKey(tuple(fqns), True) + # Only include non-empty states since as expected by + # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer + # or NamedOptimizer. + if flat_state: + flat_osd_state[key] = flat_state + elif use_orig_params: + assert len(fqns) == 1, f"use_orig_params is True but there are multiple FQNs, {fqns}." + if optim is not None: # NamedOptimizer or KeyedOptimizer case. + state = optim.state.get(param, None) # type: ignore[call-overload] + if state is not None: + flat_osd_state[key] = copy.deepcopy(state) + else: + warnings.warn(f"optim_state[{key}] is not on rank{fsdp_state.rank}.") + + else: + raise RuntimeError(f"The state of {key} is empty. This should happen when " "use_orig_params=True.") + else: # do not flatten non-FSDP parameters' states + assert len(fqns) == 1 + key = _OptimStateKey(tuple(fqns), False) + flat_osd_state[key] = copy.copy(unflat_osd_state[fqn]) + + if rank0_only: + for fqn in fqns: + if not unflat_osd_state[fqn]: + continue + for state_name, param_state in list(unflat_osd_state[fqn].items()): + if fsdp_state.rank > 0: + # Deference the tensor so that PyTorch can collect the memory. + del unflat_osd_state[fqn][state_name] + else: + # Move the tensor in the original osd back to CPU to make the + # original osd unaffected. + unflat_osd_state[fqn][state_name] = unflat_osd_state[fqn][state_name].cpu() + + # Handle user-defined state, states that are not associated with parameters. + for key in all_state_keys: + user_state = unflat_osd_state[key] + if isinstance(user_state, torch.Tensor) and rank0_only and use_orig_params: + user_state = _broadcast_state(fsdp_state, user_state, group=group) + flat_osd_state[key] = copy.copy(user_state) + + SimpleProfiler.dump_and_reset("FSDP _flatten_optim_state_dict() profiling: ") + # Construct the "param_groups" part -- copy as is since it will be + # rekeyed later according to the target rank's optimizer + # Only copy param_groups if it exists in unflat_osd + if "param_groups" in unflat_osd: + flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"]) + return {"state": flat_osd_state, "param_groups": flat_osd_param_groups} + else: + return {"state": flat_osd_state} + + +def _optim_state_dict_to_load_impl( + optim_state_dict: Dict[str, Any], + model: torch.nn.Module, + optim_input: Optional[ + Union[ + List[Dict[str, Any]], + Iterable[torch.nn.Parameter], + ] + ] = None, + optim: Optional[torch.optim.Optimizer] = None, + full_state_dict: bool = True, + rank0_only: bool = False, + is_named_optimizer: bool = False, + group: Optional[dist.ProcessGroup] = None, +) -> Dict[str, Any]: + """ + The internal API that is used by all the load optim_state_dict implementations. + Given model, optim, and the saved optim_state_dict, this API adds the FSDP + internal information and internal sharding to the optim_state_dict. + """ + if full_state_dict: + FullyShardedDataParallel._warn_optim_input(optim_input) + using_optim_input = FullyShardedDataParallel._is_using_optim_input( + optim_input, + optim, + ) + else: + using_optim_input = False + assert optim_input is None and not rank0_only + + use_orig_params = FullyShardedDataParallel.fsdp_modules(model)[0]._use_orig_params + assert all( + use_orig_params == m._use_orig_params for m in FullyShardedDataParallel.fsdp_modules(model) + ), "Not all FSDP modules have the same _use_orig_params value" + + if rank0_only and dist.get_rank(group) > 0: + optim_state_dict = {} + sharded_osd = _flatten_optim_state_dict( + optim_state_dict, + model=model, + use_orig_params=use_orig_params, + optim=(optim if is_named_optimizer else None), + rank0_only=rank0_only, + group=group, + ) + return _rekey_sharded_optim_state_dict( + sharded_osd, + model=model, + optim=optim, + optim_input=optim_input, + using_optim_input=using_optim_input, + is_named_optimizer=is_named_optimizer, + ) + + +def scatter_full_optim_state_dict( + full_optim_state_dict: Optional[Dict[str, Any]], + model: torch.nn.Module, + optim_input: Optional[ + Union[ + List[Dict[str, Any]], + Iterable[torch.nn.Parameter], + ] + ] = None, + optim: Optional[torch.optim.Optimizer] = None, + group: Optional[Any] = None, +) -> Dict[str, Any]: + """ + Scatters the full optimizer state dict from rank 0 to all other ranks, + returning the sharded optimizer state dict on each rank. The return + value is the same as :meth:`shard_full_optim_state_dict`, and on rank + 0, the first argument should be the return value of + :meth:`full_optim_state_dict`. + + Example:: + + >>> # xdoctest: +SKIP("undefined variables") + >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + >>> model, optim = ... + >>> full_osd = FSDP.full_optim_state_dict(model, optim) # only non-empty on rank 0 + >>> # Define new model with possibly different world size + >>> new_model, new_optim, new_group = ... + >>> sharded_osd = FSDP.scatter_full_optim_state_dict(full_osd, new_model, group=new_group) + >>> new_optim.load_state_dict(sharded_osd) + + .. note:: Both :meth:`shard_full_optim_state_dict` and + :meth:`scatter_full_optim_state_dict` may be used to get the + sharded optimizer state dict to load. Assuming that the full + optimizer state dict resides in CPU memory, the former requires + each rank to have the full dict in CPU memory, where each rank + individually shards the dict without any communication, while the + latter requires only rank 0 to have the full dict in CPU memory, + where rank 0 moves each shard to GPU memory (for NCCL) and + communicates it to ranks appropriately. Hence, the former has + higher aggregate CPU memory cost, while the latter has higher + communication cost. + + Args: + full_optim_state_dict (Optional[Dict[str, Any]]): Optimizer state + dict corresponding to the unflattened parameters and holding + the full non-sharded optimizer state if on rank 0; the argument + is ignored on nonzero ranks. + model (torch.nn.Module): Root module (which may or may not be a + :class:`FullyShardedDataParallel` instance) whose parameters + correspond to the optimizer state in ``full_optim_state_dict``. + optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]): + Input passed into the optimizer representing either a + :class:`list` of parameter groups or an iterable of parameters; + if ``None``, then this method assumes the input was + ``model.parameters()``. This argument is deprecated, and there + is no need to pass it in anymore. (Default: ``None``) + optim (Optional[torch.optim.Optimizer]): Optimizer that will load + the state dict returned by this method. This is the preferred + argument to use over ``optim_input``. (Default: ``None``) + group (dist.ProcessGroup): Model's process group or ``None`` if + using the default process group. (Default: ``None``) + + Returns: + Dict[str, Any]: The full optimizer state dict now remapped to + flattened parameters instead of unflattened parameters and + restricted to only include this rank's part of the optimizer state. + """ + FullyShardedDataParallel._warn_legacy_optim_state_dict("scatter_full_optim_state_dict", "optim_state_dict_to_load") + return _optim_state_dict_to_load_impl( + optim_state_dict=full_optim_state_dict, + model=model, + optim_input=optim_input, + optim=optim, + full_state_dict=True, + rank0_only=True, + is_named_optimizer=False, + group=group, + ) diff --git a/utils/fused_adam.py b/utils/fused_adam.py new file mode 100644 index 0000000000000000000000000000000000000000..29d4cba771eb60eac6eb941ab9117449defd589e --- /dev/null +++ b/utils/fused_adam.py @@ -0,0 +1,398 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from apex.multi_tensor_apply import multi_tensor_applier + +from utils import distributed, log + + +class FusedAdam(torch.optim.Optimizer): + """Implements Adam algorithm. + + Currently GPU-only. Requires Apex to be installed via + ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. + + This version of fused Adam implements 2 fusions. + + * Fusion of the Adam update's elementwise operations + * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters + into one or a few kernel launches. + + :class:`apex.optimizers.FusedAdam` may be used as a drop-in replacement for ``torch.optim.AdamW``, + or ``torch.optim.Adam`` with ``adam_w_mode=False``:: + + opt = apex.optimizers.FusedAdam(model.parameters(), lr = ....) + ... + opt.step() + + :class:`apex.optimizers.FusedAdam` may be used with or without Amp. If you wish to use :class:`FusedAdam` with Amp, + you may choose any ``opt_level``:: + + opt = apex.optimizers.FusedAdam(model.parameters(), lr = ....) + model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") + ... + opt.step() + + In general, ``opt_level="O1"`` is recommended. + + + .. warning:: + A previous version of :class:`FusedAdam` allowed a number of additional arguments to ``step``. + These additional arguments are now deprecated and unnecessary. + + Adam was been proposed in `Adam: A Method for Stochastic Optimization`_. + + Arguments: + params (iterable): iterable of parameters to optimize or dicts defining + parameter groups. + lr (float, optional): learning rate. (default: 1e-3) + betas (Tuple[float, float], optional): coefficients used for computing + running averages of gradient and its square. (default: (0.9, 0.999)) + eps (float, optional): term added to the denominator to improve + numerical stability. (default: 1e-8) + weight_decay (float, optional): weight decay (L2 penalty) (default: 0) + amsgrad (boolean, optional): whether to use the AMSGrad variant of this + algorithm from the paper `On the Convergence of Adam and Beyond`_ + (default: False) NOT SUPPORTED in FusedAdam! + adam_w_mode (boolean, optional): Apply L2 regularization or weight decay + True for decoupled weight decay(also known as AdamW) (default: True) + capturable (bool, optional): whether to use the version of the optimizer + that can be used with CUDA Graphs. (default: False) + master_weights (bool, optional): whether to maintain FP32 master weights + in the optimizer with FP16 mixed precision training, currently can + only be used with capturable set to True. (default: False) + + .. _Adam - A Method for Stochastic Optimization: + https://arxiv.org/abs/1412.6980 + .. _On the Convergence of Adam and Beyond: + https://openreview.net/forum?id=ryQu7f-RZ + """ + + def __init__( + self, + params, + lr=1e-3, + bias_correction=True, + betas=(0.9, 0.999), + eps=1e-8, + adam_w_mode=True, + weight_decay=0.0, + amsgrad=False, + capturable=False, + master_weights=False, + ): + if amsgrad: + raise RuntimeError("FusedAdam does not support the AMSGrad variant.") + if master_weights and not capturable: + raise RuntimeError("Master weights is currently only supported with the capturable version.") + # If the optimizer is capturable then LR should be a tensor (on GPU) + log.warning(f"FusedAdam master_weights: {master_weights} capturable: {capturable}") + lr = torch.tensor(lr, dtype=torch.float32) if capturable else lr + defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay) + super(FusedAdam, self).__init__(params, defaults) + self.adam_w_mode = 1 if adam_w_mode else 0 + + self.capturable = capturable + self.master_weights = master_weights + + self.param_groups_master = None + + if capturable: + for idx, group in enumerate(self.param_groups): + if len(group["params"]) == 0: + continue + device = group["params"][0].device + for item in ["lr"]: + if isinstance(group[item], float): + group[item] = torch.tensor(group[item], dtype=torch.float32) + self.param_groups[idx][item] = group[item].to(device=device) + + self._step_supports_amp_scaling = True + + if multi_tensor_applier.available: + import amp_C + + # Skip buffer + self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device="cuda") + self.multi_tensor_adam = amp_C.multi_tensor_adam + self.multi_tensor_adam_capturable = amp_C.multi_tensor_adam_capturable + self.multi_tensor_adam_capturable_master = amp_C.multi_tensor_adam_capturable_master + else: + raise RuntimeError("apex.optimizers.FusedAdam requires cuda extensions") + + def step(self, closure=None, grads=None, output_params=None, scale=None, grad_norms=None, grad_scaler=None): + """Performs a single optimization step. + + Arguments: + closure (callable, optional): A closure that reevaluates the model + and returns the loss. + + The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes. + """ + if any(p is not None for p in [grads, output_params, scale, grad_norms]): + raise RuntimeError( + "FusedAdam has been updated. " + "Simply initialize it identically to torch.optim.Adam, and call step() with no arguments." + ) + loss = None + if closure is not None: + loss = closure() + + if self.param_groups_master is None: + # Create full precision master weights + self.param_groups_master = [] + for i, pg in enumerate(self.param_groups): + param_list = pg["params"] + self.param_groups_master.append( + { + "params": [p.clone().detach().float() if self.master_weights else None for p in param_list], + } + ) + + for group, group_master in zip(self.param_groups, self.param_groups_master): + if len(group["params"]) == 0: + continue + device = group["params"][0].device + bias_correction = 1 if "bias_correction" in group and group["bias_correction"] else 0 + beta1, beta2 = group["betas"] + + # assume same step across group now to simplify things + # per parameter step can be easily support by making it tensor, or pass list into kernel + if "step" in group: + if self.capturable: + group["step"] = ( + group["step"].to(device=device) + if isinstance(group["step"], torch.Tensor) + else torch.tensor(group["step"], dtype=torch.int32, device=device) + ) + group["step"] += (self._dummy_overflow_buf != 1).to(torch.int) + else: + group["step"] += 1 + else: + group["step"] = 1 if not self.capturable else torch.tensor([1], dtype=torch.int, device=device) + + if self.capturable: + group["lr"] = ( + group["lr"].to(device=device) + if isinstance(group["lr"], torch.Tensor) + else torch.tensor(group["lr"], dtype=torch.float32, device=device) + ) + + # create lists for multi-tensor apply + g_16, p_16, m_16, v_16 = [], [], [], [] + g_bf, p_bf, m_bf, v_bf = [], [], [], [] + g_32, p_32, m_32, v_32 = [], [], [], [] + p_16_master = [] + p_32_master = [] + bf16_master = [] + + for p, p_master in zip(group["params"], group_master["params"]): + if p.grad is None: + continue + if p.grad.data.is_sparse: + raise RuntimeError( + "FusedAdam does not support sparse gradients, please consider SparseAdam instead" + ) + + state = self.state[p] + # State initialization + if len(state) == 0: + # Exponential moving average of gradient values + state["exp_avg"] = torch.zeros_like(p.data).float() + # Exponential moving average of squared gradient values + state["exp_avg_sq"] = torch.zeros_like(p.data).float() + + if p.dtype == torch.float16: + if self.master_weights: + p_16_master.append(p_master.data) + g_16.append(p.grad.data) + p_16.append(p.data) + m_16.append(state["exp_avg"]) + v_16.append(state["exp_avg_sq"]) + elif p.dtype == torch.bfloat16: + if self.master_weights: + bf16_master.append(p_master.data) + g_bf.append(p.grad) + p_bf.append(p) + m_bf.append(state["exp_avg"]) + v_bf.append(state["exp_avg_sq"]) + elif p.dtype == torch.float32: + if self.master_weights: + p_32_master.append(p_master.data) + g_32.append(p.grad.data) + p_32.append(p.data) + m_32.append(state["exp_avg"]) + v_32.append(state["exp_avg_sq"]) + else: + raise RuntimeError("FusedAdam only support fp16 and fp32.") + + # If the optimizer is capturable, then if there's a grad scaler it works + # on the GPU + a different multi_tensor_applier should be called + if self.capturable: + # overflow check of gradients + found_inf = ( + grad_scaler._check_inf_per_device(self)[device] + if grad_scaler is not None + else torch.zeros((1,), device=device) + ) + self._dummy_overflow_buf.copy_(found_inf) + + # get unscale scale factor + scale, inv_scale = None, None + if grad_scaler: + scale = grad_scaler._get_scale_async() + inv_scale = scale.double().reciprocal().float() + else: + scale = torch.ones((1,), device=device, dtype=torch.float32) + inv_scale = torch.ones((1,), device=device, dtype=torch.float32) + + if len(g_16) > 0: + multi_tensor_applier( + ( + self.multi_tensor_adam_capturable_master + if self.master_weights + else self.multi_tensor_adam_capturable + ), + self._dummy_overflow_buf, + [g_16, p_16, m_16, v_16, p_16_master] if self.master_weights else [g_16, p_16, m_16, v_16], + group["lr"], + beta1, + beta2, + group["eps"], + group["step"], + self.adam_w_mode, + bias_correction, + group["weight_decay"], + inv_scale, + ) + + if len(g_bf) > 0: + multi_tensor_applier( + ( + self.multi_tensor_adam_capturable_master + if self.master_weights + else self.multi_tensor_adam_capturable + ), + self._dummy_overflow_buf, + [g_bf, p_bf, m_bf, v_bf, bf16_master] if self.master_weights else [g_bf, p_bf, m_bf, v_bf], + group["lr"], + beta1, + beta2, + group["eps"], + group["step"], + self.adam_w_mode, + bias_correction, + group["weight_decay"], + inv_scale, + ) + + if len(g_32) > 0: + multi_tensor_applier( + ( + self.multi_tensor_adam_capturable_master + if self.master_weights + else self.multi_tensor_adam_capturable + ), + self._dummy_overflow_buf, + [g_32, p_32, m_32, v_32, p_32_master] if self.master_weights else [g_32, p_32, m_32, v_32], + group["lr"], + beta1, + beta2, + group["eps"], + group["step"], + self.adam_w_mode, + bias_correction, + group["weight_decay"], + inv_scale, + ) + else: + if len(g_16) > 0: + multi_tensor_applier( + self.multi_tensor_adam, + self._dummy_overflow_buf, + [g_16, p_16, m_16, v_16], + group["lr"], + beta1, + beta2, + group["eps"], + group["step"], + self.adam_w_mode, + bias_correction, + group["weight_decay"], + ) + + if len(g_bf) > 0: + multi_tensor_applier( + self.multi_tensor_adam, + self._dummy_overflow_buf, + [g_bf, p_bf, m_bf, v_bf], + group["lr"], + beta1, + beta2, + group["eps"], + group["step"], + self.adam_w_mode, + bias_correction, + group["weight_decay"], + ) + + if len(g_32) > 0: + multi_tensor_applier( + self.multi_tensor_adam, + self._dummy_overflow_buf, + [g_32, p_32, m_32, v_32], + group["lr"], + beta1, + beta2, + group["eps"], + group["step"], + self.adam_w_mode, + bias_correction, + group["weight_decay"], + ) + + return loss + + def load_state_dict(self, state_dict): + super().load_state_dict(state_dict) + for group in self.param_groups: + if self.capturable: + group["lr"] = ( + group["lr"].cuda() + if isinstance(group["lr"], torch.Tensor) + else torch.tensor(group["lr"], dtype=torch.float32).cuda() + ) + + if "step" in group: + if self.capturable: + if distributed.get_rank() == 0: + step = ( + group["step"].cuda() + if isinstance(group["step"], torch.Tensor) + else torch.tensor([group["step"]], dtype=torch.int32).cuda() + ) + else: + step = torch.zeros(1, dtype=torch.int32).cuda() + # make it compatible with FSDP optimizer + distributed.broadcast(step, 0) + group["step"] = step + elif isinstance(group["step"], torch.Tensor): + group["step"] = group["step"].item() + for p in group["params"]: + state = self.state[p] + if "exp_avg" in state: + state["exp_avg"] = state["exp_avg"].float() + state["exp_avg_sq"] = state["exp_avg_sq"].float() diff --git a/utils/inference.py b/utils/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..19db5f2722af527ff5247467b3b5d5c65865cc7f --- /dev/null +++ b/utils/inference.py @@ -0,0 +1,263 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Shared sample I/O and preview rendering for tokenizer and diffusion inference.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +from itertools import chain +from pathlib import Path +from tempfile import TemporaryDirectory, TemporaryFile + +import cv2 +import numpy as np +from matplotlib import colormaps + +from utils.visualize.point_cloud import CAMERA_VIEWS, VIZ_KWARGS, visualize_point_cloud + + +MIN_RANGE_M = 2.5 +MAX_RANGE_M = 100.0 +SENSOR_GRIDS = { + (128, 1024): "NVIDIA PAI", + (128, 1200): "NVIDIA PAI", + (64, 1024): "PandaSet", + (32, 1024): "nuScenes", +} +DISPLAY_YAW_DEG = { + "nvidia_pai": 0.0, + "pandar": 0.0, + "nuscenes": -90.0, + "pandaset": 180.0, + "kitti": 0.0, +} + + +def load_sample( + path: Path, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + with np.load(path) as payload: + if "range_m" not in payload or "ray_directions" not in payload: + raise ValueError( + f"{path} must contain range_m and ray_directions arrays" + ) + ranges = np.asarray(payload["range_m"], dtype=np.float32) + stored_rays = np.asarray(payload["ray_directions"], dtype=np.float32) + valid = np.asarray( + payload.get("valid_mask", ranges > 0), dtype=np.bool_ + ) + + if ranges.ndim == 2: + ranges = ranges[None] + if ranges.ndim != 3: + raise ValueError(f"range_m must have shape (T,H,W), got {ranges.shape}") + if valid.ndim == 2: + valid = valid[None] + if valid.shape != ranges.shape: + raise ValueError( + f"valid_mask shape {valid.shape} does not match range_m {ranges.shape}" + ) + if ranges.shape[0] < 1: + raise ValueError(f"Empty sequence in {path}") + grid = tuple(ranges.shape[-2:]) + if grid not in SENSOR_GRIDS: + expected = ", ".join(f"{h}x{w}" for h, w in SENSOR_GRIDS) + raise ValueError(f"Unsupported input grid {grid}; expected one of {expected}") + + if stored_rays.ndim == 3: + rays = np.broadcast_to(stored_rays[None], ranges.shape + (3,)) + elif stored_rays.ndim == 4: + rays = stored_rays + else: + raise ValueError( + "ray_directions must have shape (H,W,3) or (T,H,W,3), " + f"got {stored_rays.shape}" + ) + if rays.shape != ranges.shape + (3,): + raise ValueError( + f"ray_directions shape {rays.shape} does not match {ranges.shape}" + ) + if not np.isfinite(rays).all(): + raise ValueError(f"ray_directions contains non-finite values in {path}") + norms = np.linalg.norm(rays, axis=-1, keepdims=True) + if np.any(norms <= 1e-8): + raise ValueError(f"ray_directions contains zero-length rays in {path}") + rays = rays / norms + valid &= ( + np.isfinite(ranges) + & (ranges >= MIN_RANGE_M) + & (ranges <= MAX_RANGE_M) + ) + ranges = np.where(valid, ranges, 0.0).astype(np.float32) + rays = rays.astype(np.float32) + output_rays = rays[0] if stored_rays.ndim == 3 else rays + return ranges, valid, rays, output_rays + + +def points_from_ranges( + ranges: np.ndarray, valid: np.ndarray, rays: np.ndarray +) -> np.ndarray: + return (rays[valid] * ranges[valid][:, None]).astype(np.float32) + + +def _height_colors(points: np.ndarray) -> np.ndarray: + if not len(points): + return np.empty((0, 3), dtype=np.uint8) + scale = np.clip((points[:, 2] + 3.0) / 8.0, 0.0, 1.0) + return (colormaps["viridis"](scale)[:, :3] * 255).astype(np.uint8) + + +def write_ply(path: Path, points: np.ndarray) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + colors = _height_colors(points) + vertices = np.empty( + len(points), + dtype=[ + ("x", " np.ndarray: + colors = _height_colors(points).astype(np.float32) / 255.0 + angle = np.deg2rad(yaw_deg) + c, s = np.cos(angle), np.sin(angle) + rotation = np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]], np.float32) + # Display-only rotation; the exported PLYs remain in the original sensor frame. + displayed_points = points @ rotation.T + camera = CAMERA_VIEWS["paper_view_down"] + center = camera["center"] + eye = {axis: center[axis] + 0.6 * (camera["eye"][axis] - center[axis]) + for axis in ("x", "y", "z")} + kwargs = dict(VIZ_KWARGS) + kwargs.update( + camera_position={"eye": eye, "center": dict(center)}, + bgcolor=(1.0, 1.0, 1.0), point_size=0.8, + antialias_point_size=True, principal_y_offset=0.08, depth_sort=True, + ) + rgb = visualize_point_cloud(displayed_points, colors, **kwargs) + return np.ascontiguousarray(rgb[..., ::-1]) + + +def label_image(image: np.ndarray, text: str) -> np.ndarray: + output = image.copy() + cv2.putText( + output, + text, + (20, 42), + cv2.FONT_HERSHEY_SIMPLEX, + 0.85, + (30, 30, 30), + 2, + cv2.LINE_AA, + ) + return output + + +def write_video(path: Path, frames, fps: float) -> None: + ffmpeg = shutil.which("ffmpeg") + if ffmpeg is None: + raise RuntimeError("Install system ffmpeg to write H.264 video previews") + if not np.isfinite(fps) or fps <= 0: + raise ValueError("Video fps must be finite and positive") + path.parent.mkdir(parents=True, exist_ok=True) + frames = iter(frames) + first = next(frames, None) + if first is None: + raise ValueError(f"No video frames for {path}") + height, width = first.shape[:2] + # Match the quickstart grid's browser-compatible encoding. Publish only + # after FFmpeg has finalized the container, preserving any previous video. + with TemporaryDirectory(dir=path.parent, prefix=f".{path.stem}-") as temporary: + encoded = Path(temporary) / "video.mp4" + command = [ + ffmpeg, "-hide_banner", "-loglevel", "error", "-y", + "-f", "rawvideo", "-pix_fmt", "bgr24", + "-s:v", f"{width}x{height}", "-r", str(fps), "-i", "pipe:0", + "-an", "-c:v", "libx264", "-threads", "4", + "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p", + "-movflags", "+faststart", str(encoded), + ] + with TemporaryFile() as errors: + process = subprocess.Popen( + command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=errors, + ) + try: + with process.stdin: + for frame in chain((first,), frames): + if frame.shape != (height, width, 3) or frame.dtype != np.uint8: + raise ValueError("Video frames must be equally sized uint8 BGR images") + process.stdin.write(frame.tobytes()) + returncode = process.wait() + except BrokenPipeError: + returncode = process.wait() + errors.seek(0) + raise RuntimeError( + f"FFmpeg failed for {path}: {errors.read().decode(errors='replace')}" + ) from None + except BaseException: + process.kill() + process.wait() + raise + if returncode: + errors.seek(0) + raise RuntimeError( + f"FFmpeg failed for {path}: {errors.read().decode(errors='replace')}" + ) + encoded.replace(path) + + +def display_yaw(path: Path, dataset: str) -> float: + sidecar = path.with_suffix(".json") + display = json.loads(sidecar.read_text()) if sidecar.is_file() else {} + yaw_deg = float(display.get("visualization_yaw_deg", DISPLAY_YAW_DEG.get(dataset, 0.0))) + if not np.isfinite(yaw_deg): + raise ValueError(f"{path}: non-finite display yaw") + return yaw_deg + + +def sample_paths(path: Path) -> list[Path]: + if path.is_file(): + if path.suffix.lower() != ".npz": + raise ValueError(f"Expected an NPZ sample, got {path}") + return [path] + if not path.is_dir(): + raise FileNotFoundError(path) + samples = sorted(path.rglob("*.npz")) + if not samples: + raise FileNotFoundError(f"No NPZ samples found under {path}") + return samples + + +def sample_output(sample: Path, sample_root: Path, output_root: Path) -> Path: + if sample_root.is_file(): + return output_root + return output_root / sample.relative_to(sample_root).with_suffix("") diff --git a/utils/lazy_config/__init__.py b/utils/lazy_config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba7bc23a6d0cc21e11abcd869cb850553cfc525 --- /dev/null +++ b/utils/lazy_config/__init__.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# NVIDIA modifications: LidarVerse module imports. + +# Copyright (c) Facebook, Inc. and its affiliates. +import os + +from omegaconf import DictConfig, OmegaConf + +from utils.lazy_config.instantiate import instantiate +from utils.lazy_config.lazy import LazyCall, LazyConfig +from utils.lazy_config.omegaconf_patch import to_object + +OmegaConf.to_object = to_object + +PLACEHOLDER = None +LazyDict = DictConfig + +__all__ = ["instantiate", "LazyCall", "LazyConfig", "PLACEHOLDER", "LazyDict"] + + +DOC_BUILDING = os.getenv("_DOC_BUILDING", False) # set in docs/conf.py + + +def fixup_module_metadata(module_name, namespace, keys=None): + """ + Fix the __qualname__ of module members to be their exported api name, so + when they are referenced in docs, sphinx can find them. Reference: + https://github.com/python-trio/trio/blob/6754c74eacfad9cc5c92d5c24727a2f3b620624e/trio/_util.py#L216-L241 + """ + if not DOC_BUILDING: + return + seen_ids = set() + + def fix_one(qualname, name, obj): + # avoid infinite recursion (relevant when using + # typing.Generic, for example) + if id(obj) in seen_ids: + return + seen_ids.add(id(obj)) + + mod = getattr(obj, "__module__", None) + if mod is not None and (mod.startswith(module_name) or mod.startswith("fvcore.")): + obj.__module__ = module_name + # Modules, unlike everything else in Python, put fully-qualitied + # names into their __name__ attribute. We check for "." to avoid + # rewriting these. + if hasattr(obj, "__name__") and "." not in obj.__name__: + obj.__name__ = name + obj.__qualname__ = qualname + if isinstance(obj, type): + for attr_name, attr_value in obj.__dict__.items(): + fix_one(objname + "." + attr_name, attr_name, attr_value) + + if keys is None: + keys = namespace.keys() + for objname in keys: + if not objname.startswith("_"): + obj = namespace[objname] + fix_one(objname, objname, obj) + + +fixup_module_metadata(__name__, globals(), __all__) +del fixup_module_metadata diff --git a/utils/lazy_config/file_io.py b/utils/lazy_config/file_io.py new file mode 100644 index 0000000000000000000000000000000000000000..d9caf0081976dd08ab6ea1c04ad53304bc51d05d --- /dev/null +++ b/utils/lazy_config/file_io.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from iopath.common.file_io import HTTPURLHandler, OneDrivePathHandler, PathHandler +from iopath.common.file_io import PathManager as PathManagerBase + +__all__ = ["PathManager", "PathHandler"] + + +PathManager = PathManagerBase() +PathManager.register_handler(HTTPURLHandler()) +PathManager.register_handler(OneDrivePathHandler()) diff --git a/utils/lazy_config/instantiate.py b/utils/lazy_config/instantiate.py new file mode 100644 index 0000000000000000000000000000000000000000..59f6c2a52e57966c7e30f00d7349ac4970ca1f45 --- /dev/null +++ b/utils/lazy_config/instantiate.py @@ -0,0 +1,113 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import collections.abc as abc +import dataclasses +import logging +from typing import Any + +import attrs + +from utils.lazy_config.registry import _convert_target_to_string, locate + +__all__ = ["dump_dataclass", "instantiate"] + + +def is_dataclass_or_attrs(target): + return dataclasses.is_dataclass(target) or attrs.has(target) + + +def dump_dataclass(obj: Any): + """ + Dump a dataclass recursively into a dict that can be later instantiated. + + Args: + obj: a dataclass object + + Returns: + dict + """ + assert dataclasses.is_dataclass(obj) and not isinstance( + obj, type + ), "dump_dataclass() requires an instance of a dataclass." + ret = {"_target_": _convert_target_to_string(type(obj))} + for f in dataclasses.fields(obj): + v = getattr(obj, f.name) + if dataclasses.is_dataclass(v): + v = dump_dataclass(v) + if isinstance(v, (list, tuple)): + v = [dump_dataclass(x) if dataclasses.is_dataclass(x) else x for x in v] + ret[f.name] = v + return ret + + +def instantiate(cfg, *args, **kwargs): + """ + Recursively instantiate objects defined in dictionaries by + "_target_" and arguments. + + Args: + cfg: a dict-like object with "_target_" that defines the caller, and + other keys that define the arguments + args: Optional positional parameters pass-through. + kwargs: Optional named parameters pass-through. + + Returns: + object instantiated by cfg + """ + from omegaconf import DictConfig, ListConfig, OmegaConf + + if isinstance(cfg, ListConfig): + lst = [instantiate(x) for x in cfg] + return ListConfig(lst, flags={"allow_objects": True}) + if isinstance(cfg, list): + # Specialize for list, because many classes take + # list[objects] as arguments, such as ResNet, DatasetMapper + return [instantiate(x) for x in cfg] + + # If input is a DictConfig backed by dataclasses (i.e. omegaconf's structured config), + # instantiate it to the actual dataclass. + if isinstance(cfg, DictConfig) and is_dataclass_or_attrs(cfg._metadata.object_type): + return OmegaConf.to_object(cfg) + + if isinstance(cfg, abc.Mapping) and "_target_" in cfg: + # conceptually equivalent to hydra.utils.instantiate(cfg) with _convert_=all, + # but faster: https://github.com/facebookresearch/hydra/issues/1200 + cfg = {k: instantiate(v) for k, v in cfg.items()} + cls = cfg.pop("_target_") + cls = instantiate(cls) + + if isinstance(cls, str): + cls_name = cls + cls = locate(cls_name) + assert cls is not None, cls_name + else: + try: + cls_name = cls.__module__ + "." + cls.__qualname__ + except Exception: + # target could be anything, so the above could fail + cls_name = str(cls) + assert callable(cls), f"_target_ {cls} does not define a callable object" + try: + # override config with kwargs + instantiate_kwargs = {} + instantiate_kwargs.update(cfg) + instantiate_kwargs.update(kwargs) + return cls(*args, **instantiate_kwargs) + except TypeError: + logger = logging.getLogger(__name__) + logger.error(f"Error when instantiating {cls_name}!") + raise + return cfg # return as-is if don't know what to do diff --git a/utils/lazy_config/lazy.py b/utils/lazy_config/lazy.py new file mode 100644 index 0000000000000000000000000000000000000000..648754c6c194efe0476c78332ce64f5fbb2dbbd6 --- /dev/null +++ b/utils/lazy_config/lazy.py @@ -0,0 +1,396 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import ast +import builtins +import collections.abc as abc +import importlib +import inspect +import logging +import os +import uuid +import warnings +from collections import OrderedDict +from contextlib import contextmanager +from copy import deepcopy +from dataclasses import is_dataclass +from typing import Any, Dict, List, Tuple, Union + +import attrs +import yaml +from omegaconf import DictConfig, ListConfig, OmegaConf + +from utils.lazy_config.file_io import PathManager +from utils.lazy_config.registry import _convert_target_to_string + +__all__ = ["LazyCall", "LazyConfig"] + + +def sort_dict(d: Dict[str, Any]) -> OrderedDict[str, Any]: + return OrderedDict(sorted(d.items(), key=lambda x: x[0])) + + +def dict_representer(dumper: yaml.Dumper, data: OrderedDict[str, Any]) -> yaml.nodes.MappingNode: + return dumper.represent_mapping("tag:yaml.org,2002:map", data.items()) + + +def sort_recursive(obj: Union[Dict[str, Any], List[Any], Any]) -> Union[OrderedDict[str, Any], List[Any], Any]: + if isinstance(obj, dict): + return sort_dict({k: sort_recursive(v) for k, v in obj.items()}) + elif isinstance(obj, list): + return [sort_recursive(item) for item in obj] + return obj + + +yaml.add_representer(OrderedDict, dict_representer) + + +def get_default_params(cls_or_func): + if callable(cls_or_func): + # inspect signature for function + signature = inspect.signature(cls_or_func) + else: + # inspect signature for class + signature = inspect.signature(cls_or_func.__init__) + params = signature.parameters + default_params = { + name: param.default for name, param in params.items() if param.default is not inspect.Parameter.empty + } + return default_params + + +class LazyCall: + """ + Wrap a callable so that when it's called, the call will not be executed, + but returns a dict that describes the call. + + LazyCall object has to be called with only keyword arguments. Positional + arguments are not yet supported. + + Examples: + :: + from detectron2.config import instantiate, LazyCall + + layer_cfg = LazyCall(nn.Conv2d)(in_channels=32, out_channels=32) + layer_cfg.out_channels = 64 # can edit it afterwards + layer = instantiate(layer_cfg) + """ + + def __init__(self, target): + if not (callable(target) or isinstance(target, (str, abc.Mapping))): + raise TypeError(f"target of LazyCall must be a callable or defines a callable! Got {target}") + self._target = target + + def __call__(self, **kwargs): + if is_dataclass(self._target) or attrs.has(self._target): + # omegaconf object cannot hold dataclass type + # https://github.com/omry/omegaconf/issues/784 + target = _convert_target_to_string(self._target) + else: + target = self._target + kwargs["_target_"] = target + + _final_params = get_default_params(self._target) + _final_params.update(kwargs) + + return DictConfig(content=_final_params, flags={"allow_objects": True}) + + +def _visit_dict_config(cfg, func): + """ + Apply func recursively to all DictConfig in cfg. + """ + if isinstance(cfg, DictConfig): + func(cfg) + for v in cfg.values(): + _visit_dict_config(v, func) + elif isinstance(cfg, ListConfig): + for v in cfg: + _visit_dict_config(v, func) + + +def _validate_py_syntax(filename): + # see also https://github.com/open-mmlab/mmcv/blob/master/mmcv/utils/config.py + with PathManager.open(filename, "r") as f: + content = f.read() + try: + ast.parse(content) + except SyntaxError as e: + raise SyntaxError(f"Config file {filename} has syntax error!") from e + + +def _cast_to_config(obj): + # if given a dict, return DictConfig instead + if isinstance(obj, dict): + return DictConfig(obj, flags={"allow_objects": True}) + return obj + + +_CFG_PACKAGE_NAME = "detectron2._cfg_loader" +""" +A namespace to put all imported config into. +""" + + +def _random_package_name(filename): + # generate a random package name when loading config files + return _CFG_PACKAGE_NAME + str(uuid.uuid4())[:4] + "." + os.path.basename(filename) + + +@contextmanager +def _patch_import(): + """ + Enhance relative import statements in config files, so that they: + 1. locate files purely based on relative location, regardless of packages. + e.g. you can import file without having __init__ + 2. do not cache modules globally; modifications of module states has no side effect + 3. support other storage system through PathManager, so config files can be in the cloud + 4. imported dict are turned into omegaconf.DictConfig automatically + """ + old_import = builtins.__import__ + + def find_relative_file(original_file, relative_import_path, level): + # NOTE: "from . import x" is not handled. Because then it's unclear + # if such import should produce `x` as a python module or DictConfig. + # This can be discussed further if needed. + relative_import_err = """ +Relative import of directories is not allowed within config files. +Within a config file, relative import can only import other config files. +""".replace( + "\n", " " + ) + if not len(relative_import_path): + raise ImportError(relative_import_err) + + cur_file = os.path.dirname(original_file) + for _ in range(level - 1): + cur_file = os.path.dirname(cur_file) + cur_name = relative_import_path.lstrip(".") + for part in cur_name.split("."): + cur_file = os.path.join(cur_file, part) + if not cur_file.endswith(".py"): + cur_file += ".py" + if not PathManager.isfile(cur_file): + cur_file_no_suffix = cur_file[: -len(".py")] + if PathManager.isdir(cur_file_no_suffix): + raise ImportError(f"Cannot import from {cur_file_no_suffix}." + relative_import_err) + else: + raise ImportError( + f"Cannot import name {relative_import_path} from " f"{original_file}: {cur_file} does not exist." + ) + return cur_file + + def new_import(name, globals=None, locals=None, fromlist=(), level=0): + if ( + # Only deal with relative imports inside config files + level != 0 + and globals is not None + and (globals.get("__package__", "") or "").startswith(_CFG_PACKAGE_NAME) + ): + cur_file = find_relative_file(globals["__file__"], name, level) + _validate_py_syntax(cur_file) + spec = importlib.machinery.ModuleSpec(_random_package_name(cur_file), None, origin=cur_file) + module = importlib.util.module_from_spec(spec) + module.__file__ = cur_file + with PathManager.open(cur_file) as f: + content = f.read() + exec(compile(content, cur_file, "exec"), module.__dict__) + for name in fromlist: # turn imported dict into DictConfig automatically + val = _cast_to_config(module.__dict__[name]) + module.__dict__[name] = val + return module + return old_import(name, globals, locals, fromlist=fromlist, level=level) + + builtins.__import__ = new_import + yield new_import + builtins.__import__ = old_import + + +class LazyConfig: + """ + Provide methods to save, load, and overrides an omegaconf config object + which may contain definition of lazily-constructed objects. + """ + + @staticmethod + def load_rel(filename: str, keys: Union[None, str, Tuple[str, ...]] = None): + """ + Similar to :meth:`load()`, but load path relative to the caller's + source file. + + This has the same functionality as a relative import, except that this method + accepts filename as a string, so more characters are allowed in the filename. + """ + caller_frame = inspect.stack()[1] + caller_fname = caller_frame[0].f_code.co_filename + assert caller_fname != "", "load_rel Unable to find caller" + caller_dir = os.path.dirname(caller_fname) + filename = os.path.join(caller_dir, filename) + return LazyConfig.load(filename, keys) + + @staticmethod + def load(filename: str, keys: Union[None, str, Tuple[str, ...]] = None): + """ + Load a config file. + + Args: + filename: absolute path or relative path w.r.t. the current working directory + keys: keys to load and return. If not given, return all keys + (whose values are config objects) in a dict. + """ + has_keys = keys is not None + filename = filename.replace("/./", "/") # redundant + if os.path.splitext(filename)[1] not in [".py", ".yaml", ".yml"]: + raise ValueError(f"Config file {filename} has to be a python or yaml file.") + if filename.endswith(".py"): + _validate_py_syntax(filename) + + with _patch_import(): + # Record the filename + module_namespace = { + "__file__": filename, + "__package__": _random_package_name(filename), + } + with PathManager.open(filename) as f: + content = f.read() + # Compile first with filename to: + # 1. make filename appears in stacktrace + # 2. make load_rel able to find its parent's (possibly remote) location + exec(compile(content, filename, "exec"), module_namespace) + + ret = module_namespace + else: + with PathManager.open(filename) as f: + obj = yaml.unsafe_load(f) + ret = OmegaConf.create(obj, flags={"allow_objects": True}) + + if has_keys: + if isinstance(keys, str): + return _cast_to_config(ret[keys]) + else: + return tuple(_cast_to_config(ret[a]) for a in keys) + else: + if filename.endswith(".py"): + # when not specified, only load those that are config objects + ret = DictConfig( + { + name: _cast_to_config(value) + for name, value in ret.items() + if isinstance(value, (DictConfig, ListConfig, dict)) and not name.startswith("_") + }, + flags={"allow_objects": True}, + ) + return ret + + @staticmethod + def save_pkl(cfg, filename: str) -> str: + """Deprecated: saves config as YAML instead of pickle. + + Pickle serialization has been removed for security reasons (arbitrary + code execution). This method now delegates to :meth:`save_yaml`, + replacing the ``.pkl`` extension with ``.yaml`` so that existing call + sites continue to work without modification. + + Args: + cfg: A Config object to be serialized and saved. + filename: The requested output path. If it ends with ``.pkl``, + the extension is replaced with ``.yaml``. + + Returns: + str: The actual filename that was written. + """ + logger = logging.getLogger(__name__) + warnings.warn( + "LazyConfig.save_pkl() is deprecated. Config is now saved as YAML " + "instead of pickle. Update callers to use save_yaml() directly.", + DeprecationWarning, + stacklevel=2, + ) + yaml_filename = filename.rsplit(".pkl", 1)[0] + ".yaml" if filename.endswith(".pkl") else filename + logger.info(f"save_pkl is deprecated; saving config as YAML to {yaml_filename}") + return LazyConfig.save_yaml(cfg, yaml_filename) + + @staticmethod + def save_yaml(cfg, filename: str) -> str: + """ + Saves a Config object to a file using YAML serialization. This method is beneficial when the configuration object's content needs to be human-readable and easily editable. YAML is suitable for configurations that do not contain complex types like lambdas, which must be handled differently. The function converts unserializable items to strings before saving to ensure compatibility with YAML serialization. + + Args: + cfg: A Config object to be serialized and saved. It handles both DictConfig and ListConfig types. + filename: The path and name of the file where the configuration should be saved. The function does not require a specific file extension but typically uses '.yaml'. + + Returns: + str: The filename to which the configuration was saved. This can be used to verify the file location or log the outcome. + + Notes: + - The function logs a warning if the configuration is successfully saved using YAML. + - If saving fails, an error is logged with the exception details. + """ + logger = logging.getLogger(__name__) + try: + cfg = deepcopy(cfg) + except Exception: + pass + + # Define a function to check if an item is serializable to YAML + def is_serializable(item): + try: + OmegaConf.to_yaml(item) + return True + except Exception as e: + return False + + # Function to convert unserializable items to strings + def serialize_config(config): + if isinstance(config, DictConfig): + for key, value in config.items(): + if isinstance(value, (DictConfig, ListConfig)): + try: + if "_target_" in value: + default_params = get_default_params(value["_target_"]) + for default_key, default_v in default_params.items(): + if default_key not in value: + value[default_key] = default_v + except Exception as e: + logger.error(f"Failed to add default argument values: {e}") + + serialize_config(value) + else: + if not is_serializable(value) and value is not None: + config[key] = str(value) + elif isinstance(config, ListConfig): + for i, item in enumerate(config): + if isinstance(item, (DictConfig, ListConfig)): + serialize_config(item) + else: + if not is_serializable(item) and item is not None: + config[i] = str(item) + else: + raise NotImplementedError("Input config must be a DictConfig or ListConfig.") + return config + + # Convert Config object to a DictConfig object. + config_dict = attrs.asdict(cfg) + config_omegaconf = DictConfig(content=config_dict, flags={"allow_objects": True}) + + # Serialize the DictConfig object by converting non-serializable objects to strings. + config_omegaconf = serialize_config(config_omegaconf) + + config_dict: Dict[str, Any] = OmegaConf.to_container(config_omegaconf, resolve=True) + sorted_config: OrderedDict[str, Any] = sort_recursive(config_dict) + with open(filename, "w") as f: + yaml.dump(sorted_config, f, default_flow_style=False) + logger.warning(f"Config is saved using omegaconf at {filename}.") + return filename diff --git a/utils/lazy_config/omegaconf_patch.py b/utils/lazy_config/omegaconf_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..39dca42a0a71383de919b750cedf2606faae206d --- /dev/null +++ b/utils/lazy_config/omegaconf_patch.py @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Dict, List, Union + +from omegaconf import OmegaConf +from omegaconf.base import DictKeyType, SCMode +from omegaconf.dictconfig import DictConfig # pragma: no cover + + +def to_object(cfg: Any) -> Union[Dict[DictKeyType, Any], List[Any], None, str, Any]: + """ + Converts an OmegaConf configuration object to a native Python container (dict or list), unless + the configuration is specifically created by LazyCall, in which case the original configuration + is returned directly. + + This function serves as a modification of the original `to_object` method from OmegaConf, + preventing DictConfig objects created by LazyCall from being automatically converted to Python + dictionaries. This ensures that configurations meant to be lazily evaluated retain their intended + structure and behavior. + + Differences from OmegaConf's original `to_object`: + - Adds a check at the beginning to return the configuration unchanged if it is created by LazyCall. + + Reference: + - Original OmegaConf `to_object` method: https://github.com/omry/omegaconf/blob/master/omegaconf/omegaconf.py#L595 + + Args: + cfg (Any): The OmegaConf configuration object to convert. + + Returns: + Union[Dict[DictKeyType, Any], List[Any], None, str, Any]: The converted Python container if + `cfg` is not a LazyCall created configuration, otherwise the unchanged `cfg`. + + Examples: + >>> cfg = DictConfig({"key": "value", "_target_": "Model"}) + >>> to_object(cfg) + DictConfig({"key": "value", "_target_": "Model"}) + + >>> cfg = DictConfig({"list": [1, 2, 3]}) + >>> to_object(cfg) + {'list': [1, 2, 3]} + """ + if isinstance(cfg, DictConfig) and "_target_" in cfg.keys(): + return cfg + + return OmegaConf.to_container( + cfg=cfg, + resolve=True, + throw_on_missing=True, + enum_to_str=False, + structured_config_mode=SCMode.INSTANTIATE, + ) diff --git a/utils/lazy_config/registry.py b/utils/lazy_config/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..7c09eb428a97927d5f0407e2328a3f43afbf38fc --- /dev/null +++ b/utils/lazy_config/registry.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pydoc +from typing import Any + +""" +`locate` provide ways to map a string (typically found +in config files) to callable objects. +""" + +__all__ = ["locate"] + + +def _convert_target_to_string(t: Any) -> str: + """ + Inverse of ``locate()``. + + Args: + t: any object with ``__module__`` and ``__qualname__`` + """ + module, qualname = t.__module__, t.__qualname__ + + # Compress the path to this object, e.g. ``module.submodule._impl.class`` + # may become ``module.submodule.class``, if the later also resolves to the same + # object. This simplifies the string, and also is less affected by moving the + # class implementation. + module_parts = module.split(".") + for k in range(1, len(module_parts)): + prefix = ".".join(module_parts[:k]) + candidate = f"{prefix}.{qualname}" + try: + if locate(candidate) is t: + return candidate + except ImportError: + pass + return f"{module}.{qualname}" + + +def locate(name: str) -> Any: + """ + Locate and return an object ``x`` using an input string ``{x.__module__}.{x.__qualname__}``, + such as "module.submodule.class_name". + + Raise Exception if it cannot be found. + """ + obj = pydoc.locate(name) + + # Some cases (e.g. torch.optim.sgd.SGD) not handled correctly + # by pydoc.locate. Try a private function from hydra. + if obj is None: + try: + # from hydra.utils import get_method - will print many errors + from hydra.utils import _locate + except ImportError as e: + raise ImportError(f"Cannot dynamically locate object {name}!") from e + else: + obj = _locate(name) # it raises if fails + + return obj diff --git a/utils/lidar_rangemap.py b/utils/lidar_rangemap.py new file mode 100644 index 0000000000000000000000000000000000000000..ab74414abb524f4e27bf3e59941099ac90c4c2b7 --- /dev/null +++ b/utils/lidar_rangemap.py @@ -0,0 +1,756 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os +import numpy as np +import torch +import yaml +import re +from einops import rearrange +from matplotlib import cm +import mediapy as media +import matplotlib.pyplot as plt +from utils.camera.ftheta import FThetaCamera +from utils.misc import make_sure_numpy +from scipy import spatial, interpolate +from scipy.spatial.transform import Rotation as R + +RANGE_BANDS = { + 3: [5, 9.898, 21.813, 100], + 4: [5, 7.933, 15.109, 26.813, 100], + 8: [5, 5.762, 7.934, 11.023, 15.109, 19.906, 26.813, 40.656, 100], + 16: [ + 0, 4.973, 5.762, 6.715, 7.934, 9.367, 11.023, 12.930, 15.109, 17.422, + 19.906, 22.891, 26.813, 32.219, 40.656, 56.125, 100 + ], + 32: [ + 0, 4.563, 4.973, 5.352, 5.762, 6.207, 6.715, 7.289, 7.934, 8.625, + 9.367, 10.172, 11.023, 11.938, 12.930, 13.992, 15.109, 16.250, 17.422, + 18.625, 19.906, 21.313, 22.891, 24.719, 26.813, 29.297, 32.219, 35.906, + 40.656, 47.063, 56.125, 71.125, 100 + ], +} + +def transform_point_cloud(pc, T): + """Transform the point cloud with the provided transformation matrix, + support torch.Tensor and np.ndarry. + Args: + pc (np.array): point cloud coordinates (x,y,z) [num_pts, 3] or [bs, num_pts, 3] + T (np.array): se3 transformation matrix [4, 4] or [bs, 4, 4] + + Out: + (np array): transformed point cloud coordinated [num_pts, 3] or [bs, num_pts, 3] + """ + if len(pc.shape) == 3: + if isinstance(pc, np.ndarray): + trans_pts = T[:, :3, :3] @ pc.transpose(0, 2, 1) + T[:, :3, 3:4] + return trans_pts.transpose(0, 2, 1) + else: + trans_pts = T[:, :3, :3] @ pc.permute(0, 2, 1) + T[:, :3, 3:4] + return trans_pts.permute(0, 2, 1) + + else: + trans_pts = T[:3, :3] @ pc.transpose() + T[:3, 3:4] + return trans_pts.transpose() + +class PoseInterpolator: + """ + Interpolates the poses to the desired time stamps. The translation component is interpolated linearly, + while spherical linear interpolation (SLERP) is used for the rotations. https://en.wikipedia.org/wiki/Slerp + + Args: + poses (np.array): poses at given timestamps in a se3 representation [n,4,4] + timestamps (np.array): timestamps of the known poses [n] + ts_target (np.array): timestamps for which the poses will be interpolated [m] + Out: + (np.array): interpolated poses in se3 representation [m,4,4] + """ + + def __init__(self, poses, timestamps): + self.slerp = spatial.transform.Slerp(timestamps, R.from_matrix(poses[:, :3, :3])) + self.f_x = interpolate.interp1d(timestamps, poses[:, 0, 3]) + self.f_y = interpolate.interp1d(timestamps, poses[:, 1, 3]) + self.f_z = interpolate.interp1d(timestamps, poses[:, 2, 3]) + + self.last_row = np.array([0, 0, 0, 1], dtype=np.float32).reshape(1, 1, -1) + + self.start_timestamp = timestamps[0] + self.end_timestamp = timestamps[-1] + + def in_range(self, ts) -> bool: + """Returns true if all provided timestamps (scalar or array-like) are within the interpolation range""" + return ( + np.logical_and(self.start_timestamp <= (ts_array := np.asarray(ts)), ts_array <= self.end_timestamp) + .all() + .item() + ) + + def interpolate_to_timestamps(self, ts_target): + x_interp = self.f_x(ts_target).reshape(-1, 1, 1).astype(np.float32) + y_interp = self.f_y(ts_target).reshape(-1, 1, 1).astype(np.float32) + z_interp = self.f_z(ts_target).reshape(-1, 1, 1).astype(np.float32) + R_interp = self.slerp(ts_target).as_matrix().reshape(-1, 3, 3).astype(np.float32) + + t_interp = np.concatenate([x_interp, y_interp, z_interp], axis=-2) + + return np.concatenate( + (np.concatenate([R_interp, t_interp], axis=-1), np.tile(self.last_row, (R_interp.shape[0], 1, 1))), axis=1 + ) + +def load_each_frame_from_tar_data(tar_data, frame_idx, n_rows=128, n_cols=3600, load_intensity=False): + """ + Load range map (and optionally intensity map) of each frame. + When load_intensity=True, returns (range_map, intensity_map). + """ + lidar_row = np.load(tar_data.extractfile(f'{frame_idx}.lidar_row.npz'))['arr_0'] + lidar_col = np.load(tar_data.extractfile(f'{frame_idx}.lidar_col.npz'))['arr_0'] + lidar_range = np.load(tar_data.extractfile(f'{frame_idx}.lidar_range.npz'))['arr_0'] + + # convert to range map + range_map = np.zeros((n_rows, n_cols), dtype=np.float32) + range_map[lidar_row, lidar_col] = lidar_range.astype(np.float32) + + if load_intensity: + lidar_intensity = np.load(tar_data.extractfile(f'{frame_idx}.lidar_intensity.npz'))['arr_0'] + intensity_map = np.zeros((n_rows, n_cols), dtype=np.float32) + intensity_map[lidar_row, lidar_col] = lidar_intensity.astype(np.float32) + return range_map, intensity_map + + return range_map + +def load_range_map(tar_file, n_rows=128, n_cols=3600): + frame_idx_list = np.array([x.strip(".lidar_row.npz") for x in tar_file.getnames() if "lidar_row" in x]) + + range_map_list = [] + for frame_idx in frame_idx_list: + range_map = load_each_frame_from_tar_data(tar_file, frame_idx, n_rows, n_cols) + range_map_list.append(range_map) + range_map = np.stack(range_map_list, axis=0) + return range_map + + +def load_pandar128_elevations(): + with open("assets/lidar/lidar_model.yaml", "r") as file: + config = yaml.safe_load(file) + + # Access the inclinations_deg from the HESAI-Pandar128 model + elevations = config["lidar_models"]["spinning"]["HESAI-Pandar128"]["inclinations_deg"] + return elevations # load the elevation angles + + +def undo_row_col_temporal_repeat(range_map, repeat_row, repeat_col, repeat_temporal=None): + """ + range_map: numpy array of shape (N, 3, H, W) / N, 3, T, H, W + """ + dim = range_map.ndim + assert dim in [4, 5], f"Range map dimension must be 4 or 5, but got {dim}" + if dim == 4: # undo row and col repeat + range_map = range_map[:, :, repeat_row // 2 :: repeat_row, repeat_col // 2 :: repeat_col] + elif dim == 5: # undo row, col and temporal repeat + range_map = range_map[:, :, :, repeat_row // 2 :: repeat_row, repeat_col // 2 :: repeat_col] + assert repeat_temporal is not None, "repeat_temporal must be provided for 5D range map" + if repeat_temporal > 1: + range_map = torch.cat( + (range_map[:, :, 0:1, :, :], range_map[:, :, 1 + repeat_temporal // 2 :: repeat_temporal, :, :]), dim=2 + ) # add 1+ to skip the first reconstructed frame + + return range_map + +def normalize_range_map(range_map, max_range, min_range, min_value, inverse_depth): + """ + Normalize the range map from [min_range, max_range] to [-1, 1]/[0, 1] + Input: + range_map: numpy array of shape (N, H, W) / (N, 3, H, W) + max_range: float + min_range: float + min_value: float + inverse_depth: bool + Output: + range_map: numpy array of shape (N, H, W) / (N, 3, H, W) + """ + c_min_range = min_range if not inverse_depth else 1 / max_range + c_max_range = max_range if not inverse_depth else 1 / min_range + + if inverse_depth: + mask = range_map == 0 + range_map[mask] = max_range + range_map = 1 / range_map + range_map[mask] = c_min_range + + # normalise the range map + if isinstance(range_map, torch.Tensor): + range_map = torch.clamp(range_map, c_min_range, c_max_range) + else: + range_map = np.clip(range_map, c_min_range, c_max_range) + + if min_value == -1: + range_map = (range_map - c_min_range) / (c_max_range - c_min_range) * 2 - 1 + else: + range_map = (range_map - c_min_range) / (c_max_range - c_min_range) + + return range_map + + +def unnormalize_range_map( + range_map, max_range, min_range, min_value, inverse_depth, near_buffer, far_buffer, valid_mask=None, apply_valid_mask=True +): + """ + Unnormalize the range map from [-1, 1]/[0, 1] to [min_range, max_range] + Input: + range_map: numpy array of shape (N, H, W) + Output: + range_map: numpy array of shape (N, H, W) + """ + c_min_range = min_range if not inverse_depth else 1 / max_range + c_max_range = max_range if not inverse_depth else 1 / min_range + + if min_value == -1: + # range_map = range_map.clip(-1, 1) + range_map = (range_map + 1) / 2 * (c_max_range - c_min_range) + c_min_range + else: + # range_map = range_map.clip(0, 1) + range_map = range_map * (c_max_range - c_min_range) + c_min_range + + if inverse_depth: + range_map = 1 / range_map + + if valid_mask is None: + valid_mask = (range_map > min_range + near_buffer) & ( + range_map < max_range - far_buffer + ) # add buffer to deal with low precision of bfloat16 + + if apply_valid_mask: + if isinstance(range_map, torch.Tensor): + range_map = torch.where(valid_mask, range_map, torch.zeros_like(range_map)) + else: + range_map = range_map.copy() + range_map[~valid_mask] = 0 + + return range_map, valid_mask + + +def unnormalize_intensity(intensity_map, min_value, transform="legacy"): + """Invert the selected intensity transform. + + ``legacy`` preserves the historical [min_value, 1] <-> [0, 1] contract. + ``log1p`` stores normalized log-intensity in [-1, 1] and inverts it back + to normalized linear intensity in [0, 1]. The latter is opt-in for + cross-dataset tokenizers. + """ + if transform == "log1p": + if isinstance(intensity_map, torch.Tensor): + log_intensity = (intensity_map.clamp(-1, 1) + 1.0) * ( + 0.5 * np.log(2.0) + ) + return torch.expm1(log_intensity) + log_intensity = (np.clip(intensity_map, -1, 1) + 1.0) * ( + 0.5 * np.log(2.0) + ) + return np.expm1(log_intensity) + if transform != "legacy": + raise ValueError(f"Unknown intensity transform: {transform!r}") + if min_value == -1: + return (intensity_map + 1) / 2 + return intensity_map + + +def unnormalize_and_reduce_channels( + range_map, + max_range, + min_range, + min_value, + inverse_depth, + process_output, + near_buffer=0.5, + far_buffer=0.5, + inv_depth_threshold=20, + num_bands=3, + apply_valid_mask=True, + has_intensity=False, + intensity_transform="legacy", + channel_reduce=None, +): + """ + Unnormalize the range map and reduce the channels to 1 (output processing). + Input: + range_map: tensor of shape (N, C, H, W) or (N, C, T, H, W) + has_intensity: if True, the last channel is intensity and will be stripped + before processing range channels. The unnormalized intensity + is returned as the third element of the tuple. + channel_reduce: how to collapse the repeated range channels ("mean" or + "median"). Defaults to the ``LIDAR_CHANNEL_REDUCE`` env + var (falling back to "mean"), so existing callers are + unchanged unless that env var is set. + Output: + Without intensity: (final_range_map, valid_mask) + With intensity: (final_range_map, valid_mask, intensity_map) + """ + if channel_reduce is None: + channel_reduce = os.environ.get("LIDAR_CHANNEL_REDUCE", "mean") + + def _reduce_channels(x): + if channel_reduce == "median": + return x.median(dim=1).values + return x.mean(dim=1) + + intensity_map = None + if has_intensity: + intensity_map = unnormalize_intensity( + range_map[:, -1], min_value, transform=intensity_transform + ) + range_map = range_map[:, :-1] + + if process_output == "repeat": + range_map = _reduce_channels(range_map) + final_range_map, valid_mask = unnormalize_range_map( + range_map, max_range, min_range, min_value, inverse_depth, near_buffer, far_buffer, apply_valid_mask=apply_valid_mask + ) + elif process_output == "mono": + # Input: (N, 1, H, W) or (N, 1, T, H, W); single channel, just unnormalize + range_map = range_map.squeeze(1) + final_range_map, valid_mask = unnormalize_range_map( + range_map, max_range, min_range, min_value, inverse_depth, near_buffer, far_buffer, apply_valid_mask=apply_valid_mask + ) + elif process_output == "concat": + # the first channel is inverse depth, the second and third channels are depths + inverse_depth = range_map[:, 0] # shape: (N, H, W) or (N, T, H, W) + depth = range_map[:, 1:].mean(dim=1) # shape: (N, H, W) or (N, T, H, W) + + inverse_depth, inv_depth_valid_mask = unnormalize_range_map( + inverse_depth, max_range, min_range, min_value, True, near_buffer, far_buffer, apply_valid_mask=apply_valid_mask + ) + depth, depth_valid_mask = unnormalize_range_map( + depth, max_range, min_range, min_value, False, near_buffer, far_buffer, apply_valid_mask=apply_valid_mask + ) + + # for the valid pixels, if the inverse depth value is below 20m, then use the inverse depth value, otherwise use the depth value + inv_depth_valid_mask = inv_depth_valid_mask & (inverse_depth < inv_depth_threshold) + final_range_map = torch.where(inv_depth_valid_mask, inverse_depth, depth) + valid_mask = depth_valid_mask | inv_depth_valid_mask + elif process_output == "band": + assert range_map.shape[1] == num_bands, f"Range map {range_map.shape} must have {num_bands} channels" + valid_mask = torch.ones_like(range_map[:, 0], dtype=torch.bool) + + final_range_map = torch.zeros_like(range_map[:, 0]) + for i in range(num_bands): + if i == 0: + band_range_map, _ = unnormalize_range_map( + range_map[:, i], + RANGE_BANDS[num_bands][i+1], + RANGE_BANDS[num_bands][i], + min_value, + inverse_depth, + near_buffer, far_buffer, apply_valid_mask=False + ) + else: + band_range_map, _ = unnormalize_range_map( + range_map[:, i], + RANGE_BANDS[num_bands][i+1] - RANGE_BANDS[num_bands][i], + 0, + min_value, + inverse_depth, + near_buffer, far_buffer, apply_valid_mask=False + ) + final_range_map += band_range_map + + valid_mask = (final_range_map > min_range + near_buffer) & ( + final_range_map < max_range - far_buffer + ) + if apply_valid_mask: + final_range_map = torch.where(valid_mask, final_range_map, torch.zeros_like(final_range_map)) + else: + raise ValueError(f"Invalid process_output: {process_output}") + + if has_intensity: + return final_range_map, valid_mask, intensity_map + return final_range_map, valid_mask + +def range_map_to_ray_directions(n_cols, sensor_elevation_angles): + """ + Generate ray directions for each pixel in a range map. + + Args: + n_cols: number of columns in the range map + sensor_elevation_angles: list/array of elevation angles in degrees for each scan line + (determines the number of rows) + + Returns: + ray_directions: numpy array of shape (n_rows, n_cols, 3) containing unit vectors + for each pixel's ray direction + """ + # Create arrays for azimuth and elevation angles + # Azimuth angles are uniformly distributed around 360 degrees + azimuth_angles = np.linspace(np.pi, -np.pi, n_cols, endpoint=False) + + # Convert elevation angles from degrees to radians + elevation_angles_rad = np.radians(sensor_elevation_angles) + + # Create meshgrid for all combinations of angles + elevation_grid, azimuth_grid = np.meshgrid(elevation_angles_rad, azimuth_angles, indexing="ij") + + x = np.cos(elevation_grid) * np.cos(azimuth_grid) # shape: (H, W) + y = np.cos(elevation_grid) * np.sin(azimuth_grid) + z = np.sin(elevation_grid) + + # Stack to create ray directions + ray_directions = np.stack([x, y, z], axis=-1) # shape: (H, W, 3) + + return ray_directions + + +def build_decomp_ray_directions(resolution, ray_dirs_path: str = ""): + """Per-pixel unit ray directions ``(H, W, 3)`` for the decomp-BEV networks. + + When ``ray_dirs_path`` is a non-empty path to a ``.npy`` of shape ``(H, W, 3)`` + (e.g. the precomputed Waymo table from ``scripts/dump_waymo_ray_dirs.py``, + built from the sensor's measured elevation/azimuth tables + per-row offset), + it is loaded and shape-checked against ``resolution``. Otherwise the legacy + Pandar128 geometry (uniform-linspace azimuth + the 128-beam inclination table) + is rebuilt -- so every existing config stays bit-identical. + + Returns a float32 ``torch.Tensor`` of shape ``(H, W, 3)``. + """ + H, W = int(resolution[0]), int(resolution[1]) + if ray_dirs_path: + dirs = np.load(ray_dirs_path) + if dirs.shape != (H, W, 3): + raise ValueError( + f"ray_dirs_path={ray_dirs_path} has shape {dirs.shape}, expected " + f"({H}, {W}, 3) to match resolution {(H, W)}. Regenerate the asset " + "with the matching resample_width (W) and lidar." + ) + return torch.from_numpy(dirs).float() + elevations = torch.tensor(load_pandar128_elevations(), dtype=torch.float32) + return torch.from_numpy(range_map_to_ray_directions(W, elevations)).float() + + +def range_map_to_point_cloud(range_map): + """ + Convert the range map to a point cloud. + Input: + range_map: numpy array of shape (H, W), unnormalized range values + Output: + point_cloud: numpy array of shape (N, 3) + """ + elevation_angles = load_pandar128_elevations() + assert len(elevation_angles) == range_map.shape[0] + + ray_directions = range_map_to_ray_directions(range_map.shape[1], elevation_angles) # shape: (H, W, 3) + + points = range_map[..., np.newaxis] * ray_directions # shape: (H, W, 3) + points = points[range_map > 0] + return points + +def apply_color_map_to_image( + x, + mask=None, + color_map="Spectral", +): + if color_map == "gray": + mapped = np.repeat(x.detach().clip(min=0, max=1).cpu().numpy()[..., np.newaxis], 3, axis=-1) + else: + cmap = cm.get_cmap(color_map) + # Convert to NumPy so that Matplotlib color maps can be used. + mapped = cmap(x.detach().float().clip(min=0, max=1).cpu().numpy())[..., :3] + image = torch.tensor(mapped, device=x.device, dtype=x.dtype) + if mask is not None: + image[mask] = torch.tensor([0.82, 0.82, 0.82], device=x.device, dtype=x.dtype) # Set masked areas to light gray + + return rearrange(image, "... h w c -> ... c h w") + + +def apply_motion_compensation_impl( + xyz: np.ndarray, T_sensor_end_sensor_start: np.ndarray, timestamps_startend_us: list, timestamp_us: np.ndarray +) -> np.ndarray: + """ + undo motion-compensation to bring ray's into time-dependent sensor-frame + Here the input lidar points are motion compensated to the beginning of the spin. + + Args: + xyz (np.array): points from the sensor space [n,3] + T_sensor_end_sensor_start (np.array): relative pose from end-of-frame to start-of-frame in sensor space [4,4] + timestamps_startend_us (list): contains [start timestamp, end timestamp] + timestamp_us (np.array): recoding target per-point timestamps [n] + Out: + (np.array): points after undo motion-compensation[n,3] + """ + + xyz = make_sure_numpy(xyz) + T_sensor_end_sensor_start = make_sure_numpy(T_sensor_end_sensor_start) + timestamp_us = make_sure_numpy(timestamp_us) + + # ) + pose_interpolator = PoseInterpolator( + np.stack([np.eye(4, dtype=np.float32),np.linalg.inv(T_sensor_end_sensor_start)]), + timestamps_startend_us, + ) + + # Note: this interpolation will fail if the point's timestamps are outside of the frame's start/end times - issue dedicated error in that case + assert ( + (timestamps_startend_us[0] <= timestamp_us).all() and (timestamp_us <= timestamps_startend_us[1]).all() + ), f"Lidar point timestamps out of frame timestamp bounds - this is an inconsistency in the dataset's internal data and needs to be fixed at dataset creation time" + T_sensor_end_sensor_pointtime = pose_interpolator.interpolate_to_timestamps(timestamp_us) + + xyz = transform_point_cloud(xyz[:, np.newaxis, :], T_sensor_end_sensor_pointtime).squeeze(1) + + return xyz + + + +def draw_lidar_points(lidar_points, camera_model, camera_to_lidar): + cmap = plt.colormaps['rainbow'] + lidar_points_z = lidar_points[:, 2] + lidar_points_z = lidar_points_z.clip(-2, 4) + lidar_points_z = (lidar_points_z + 2) / 6 + lidar_z_colors = cmap(lidar_points_z)[:, :3] + lidar_z_colors = (lidar_z_colors * 255).astype(np.uint8) + + # cmap = plt.colormaps['rainbow'] + # depth = np.linalg.norm(lidar_points, axis=1) + # depth = torch.from_numpy(depth).float().log() + # near = depth[depth > 0].quantile(0.02) + # far = depth[depth > 0].quantile(0.98) + # depth = 1 - (depth - near) / (far - near) + # depth = depth.clip(0, 1).numpy() + # lidar_z_colors = cmap(depth)[:, :3] + # lidar_z_colors = (lidar_z_colors * 255).astype(np.uint8) + + visual_lidar_points = camera_model.draw_points( + camera_to_lidar, + lidar_points, + colors=lidar_z_colors, + radius=2, + ) + return visual_lidar_points + + + +def project_lidar_to_rgb_impl(camera_intrinsics, camera_2_lidar, input_points_compensated, recon_points_compensated): + # init camera model + camera_model = FThetaCamera.from_numpy(camera_intrinsics.cpu().numpy(), device='cpu') + + # project points to rgb + visual_lidar_input = draw_lidar_points(input_points_compensated, camera_model, camera_2_lidar).astype(np.float32) / 255.0 # [H, W, 3], 0-1 + visual_lidar_recon = draw_lidar_points(recon_points_compensated, camera_model, camera_2_lidar).astype(np.float32) / 255.0 # [H, W, 3], 0-1 + + return visual_lidar_input, visual_lidar_recon + + +def colorcode_depth_maps(result, near=None, far=None, cmap="turbo"): + """ + Input: B x H x W + Output: B x 3 x H x W, normalized to [0, 1] + """ + mask = result == 0 + n_frames = result.shape[0] + if far is None: + far = result[n_frames // 2].view(-1).quantile(0.99).log() + if near is None: + try: + near = result[n_frames // 2][result[n_frames // 2] > 0].quantile(0.01).log() + except: + print("No valid depth values found.") + near = torch.zeros_like(far) + + result = result.log() + result = 1 - (result - near) / (far - near) + return apply_color_map_to_image(result, mask, cmap) + + +def save_depth_maps_to_video(depth_maps, save_path, cmap="Spectral", fps=10): + """ + depth_maps: B x H x W + save_path: str + fps: int + """ + # Convert depth maps to uint8 + depth_maps = colorcode_depth_maps(depth_maps, cmap=cmap) # B x 3 x H x W + depth_maps = (depth_maps * 255 + 0.5).permute(0, 2, 3, 1).numpy().astype(np.uint8) # B x H x W x 3 + media.write_video(save_path, depth_maps, fps=fps) + +class RangeMapDownsampler: + """ + A class to handle range map downsampling operations along with associated data. + """ + + def __init__(self, row_factor=1, col_factor=1, method="scatter_min"): + """ + Initialize the downsampler with factors and method. + + Args: + row_factor: Factor to downsample rows by (default: 1) + col_factor: Factor to downsample columns by (default: 1) + method: Downsampling method - "scatter_min", "scatter_max", or "every_n" (default: "scatter_min") + """ + self.row_factor = row_factor + self.col_factor = col_factor + self.method = method + + if method not in ["scatter_min", "scatter_max", "every_n"]: + raise ValueError(f"Invalid method: {method}") + + def _downsample_vertical(self, data: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Downsample vertically using the configured method.""" + if self.row_factor == 1: + return data, np.zeros_like(data) + + N, H, W = data.shape + assert H % self.row_factor == 0, f"Height {H} must be divisible by row_factor {self.row_factor}" + + if self.method == "every_n": + return data[:, ::self.row_factor], np.zeros((N, H // self.row_factor, W)) + + # Reshape to compare adjacent rows + groups = data.reshape(N, H // self.row_factor, self.row_factor, W) + + if self.method == "scatter_min": + # Handle zeros by setting them to large values + groups_clean = np.where(groups == 0, 1e3, groups) + min_values = np.min(groups_clean, axis=2) + min_indices = np.argmin(groups_clean, axis=2) + # Restore zeros + min_values = np.where(min_values == 1e3, 0, min_values) + else: # scatter_max + min_values = np.max(groups, axis=2) + min_indices = np.argmax(groups, axis=2) + + return min_values, min_indices + + def _downsample_horizontal(self, data: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Downsample horizontally using the configured method.""" + if self.col_factor == 1: + return data, np.zeros_like(data) + + N, H, W = data.shape + assert W % self.col_factor == 0, f"Width {W} must be divisible by col_factor {self.col_factor}" + + if self.method == "every_n": + return data[:, :, ::self.col_factor], np.zeros((N, H, W // self.col_factor)) + + # Reshape to compare adjacent columns + groups = data.reshape(N, H, W // self.col_factor, self.col_factor) + + if self.method == "scatter_min": + # Handle zeros by setting them to large values + groups_clean = np.where(groups == 0, 1e3, groups) + min_values = np.min(groups_clean, axis=3) + min_indices = np.argmin(groups_clean, axis=3) + # Restore zeros + min_values = np.where(min_values == 1e3, 0, min_values) + else: # scatter_max + min_values = np.max(groups, axis=3) + min_indices = np.argmax(groups, axis=3) + + return min_values, min_indices + + def _apply_indices(self, data: np.ndarray, indices: np.ndarray, axis: int) -> np.ndarray: + """Apply downsampling indices to data along specified axis.""" + if indices is None or np.all(indices == 0): + return data + + N, H, W = data.shape[:3] + scale_factor = H // indices.shape[1] if axis == 1 else W // indices.shape[2] + + if axis == 1: # vertical + reshaped = data.reshape(N, H // scale_factor, scale_factor, W, *data.shape[3:]) + batch_idx = np.arange(N)[:, None, None] + height_idx = np.arange(H // scale_factor)[None, :, None] + width_idx = np.arange(W)[None, None, :] + return reshaped[batch_idx, height_idx, indices, width_idx] + else: # horizontal + reshaped = data.reshape(N, H, W // scale_factor, scale_factor, *data.shape[3:]) + batch_idx = np.arange(N)[:, None, None] + height_idx = np.arange(H)[None, :, None] + width_idx = np.arange(W // scale_factor)[None, None, :] + # Broadcast indices for advanced indexing + batch_idx = np.broadcast_to(batch_idx, (N, H, W // scale_factor)) + height_idx = np.broadcast_to(height_idx, (N, H, W // scale_factor)) + width_idx = np.broadcast_to(width_idx, (N, H, W // scale_factor)) + return reshaped[batch_idx, height_idx, width_idx, indices] + + def downsample(self, range_map: np.ndarray, extra_maps: list = None) -> tuple: + """ + Downsample the range map and any extra maps using the configured factors and method. + + Args: + range_map: Array of shape (N, H, W) + extra_maps: Optional list of arrays to downsample along with range_map + + Returns: + Tuple of (downsampled_range_map, downsampled_extra_maps) or just downsampled_range_map + """ + current_range = range_map.copy() + + # Downsample vertically first + current_range, v_indices = self._downsample_vertical(current_range) + if extra_maps is not None: + extra_maps = [self._apply_indices(em, v_indices, axis=1) for em in extra_maps] + + # Then downsample horizontally + current_range, h_indices = self._downsample_horizontal(current_range) + if extra_maps is not None: + extra_maps = [self._apply_indices(em, h_indices, axis=2) for em in extra_maps] + + if extra_maps is not None: + return current_range, extra_maps + return current_range + + def __call__(self, range_map: np.ndarray, extra_maps: list = None) -> tuple: + """Convenience method to call downsample directly.""" + return self.downsample(range_map, extra_maps) + +class SinusoidalEncoder(torch.nn.Module): + """Sinusoidal Positional Encoder used in Nerf.""" + + def __init__( + self, + n_input_dims: int = 3, + min_deg: int = 0, + max_deg: int = 10, + enable_identity: bool = True, + ): + super().__init__() + self.n_input_dims = n_input_dims + self.min_deg = min_deg + self.max_deg = max_deg + self.enable_identity = enable_identity + self.scales = torch.tensor([2**i for i in range(min_deg, max_deg + 1)], dtype=torch.get_default_dtype()) + + @property + def n_output_dims(self) -> int: + return ( + int(self.enable_identity) + (self.max_deg - self.min_deg + 1) * 2 + ) * self.n_input_dims + + @torch.no_grad() + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: [..., n_input_dims] + Returns: + encoded: [..., n_output_dims] + """ + if self.max_deg == self.min_deg: + return x + xb = torch.reshape( + (x[..., None, :] * self.scales[:, None]), + list(x.shape[:-1]) + + [(self.max_deg - self.min_deg + 1) * self.n_input_dims], + ) + encoded = torch.sin(torch.cat([xb, xb + 0.5 * torch.pi], dim=-1)) + if self.enable_identity: + encoded = torch.cat([x] + [encoded], dim=-1) + return encoded \ No newline at end of file diff --git a/utils/log.py b/utils/log.py new file mode 100644 index 0000000000000000000000000000000000000000..45f98624193c5551c6c390dd0110d1440a610133 --- /dev/null +++ b/utils/log.py @@ -0,0 +1,152 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import atexit +import os +from typing import Any, Optional + +import torch.distributed as dist +from loguru._logger import Core, Logger +from tqdm import tqdm + +RANK0_ONLY = True +LEVEL = os.environ.get("LOGURU_LEVEL", "INFO") + +logger = Logger( + core=Core(), + exception=None, + depth=1, + record=False, + lazy=False, + colors=False, + raw=False, + capture=True, + patchers=[], + extra={}, +) + +atexit.register(logger.remove) + + +def _add_relative_path(record: dict[str, Any]) -> None: + start = os.getcwd() + record["extra"]["relative_path"] = os.path.relpath(record["file"].path, start) + + +*options, _, extra = logger._options # type: ignore +logger._options = tuple([*options, [_add_relative_path], extra]) # type: ignore + + +def init_loguru_stdout() -> None: + logger.remove() + machine_format = get_machine_format() + message_format = get_message_format() + logger.add( + lambda msg: tqdm.write(msg, end=""), # stdout is replaced with tqdm.write to avoid tqdm log pollution.. + level=LEVEL, + format="[{time:MM-DD HH:mm:ss}|" f"{machine_format}" f"{message_format}", + filter=_rank0_only_filter, + ) + + +def init_loguru_file(path: str) -> None: + machine_format = get_machine_format() + message_format = get_message_format() + logger.add( + path, + encoding="utf8", + level=LEVEL, + format="[{time:MM-DD HH:mm:ss}|" f"{machine_format}" f"{message_format}", + rotation="100 MB", + filter=lambda result: _rank0_only_filter(result) or not RANK0_ONLY, + enqueue=True, + ) + + +def get_machine_format() -> str: + node_id = os.environ.get("NGC_ARRAY_INDEX", "0") + num_nodes = int(os.environ.get("NGC_ARRAY_SIZE", "1")) + machine_format = "" + rank = 0 + if dist.is_available(): + if not RANK0_ONLY and dist.is_initialized(): + rank = dist.get_rank() + world_size = dist.get_world_size() + machine_format = ( + f"[Node{node_id:<3}/{num_nodes:<3}][RANK{rank:<5}/{world_size:<5}]" + "[{process.name:<8}]| " + ) + return machine_format + + +def get_message_format() -> str: + message_format = "{level}|{extra[relative_path]}:{line}:{function}] {message}" + return message_format + + +def _rank0_only_filter(record: Any) -> bool: + is_rank0 = record["extra"].get("rank0_only", True) + if _get_rank() == 0 and is_rank0: + return True + if not is_rank0: + record["message"] = f"[RANK {_get_rank()}] " + record["message"] + return not is_rank0 + + +def trace(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).trace(message) + + +def debug(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).debug(message) + + +def info(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).info(message) + + +def success(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).success(message) + + +def warning(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).warning(message) + + +def error(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).error(message) + + +def critical(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).critical(message) + + +def exception(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).exception(message) + + +def _get_rank(group: Optional[dist.ProcessGroup] = None) -> int: + """Get the rank (GPU device) of the worker. + + Returns: + rank (int): The rank of the worker. + """ + rank = 0 + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank(group) + return rank + + +# Execute at import time. +init_loguru_stdout() diff --git a/utils/misc.py b/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..2bcb6613740f3256bdb3c74d4ccfc5febc1a4190 --- /dev/null +++ b/utils/misc.py @@ -0,0 +1,576 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import collections +import collections.abc +import functools +import json +import os +import random +import time +from contextlib import ContextDecorator +from pathlib import Path +from typing import Any, Callable, List, Optional, Tuple, TypeVar +from urllib.parse import urlparse +import re +import boto3 +import numpy as np +import termcolor +import torch +from torch import nn +from torch.distributed._functional_collectives import AsyncCollectiveTensor +from torch.distributed._tensor.api import DTensor + +from utils import distributed, log +from utils.easy_io import easy_io + +def natural_key(string_): + """ + Sort strings by numbers in the name + """ + return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_)] + +def make_sure_numpy(data): + if isinstance(data, torch.Tensor): + return data.cpu().numpy() + else: + return data + + +def make_sure_torch(x): + if isinstance(x, np.ndarray): + return torch.from_numpy(x) + return x + + + +def to( + data: Any, + device: str | torch.device | None = None, + dtype: torch.dtype | None = None, + memory_format: torch.memory_format = torch.preserve_format, +) -> Any: + """Recursively cast data into the specified device, dtype, and/or memory_format. + + The input data can be a tensor, a list of tensors, a dict of tensors. + See the documentation for torch.Tensor.to() for details. + + Args: + data (Any): Input data. + device (str | torch.device): GPU device (default: None). + dtype (torch.dtype): data type (default: None). + memory_format (torch.memory_format): memory organization format (default: torch.preserve_format). + + Returns: + data (Any): Data cast to the specified device, dtype, and/or memory_format. + """ + assert ( + device is not None or dtype is not None or memory_format is not None + ), "at least one of device, dtype, memory_format should be specified" + if isinstance(data, torch.Tensor): + is_cpu = (isinstance(device, str) and device == "cpu") or ( + isinstance(device, torch.device) and device.type == "cpu" + ) + data = data.to( + device=device, + dtype=dtype, + memory_format=memory_format, + non_blocking=(not is_cpu), + ) + return data + elif isinstance(data, collections.abc.Mapping): + return type(data)({key: to(data[key], device=device, dtype=dtype, memory_format=memory_format) for key in data}) + elif isinstance(data, collections.abc.Sequence) and not isinstance(data, (str, bytes)): + return type(data)([to(elem, device=device, dtype=dtype, memory_format=memory_format) for elem in data]) + else: + return data + + +def serialize(data: Any) -> Any: + """Serialize data by hierarchically traversing through iterables. + + Args: + data (Any): Input data. + + Returns: + data (Any): Serialized data. + """ + if isinstance(data, collections.abc.Mapping): + return type(data)({key: serialize(data[key]) for key in data}) + elif isinstance(data, collections.abc.Sequence) and not isinstance(data, (str, bytes)): + return type(data)([serialize(elem) for elem in data]) + else: + try: + json.dumps(data) + except TypeError: + data = str(data) + return data + + +def print_environ_variables(env_vars: list[str]) -> None: + """Print a specific list of environment variables. + + Args: + env_vars (list[str]): List of specified environment variables. + """ + for env_var in env_vars: + if env_var in os.environ: + log.info(f"Environment variable {Color.green(env_var)}: {Color.yellow(os.environ[env_var])}") + else: + log.warning(f"Environment variable {Color.green(env_var)} not set!") + + +def set_random_seed(seed: int, by_rank: bool = False) -> None: + """Set random seed. This includes random, numpy, Pytorch. + + Args: + seed (int): Random seed. + by_rank (bool): if true, each GPU will use a different random seed. + """ + if by_rank: + seed += distributed.get_rank() + log.info(f"Using random seed {seed}.") + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) # sets seed on the current CPU & all GPUs + + +def arch_invariant_rand( + shape: List[int] | Tuple[int], dtype: torch.dtype, device: str | torch.device, seed: int | None = None +): + """Produce a GPU-architecture-invariant randomized Torch tensor. + + Args: + shape (list or tuple of ints): Output tensor shape. + dtype (torch.dtype): Output tensor type. + device (torch.device): Device holding the output. + seed (int): Optional randomization seed. + + Returns: + tensor (torch.tensor): Randomly-generated tensor. + """ + # Create a random number generator, optionally seeded + rng = np.random.RandomState(seed) + + # # Generate random numbers using the generator + random_array = rng.standard_normal(shape).astype(np.float32) # Use standard_normal for normal distribution + + # Convert to torch tensor and return + return torch.from_numpy(random_array).to(dtype=dtype, device=device) + + +T = TypeVar("T", bound=Callable[..., Any]) + + +class timer(ContextDecorator): # noqa: N801 + """Simple timer for timing the execution of code. + + It can be used as either a context manager or a function decorator. The timing result will be logged upon exit. + + Example: + def func_a(): + time.sleep(1) + with timer("func_a"): + func_a() + + @timer("func_b) + def func_b(): + time.sleep(1) + func_b() + """ + + def __init__(self, context: str, debug: bool = False): + self.context = context + self.debug = debug + + def __enter__(self) -> None: + self.tic = time.time() + + def __exit__(self, exc_type, exc_value, traceback) -> None: # noqa: ANN001 + time_spent = time.time() - self.tic + if self.debug: + log.debug(f"Time spent on {self.context}: {time_spent:.4f} seconds") + else: + log.debug(f"Time spent on {self.context}: {time_spent:.4f} seconds") + + def __call__(self, func: T) -> T: + @functools.wraps(func) + def wrapper(*args, **kwargs): # noqa: ANN202 + tic = time.time() + result = func(*args, **kwargs) + time_spent = time.time() - tic + if self.debug: + log.debug(f"Time spent on {self.context}: {time_spent:.4f} seconds") + else: + log.debug(f"Time spent on {self.context}: {time_spent:.4f} seconds") + return result + + return wrapper # type: ignore + + +class TrainingTimer: + """Timer for timing the execution of code, aggregating over multiple training iterations. + + It is used as a context manager to measure the execution time of code and store the timing results + for each function. The context managers can be nested. + + Attributes: + results (dict): A dictionary to store timing results for various code. + + Example: + timer = Timer() + for i in range(100): + with timer("func_a"): + func_a() + avg_time = sum(timer.results["func_a"]) / len(timer.results["func_a"]) + print(f"func_a() took {avg_time} seconds.") + """ + + def __init__(self) -> None: + self.results = dict() + self.average_results = dict() + self.start_time = [] + self.func_stack = [] + self.reset() + + def reset(self) -> None: + self.results = {key: [] for key in self.results} + + def __enter__(self) -> TrainingTimer: + self.start_time.append(time.time()) + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: # noqa: ANN001 + end_time = time.time() + result = end_time - self.start_time.pop() + key = self.func_stack.pop() + self.results.setdefault(key, []) + self.results[key].append(result) + + def __call__(self, func_name: str) -> TrainingTimer: + self.func_stack.append(func_name) + return self + + def __getattr__(self, func_name: str) -> TrainingTimer: + return self.__call__(func_name) + + def nested(self, func_name: str) -> TrainingTimer: + return self.__call__(func_name) + + def compute_average_results(self) -> dict[str, float]: + results = dict() + for key, value_list in self.results.items(): + results[key] = sum(value_list) / len(value_list) + return results + + +def timeout_handler(timeout_period: float, signum: int, frame: int) -> None: + # What to do when the process gets stuck. For now, we simply end the process. + error_message = f"Timeout error: more than {timeout_period} seconds passed since the last iteration." + raise TimeoutError(error_message) + + +class Color: + """A convenience class to colorize strings in the console. + + Example: + import + print("This is {Color.red('important')}.") + """ + + @staticmethod + def red(x: str) -> str: + return termcolor.colored(str(x), color="red") + + @staticmethod + def green(x: str) -> str: + return termcolor.colored(str(x), color="green") + + @staticmethod + def cyan(x: str) -> str: + return termcolor.colored(str(x), color="cyan") + + @staticmethod + def yellow(x: str) -> str: + return termcolor.colored(str(x), color="yellow") + + +class BufferCnt: + """ + Buffer counter which keeps track of the condition when called and returns True when the condition in met "thres" + amount of times, otherwise returns False. + + Example usage: + buf = BufferCnt(thres=3) + for _ in range(5): + if buf(random.random() > 0.5): + print("We got lucky 3 times out of 5.") + + Args: + thres (int): The amount of times the expression needs to be True before returning True. + reset_over_thres (bool): Whether to reset the buffer after returning True. + """ + + def __init__(self, thres=10, reset_over_thres=False): + self._cnt = 0 + self.thres = thres + self.reset_over_thres = reset_over_thres + + def __call__(self, expre, thres=None): + if expre is True: + self._cnt += 1 + else: + self._cnt = 0 + + if thres is None: + thres = self.thres + + if self._cnt >= thres: + if self.reset_over_thres: + self.reset() + return True + + return False + + @property + def cnt(self): + return self._cnt + + def reset(self): + self._cnt = 0 + + +def get_local_tensor_if_DTensor(tensor: torch.Tensor | DTensor) -> torch.tensor: + if isinstance(tensor, DTensor): + local = tensor.to_local() + # As per PyTorch documentation, if the communication is not finished yet, we need to wait for it to finish + # https://pytorch.org/docs/stable/distributed.tensor.html#torch.distributed.tensor.DTensor.to_local + if isinstance(local, AsyncCollectiveTensor): + return local.wait() + else: + return local + return tensor + + +def disabled_train(self: Any, mode: bool = True) -> Any: + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" + return self + + +def count_params(model: nn.Module, verbose=False) -> int: + total_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + if verbose: + print(f"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.") + return total_params + + +def expand_dims_like(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + while x.dim() != y.dim(): + x = x.unsqueeze(-1) + return x + + +def download_from_s3_with_cache( + s3_path: str, + cache_fp: Optional[str] = None, + cache_dir: Optional[str] = None, + rank_sync: bool = True, + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, +) -> str: + """download data from S3 with optional caching. + + This function first attempts to load the data from a local cache file. If + the cache file doesn't exist, it downloads the data from S3 to the cache + location. Caching is performed in a rank-aware manner + using `distributed.barrier()` to ensure only one download occurs across + distributed workers (if `rank_sync` is True). + + Args: + s3_path (str): The S3 path of the data to load. + cache_fp (str, optional): The path to the local cache file. If None, + a filename will be generated based on `s3_path` within `cache_dir`. + cache_dir (str, optional): The directory to store the cache file. If + None, the environment variable `COSMOS_CACHE_DIR` (defaulting + to "/tmp") will be used. + rank_sync (bool, optional): Whether to synchronize download across + distributed workers using `distributed.barrier()`. Defaults to True. + backend_args (dict, optional): The backend arguments passed to easy_io to construct the backend. + backend_key (str, optional): The backend key passed to easy_io to registry the backend or retrieve the backend if it is already registered. + + Returns: + cache_fp (str): The path to the local cache file. + + Raises: + FileNotFoundError: If the data cannot be found in S3 or the cache. + """ + cache_dir = os.environ.get("TORCH_HOME") if cache_dir is None else cache_dir + cache_dir = ( + os.environ.get("COSMOS_CACHE_DIR", os.path.expanduser("~/.cache/cosmos")) if cache_dir is None else cache_dir + ) + cache_dir = os.path.expanduser(cache_dir) + if cache_fp is None: + cache_fp = os.path.join(cache_dir, s3_path.replace("s3://", "")) + if not cache_fp.startswith("/"): + cache_fp = os.path.join(cache_dir, cache_fp) + + if distributed.get_rank() == 0: + if os.path.exists(cache_fp): + # check the size of cache_fp + if os.path.getsize(cache_fp) < 1: + os.remove(cache_fp) + log.warning(f"Removed empty cache file {cache_fp}.") + + if rank_sync: + if not os.path.exists(cache_fp): + log.critical(f"Local cache {cache_fp} Not exist! Downloading {s3_path} to {cache_fp}.") + log.info(f"backend_args: {backend_args}") + log.info(f"backend_key: {backend_key}") + + easy_io.copyfile_to_local( + s3_path, cache_fp, dst_type="file", backend_args=backend_args, backend_key=backend_key + ) + log.info(f"Downloaded {s3_path} to {cache_fp}.") + else: + log.info(f"Local cache {cache_fp} already exist! {s3_path} -> {cache_fp}.") + + distributed.barrier() + else: + if not os.path.exists(cache_fp): + easy_io.copyfile_to_local( + s3_path, cache_fp, dst_type="file", backend_args=backend_args, backend_key=backend_key + ) + + log.info(f"Downloaded {s3_path} to {cache_fp}.") + return cache_fp + + +def load_from_s3_with_cache( + s3_path: str, + cache_fp: Optional[str] = None, + cache_dir: Optional[str] = None, + rank_sync: bool = True, + backend_args: Optional[dict] = None, + backend_key: Optional[str] = None, + easy_io_kwargs: Optional[dict] = None, +) -> Any: + """Loads data from S3 with optional caching. + + This function first attempts to load the data from a local cache file. If + the cache file doesn't exist, it downloads the data from S3 to the cache + location and then loads it. Caching is performed in a rank-aware manner + using `distributed.barrier()` to ensure only one download occurs across + distributed workers (if `rank_sync` is True). + + Args: + s3_path (str): The S3 path of the data to load. + cache_fp (str, optional): The path to the local cache file. If None, + a filename will be generated based on `s3_path` within `cache_dir`. + cache_dir (str, optional): The directory to store the cache file. If + None, the environment variable `COSMOS_CACHE_DIR` (defaulting + to "/tmp") will be used. + rank_sync (bool, optional): Whether to synchronize download across + distributed workers using `distributed.barrier()`. Defaults to True. + backend_args (dict, optional): The backend arguments passed to easy_io to construct the backend. + backend_key (str, optional): The backend key passed to easy_io to registry the backend or retrieve the backend if it is already registered. + + Returns: + Any: The loaded data from the S3 path or cache file. + + Raises: + FileNotFoundError: If the data cannot be found in S3 or the cache. + """ + cache_fp = download_from_s3_with_cache(s3_path, cache_fp, cache_dir, rank_sync, backend_args, backend_key) + + if easy_io_kwargs is None: + easy_io_kwargs = {} + return easy_io.load(cache_fp, **easy_io_kwargs) + + +def sync_s3_dir_to_local( + s3_dir: str, + s3_credential_path: str, + cache_dir: Optional[str] = None, + rank_sync: bool = True, +) -> str: + """ + Download an entire directory from S3 to the local cache directory. + + Args: + s3_dir (str): The AWS S3 directory to download. + s3_credential_path (str): The path to the AWS S3 credentials file. + rank_sync (bool, optional): Whether to synchronize download across + distributed workers using `distributed.barrier()`. Defaults to True. + cache_dir (str, optional): The cache folder to sync the S3 directory to. + If None, the environment variable `COSMOS_CACHE_DIR` (defaulting + to "~/.cache/cosmos") will be used. + + Returns: + local_dir (str): The path to the local directory. + """ + if not s3_dir.startswith("s3://"): + # If the directory exists locally, return the local path + assert os.path.exists(s3_dir), f"{s3_dir} is not a S3 path or a local path." + return s3_dir + + # Load AWS credentials from the file + with open(s3_credential_path, "r") as f: + credentials = json.load(f) + + # Create an S3 client + s3 = boto3.client( + "s3", + **credentials, + ) + + # Parse the S3 URL + parsed_url = urlparse(s3_dir) + source_bucket = parsed_url.netloc + source_prefix = parsed_url.path.lstrip("/") + + # If the local directory is not specified, use the default cache directory + cache_dir = ( + os.environ.get("COSMOS_CACHE_DIR", os.path.expanduser("~/.cache/cosmos")) if cache_dir is None else cache_dir + ) + cache_dir = os.path.expanduser(cache_dir) + Path(cache_dir).mkdir(parents=True, exist_ok=True) + + # List objects in the bucket with the given prefix + response = s3.list_objects_v2(Bucket=source_bucket, Prefix=source_prefix) + # Download each matching object + for obj in response.get("Contents", []): + if obj["Key"].startswith(source_prefix): + # Create the full path for the destination file, preserving the directory structure + rel_path = os.path.relpath(obj["Key"], source_prefix) + dest_path = os.path.join(cache_dir, source_prefix, rel_path) + + # Ensure the directory exists + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + + # Check if the file already exists + if os.path.exists(dest_path): + continue + else: + log.info(f"Downloading {obj['Key']} to {dest_path}") + # Download the file + if not rank_sync or distributed.get_rank() == 0: + s3.download_file(source_bucket, obj["Key"], dest_path) + if rank_sync: + distributed.barrier() + local_dir = os.path.join(cache_dir, source_prefix) + return local_dir diff --git a/utils/model.py b/utils/model.py new file mode 100644 index 0000000000000000000000000000000000000000..40e7c3057f74a4fc2f731b8a78dab4a4a11b84f1 --- /dev/null +++ b/utils/model.py @@ -0,0 +1,136 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +import torch + +from utils.lazy_config import LazyDict, instantiate + + +class Model(torch.nn.Module): + """The base model class. It is inherited from torch.nn.Module. + + All models should inherit Model. It should include the implementions for all the + computation graphs. All inheriting child classes should implement the following methods: + - training_step(): The training step of the model, including the loss computation. + - validation_step(): The validation step of the model, including the loss computation. + - forward(): The computation graph for model inference. + The following methods have default implementations in Model: + - init_optimizer_scheduler(): Creates the optimizer and scheduler for the model. + """ + + def __init__(self) -> None: + super().__init__() + self.on_model_init_start(set_barrier=False) + + def init_optimizer_scheduler( + self, optimizer_config: LazyDict, scheduler_config: LazyDict + ) -> tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler]: + """Creates the optimizer and scheduler for the model. + + Args: + config_model (ModelConfig): The config object for the model. + + Returns: + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + """ + optimizer_config.params = self.parameters() + optimizer = instantiate(optimizer_config) + scheduler_config.optimizer = optimizer + scheduler = instantiate(scheduler_config) + return optimizer, scheduler + + def training_step( + self, data_batch: dict[str, torch.Tensor], iteration: int + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + """The training step of the model, including the loss computation. + + Args: + data (dict[str, torch.Tensor]): Data batch (dictionary of tensors). + iteration (int): Current iteration number. + + Returns: + output_batch (dict[str, torch.Tensor]): Auxiliary model output from the training batch. + loss (torch.Tensor): The total loss for backprop (weighted sum of various losses). + """ + raise NotImplementedError + + @torch.no_grad() + def validation_step( + self, data_batch: dict[str, torch.Tensor], iteration: int + ) -> tuple[dict[str, torch.Tensor], torch.Tensor]: + """The validation step of the model, including the loss computation. + + Args: + data (dict[str, torch.Tensor]): Data batch (dictionary of tensors). + iteration (int): Current iteration number. + + Returns: + output_batch (dict[str, torch.Tensor]): Auxiliary model output from the validation batch. + loss (torch.Tensor): The total loss (weighted sum of various losses). + """ + raise NotImplementedError + + @torch.inference_mode() + def forward(self, *args: Any, **kwargs: Any) -> Any: + """The computation graph for model inference. + + Args: + *args: Whatever you decide to pass into the forward method. + **kwargs: Keyword arguments are also possible. + + Return: + Your model's output. + """ + raise NotImplementedError + + def on_model_init_start(self, set_barrier=False) -> None: + return + + def on_model_init_end(self, set_barrier=False) -> None: + return + + def on_train_start(self, memory_format: torch.memory_format = torch.preserve_format) -> None: + """The model preparation before the training is launched + + Args: + memory_format (torch.memory_format): Memory format of the model. + """ + pass + + def on_before_zero_grad( + self, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler.LRScheduler, iteration: int + ) -> None: + """Hook before zero_grad() is called. + + Args: + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + iteration (int): Current iteration number. + """ + pass + + def on_after_backward(self, iteration: int = 0) -> None: + """Hook after loss.backward() is called. + + This method is called immediately after the backward pass, allowing for custom operations + or modifications to be performed on the gradients before the optimizer step. + + Args: + iteration (int): Current iteration number. + """ + pass diff --git a/utils/pai_batch.py b/utils/pai_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..b87add3178c92f5dccf3de4d0a421d33a0f14b2e --- /dev/null +++ b/utils/pai_batch.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Shared processed-PAI batch contract for training and inference.""" + +import numpy as np +import torch + + +def make_pai_batch(sample, length, *, input_frames=None, hdmap=True, boxes=True, device="cpu"): + ranges = sample["range_m"][:length] + valid = sample["valid_mask"][:length] & np.isfinite(ranges) & (ranges >= 2.5) & (ranges <= 100) + video = np.where(valid, 2 * (ranges - 2.5) / 97.5 - 1, -1).astype(np.float32) + if input_frames is not None: + video[input_frames:] = -1 # Never expose future GT during inference. + poses = sample["pose_sensor_start_end"][:length] + tensor = lambda value: torch.as_tensor(value, device=device) + batch = dict( + video=tensor(video)[None, None], is_preprocessed=True, + lidar_hdmap=tensor(sample["hdmap"][:length].astype(np.float32))[None, None] + if hdmap else torch.full((1, 1, length, 128, 1024), -1., device=device), + sensor_dataset_id=tensor([0]).long(), sensor_ray_directions=tensor(sample["ray_directions"])[None].float(), + sensor_depth_bounds=tensor([[2.5, 100.0]]).float(), + lidar_to_world=tensor(poses[:, 0])[None].float(), + pose_sensor_start_end=tensor(np.linalg.inv(poses[:, 1]) @ poses[:, 0])[None].float(), + fps=tensor([10.0]), num_frames=tensor([length]), image_size=tensor([[128, 1024]]), + padding_mask=torch.zeros(1, 1, 128, 1024, device=device), + t5_text_embeddings=torch.zeros(1, 512, 1024, device=device), + t5_text_mask=torch.zeros(1, 512, device=device), + ) + batch["t5_text_mask"][:, 0] = 1 + if boxes: + valid_boxes = sample["box_valid"][:length].astype(bool) + tracks = sample["box_track_id"][:length] + dynamic_ids = np.unique(tracks[valid_boxes & sample["box_is_moving"][:length]]) + dynamic = valid_boxes & np.isin(tracks, dynamic_ids) + for key in ("object_to_world", "lwh", "track_id"): + array = sample[f"box_{key}"][:length] + packed = np.zeros((length, 256) + array.shape[2:], dtype=array.dtype) + if key == "track_id": + packed.fill(-1) + for t in range(length): + selected = array[t, dynamic[t]] + if len(selected) > 256: + raise ValueError("More than 256 dynamic boxes in a sweep") + packed[t, :len(selected)] = selected + batch[f"moving_box_{key}"] = tensor(packed)[None] + batch["moving_box_valid"] = tensor(np.arange(256)[None] < dynamic.sum(axis=1)[:, None])[None] + return batch diff --git a/utils/parallel_state_helper.py b/utils/parallel_state_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..f531ab00c9d45a7dbf5015a43147bf635d72c5ec --- /dev/null +++ b/utils/parallel_state_helper.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from megatron.core import parallel_state + + +def is_tp_cp_pp_rank0(): + return ( + parallel_state.get_tensor_model_parallel_rank() == 0 + and parallel_state.get_pipeline_model_parallel_rank() == 0 + and parallel_state.get_context_parallel_rank() == 0 + ) diff --git a/utils/per_row_norm.py b/utils/per_row_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..c8235ead1b72758aa98155558a3b8e858c8f9758 --- /dev/null +++ b/utils/per_row_norm.py @@ -0,0 +1,299 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Per-row depth normalization helpers (vendored, no external deps). + +The lidar range map is heavily heteroscedastic across elevation rows: ground +rows have std ~1 m, mid rows ~23 m. Plain min-max normalization to ``[-1, 1]`` +preserves this disparity, so the model's first layers waste capacity learning +per-row scale. This module standardizes per-row residuals around precomputed +training-set statistics. + +The pipeline is: + + metric depth -> ``normalize_range_map`` -> ``[-1, 1]`` space (existing) + -> :func:`apply_per_row_norm` -> unit-variance per row (new) + +Inversion: + + unit-variance per row -> :func:`invert_per_row_norm` -> ``[-1, 1]`` space + -> ``unnormalize_range_map`` -> metric depth (existing) + +Stats are loaded from a ``.npz`` with per-row ``means`` / ``stds`` in metric +units (e.g. ``scripts/analyze_per_row_depth.py`` or r2flow's depth-stats dump) +and converted to the dataset's normalized space via the same +``min_range``/``max_range``/``min_value`` used by ``normalize_range_map``. + +Smoothing the raw per-row stats is recommended (default +``smooth_sigma = 5.0`` rows): adjacent-row stats become nearly identical, so +objects spanning multiple rows are not distorted by the normalization. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from typing import Optional + +import numpy as np +import torch +import torch.nn.functional as F + + +def _gaussian_kernel(sigma: float, radius: int | None = None) -> np.ndarray: + if radius is None: + radius = max(1, int(round(3.0 * sigma))) + x = np.arange(-radius, radius + 1, dtype=np.float64) + k = np.exp(-(x ** 2) / (2.0 * sigma ** 2)) + return (k / k.sum()).astype(np.float32) + + +def _gaussian_smooth_1d(arr: np.ndarray, sigma: float) -> np.ndarray: + """Reflect-pad and convolve a 1D array with a Gaussian kernel.""" + if sigma <= 0: + return arr.astype(np.float32) + kernel = _gaussian_kernel(sigma) + pad = (len(kernel) - 1) // 2 + padded = np.pad(arr.astype(np.float32), pad, mode="edge") + return np.convolve(padded, kernel, mode="valid") + + +def metric_stats_to_normalized( + means_metric: np.ndarray, + stds_metric: np.ndarray, + *, + min_range: float, + max_range: float, + min_value: float = -1.0, + log_depth: bool = False, +) -> tuple[np.ndarray, np.ndarray]: + """Convert per-row (mean, std) to the dataset's ``[-1, 1]`` space. + + The min-max normalization ``(d - min_range) / (max_range - min_range) * 2 - 1`` + is affine, so: + + mean_norm = (mean - min_range) / span * scale - shift_offset + std_norm = std / span * scale + + where ``scale = 2`` and ``shift_offset = 1`` for ``min_value = -1`` (the + project default), and ``scale = 1, shift_offset = 0`` for ``min_value = 0``. + + When ``log_depth=True`` the input ``means_metric`` / ``stds_metric`` are + expected to be the mean / std of ``log(d)`` (since ``mean(log(d)) != + log(mean(d))``), and the affine is taken in log space: + + span = log(max_range) - log(min_range) + mean_norm = (log_mean - log(min_range)) / span * scale - shift + std_norm = log_std / span * scale + """ + if log_depth: + c_min = float(np.log(min_range)) + c_max = float(np.log(max_range)) + else: + c_min = min_range + c_max = max_range + span = c_max - c_min + scale = 2.0 if min_value == -1 else 1.0 + shift = 1.0 if min_value == -1 else 0.0 + means_norm = (means_metric - c_min) / span * scale - shift + stds_norm = stds_metric / span * scale + return means_norm.astype(np.float32), stds_norm.astype(np.float32) + + +@dataclass +class PerRowNormalizer: + """Holds smoothed per-row stats and applies/inverts the normalization. + + The stats are stored in normalized space (i.e. corresponding to ``x`` after + ``normalize_range_map``). Apply happens after the existing min-max + normalization, invert happens before ``unnormalize_range_map``. + """ + means_norm: np.ndarray # shape (H_native,) + stds_norm: np.ndarray # shape (H_native,) + eps: float = 1e-3 # avoid div-by-zero on rows with no valid returns + + @classmethod + def from_npz( + cls, + path: str, + *, + min_range: float, + max_range: float, + min_value: float = -1.0, + smooth_sigma: float = 5.0, + expected_log_depth: bool = False, + ) -> "PerRowNormalizer": + if not os.path.exists(path): + raise FileNotFoundError( + f"per-row stats file not found: {path}. Run " + f"`python scripts/analyze_per_row_depth.py` to generate it." + ) + data = np.load(path) + if "means" not in data or "stds" not in data: + raise KeyError( + f"per-row stats file {path} is missing 'means' / 'stds' keys " + f"(got {list(data.keys())})." + ) + # Validate that the stats file's depth-mode matches the dataset config. + # Older stats files (no ``log_depth`` key) are assumed to be linear-metric + # for backward compatibility. + stats_log_depth = bool(data["log_depth"]) if "log_depth" in data else False + if stats_log_depth != expected_log_depth: + raise ValueError( + f"per-row stats file {path} has log_depth={stats_log_depth} but " + f"the dataset config expects log_depth={expected_log_depth}. " + f"Regenerate the stats with the matching depth mode." + ) + means = data["means"].astype(np.float32) + stds = data["stds"].astype(np.float32) + # Replace NaNs (rows with no valid returns) with neutral values so the + # transform is a no-op there. Such rows usually have no model loss + # anyway because the validity mask zeros them out. + nan_mask = np.isnan(means) | np.isnan(stds) | (stds <= 0) + if nan_mask.any(): + # Use nearest non-NaN neighbour for a reasonable extrapolation, + # falling back to global mean/std if the entire array is NaN. + valid = ~nan_mask + if not valid.any(): + global_mean = float(np.nanmean(means)) if not np.isnan(means).all() else 0.0 + global_std = float(np.nanmean(stds)) if not np.isnan(stds).all() else 1.0 + means = np.full_like(means, global_mean) + stds = np.full_like(stds, global_std) + else: + idx_valid = np.where(valid)[0] + for i in np.where(nan_mask)[0]: + j = idx_valid[np.argmin(np.abs(idx_valid - i))] + means[i] = means[j] + stds[i] = stds[j] + + # Smooth before converting to normalized space (smoothing is in metric + # units; equivalent up to the affine transform anyway). + means_smooth = _gaussian_smooth_1d(means, smooth_sigma) + stds_smooth = _gaussian_smooth_1d(stds, smooth_sigma) + + means_norm, stds_norm = metric_stats_to_normalized( + means_smooth, stds_smooth, + min_range=min_range, max_range=max_range, min_value=min_value, + log_depth=stats_log_depth, + ) + return cls(means_norm=means_norm, stds_norm=stds_norm) + + # ------------------------------------------------------------------ + # Public ops + # ------------------------------------------------------------------ + + def _resample(self, vec: np.ndarray, h: int) -> np.ndarray: + """Resample a (H_native,) stats vector to (h,) via nearest-exact, so + per-row identity is preserved when the dataset / model resolution + differs from the analysis resolution.""" + if vec.shape[0] == h: + return vec + x = torch.from_numpy(vec).view(1, 1, 1, -1).float() + y = F.interpolate(x, size=(1, h), mode="nearest-exact") + return y.view(-1).numpy() + + def _resample_torch(self, vec: np.ndarray, h: int, device) -> torch.Tensor: + if vec.shape[0] == h: + return torch.from_numpy(vec).to(device) + x = torch.from_numpy(vec).view(1, 1, 1, -1).float() + y = F.interpolate(x, size=(1, h), mode="nearest-exact").view(-1) + return y.to(device) + + def apply_numpy(self, x: np.ndarray) -> np.ndarray: + """Standardize a numpy array of shape ``(..., H, W)``.""" + H = x.shape[-2] + m = self._resample(self.means_norm, H) + s = self._resample(self.stds_norm, H) + m = m.reshape((1,) * (x.ndim - 2) + (H, 1)) + s = s.reshape((1,) * (x.ndim - 2) + (H, 1)) + return (x - m) / (s + self.eps) + + def invert_numpy(self, x: np.ndarray) -> np.ndarray: + H = x.shape[-2] + m = self._resample(self.means_norm, H) + s = self._resample(self.stds_norm, H) + m = m.reshape((1,) * (x.ndim - 2) + (H, 1)) + s = s.reshape((1,) * (x.ndim - 2) + (H, 1)) + return x * (s + self.eps) + m + + def apply_torch(self, x: torch.Tensor) -> torch.Tensor: + """Standardize a torch tensor of shape ``(..., H, W)``.""" + H = x.shape[-2] + m = self._resample_torch(self.means_norm, H, x.device).to(x.dtype) + s = self._resample_torch(self.stds_norm, H, x.device).to(x.dtype) + view = (1,) * (x.ndim - 2) + (H, 1) + return (x - m.view(*view)) / (s.view(*view) + self.eps) + + def invert_torch(self, x: torch.Tensor) -> torch.Tensor: + H = x.shape[-2] + m = self._resample_torch(self.means_norm, H, x.device).to(x.dtype) + s = self._resample_torch(self.stds_norm, H, x.device).to(x.dtype) + view = (1,) * (x.ndim - 2) + (H, 1) + return x * (s.view(*view) + self.eps) + m.view(*view) + + +_normalizer_cache: dict = {} + + +def get_per_row_normalizer( + per_row_normalize: bool, + per_row_stats_path: str, + *, + min_range: float, + max_range: float, + min_value: float = -1.0, + smooth_sigma: float = 5.0, + log_depth: bool = False, +) -> Optional[PerRowNormalizer]: + """Build (or reuse a cached) :class:`PerRowNormalizer`. + + Returns ``None`` when ``per_row_normalize`` is False, so callers can use the + result as a drop-in argument to :func:`apply_per_row_norm` / + :func:`invert_per_row_norm` even when per-row norm is disabled. + """ + if not per_row_normalize: + return None + if not per_row_stats_path: + raise ValueError( + "per_row_normalize=True requires per_row_stats_path to point to a " + ".npz with per-row 'means'/'stds'." + ) + key = ( + per_row_stats_path, + float(min_range), float(max_range), float(min_value), + float(smooth_sigma), bool(log_depth), + ) + if key not in _normalizer_cache: + _normalizer_cache[key] = PerRowNormalizer.from_npz( + per_row_stats_path, + min_range=float(min_range), + max_range=float(max_range), + min_value=float(min_value), + smooth_sigma=float(smooth_sigma), + expected_log_depth=bool(log_depth), + ) + return _normalizer_cache[key] + + +def apply_per_row_norm( + x: np.ndarray | torch.Tensor, + normalizer: Optional[PerRowNormalizer], +) -> np.ndarray | torch.Tensor: + """Apply per-row normalization if ``normalizer`` is provided; else identity.""" + if normalizer is None: + return x + if isinstance(x, torch.Tensor): + return normalizer.apply_torch(x) + return normalizer.apply_numpy(x) + + +def invert_per_row_norm( + x: np.ndarray | torch.Tensor, + normalizer: Optional[PerRowNormalizer], +) -> np.ndarray | torch.Tensor: + """Invert per-row normalization if ``normalizer`` is provided; else identity.""" + if normalizer is None: + return x + if isinstance(x, torch.Tensor): + return normalizer.invert_torch(x) + return normalizer.invert_numpy(x) diff --git a/utils/processed_pai.py b/utils/processed_pai.py new file mode 100644 index 0000000000000000000000000000000000000000..ed7d64bf0fee3d73642d2657e3c1373be465252b --- /dev/null +++ b/utils/processed_pai.py @@ -0,0 +1,83 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Small NPZ training adapter using the same PAI contract as the quickstarts.""" + +import os +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader, Dataset, DistributedSampler, default_collate + +from utils.pai_batch import make_pai_batch + + +class ProcessedPAI(Dataset): + def __init__(self, root, frames, tokenizer=False): + self.paths = sorted(Path(root).rglob("*.npz")) + if not self.paths: + raise FileNotFoundError(f"No processed samples under {root}; run prepare_pai_bidir.py first") + self.frames = frames + self.tokenizer = tokenizer + + def __len__(self): + return len(self.paths) + + def __getitem__(self, index): + path = self.paths[index] + with np.load(path, allow_pickle=False) as data: + sample = {key: data[key] for key in data.files} + ranges = sample["range_m"] + if ranges.shape[1:] != (128, 1024) or len(ranges) < self.frames: + raise ValueError(f"{path}: need {self.frames} real 128x1024 sweeps") + if (str(sample["dataset"]) != "pandar" or int(sample["sensor_dataset_id"]) != 0 + or float(sample["min_range_m"]) != 2.5 or float(sample["max_range_m"]) != 100 + or float(sample["fps"]) != 10 or bool(sample["has_prepend"])): + raise ValueError(f"{path}: sample does not match the PAI release contract") + start = int(torch.randint(len(ranges) - self.frames + 1, ()).item()) + temporal = ("range_m", "valid_mask", "hdmap", "pose_sensor_start_end", + "box_valid", "box_object_to_world", "box_lwh", "box_track_id", "box_is_moving") + for key in temporal: + if key in sample: + sample[key] = sample[key][start:start + self.frames] + if self.tokenizer: + ranges = sample["range_m"] + valid = sample["valid_mask"] & np.isfinite(ranges) & (ranges >= 2.5) & (ranges <= 100) + video = np.where(valid, 2 * (ranges - 2.5) / 97.5 - 1, -1).astype(np.float32) + # Match tokenizer training's repeated first sweep, not the DiT layout. + video = torch.from_numpy(np.concatenate((video[:1], video)))[None] + mask = torch.from_numpy(np.concatenate((valid[:1], valid)))[None].float() + batch = dict(video=video, recon_target=video.clone(), loss_mask=mask, + loss_mask_is_validity=True, sensor_dataset_id=torch.tensor(0), + sensor_ray_directions=torch.from_numpy(sample["ray_directions"]).float(), + sensor_depth_bounds=torch.tensor([2.5, 100.])) + else: + batch = make_pai_batch(sample, self.frames) + batch = {key: value[0] if torch.is_tensor(value) else value for key, value in batch.items()} + batch.update(clip_name=path.stem, data_type="lidar", __key__=path.stem) + return batch + + +def _collate(samples): + batch = default_collate(samples) + for key in ("is_preprocessed", "loss_mask_is_validity"): + if key in batch: + batch[key] = True + return batch + + +def build_loader(root, frames=21, tokenizer=False, validation=False, num_workers=2, batch_size=1): + dataset = ProcessedPAI(root, frames, tokenizer) + sampler = DistributedSampler(dataset, shuffle=not validation) + return DataLoader(dataset, batch_size=batch_size, sampler=sampler, num_workers=num_workers, + pin_memory=True, drop_last=False, collate_fn=_collate) + + +def loader_config(*, tokenizer=False, validation=False): + from utils.lazy_config import LazyCall as L + + root = os.environ.get("LIDARVERSE_PAI_VAL_DATA" if validation else "LIDARVERSE_PAI_TRAIN_DATA", + "data/bidir_quick_start/nvidia_pai") + return L(build_loader)(root=root, frames=8 if tokenizer else 21, tokenizer=tokenizer, + validation=validation, num_workers=2, batch_size=1) diff --git a/utils/scheduler.py b/utils/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..e45eb96a94208ad86348a785ab799bd8e71c2c7c --- /dev/null +++ b/utils/scheduler.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import List + +import torch + + +class WarmupLambdaLR(torch.optim.lr_scheduler.LambdaLR): + def __init__(self, optimizer, warmup, last_epoch=-1, verbose=False): + # Define the lambda function based on the warmup period + self.warmup = warmup + + def lr_lambda(epoch): + # Increase lr linearly for the first 'warmup' epochs + if epoch < warmup: + return float(epoch + 1) / warmup + # After 'warmup' epochs, keep lr constant + return 1.0 + + # Initialize the parent class with the generated lr_lambda + super(WarmupLambdaLR, self).__init__(optimizer, lr_lambda, last_epoch) + + +# cosine lr decay scheduler with warmup from https://github.com/karpathy/nanoGPT/blob/master/train.py#L228 +class WarmupCosineLR(torch.optim.lr_scheduler.LRScheduler): + def __init__( + self, + optimizer: torch.optim.Optimizer, + warmup_iters: int, + lr_decay_iters: int, + min_lr: float, + last_epoch: int = -1, + ): + self.warmup_iters = warmup_iters + self.lr_decay_iters = lr_decay_iters + self.min_lr = min_lr + super().__init__(optimizer, last_epoch) + + def get_lr(self) -> List[float]: + # 1) linear warmup for warmup_iters steps + if self.last_epoch < self.warmup_iters: + return [base_lr * self.last_epoch / self.warmup_iters for base_lr in self.base_lrs] + # 2) if it > lr_decay_iters, return min learning rate + if self.last_epoch > self.lr_decay_iters: + return [self.min_lr for _ in self.base_lrs] + # 3) in between, use cosine decay down to min learning rate + decay_ratio = (self.last_epoch - self.warmup_iters) / (self.lr_decay_iters - self.warmup_iters) + assert 0 <= decay_ratio <= 1 + coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1 + return [self.min_lr + coeff * (base_lr - self.min_lr) for base_lr in self.base_lrs] diff --git a/utils/trainer.py b/utils/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f15f5d8a7ca328d5bdf6dd60f11cb8cd6879b635 --- /dev/null +++ b/utils/trainer.py @@ -0,0 +1,297 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import os +import signal + +import torch +import torch.distributed as dist +import torch.utils.data +from megatron.core import parallel_state + +from utils import callback, distributed, ema, log, misc +from utils.checkpointer import Checkpointer +from utils.lazy_config import LazyConfig, instantiate +from utils.model import Model + + +class Trainer: + """The base trainer class. + + All trainers should inherit Trainer. It contains the basic functionality for model training + (particularly suited for large-scale training), including data parallel (DDP/FSDP), model weight average (EMA), + mixed-precision training (fp16/bf16). + + Attributes: + checkpointer (Checkpointer): checkpointer object to save/load model weights and optimizer states. + training_timer (misc.Timer): Timer object to time code blocks and functions. + """ + + def __init__(self, config): + """Constructor of the trainer. + + Args: + config (Config): The config object for the codebase. + """ + super().__init__() + self.config = config + # Set up the distributed computing environment. + with misc.timer("init_distributed"): + distributed.init() + # Set up parallel states. + if hasattr(config.model, "context_parallel_size"): + if config.model_parallel.context_parallel_size > 1: + raise ValueError( + "Both config.model.context_parallel_size and config.model_parallel.context_parallel_size are set. " + "config.model.context_parallel_size is deprecated. Please only set config.model_parallel.context_parallel_size." + ) + else: + log.critical( + "Using deprecated config.model.context_parallel_size. Please use config.model_parallel.context_parallel_size instead." + ) + config.model_parallel.context_parallel_size = config.model.context_parallel_size + parallel_state.initialize_model_parallel( + pipeline_model_parallel_size=config.model_parallel.pipeline_model_parallel_size, + tensor_model_parallel_size=config.model_parallel.tensor_model_parallel_size, + context_parallel_size=config.model_parallel.context_parallel_size, + ) + # `config.model_parallel.sequence_parallel` is a bool that indicates whether to use sequence parallelism. + # It is not part of the original `parallel_state` API, so we need to set it manually. + parallel_state.sequence_parallel = config.model_parallel.sequence_parallel + if parallel_state.sequence_parallel: + os.environ["CUDA_DEVICE_MAX_CONNECTIONS"] = "1" + + # Create the local job directory, save the config file, and pipe to a local log. + if distributed.is_rank0(): + os.makedirs(config.job.path_local, exist_ok=True) + # Save the config as YAML for reproducibility and readability. + LazyConfig.save_yaml(config, f"{config.job.path_local}/config.yaml") + dist.barrier() + log.init_loguru_file(f"{config.job.path_local}/stdout.log") + if distributed.is_rank0(): + # Print important environment variables and the effective config. + log.info("Config:\n" + config.pretty_print(use_color=True)) + misc.print_environ_variables(["TORCH_HOME", "OUTPUT_ROOT"]) + # Set the random seed. If multi-GPU, different ranks are set with different seeds. + misc.set_random_seed(seed=config.trainer.seed, by_rank=True) + # Initialize cuDNN. + torch.backends.cudnn.deterministic = config.trainer.cudnn.deterministic + torch.backends.cudnn.benchmark = config.trainer.cudnn.benchmark + # Floating-point precision settings. + torch.backends.cudnn.allow_tf32 = torch.backends.cuda.matmul.allow_tf32 = True + # Initialize the callback functions. + self.callbacks = callback.CallBackGroup(config=config, trainer=self) + # Initialize the model checkpointer. + if config.checkpoint.type is None: + self.checkpointer = Checkpointer(config.checkpoint, config.job, callbacks=self.callbacks) + else: + self.checkpointer: Checkpointer = instantiate( + config.checkpoint.type, config.checkpoint, config.job, callbacks=self.callbacks + ) + # Initialize the timer for speed benchmarking. + self.training_timer = misc.TrainingTimer() + # Send a TimeoutError if a training step takes over timeout_period seconds. + signal.signal(signal.SIGALRM, functools.partial(misc.timeout_handler, config.trainer.timeout_period)) # type: ignore + + @staticmethod + def _log_param_count(model: Model) -> None: + total = sum(p.numel() for p in model.parameters()) + trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) + log.info(f"Model total params: {total / 1e6:.2f}M (trainable: {trainable / 1e6:.2f}M)") + for name, child in model.named_children(): + n = sum(p.numel() for p in child.parameters()) + if n > 0: + log.info(f" {name}: {n / 1e6:.2f}M") + + def train( + self, + model: Model, + dataloader_train: torch.utils.data.DataLoader, + dataloader_val: torch.utils.data.DataLoader, + ) -> None: + """The training function. + + Args: + model (Model): The PyTorch model. + dataloader_train (torch.utils.data.DataLoader): The training data loader. + dataloader_val (torch.utils.data.DataLoader): The validation data loader. + """ + # Leaving this for backward compability for now, but we can think about moving this to model.on_train_start for all models. + model = model.to("cuda", memory_format=self.config.trainer.memory_format) # type: ignore + model.on_train_start(self.config.trainer.memory_format) + self._log_param_count(model) + + # Initialize the optimizer, scheduler, and grad_scaler. + self.callbacks.on_optimizer_init_start() + optimizer, scheduler = model.init_optimizer_scheduler(self.config.optimizer, self.config.scheduler) + grad_scaler = torch.amp.GradScaler("cuda", **self.config.trainer.grad_scaler_args) + self.callbacks.on_optimizer_init_end() + # Load the model checkpoint and get the starting iteration number. + iteration = self.checkpointer.load(model, optimizer, scheduler, grad_scaler) + grad_accum_iter = 0 + log.critical(f"Distributed parallelism mode: {self.config.trainer.distributed_parallelism}") + if self.config.trainer.distributed_parallelism == "ddp": + # Create a DDP model wrapper. + model_ddp = distributed.parallel_model_wrapper(self.config.trainer.ddp, model) + elif self.config.trainer.distributed_parallelism == "fsdp": + model_ddp = model + else: + raise ValueError(f"Unknown distributed parallelism mode: {self.config.trainer.distributed_parallelism}") + log.info("Starting training...") + self.callbacks.on_train_start(model, iteration=iteration) + # Initial validation. + if self.config.trainer.run_validation and iteration == 0: + self.validate(model, dataloader_val, iteration=iteration) + _end_training = False + while True: + dataloader_train_iter = iter(dataloader_train) + while True: + self.callbacks.on_before_dataloading(iteration) + with self.training_timer("dataloader_train"): + try: + data_batch = next(dataloader_train_iter) + for k in data_batch.keys(): + if torch.is_tensor(data_batch[k]): + data_batch[k] = data_batch[k].cuda() + except StopIteration: + break + self.callbacks.on_after_dataloading(iteration) + # If max_iter is reached, exit the training loop. + if iteration >= self.config.trainer.max_iter: + _end_training = True + break + # Move all tensors in the data batch to GPU device. + data_batch = misc.to(data_batch, device="cuda") + # The actual training step. + self.callbacks.on_training_step_start(model, data_batch, iteration=iteration) + if not model.training: + model_ddp.train() + assert model_ddp.training, "model_ddp is not in training mode." + assert model.training, "model is not in training mode." + output_batch, loss, grad_accum_iter = self.training_step( + model_ddp, + optimizer, + scheduler, + grad_scaler, + data_batch, + iteration=iteration, + grad_accum_iter=grad_accum_iter, + ) + # Do the following when an actual optimizer (update) step has been made. + iteration += 1 + # Save checkpoint. + if iteration % self.config.checkpoint.save_iter == 0: + async_saving = getattr(self.config.checkpoint, "async_saving", True) + self.checkpointer.save( + model, optimizer, scheduler, grad_scaler, iteration=iteration, async_saving=async_saving + ) + self.callbacks.on_training_step_end(model, data_batch, output_batch, loss, iteration=iteration) + # Validation. + if self.config.trainer.run_validation and iteration % self.config.trainer.validation_iter == 0: + self.validate(model, dataloader_val, iteration=iteration) + # This iteration is successful; reset the timeout signal. + signal.alarm(self.config.trainer.timeout_period) + if _end_training: + break + log.success("Done with training.") + if iteration % self.config.checkpoint.save_iter != 0: + async_saving = getattr(self.config.checkpoint, "async_saving", True) + self.checkpointer.save( + model, optimizer, scheduler, grad_scaler, iteration=iteration, async_saving=async_saving + ) + self.callbacks.on_train_end(model, iteration=iteration) + self.checkpointer.finalize() + distributed.barrier() + self.callbacks.on_app_end() + + def training_step( + self, + model_ddp: torch.nn.Module | distributed.DistributedDataParallel, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler.LRScheduler, + grad_scaler: torch.amp.GradScaler, + data: dict[str, torch.Tensor], + iteration: int = 0, + grad_accum_iter: int = 0, + ) -> tuple[dict[str, torch.Tensor], torch.Tensor, int]: + """The training step. + + Args: + model_ddp (torch.nn.Module | distributed.DistributedDataParallel): The model with a DDP wrapper or, the bare + module, depending on whether distributed training is enabled or not. + optimizer (torch.optim.Optimizer): The model optimizer. + scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler. + grad_scaler (torch.amp.GradScaler): The gradient scaler (for mixed precision training). + data (dict[str, torch.Tensor]): Data batch (dictionary of tensors). + iteration (int): Current iteration number. + grad_accum_iter (int): Number of gradient accumulation iterations. + + Returns: + output (dict[str, torch.Tensor]): The model output from the training data batch (dictionary of tensors). + loss (torch.Tensor): The total loss of the training data batch. + """ + # Only let DDP sync gradient at the last iteration of the gradient accumulation window + with distributed.ddp_sync_grad(model_ddp, grad_accum_iter == self.config.trainer.grad_accum_iter - 1): + with self.training_timer("forward"): + output_batch, loss = model_ddp.training_step(data, iteration) + self.callbacks.on_before_backward(model_ddp, loss, iteration=iteration) + with self.training_timer("backward"): + loss_scaled = grad_scaler.scale(loss / self.config.trainer.grad_accum_iter) + loss_scaled.backward() + if self.config.trainer.distributed_parallelism == "ddp": + model_ddp.module.on_after_backward() + else: + model_ddp.on_after_backward() + self.callbacks.on_after_backward(model_ddp, iteration=iteration) + grad_accum_iter += 1 + if grad_accum_iter == self.config.trainer.grad_accum_iter: + with self.training_timer("optimizer_step"): + self.callbacks.on_before_optimizer_step( + model_ddp, optimizer, scheduler, grad_scaler, iteration=iteration + ) + grad_scaler.step(optimizer) + grad_scaler.update() + scheduler.step() + self.callbacks.on_before_zero_grad(model_ddp, optimizer, scheduler, iteration=iteration) + if self.config.trainer.distributed_parallelism == "ddp": + model_ddp.module.on_before_zero_grad(optimizer, scheduler, iteration=iteration) + else: + model_ddp.on_before_zero_grad(optimizer, scheduler, iteration=iteration) + optimizer.zero_grad(set_to_none=True) + grad_accum_iter = 0 + return output_batch, loss, grad_accum_iter + + @torch.no_grad() + def validate(self, model: Model, dataloader_val: torch.utils.data.DataLoader, iteration: int = 0) -> None: + """Validate on the full validation dataset. + + Args: + model (Model): The PyTorch model. + dataloader_val (torch.utils.data.DataLoader): The validation data loader. + iteration (int): Current iteration number. + """ + self.callbacks.on_validation_start(model, dataloader_val, iteration=iteration) + model.eval() + # Evaluate on the full validation set. + with ema.ema_scope(model, enabled=model.config.ema.enabled): + for val_iter, data_batch in enumerate(dataloader_val): + if self.config.trainer.max_val_iter is not None and val_iter >= self.config.trainer.max_val_iter: + break + data_batch = misc.to(data_batch, device="cuda") + self.callbacks.on_validation_step_start(model, data_batch, iteration=iteration) + output_batch, loss = model.validation_step(data_batch, iteration) + self.callbacks.on_validation_step_end(model, data_batch, output_batch, loss, iteration=iteration) + self.callbacks.on_validation_end(model, iteration=iteration) diff --git a/utils/visualize/hdmap.py b/utils/visualize/hdmap.py new file mode 100644 index 0000000000000000000000000000000000000000..669e0dc2e74115cb329f4bf67e6ae7e1b31a9321 --- /dev/null +++ b/utils/visualize/hdmap.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Raw-map polylines and translucent actor boxes for PAI quickstart previews. + +Map vertices and actors are in the clip reference frame; sensor poses bring +both into the same ego frame as the generated cloud. This is display-only. +""" + +import json +import tarfile + +import cv2 +import numpy as np + +from utils.visualize.point_cloud import CAMERA_VIEWS, VIZ_KWARGS + +MAP_KINDS = ("lanes", "lanelines", "road_boundaries", "crosswalks", "wait_lines", + "road_markings", "poles", "traffic_signs", "traffic_lights") +MAP_COLORS = ((168, 96, 224), (232, 86, 232), (226, 42, 214), (46, 204, 113), + (255, 214, 44), (255, 214, 44), (150, 92, 224), (131, 175, 155), (252, 157, 155)) +BOX_COLORS = ((74, 144, 240), (52, 106, 204), (46, 204, 113), (255, 196, 44), (176, 184, 196)) +EDGES = ((0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)) + + +def object_class(name): + aliases = {"Bus": "Truck", "Heavy_truck": "Truck", "Train_or_tram_car": "Truck", + "Trolley_bus": "Truck", "Trailer": "Truck", "Vehicle": "Car", + "Automobile": "Car", "Other_vehicle": "Car", "Person": "Pedestrian", "Rider": "Cyclist"} + return {"Car": 0, "Truck": 1, "Pedestrian": 2, "Cyclist": 3}.get(aliases.get(name, name), 4) + + +def _vertices(node): + if isinstance(node, dict): + for key, value in node.items(): + if key == "vertices": + yield np.asarray(value, dtype=np.float32) + else: + yield from _vertices(value) + elif isinstance(node, list): + for item in node: + yield from _vertices(item) + + +def load_vectors(root, clip): + points, offsets, kinds = [], [0], [] + for kind_id, kind in enumerate(MAP_KINDS): + with tarfile.open(root / f"3d_{kind}" / f"{clip}.tar") as archive: + members = [m for m in archive.getmembers() if m.isfile() and m.name.endswith(".json")] + if len(members) != 1: + raise ValueError(f"{clip}/{kind}: expected one vector-map JSON") + with archive.extractfile(members[0]) as handle: + data = json.load(handle) + for vertices in _vertices(data): + if vertices.ndim != 2 or vertices.shape[1] != 3 or not np.isfinite(vertices).all(): + raise ValueError(f"{clip}/{kind}: invalid vertices") + if len(vertices) < 2: + continue + if kind in ("traffic_signs", "traffic_lights") and len(vertices) == 8: + vertices = vertices[[0, 1, 2, 3, 0, 4, 5, 6, 7, 4, 5, 1, 2, 6, 7, 3]] + elif kind in ("crosswalks", "road_markings"): + vertices = np.concatenate((vertices, vertices[:1])) + points.append(vertices) + offsets.append(offsets[-1] + len(vertices)) + kinds.append(kind_id) + return dict(map_vertices=np.concatenate(points) if points else np.empty((0, 3), np.float32), + map_offsets=np.asarray(offsets, np.int64), map_kinds=np.asarray(kinds, np.int64)) + + +def render_hdmap(sample, frame): + """Return a white-background BGR frame matching the point-cloud camera.""" + for key in ("map_vertices", "map_offsets", "map_kinds", "box_class"): + if key not in sample: + raise ValueError(f"Missing {key}; rerun scripts/data/prepare_pai_bidir.py for raw-map previews") + width, height = VIZ_KWARGS["width"], VIZ_KWARGS["height"] + camera = CAMERA_VIEWS["paper_view_down"] + center = np.array([camera["center"][a] for a in "xyz"]) * VIZ_KWARGS["range"] + eye = np.array([camera["eye"][a] for a in "xyz"]) * VIZ_KWARGS["range"] + eye = center + .6 * (eye - center) + forward = center - eye + forward /= np.linalg.norm(forward) + right = np.cross(forward, [0, 0, 1]) + right /= np.linalg.norm(right) + up = np.cross(right, forward) + transform = np.linalg.inv(sample["pose_sensor_start_end"][frame, 0]) + tangent = np.tan(np.deg2rad(VIZ_KWARGS.get("fov_deg", 60)) / 2) + + def project(points, world=True): + local = points @ transform[:3, :3].T + transform[:3, 3] if world else points + relative = local - eye + depth = relative @ forward + x = (relative @ right / (np.maximum(depth, 1e-3) * tangent * width / height) * .5 + .5) * width + y = (1 - (relative @ up / (np.maximum(depth, 1e-3) * tangent) * .5 + .5 + .08)) * height + return np.clip(np.stack((x, y), -1), -100000, 100000).astype(np.int32), depth, local + + image = np.full((height, width, 3), 255, np.uint8) + map_lines = [] + box_lines = [] + for start, end, kind in zip(sample["map_offsets"][:-1], sample["map_offsets"][1:], sample["map_kinds"]): + pixels, depth, local = project(sample["map_vertices"][start:end]) + for i in range(len(pixels) - 1): + if min(depth[i:i+2]) > .1 and np.linalg.norm(local[i:i+2], axis=1).min() < 100: + map_lines.append((pixels[i], pixels[i+1], MAP_COLORS[kind][::-1])) + + def box(size, pose, color, world=True): + corners = np.array([[1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1], + [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1]]) * size / 2 + pixels, depth, local = project(corners @ pose[:3, :3].T + pose[:3, 3], world) + if depth.min() <= .1 or np.linalg.norm(local.mean(0)) > 100: + return + overlay = image.copy() + hull = cv2.convexHull(pixels) + cv2.fillConvexPoly(overlay, hull, color, cv2.LINE_AA) + cv2.addWeighted(overlay, .25, image, .75, 0, dst=image) + box_lines.extend((pixels[a], pixels[b], color) for a, b in EDGES) + + active = np.flatnonzero(sample["box_valid"][frame]) + # Paint distant boxes first. Outlines are drawn after all translucent fills. + origin = sample["pose_sensor_start_end"][frame, 0, :3, 3] + active = sorted(active, key=lambda i: -np.linalg.norm(sample["box_object_to_world"][frame, i, :3, 3] - origin)) + for i in active: + box(sample["box_lwh"][frame, i], sample["box_object_to_world"][frame, i], + BOX_COLORS[int(sample["box_class"][frame, i])][::-1]) + ego = np.eye(4) + ego[2, 3] = -1.1 + box(np.array([4.5, 2., 1.6]), ego, (40, 122, 240), world=False) + for a, b, color in map_lines: + cv2.line(image, tuple(a), tuple(b), color, 1, cv2.LINE_AA) + # Confine the soft halo to box edges; map polylines stay crisp and thin. + halo = np.zeros_like(image, dtype=np.float32) + coverage = np.zeros((height, width), dtype=np.float32) + for a, b, color in box_lines: + cv2.line(halo, tuple(a), tuple(b), color, 3) + cv2.line(coverage, tuple(a), tuple(b), 1., 3) + halo = cv2.GaussianBlur(halo, (5, 5), .8) + coverage = cv2.GaussianBlur(coverage, (5, 5), .8)[..., None] + image = np.clip(image * (1 - .12 * coverage) + .12 * halo, 0, 255).astype(np.uint8) + for a, b, color in box_lines: + cv2.line(image, tuple(a), tuple(b), color, 1, cv2.LINE_AA) + return image diff --git a/utils/visualize/point_cloud.py b/utils/visualize/point_cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..09901a50d4e03feef82aaa139d795d38a29e9e65 --- /dev/null +++ b/utils/visualize/point_cloud.py @@ -0,0 +1,543 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import io +import os +import torch +import numpy as np +from PIL import Image +# open3d is only needed by the PLY-save / statistical-filter helpers below, NOT by +# the pure-numpy ``visualize_point_cloud`` proj renderer. Importing it eagerly pulls +# ``open3d.ml`` -> sklearn -> pandas, which crashes on numpy-ABI-mismatched containers +# ("numpy.dtype size changed"). Guard it so the proj render path (infer_diffusion / +# infer_forecast) works everywhere; the o3d-using helpers fail only if actually called. +try: + import open3d as o3d +except Exception: # noqa: BLE001 + o3d = None + +# Configure environment for better Kaleido performance +os.environ["KALEIDO_SCOPE_TIMEOUT"] = "60" # Increase timeout to 60 seconds + +# eye: camera position +# center: view direction +CAMERA_VIEWS = { + "front_view_1": { + "eye": {"x": -0.3, "y": 0, "z": 0.2}, + "center": {"x": 0.1, "y": 0, "z": 0}, + }, + "paper_view_down": { + "eye": {"x": -0.3, "y": 0, "z": 0.26}, + "center": {"x": 0.1, "y": 0, "z": -0.03}, + }, + "paper_view_down_strong": { + "eye": {"x": -0.3, "y": 0, "z": 0.3}, + "center": {"x": 0.1, "y": 0, "z": -0.08}, + }, + "paper_side_view": { + "eye": {"x": 0.0, "y": -0.12, "z": 0.04}, + "center": {"x": 0.0, "y": 0.0, "z": 0.0}, + }, + "front_view_2": { + "eye": {"x": -0.1, "y": 0, "z": 0.05}, + "center": {"x": 0.1, "y": 0, "z": 0}, + }, + "front_view_3": { + "eye": {"x": -0.05, "y": 0, "z": 0.05}, + "center": {"x": 0.1, "y": 0, "z": 0}, + }, + "front_view_4": { + "eye": {"x": -0.01, "y": 0, "z": 0.01}, + "center": {"x": 0.1, "y": 0, "z": 0}, + }, + "front_view_5": { + "eye": {"x": -0.12, "y": 0, "z": 0.05}, + "center": {"x": 0.1, "y": 0, "z": 0}, + }, + "front_view_6": { + "eye": {"x": -0.075, "y": 0, "z": 0.05}, + "center": {"x": 0.075, "y": 0, "z": 0.0}, + }, + "top_down_view_1": { + "eye": {"x": 0, "y": -0.05, "z": 0.5}, + "center": {"x": 0, "y": -0.05, "z": 0}, + }, +} + + +VIZ_KWARGS = { + "point_size": 0.3, + "camera_position": CAMERA_VIEWS["front_view_1"], + "width": 1280, + "height": 720, + "bgcolor": [0.0, 0.0, 0.0], + "range": 200, +} + + +def visualize_point_cloud( + point_cloud, + colors, + point_size, + camera_position, + width, + height, + range=80, + opacity=1.0, + bgcolor=(0, 0, 0), + fov_deg=60.0, + antialias_point_size=False, + principal_y_offset=0.0, + depth_sort=False, + depth_sort_bin=0.0, + point_opacity=None, +): + """ + Ultra-fast 2D projection visualization (no rendering overhead). + """ + # Plotly camera system: eye, center, up are in normalized domain coordinates + # Scale eye and center to match the point cloud's coordinate system + point_cloud_center = np.array([0, 0, 0]) # Lidar origin is always at (0,0,0) + scale = range + + # Scale eye and center from normalized coordinates to match point cloud scale + # eye: camera position (scaled to point cloud coordinates) + # center: point the camera looks at (scaled to point cloud coordinates) + # up: up direction on the page (normalized vector, default [0, 0, 1]) + eye = np.array([camera_position["eye"]["x"], + camera_position["eye"]["y"], + camera_position["eye"]["z"]]) * scale + center = np.array([camera_position["center"]["x"], + camera_position["center"]["y"], + camera_position["center"]["z"]]) * scale + + # Get up vector from camera_position if provided, otherwise use default [0, 0, 1] + # Up is a direction vector (normalized), not scaled by range + if "up" in camera_position: + up_world = np.array([camera_position["up"]["x"], + camera_position["up"]["y"], + camera_position["up"]["z"]]) + else: + up_world = np.array([0, 0, 1]) # Plotly default + + # Calculate view direction (from eye to center) + forward = center - eye + forward = forward / np.linalg.norm(forward) + + # Calculate right vector (perpendicular to forward and up_world) + right = np.cross(forward, up_world) + right_norm = np.linalg.norm(right) + + # Handle edge case when forward is parallel to up_world + if right_norm < 1e-6: + # Use a different reference vector + up_world = np.array([0, 1, 0]) + right = np.cross(forward, up_world) + right_norm = np.linalg.norm(right) + + right = right / right_norm + + # Calculate camera up vector (perpendicular to forward and right) + # This ensures up is in the plane defined by forward and up_world + up = np.cross(right, forward) + up = up / np.linalg.norm(up) + + # Project points to 2D using a perspective projection (Plotly uses perspective) + # Camera coordinate system: right (x), up (y), forward (z) + points_relative = point_cloud - eye # Points relative to camera position + x_cam = np.dot(points_relative, right) + y_cam = np.dot(points_relative, up) + z_cam = np.dot(points_relative, forward) + + if point_opacity is None: + point_opacity = np.ones(len(point_cloud), dtype=np.float32) + else: + point_opacity = np.broadcast_to( + np.asarray(point_opacity, dtype=np.float32).reshape(-1), + (len(point_cloud),), + ) + + # Keep only points in front of the camera + eps = 1e-6 + depth_mask = z_cam > eps + x_cam = x_cam[depth_mask] + y_cam = y_cam[depth_mask] + z_cam = z_cam[depth_mask] + colors = colors[depth_mask] + point_opacity = point_opacity[depth_mask] + + # Perspective projection + # Use fov_deg as vertical field of view, zoom scales the FOV + fov_rad = np.deg2rad(fov_deg) + tan_half_fov = np.tan(fov_rad / 2.0) + aspect = width / height + + x_norm = (x_cam / (z_cam * tan_half_fov * aspect)) * 0.5 + 0.5 + y_norm = ( + (y_cam / (z_cam * tan_half_fov)) * 0.5 + + 0.5 + + float(principal_y_offset) + ) + + # Create image + img = np.zeros((height, width, 3), dtype=np.uint8) + img[:] = np.array(bgcolor) * 255 + + # Convert to pixel coordinates + x_pix = (x_norm * width).astype(int) + y_pix = ((1 - y_norm) * height).astype(int) # Flip Y + + # Filter valid pixels + valid = (x_pix >= 0) & (x_pix < width) & (y_pix >= 0) & (y_pix < height) + x_pix = x_pix[valid] + y_pix = y_pix[valid] + # reshape(-1, 3) keeps an empty/1-D color array broadcastable into the (0, 3) + # pixel slice (e.g. when every point is filtered out -> nothing to draw). + colors_valid = (colors[valid] * 255).astype(np.uint8).reshape(-1, 3) + opacity_valid = np.clip(point_opacity[valid], 0.0, 1.0) + if depth_sort: + # Painter's algorithm: far points first, near points last. Stable sorting + # preserves caller ordering for equal-depth temporal composites. + sort_depth = z_cam[valid] + if depth_sort_bin > 0.0: + sort_depth = np.floor(sort_depth / float(depth_sort_bin)) + order = np.argsort(-sort_depth, kind="stable") + x_pix = x_pix[order] + y_pix = y_pix[order] + colors_valid = colors_valid[order] + opacity_valid = opacity_valid[order] + + # Draw points. The legacy path quantizes the requested radius to an integer. + # The opt-in antialiased path blends the boundary pixels by their fractional + # disk coverage, then restores every projected center at full opacity. + if antialias_point_size: + radius = max(0.0, float(point_size)) + extent = int(np.ceil(radius + 0.5)) + for dy in np.arange(-extent, extent + 1): + for dx in np.arange(-extent, extent + 1): + if dx == 0 and dy == 0: + continue + coverage = float(np.clip(radius + 0.5 - np.hypot(dx, dy), 0.0, 1.0)) + if coverage == 0.0: + continue + shifted_x = x_pix + dx + shifted_y = y_pix + dy + shifted_valid = ( + (shifted_x >= 0) + & (shifted_x < width) + & (shifted_y >= 0) + & (shifted_y < height) + ) + target_x = shifted_x[shifted_valid] + target_y = shifted_y[shifted_valid] + foreground = colors_valid[shifted_valid].astype(np.float32) + background = img[target_y, target_x].astype(np.float32) + alpha = coverage * opacity_valid[shifted_valid, None] + img[target_y, target_x] = np.rint( + alpha * foreground + (1.0 - alpha) * background + ).astype(np.uint8) + foreground = colors_valid.astype(np.float32) + background = img[y_pix, x_pix].astype(np.float32) + alpha = opacity_valid[:, None] + img[y_pix, x_pix] = np.rint( + alpha * foreground + (1.0 - alpha) * background + ).astype(np.uint8) + else: + radius_px = max(0, int(round(float(point_size)))) + if radius_px == 0: + foreground = colors_valid.astype(np.float32) + background = img[y_pix, x_pix].astype(np.float32) + alpha = opacity_valid[:, None] + img[y_pix, x_pix] = np.rint( + alpha * foreground + (1.0 - alpha) * background + ).astype(np.uint8) + else: + for dy in np.arange(-radius_px, radius_px + 1): + for dx in np.arange(-radius_px, radius_px + 1): + if dx * dx + dy * dy > radius_px * radius_px: + continue + shifted_x = x_pix + dx + shifted_y = y_pix + dy + shifted_valid = ( + (shifted_x >= 0) + & (shifted_x < width) + & (shifted_y >= 0) + & (shifted_y < height) + ) + target = ( + shifted_y[shifted_valid], + shifted_x[shifted_valid], + ) + foreground = colors_valid[shifted_valid].astype(np.float32) + background = img[target].astype(np.float32) + alpha = opacity_valid[shifted_valid, None] + img[target] = np.rint( + alpha * foreground + (1.0 - alpha) * background + ).astype(np.uint8) + + return img + + +def vis_point_cloud_to_numpy(point_cloud, colors, point_size=None): + kwargs = dict(VIZ_KWARGS) + if point_size is not None: + kwargs["point_size"] = point_size + img = visualize_point_cloud(point_cloud, colors, **kwargs) + return img + + +def vis_point_cloud(point_cloud, colors, save_path): + img = visualize_point_cloud(point_cloud, colors, **VIZ_KWARGS) + img = Image.fromarray(img) + img.save(save_path) + +def o3d_statistical_filter(pts, nb_neighbors=20, std_ratio=1.0, return_ind=False): + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(pts) + + cl, ind = pcd.remove_statistical_outlier(nb_neighbors=nb_neighbors, std_ratio=std_ratio) + + inlier_cloud = pcd.select_by_index(ind) + + # get the numpy point cloud + inlier_pts = np.asarray(inlier_cloud.points) + if return_ind: + # ``ind`` maps inlier rows back to the input order so callers can keep + # per-point attributes (e.g. intensity) aligned with the kept points. + return inlier_pts, np.asarray(ind, dtype=np.int64) + return inlier_pts + + + +def save_range_map_to_ply( + range_map_input, save_path +): + """ + Save the range map to a point cloud + Input: + range_map_input: numpy array of shape (H, W), unnormalized range values + """ + + from utils.lidar_rangemap import range_map_to_point_cloud + + # get the ray directions and ray directions + input_points = range_map_to_point_cloud(range_map_input) + + n_pts = input_points.shape[0] + input_colors = np.array([[1, 0.706, 0]] * n_pts, dtype=np.float32) + + + pcd_ref = o3d.geometry.PointCloud() + pcd_ref.points = o3d.utility.Vector3dVector(input_points) + pcd_ref.colors = o3d.utility.Vector3dVector(input_colors) + + o3d.io.write_point_cloud(save_path, pcd_ref) + + +def render_range_map_to_point_cloud( + range_map_input, + range_map_recon, + filter_outlier=False, + save_path=None, + point_size=None, + ray_directions=None, + filter_nb_neighbors=20, + filter_std_ratio=1.0, +): + """ + Render the range map to a point cloud. + Input: + range_map_input: numpy array of shape (N, H, W), unnormalized range values + range_map_recon: numpy array of shape (N, H, W), unnormalized range values + ray_directions: optional (H, W, 3) unit ray-direction grid. When given it + overrides the default Pandar128 geometry (e.g. the Waymo sensor's + measured elevation/azimuth tables); must match the range-map H, W. + Output: + point_cloud: numpy array of shape (N, 3, H, W) + """ + # unnormalize the range map + valid_mask_input = range_map_input > 0 + valid_mask_recon = range_map_recon > 0 + + # get the ray directions (default Pandar128 unless an override is supplied) + if ray_directions is None: + from utils.lidar_rangemap import ( + load_pandar128_elevations, + range_map_to_ray_directions, + ) + + elevation_angles = load_pandar128_elevations() + assert len(elevation_angles) == range_map_input.shape[1] + ray_directions = range_map_to_ray_directions(range_map_input.shape[2], elevation_angles) # shape: (H, W, 3) + else: + ray_directions = np.asarray(ray_directions, dtype=np.float32) + assert ray_directions.shape[:2] == range_map_input.shape[1:3], ( + f"ray_directions {ray_directions.shape} does not match range map " + f"{range_map_input.shape}" + ) + ray_origins = np.zeros_like(ray_directions) # shape: (H, W, 3) + + # get the point cloud + bs = range_map_input.shape[0] + + vis_list = [] + for batch_idx in range(bs): + c_range_map_input = range_map_input[batch_idx] # shape: (H, W) + c_range_map_recon = range_map_recon[batch_idx] # shape: (H, W) + c_ray_directions = ray_directions # shape: (H, W, 3) + c_ray_origins = ray_origins # shape: (H, W, 3) + + c_valid_mask_input = valid_mask_input[batch_idx] + c_valid_mask_recon = valid_mask_recon[batch_idx] + + input_points = ( + c_ray_origins[c_valid_mask_input] + + c_ray_directions[c_valid_mask_input] * c_range_map_input[c_valid_mask_input][:, np.newaxis] + ) # shape: (N, 3) + recon_points = ( + c_ray_origins[c_valid_mask_recon] + + c_ray_directions[c_valid_mask_recon] * c_range_map_recon[c_valid_mask_recon][:, np.newaxis] + ) # shape: (N, 3) + + if filter_outlier: + recon_points = o3d_statistical_filter( + recon_points, + nb_neighbors=filter_nb_neighbors, + std_ratio=filter_std_ratio, + ) + + n_pts = input_points.shape[0] + input_colors = np.array([[1, 0.706, 0]] * n_pts, dtype=np.float32) + n_pts = recon_points.shape[0] + recon_colors = np.array([[0, 0.651, 0.929]] * n_pts, dtype=np.float32) + + if save_path is not None: + os.makedirs(save_path, exist_ok=True) + o3d.io.write_point_cloud( + f"{save_path}/input_pcd_{batch_idx}.ply", + o3d.geometry.PointCloud( + points=o3d.utility.Vector3dVector(input_points) + ) + ) + o3d.io.write_point_cloud( + f"{save_path}/recon_pcd_{batch_idx}.ply", + o3d.geometry.PointCloud( + points=o3d.utility.Vector3dVector(recon_points) + ) + ) + + input_img = vis_point_cloud_to_numpy(input_points, input_colors, point_size=point_size) # shape: (H, W, 3) + recon_img = vis_point_cloud_to_numpy(recon_points, recon_colors, point_size=point_size) # shape: (H, W, 3) + + recon_images = np.concatenate([input_img, recon_img], axis=1) # shape: (H, 2W, 3) + vis_list.append(recon_images) + + vis_list = np.array(vis_list) # shape: (bs, H, 2W, 3) + + return vis_list + +def render_range_map_to_point_cloud_with_intensity( + range_map_input, + range_map_recon, + intensity_input, + intensity_recon, + filter_outlier=False, + ray_directions=None, + filter_nb_neighbors=20, + filter_std_ratio=1.0, +): + """ + Render point clouds colored by intensity (viridis colormap). + Input: + range_map_input/recon: numpy array of shape (N, H, W), unnormalized range + intensity_input/recon: numpy array of shape (N, H, W), values in [0, 1] + ray_directions: optional (H, W, 3) unit ray-direction grid. When given it + overrides the default Pandar128 geometry (e.g. the Waymo sensor's + measured elevation/azimuth tables); must match the range-map H, W. + Output: + vis_list: numpy array of shape (N, H, 2W, 3) + """ + from matplotlib import cm + cmap = cm.get_cmap("viridis") + + valid_mask_input = range_map_input > 0 + valid_mask_recon = range_map_recon > 0 + + if ray_directions is None: + from utils.lidar_rangemap import ( + load_pandar128_elevations, + range_map_to_ray_directions, + ) + + elevation_angles = load_pandar128_elevations() + assert len(elevation_angles) == range_map_input.shape[1] + ray_directions = range_map_to_ray_directions(range_map_input.shape[2], elevation_angles) + else: + ray_directions = np.asarray(ray_directions, dtype=np.float32) + assert ray_directions.shape[:2] == range_map_input.shape[1:3], ( + f"ray_directions {ray_directions.shape} does not match range map " + f"{range_map_input.shape}" + ) + + bs = range_map_input.shape[0] + vis_list = [] + for b in range(bs): + mask_in = valid_mask_input[b] + mask_re = valid_mask_recon[b] + + pts_in = ray_directions[mask_in] * range_map_input[b][mask_in][:, np.newaxis] + pts_re = ray_directions[mask_re] * range_map_recon[b][mask_re][:, np.newaxis] + + if filter_outlier: + pts_re = o3d_statistical_filter( + pts_re, + nb_neighbors=filter_nb_neighbors, + std_ratio=filter_std_ratio, + ) + + colors_in = cmap(np.clip(intensity_input[b][mask_in], 0, 1))[:, :3].astype(np.float32) + colors_re = cmap(np.clip(intensity_recon[b][mask_re], 0, 1))[:, :3].astype(np.float32) + + img_in = vis_point_cloud_to_numpy(pts_in, colors_in) + img_re = vis_point_cloud_to_numpy(pts_re, colors_re) + vis_list.append(np.concatenate([img_in, img_re], axis=1)) + + return np.array(vis_list) + + +def range_map_to_structured_point_cloud(range_map: torch.Tensor): + """ + Convert the range map to a structured point cloud. + Input: + range_map: torch tensor of shape (N, H, W), unnormalized range values + Output: + point_cloud: torch tensor of shape (N, 3, H, W) + """ + from utils.lidar_rangemap import ( + load_pandar128_elevations, + range_map_to_ray_directions, + ) + + elevation_angles = load_pandar128_elevations() + assert len(elevation_angles) == range_map.shape[1] + + valid_mask = range_map > 0 + + ray_directions = range_map_to_ray_directions(range_map.shape[2], elevation_angles) # shape: (H, W, 3) + ray_origins = np.zeros_like(ray_directions) # shape: (H, W, 3) + + points = range_map[..., np.newaxis] * ray_directions # shape: (H, W, 3) + points = points[range_map > 0] + return points diff --git a/utils/wandb_utils.py b/utils/wandb_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e0bfc09128a5a52c6d163758546801d3f150a571 --- /dev/null +++ b/utils/wandb_utils.py @@ -0,0 +1,75 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from __future__ import annotations + +import os + +import attrs +import wandb +import wandb.util +from omegaconf import DictConfig +from utils.lazy_config.lazy import LazyConfig +from utils import distributed, log +from utils.easy_io import easy_io +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from utils.config import Config + from utils.model import Model + + +@distributed.rank0_only +def init_wandb(config: Config, model: Model) -> None: + """Initialize Weights & Biases (wandb) logger. + + Args: + config (Config): The config object for the Imaginaire codebase. + model (Model): The PyTorch model. + """ + if isinstance(config.job, DictConfig): + from utils.config import JobConfig + + config_job = JobConfig(**config.job) + else: + config_job = config.job + + # init the wandb id + wandb_id = wandb.util.generate_id() + log.info(f"Generating new wandb ID: {wandb_id}") + + # write to a txt file + with open(os.path.join(config_job.path_local, "wandb_id.txt"), "w") as f: + f.write(wandb_id) + + # refactor config so that wandb better understands it + local_safe_yaml_fp = LazyConfig.save_yaml(config, os.path.join(config_job.path_local, "config.yaml")) + if os.path.exists(local_safe_yaml_fp): + config_resolved = easy_io.load(local_safe_yaml_fp) + else: + config_resolved = attrs.asdict(config) + # Initialize the wandb library. + wandb.init( + force=True, + id=wandb_id, + project=config_job.project, + group=config_job.group, + name=config_job.name, + config=config_resolved, + dir=config_job.path_local, + resume="allow", + mode=config_job.wandb_mode, + ) \ No newline at end of file