Spaces:
Running on Zero
Running on Zero
LidarVerse Stage-3 world generation demo
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- LICENSE +201 -0
- README.md +26 -7
- app.py +205 -0
- assets/lidar/lidar_model.yaml +536 -0
- assets/lidar/sensors.yaml +27 -0
- diffusion/checkpointers/ema_fsdp_checkpointer.py +54 -0
- diffusion/conditioner.py +340 -0
- diffusion/config/__init__.py +2 -0
- diffusion/config/base/__init__.py +2 -0
- diffusion/config/base/conditioner.py +261 -0
- diffusion/functional/batch_ops.py +61 -0
- diffusion/functional/multi_step.py +60 -0
- diffusion/functional/runge_kutta.py +333 -0
- diffusion/inference/__init__.py +4 -0
- diffusion/inference/causal.py +162 -0
- diffusion/inference/hdmap.py +305 -0
- diffusion/inference/pai.py +366 -0
- diffusion/inference/raw_hdmap.py +122 -0
- diffusion/module/__init__.py +2 -0
- diffusion/module/attention.py +313 -0
- diffusion/module/blocks.py +558 -0
- diffusion/modules/denoiser_scaling.py +30 -0
- diffusion/modules/res_sampler.py +283 -0
- diffusion/training/conditioner.py +333 -0
- diffusion/training/config/base/ema.py +27 -0
- diffusion/training/config/base/lidarverse_vae.py +38 -0
- diffusion/training/config/base/model.py +457 -0
- diffusion/training/config/base/optim.py +40 -0
- diffusion/training/config/config_lidar.py +100 -0
- diffusion/training/config/text2world/registry.py +136 -0
- diffusion/training/config/text2world_hdmaptolidar/__init__.py +2 -0
- diffusion/training/config/text2world_hdmaptolidar/experiment_lidarverse.py +495 -0
- diffusion/training/config/text2world_hdmaptolidar/experiment_pai_release.py +56 -0
- diffusion/training/context_parallel.py +122 -0
- diffusion/training/datasets/lidar_dataset/configs.py +187 -0
- diffusion/training/datasets/lidar_dataset/forecast_warp.py +0 -0
- diffusion/training/datasets/lidar_dataset/hdmaptolidar_dataloader.py +960 -0
- diffusion/training/datasets/lidar_dataset/imagetolidar_dataloader.py +969 -0
- diffusion/training/datasets/lidar_dataset/waymo_track_ids.py +191 -0
- diffusion/training/functional/loss.py +135 -0
- diffusion/training/functional/lr_scheduler.py +178 -0
- diffusion/training/models/fm_solvers_dpm.py +420 -0
- diffusion/training/models/fm_solvers_unipc.py +790 -0
- diffusion/training/models/hdmaptolidar_model.py +821 -0
- diffusion/training/models/hdmaptolidar_model_rf.py +0 -0
- diffusion/training/models/hdmaptolidar_model_sf_dmd.py +0 -0
- diffusion/training/models/model.py +663 -0
- diffusion/training/models/model_image.py +1009 -0
- diffusion/training/module/pretrained_vae_base.py +844 -0
- diffusion/training/module/vae_utils.py +67 -0
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,13 +1,32 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.30.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: LidarVerse
|
| 3 |
+
emoji: 🛰️
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.30.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
short_description: Generate LiDAR sweeps from a road scene you design
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
+
license: apache-2.0
|
| 13 |
+
models:
|
| 14 |
+
- nvidia/lidarverse
|
| 15 |
---
|
| 16 |
|
| 17 |
+
# LidarVerse: HD map → LiDAR world generation
|
| 18 |
+
|
| 19 |
+
Demo for [nvidia/lidarverse](https://huggingface.co/nvidia/lidarverse) ("Into the LidarVerse: A Real-Time Unified
|
| 20 |
+
LiDAR World Model Across Tasks and Sensors", [arXiv 2610.19201](https://arxiv.org/abs/2610.19201)).
|
| 21 |
+
|
| 22 |
+
* Uses the released **Stage-3 SF-DMD EMA** package (4 SDE steps, CFG 1, four-frame causal blocks, 9-frame K/V
|
| 23 |
+
cache incl. sink, persistent spatial cache with 0.10 m voxels) and the FP32 PAI range tokenizer, following the
|
| 24 |
+
official `scripts/diffusion/getting_started.sh STAGE=3` quickstart.
|
| 25 |
+
* The HD map is built procedurally (lanes, curbs, crosswalks, stop lines, poles, moving / parked vehicles, ego motion)
|
| 26 |
+
in the prepared-PAI sample format and conditioned through the official raw-HDMap rasterizer
|
| 27 |
+
(`RAW_HDMAP_CONDITION_RASTERIZE=1`, 3x3 bbox dilation, 0.1 m segment spacing).
|
| 28 |
+
* Inference code is from [nv-tlabs/LidarVerse](https://github.com/nv-tlabs/LidarVerse) (Apache-2.0). Transformer
|
| 29 |
+
Engine, Megatron, Apex and NATTEN are replaced by small pure-PyTorch equivalents in `shims/` (RMSNorm, RoPE,
|
| 30 |
+
exact neighborhood attention with NATTEN's window clamping) so the app runs on ZeroGPU.
|
| 31 |
+
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 5 |
+
os.environ.setdefault("MPLCONFIGDIR", "/tmp/lidarverse-matplotlib")
|
| 6 |
+
ROOT = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
+
# Pure-PyTorch stand-ins for Transformer Engine / Megatron / Apex / NATTEN come first on the path.
|
| 8 |
+
sys.path[:0] = [os.path.join(ROOT, "shims"), ROOT]
|
| 9 |
+
|
| 10 |
+
import spaces # noqa: E402 (must precede torch)
|
| 11 |
+
import tempfile # noqa: E402
|
| 12 |
+
import time # noqa: E402
|
| 13 |
+
from pathlib import Path # noqa: E402
|
| 14 |
+
from types import SimpleNamespace # noqa: E402
|
| 15 |
+
|
| 16 |
+
import gradio as gr # noqa: E402
|
| 17 |
+
import numpy as np # noqa: E402
|
| 18 |
+
import plotly.graph_objects as go # noqa: E402
|
| 19 |
+
import torch # noqa: E402
|
| 20 |
+
from huggingface_hub import snapshot_download # noqa: E402
|
| 21 |
+
|
| 22 |
+
from diffusion.inference.pai import MODES, load_model, load_package, load_sample, preview # noqa: E402
|
| 23 |
+
from scene import LAYOUTS, build_scene # noqa: E402
|
| 24 |
+
from utils import inference as common # noqa: E402
|
| 25 |
+
from utils.visualize.hdmap import render_hdmap # noqa: E402
|
| 26 |
+
|
| 27 |
+
# ----------------------------------------------------------------------------- model (Stage 3, SF-DMD EMA)
|
| 28 |
+
CKPT = Path(snapshot_download("nvidia/lidarverse",
|
| 29 |
+
allow_patterns=["lidarverse-sfdmd-pai/*", "lidarverse-tokenizer-pai/*"]))
|
| 30 |
+
CHECKPOINT = CKPT / "lidarverse-sfdmd-pai" / "ema_model.pt"
|
| 31 |
+
PACKAGE = load_package(CHECKPOINT, 3)
|
| 32 |
+
MODEL = load_model(CHECKPOINT, CKPT / "lidarverse-tokenizer-pai" / "ckpt.pt",
|
| 33 |
+
CKPT / "lidarverse-tokenizer-pai" / "latent_stats.pt", stage=3, package=PACKAGE)
|
| 34 |
+
ARGS = SimpleNamespace(stage=3, kv_cache_frames=9, num_steps=4, sde_eta=1.0, sampler="sde", guidance=1.0)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@spaces.GPU(duration=90)
|
| 38 |
+
def _run_model(sample: dict, mode: str, seed: int):
|
| 39 |
+
"""Raw-HDMap rasterization (world mode) + Stage-3 causal 4-step sampling, all on GPU."""
|
| 40 |
+
from diffusion.inference.causal import generate
|
| 41 |
+
from diffusion.inference.raw_hdmap import rasterize_raw_hdmap
|
| 42 |
+
|
| 43 |
+
t0 = time.perf_counter()
|
| 44 |
+
with torch.inference_mode():
|
| 45 |
+
if mode == "world" and "map_vertices" in sample and len(sample.get("map_offsets", [])) > 1:
|
| 46 |
+
condition, _ = rasterize_raw_hdmap(sample, bbox_dilation=3, seg_interval=0.1)
|
| 47 |
+
sample["hdmap"] = condition
|
| 48 |
+
generated, valid = generate(MODEL, sample, mode, ARGS, int(seed), sys.stdout)
|
| 49 |
+
torch.cuda.synchronize()
|
| 50 |
+
return generated, valid, sample.get("hdmap"), time.perf_counter() - t0
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _scatter3d(points: np.ndarray, title: str) -> go.Figure:
|
| 54 |
+
if len(points) > 60000:
|
| 55 |
+
points = points[np.random.default_rng(0).choice(len(points), 60000, replace=False)]
|
| 56 |
+
fig = go.Figure(go.Scatter3d(
|
| 57 |
+
x=points[:, 0], y=points[:, 1], z=points[:, 2], mode="markers",
|
| 58 |
+
marker=dict(size=1.2, color=np.clip(points[:, 2], -3, 5), colorscale="Viridis", opacity=0.9),
|
| 59 |
+
))
|
| 60 |
+
fig.update_layout(
|
| 61 |
+
title=title, height=520, margin=dict(l=0, r=0, t=40, b=0),
|
| 62 |
+
scene=dict(aspectmode="data", xaxis_visible=False, yaxis_visible=False, zaxis_visible=False,
|
| 63 |
+
camera=dict(eye=dict(x=-0.9, y=0, z=0.55), center=dict(x=0.15, y=0, z=-0.1))),
|
| 64 |
+
)
|
| 65 |
+
return fig
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _finish(sample, generated, valid, mode, seed, elapsed):
|
| 69 |
+
out = Path(tempfile.mkdtemp(prefix="lidarverse-"))
|
| 70 |
+
video = out / "generation.mp4"
|
| 71 |
+
common.write_video(video, preview(sample, generated, valid, mode, out), 10)
|
| 72 |
+
npz = out / f"lidarverse_{mode}_seed{seed}.npz"
|
| 73 |
+
np.savez_compressed(npz, range_m=generated, valid_mask=valid, ray_directions=sample["ray_directions"],
|
| 74 |
+
pose_sensor_start_end=sample["pose_sensor_start_end"][:len(generated)], fps=np.float32(10),
|
| 75 |
+
known_frame_mask=np.arange(len(generated)) < MODES[mode]["input_frames"])
|
| 76 |
+
last = len(generated) - 1
|
| 77 |
+
pts = common.points_from_ranges(generated[last], valid[last], sample["ray_directions"])
|
| 78 |
+
fig = _scatter3d(pts, f"Generated sweep {last} (sensor frame, {len(pts):,} points)")
|
| 79 |
+
status = (f"**{mode}** | {len(generated)} sweeps @ 10 Hz | 4-step SF-DMD causal sampling | "
|
| 80 |
+
f"GPU time {elapsed:.1f}s | seed {seed}")
|
| 81 |
+
return str(video), fig, str(npz), status
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def generate_scene(layout: str, lanes_per_direction: int = 2, ego_speed_kmh: float = 30.0,
|
| 85 |
+
num_vehicles: int = 8, parked_cars: bool = True, seed: int = 0):
|
| 86 |
+
"""Generate a 21-sweep LiDAR sequence (2 s @ 10 Hz) from a procedurally built HD map.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
layout: "Straight road", "Four-way intersection" or "Curved road".
|
| 90 |
+
lanes_per_direction: lanes in each driving direction (1-3).
|
| 91 |
+
ego_speed_kmh: speed of the ego vehicle carrying the LiDAR.
|
| 92 |
+
num_vehicles: number of other moving vehicles on the road.
|
| 93 |
+
parked_cars: whether to park cars along the curbs.
|
| 94 |
+
seed: random seed for both the scene layout and the diffusion sampler.
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
Side-by-side video (HD map | generated LiDAR), a 3D plot of the last sweep,
|
| 98 |
+
the generated range sequence as .npz, and a status line.
|
| 99 |
+
"""
|
| 100 |
+
seed = int(seed)
|
| 101 |
+
sample = build_scene(layout, int(lanes_per_direction), float(ego_speed_kmh), int(num_vehicles),
|
| 102 |
+
bool(parked_cars), seed)
|
| 103 |
+
generated, valid, hdmap, elapsed = _run_model(sample, "world", seed)
|
| 104 |
+
sample["hdmap"] = hdmap
|
| 105 |
+
return _finish(sample, generated, valid, "world", seed, elapsed)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def generate_from_npz(npz_file: str, mode: str = "world", seed: int = 0):
|
| 109 |
+
"""Run world generation / forecasting / resimulation on a prepared NVIDIA PAI clip.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
npz_file: an NPZ produced by LidarVerse's scripts/data/prepare_pai_bidir.py (128x1024, 10 Hz).
|
| 113 |
+
mode: "world" (HD map -> LiDAR), "forecast" (10 observed -> 11 future sweeps) or
|
| 114 |
+
"resim" (15 observed sweeps + future actor poses -> 5 sweeps).
|
| 115 |
+
seed: sampler seed.
|
| 116 |
+
"""
|
| 117 |
+
if not npz_file:
|
| 118 |
+
raise gr.Error("Upload a prepared PAI .npz clip first.")
|
| 119 |
+
try:
|
| 120 |
+
sample = load_sample(npz_file, [mode], 3)
|
| 121 |
+
except ValueError as e:
|
| 122 |
+
raise gr.Error(str(e))
|
| 123 |
+
seed = int(seed)
|
| 124 |
+
generated, valid, hdmap, elapsed = _run_model(sample, mode, seed)
|
| 125 |
+
if hdmap is not None:
|
| 126 |
+
sample["hdmap"] = hdmap
|
| 127 |
+
if mode == "world" and "map_kinds" not in sample:
|
| 128 |
+
raise gr.Error("World-mode previews need the raw vector map (map_vertices/map_offsets/map_kinds).")
|
| 129 |
+
return _finish(sample, generated, valid, mode, seed, elapsed)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def preview_scene(layout, lanes_per_direction=2, ego_speed_kmh=30.0, num_vehicles=8, parked_cars=True, seed=0):
|
| 133 |
+
"""Render the procedural HD map + actor boxes (first sweep) from the LiDAR's viewpoint."""
|
| 134 |
+
sample = build_scene(layout, int(lanes_per_direction), float(ego_speed_kmh), int(num_vehicles),
|
| 135 |
+
bool(parked_cars), int(seed))
|
| 136 |
+
return render_hdmap(sample, 0)[..., ::-1]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
CSS = """
|
| 140 |
+
#col-container { max-width: 1200px; margin: 0 auto; }
|
| 141 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
|
| 145 |
+
with gr.Column(elem_id="col-container"):
|
| 146 |
+
gr.Markdown(
|
| 147 |
+
"# LidarVerse: HD map → LiDAR world generation\n"
|
| 148 |
+
"Design a road scene. NVIDIA's [LidarVerse](https://huggingface.co/nvidia/lidarverse) "
|
| 149 |
+
"Stage-3 self-forcing model (2B DiT, 4 denoising steps, rolling K/V + spatial cache) then generates "
|
| 150 |
+
"2 s of 128-beam LiDAR sweeps conditioned on the HD map and actor boxes. "
|
| 151 |
+
"[Paper](https://arxiv.org/abs/2610.19201) · [Code](https://github.com/nv-tlabs/LidarVerse) · "
|
| 152 |
+
"[Project page](https://research.nvidia.com/labs/sil/projects/lidarverse/)"
|
| 153 |
+
)
|
| 154 |
+
with gr.Row():
|
| 155 |
+
with gr.Column(scale=2):
|
| 156 |
+
layout = gr.Radio(list(LAYOUTS), value="Four-way intersection", label="Road layout")
|
| 157 |
+
with gr.Row():
|
| 158 |
+
lanes = gr.Slider(1, 3, value=2, step=1, label="Lanes per direction")
|
| 159 |
+
speed = gr.Slider(0, 60, value=30, step=5, label="Ego speed (km/h)")
|
| 160 |
+
with gr.Row():
|
| 161 |
+
vehicles = gr.Slider(0, 16, value=8, step=1, label="Moving vehicles")
|
| 162 |
+
parked = gr.Checkbox(value=True, label="Parked cars along the curb")
|
| 163 |
+
seed = gr.Number(value=0, precision=0, label="Seed (scene + sampler)")
|
| 164 |
+
run = gr.Button("Generate LiDAR", variant="primary")
|
| 165 |
+
with gr.Column(scale=3):
|
| 166 |
+
scene_img = gr.Image(label="HD-map condition preview (first sweep)", interactive=False)
|
| 167 |
+
status = gr.Markdown()
|
| 168 |
+
video = gr.Video(label="HD map | generated LiDAR (10 Hz)", autoplay=True, loop=True)
|
| 169 |
+
with gr.Row():
|
| 170 |
+
plot = gr.Plot(label="Last generated sweep (drag to orbit)")
|
| 171 |
+
npz_out = gr.File(label="Generated range sequence (.npz)")
|
| 172 |
+
|
| 173 |
+
with gr.Accordion("Advanced: run on your own prepared NVIDIA PAI clip (forecast / resimulate)", open=False):
|
| 174 |
+
gr.Markdown(
|
| 175 |
+
"Upload a clip prepared with `scripts/data/prepare_pai_bidir.py` from the LidarVerse repo "
|
| 176 |
+
"(128x1024 Pandar128 range images, 10 Hz, 21 sweeps). **forecast** observes 10 sweeps and "
|
| 177 |
+
"predicts 11; **resim** observes 15 and re-simulates 5 under the given actor poses."
|
| 178 |
+
)
|
| 179 |
+
with gr.Row():
|
| 180 |
+
npz_in = gr.File(label="Prepared PAI clip (.npz)", file_types=[".npz"], type="filepath")
|
| 181 |
+
mode = gr.Radio(["world", "forecast", "resim"], value="forecast", label="Task")
|
| 182 |
+
seed2 = gr.Number(value=0, precision=0, label="Seed")
|
| 183 |
+
run2 = gr.Button("Run on uploaded clip")
|
| 184 |
+
|
| 185 |
+
gr.Examples(
|
| 186 |
+
examples=[
|
| 187 |
+
["Four-way intersection", 2, 30, 8, True, 0],
|
| 188 |
+
["Straight road", 3, 50, 12, False, 3],
|
| 189 |
+
["Curved road", 1, 25, 4, True, 7],
|
| 190 |
+
["Four-way intersection", 1, 0, 3, True, 11],
|
| 191 |
+
],
|
| 192 |
+
inputs=[layout, lanes, speed, vehicles, parked, seed],
|
| 193 |
+
outputs=[video, plot, npz_out, status],
|
| 194 |
+
fn=generate_scene, cache_examples=True, cache_mode="lazy",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
scene_inputs = [layout, lanes, speed, vehicles, parked, seed]
|
| 198 |
+
for comp in scene_inputs:
|
| 199 |
+
comp.change(preview_scene, scene_inputs, scene_img, api_name=False, show_progress="hidden")
|
| 200 |
+
demo.load(preview_scene, scene_inputs, scene_img, api_name=False)
|
| 201 |
+
run.click(generate_scene, scene_inputs, [video, plot, npz_out, status], api_name="generate")
|
| 202 |
+
run2.click(generate_from_npz, [npz_in, mode, seed2], [video, plot, npz_out, status], api_name="generate_from_npz")
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
demo.launch(mcp_server=True)
|
assets/lidar/lidar_model.yaml
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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/
|
| 7 |
+
# Manu: HESAI Device: AT128
|
| 8 |
+
# Params is derived from https://www.hesaitech.com/wp-content/uploads/2023/03/PandarView2_User_Manual_PV2-en-230810-1.pdf
|
| 9 |
+
HESAI-AT128: {n_vertical_bins: 128, frequency: 10, horizontal_fov: 120, n_horizontal_bins: 1200,
|
| 10 |
+
sync_angle_deg: 0, # always zero for AT128.
|
| 11 |
+
azimuths_deg_offset: [
|
| 12 |
+
2.4,
|
| 13 |
+
-0.65,
|
| 14 |
+
2.4,
|
| 15 |
+
-0.65,
|
| 16 |
+
2.4,
|
| 17 |
+
-0.65,
|
| 18 |
+
2.4,
|
| 19 |
+
-0.65,
|
| 20 |
+
2.4,
|
| 21 |
+
-0.65,
|
| 22 |
+
2.4,
|
| 23 |
+
-0.65,
|
| 24 |
+
2.4,
|
| 25 |
+
-0.65,
|
| 26 |
+
2.4,
|
| 27 |
+
-0.65,
|
| 28 |
+
-2.4,
|
| 29 |
+
0.65,
|
| 30 |
+
-2.4,
|
| 31 |
+
0.65,
|
| 32 |
+
-2.4,
|
| 33 |
+
0.659,
|
| 34 |
+
-2.4,
|
| 35 |
+
0.659,
|
| 36 |
+
-2.4,
|
| 37 |
+
0.659,
|
| 38 |
+
-2.4,
|
| 39 |
+
0.65,
|
| 40 |
+
-2.4,
|
| 41 |
+
0.65,
|
| 42 |
+
-2.4,
|
| 43 |
+
0.65,
|
| 44 |
+
2.4,
|
| 45 |
+
-0.65,
|
| 46 |
+
2.4,
|
| 47 |
+
-0.65,
|
| 48 |
+
2.4,
|
| 49 |
+
-0.65,
|
| 50 |
+
2.4,
|
| 51 |
+
-0.65,
|
| 52 |
+
2.4,
|
| 53 |
+
-0.65,
|
| 54 |
+
2.4,
|
| 55 |
+
-0.65,
|
| 56 |
+
2.4,
|
| 57 |
+
-0.65,
|
| 58 |
+
2.4,
|
| 59 |
+
-0.65,
|
| 60 |
+
-2.4,
|
| 61 |
+
0.65,
|
| 62 |
+
-2.4,
|
| 63 |
+
0.65,
|
| 64 |
+
-2.4,
|
| 65 |
+
0.65,
|
| 66 |
+
-2.4,
|
| 67 |
+
0.65,
|
| 68 |
+
-2.4,
|
| 69 |
+
0.65,
|
| 70 |
+
-2.4,
|
| 71 |
+
0.65,
|
| 72 |
+
-2.4,
|
| 73 |
+
0.65,
|
| 74 |
+
-2.4,
|
| 75 |
+
0.65,
|
| 76 |
+
2.4,
|
| 77 |
+
-0.65,
|
| 78 |
+
2.4,
|
| 79 |
+
-0.65,
|
| 80 |
+
2.4,
|
| 81 |
+
-0.65,
|
| 82 |
+
2.4,
|
| 83 |
+
-0.65,
|
| 84 |
+
2.4,
|
| 85 |
+
-0.65,
|
| 86 |
+
2.4,
|
| 87 |
+
-0.65,
|
| 88 |
+
2.4,
|
| 89 |
+
-0.65,
|
| 90 |
+
2.4,
|
| 91 |
+
-0.65,
|
| 92 |
+
-2.4,
|
| 93 |
+
0.65,
|
| 94 |
+
-2.4,
|
| 95 |
+
0.65,
|
| 96 |
+
-2.4,
|
| 97 |
+
0.65,
|
| 98 |
+
-2.4,
|
| 99 |
+
0.65,
|
| 100 |
+
-2.4,
|
| 101 |
+
0.65,
|
| 102 |
+
-2.4,
|
| 103 |
+
0.65,
|
| 104 |
+
-2.4,
|
| 105 |
+
0.65,
|
| 106 |
+
-2.4,
|
| 107 |
+
0.65,
|
| 108 |
+
2.4,
|
| 109 |
+
-0.65,
|
| 110 |
+
2.4,
|
| 111 |
+
-0.65,
|
| 112 |
+
2.4,
|
| 113 |
+
-0.65,
|
| 114 |
+
2.4,
|
| 115 |
+
-0.65,
|
| 116 |
+
2.4,
|
| 117 |
+
-0.65,
|
| 118 |
+
2.4,
|
| 119 |
+
-0.65,
|
| 120 |
+
2.4,
|
| 121 |
+
-0.65,
|
| 122 |
+
2.4,
|
| 123 |
+
-0.65,
|
| 124 |
+
-2.4,
|
| 125 |
+
0.65,
|
| 126 |
+
-2.4,
|
| 127 |
+
0.65,
|
| 128 |
+
-2.4,
|
| 129 |
+
0.65,
|
| 130 |
+
-2.4,
|
| 131 |
+
0.65,
|
| 132 |
+
-2.4,
|
| 133 |
+
0.65,
|
| 134 |
+
-2.4,
|
| 135 |
+
0.65,
|
| 136 |
+
-2.4,
|
| 137 |
+
0.65,
|
| 138 |
+
-2.4,
|
| 139 |
+
0.65,
|
| 140 |
+
],
|
| 141 |
+
inclinations_deg: [
|
| 142 |
+
12.93,
|
| 143 |
+
12.73,
|
| 144 |
+
12.53,
|
| 145 |
+
12.33,
|
| 146 |
+
12.13,
|
| 147 |
+
11.93,
|
| 148 |
+
11.73,
|
| 149 |
+
11.53,
|
| 150 |
+
11.33,
|
| 151 |
+
11.13,
|
| 152 |
+
10.93,
|
| 153 |
+
10.73,
|
| 154 |
+
10.53,
|
| 155 |
+
10.33,
|
| 156 |
+
10.13,
|
| 157 |
+
9.93,
|
| 158 |
+
9.73,
|
| 159 |
+
9.53,
|
| 160 |
+
9.33,
|
| 161 |
+
9.13,
|
| 162 |
+
8.93,
|
| 163 |
+
8.73,
|
| 164 |
+
8.53,
|
| 165 |
+
8.33,
|
| 166 |
+
8.13,
|
| 167 |
+
7.93,
|
| 168 |
+
7.73,
|
| 169 |
+
7.53,
|
| 170 |
+
7.33,
|
| 171 |
+
7.13,
|
| 172 |
+
6.93,
|
| 173 |
+
6.73,
|
| 174 |
+
6.53,
|
| 175 |
+
6.33,
|
| 176 |
+
6.13,
|
| 177 |
+
5.93,
|
| 178 |
+
5.73,
|
| 179 |
+
5.53,
|
| 180 |
+
5.33,
|
| 181 |
+
5.13,
|
| 182 |
+
4.93,
|
| 183 |
+
4.73,
|
| 184 |
+
4.53,
|
| 185 |
+
4.33,
|
| 186 |
+
4.13,
|
| 187 |
+
3.93,
|
| 188 |
+
3.73,
|
| 189 |
+
3.53,
|
| 190 |
+
3.33,
|
| 191 |
+
3.13,
|
| 192 |
+
2.93,
|
| 193 |
+
2.73,
|
| 194 |
+
2.53,
|
| 195 |
+
2.33,
|
| 196 |
+
2.13,
|
| 197 |
+
1.93,
|
| 198 |
+
1.73,
|
| 199 |
+
1.53,
|
| 200 |
+
1.33,
|
| 201 |
+
1.13,
|
| 202 |
+
0.93,
|
| 203 |
+
0.73,
|
| 204 |
+
0.53,
|
| 205 |
+
0.33,
|
| 206 |
+
0.13,
|
| 207 |
+
-0.07,
|
| 208 |
+
-0.27,
|
| 209 |
+
-0.47,
|
| 210 |
+
-0.67,
|
| 211 |
+
-0.87,
|
| 212 |
+
-1.07,
|
| 213 |
+
-1.27,
|
| 214 |
+
-1.47,
|
| 215 |
+
-1.67,
|
| 216 |
+
-1.87,
|
| 217 |
+
-2.07,
|
| 218 |
+
-2.27,
|
| 219 |
+
-2.47,
|
| 220 |
+
-2.67,
|
| 221 |
+
-2.87,
|
| 222 |
+
-3.07,
|
| 223 |
+
-3.27,
|
| 224 |
+
-3.47,
|
| 225 |
+
-3.67,
|
| 226 |
+
-3.87,
|
| 227 |
+
-4.07,
|
| 228 |
+
-4.27,
|
| 229 |
+
-4.47,
|
| 230 |
+
-4.67,
|
| 231 |
+
-4.87,
|
| 232 |
+
-5.07,
|
| 233 |
+
-5.27,
|
| 234 |
+
-5.47,
|
| 235 |
+
-5.67,
|
| 236 |
+
-5.87,
|
| 237 |
+
-6.07,
|
| 238 |
+
-6.27,
|
| 239 |
+
-6.47,
|
| 240 |
+
-6.67,
|
| 241 |
+
-6.87,
|
| 242 |
+
-7.07,
|
| 243 |
+
-7.27,
|
| 244 |
+
-7.47,
|
| 245 |
+
-7.67,
|
| 246 |
+
-7.87,
|
| 247 |
+
-8.07,
|
| 248 |
+
-8.27,
|
| 249 |
+
-8.47,
|
| 250 |
+
-8.67,
|
| 251 |
+
-8.87,
|
| 252 |
+
-9.07,
|
| 253 |
+
-9.27,
|
| 254 |
+
-9.47,
|
| 255 |
+
-9.67,
|
| 256 |
+
-9.87,
|
| 257 |
+
-10.07,
|
| 258 |
+
-10.27,
|
| 259 |
+
-10.47,
|
| 260 |
+
-10.67,
|
| 261 |
+
-10.87,
|
| 262 |
+
-11.07,
|
| 263 |
+
-11.27,
|
| 264 |
+
-11.47,
|
| 265 |
+
-11.67,
|
| 266 |
+
-11.87,
|
| 267 |
+
-12.07,
|
| 268 |
+
-12.27,
|
| 269 |
+
-12.47,
|
| 270 |
+
]}
|
| 271 |
+
|
| 272 |
+
# https://www.hesaitech.com/product/pandar128/
|
| 273 |
+
# Manu: HESAI Device: Pandar128
|
| 274 |
+
# Params is derived from https://www.hesaitech.com/wp-content/uploads/2023/03/PandarView2_User_Manual_PV2-en-230810-1.pdf
|
| 275 |
+
HESAI-Pandar128: {n_vertical_bins: 128, frequency: 10, horizontal_fov: 360, n_horizontal_bins: 3600,
|
| 276 |
+
sync_angle_deg: 0,
|
| 277 |
+
azimuths_deg_offset: [
|
| 278 |
+
3.257,
|
| 279 |
+
3.263,
|
| 280 |
+
1.091,
|
| 281 |
+
3.268,
|
| 282 |
+
1.093,
|
| 283 |
+
3.273,
|
| 284 |
+
1.094,
|
| 285 |
+
3.278,
|
| 286 |
+
1.095,
|
| 287 |
+
3.283,
|
| 288 |
+
1.096,
|
| 289 |
+
3.288,
|
| 290 |
+
1.097,
|
| 291 |
+
3.291,
|
| 292 |
+
1.098,
|
| 293 |
+
-1.101,
|
| 294 |
+
1.100,
|
| 295 |
+
-1.104,
|
| 296 |
+
-3.306,
|
| 297 |
+
-1.106,
|
| 298 |
+
-3.311,
|
| 299 |
+
-1.109,
|
| 300 |
+
-3.318,
|
| 301 |
+
-1.111,
|
| 302 |
+
-3.324,
|
| 303 |
+
-1.113,
|
| 304 |
+
7.72,
|
| 305 |
+
5.535,
|
| 306 |
+
3.325,
|
| 307 |
+
-3.33,
|
| 308 |
+
1.107,
|
| 309 |
+
-5.538,
|
| 310 |
+
-7.726,
|
| 311 |
+
-1.115,
|
| 312 |
+
7.731,
|
| 313 |
+
5.543,
|
| 314 |
+
3.329,
|
| 315 |
+
-3.336,
|
| 316 |
+
1.108,
|
| 317 |
+
-5.547,
|
| 318 |
+
-7.738,
|
| 319 |
+
-1.117,
|
| 320 |
+
7.743,
|
| 321 |
+
5.551,
|
| 322 |
+
3.335,
|
| 323 |
+
-3.342,
|
| 324 |
+
1.110,
|
| 325 |
+
-5.555,
|
| 326 |
+
-7.750,
|
| 327 |
+
-1.119,
|
| 328 |
+
7.757,
|
| 329 |
+
5.560,
|
| 330 |
+
3.340,
|
| 331 |
+
-3.347,
|
| 332 |
+
1.111,
|
| 333 |
+
-5.564,
|
| 334 |
+
-7.762,
|
| 335 |
+
-1.121,
|
| 336 |
+
7.768,
|
| 337 |
+
5.569,
|
| 338 |
+
3.345,
|
| 339 |
+
-3.353,
|
| 340 |
+
1.113,
|
| 341 |
+
-5.573,
|
| 342 |
+
-7.775,
|
| 343 |
+
-1.123,
|
| 344 |
+
7.780,
|
| 345 |
+
5.578,
|
| 346 |
+
3.351,
|
| 347 |
+
-3.358,
|
| 348 |
+
1.115,
|
| 349 |
+
-5.582,
|
| 350 |
+
-7.787,
|
| 351 |
+
-1.125,
|
| 352 |
+
7.792,
|
| 353 |
+
5.586,
|
| 354 |
+
3.356,
|
| 355 |
+
-3.363,
|
| 356 |
+
1.116,
|
| 357 |
+
-5.591,
|
| 358 |
+
-7.799,
|
| 359 |
+
-1.127,
|
| 360 |
+
7.804,
|
| 361 |
+
5.595,
|
| 362 |
+
3.360,
|
| 363 |
+
-3.369,
|
| 364 |
+
1.118,
|
| 365 |
+
-5.599,
|
| 366 |
+
-7.811,
|
| 367 |
+
-1.129,
|
| 368 |
+
-3.374,
|
| 369 |
+
-1.130,
|
| 370 |
+
-3.379,
|
| 371 |
+
-1.132,
|
| 372 |
+
-3.383,
|
| 373 |
+
3.381,
|
| 374 |
+
-3.388,
|
| 375 |
+
3.386,
|
| 376 |
+
1.129,
|
| 377 |
+
3.390,
|
| 378 |
+
1.129,
|
| 379 |
+
3.395,
|
| 380 |
+
1.131,
|
| 381 |
+
3.401,
|
| 382 |
+
1.133,
|
| 383 |
+
3.406,
|
| 384 |
+
1.135,
|
| 385 |
+
3.410,
|
| 386 |
+
1.137,
|
| 387 |
+
3.416,
|
| 388 |
+
1.139,
|
| 389 |
+
-1.142,
|
| 390 |
+
1.142,
|
| 391 |
+
-1.143,
|
| 392 |
+
-3.426,
|
| 393 |
+
-1.143,
|
| 394 |
+
-3.429,
|
| 395 |
+
-1.145,
|
| 396 |
+
-3.433,
|
| 397 |
+
-1.145,
|
| 398 |
+
-3.436,
|
| 399 |
+
-1.146,
|
| 400 |
+
-3.440,
|
| 401 |
+
-1.146,
|
| 402 |
+
-3.443,
|
| 403 |
+
-1.146,
|
| 404 |
+
-3.446,
|
| 405 |
+
-3.449,
|
| 406 |
+
],
|
| 407 |
+
inclinations_deg: [
|
| 408 |
+
14.436,
|
| 409 |
+
13.535,
|
| 410 |
+
13.082,
|
| 411 |
+
12.624,
|
| 412 |
+
12.165,
|
| 413 |
+
11.702,
|
| 414 |
+
11.239,
|
| 415 |
+
10.771,
|
| 416 |
+
10.305,
|
| 417 |
+
9.830,
|
| 418 |
+
9.356,
|
| 419 |
+
8.880,
|
| 420 |
+
8.401,
|
| 421 |
+
7.921,
|
| 422 |
+
7.438,
|
| 423 |
+
6.953,
|
| 424 |
+
6.467,
|
| 425 |
+
5.978,
|
| 426 |
+
5.487,
|
| 427 |
+
4.996,
|
| 428 |
+
4.501,
|
| 429 |
+
4.007,
|
| 430 |
+
3.509,
|
| 431 |
+
3.013,
|
| 432 |
+
2.512,
|
| 433 |
+
2.013,
|
| 434 |
+
1.885,
|
| 435 |
+
1.761,
|
| 436 |
+
1.637,
|
| 437 |
+
1.511,
|
| 438 |
+
1.386,
|
| 439 |
+
1.258,
|
| 440 |
+
1.13,
|
| 441 |
+
1.008,
|
| 442 |
+
0.88,
|
| 443 |
+
0.756,
|
| 444 |
+
0.63,
|
| 445 |
+
0.505,
|
| 446 |
+
0.379,
|
| 447 |
+
0.251,
|
| 448 |
+
0.124,
|
| 449 |
+
0.000,
|
| 450 |
+
-0.129,
|
| 451 |
+
-0.254,
|
| 452 |
+
-0.380,
|
| 453 |
+
-0.506,
|
| 454 |
+
-0.632,
|
| 455 |
+
-0.760,
|
| 456 |
+
-0.887,
|
| 457 |
+
-1.012,
|
| 458 |
+
-1.141,
|
| 459 |
+
-1.266,
|
| 460 |
+
-1.393,
|
| 461 |
+
-1.519,
|
| 462 |
+
-1.646,
|
| 463 |
+
-1.773,
|
| 464 |
+
-1.901,
|
| 465 |
+
-2.027,
|
| 466 |
+
-2.155,
|
| 467 |
+
-2.282,
|
| 468 |
+
-2.409,
|
| 469 |
+
-2.535,
|
| 470 |
+
-2.663,
|
| 471 |
+
-2.789,
|
| 472 |
+
-2.916,
|
| 473 |
+
-3.044,
|
| 474 |
+
-3.172,
|
| 475 |
+
-3.299,
|
| 476 |
+
-3.425,
|
| 477 |
+
-3.552,
|
| 478 |
+
-3.680,
|
| 479 |
+
-3.806,
|
| 480 |
+
-3.933,
|
| 481 |
+
-4.062,
|
| 482 |
+
-4.190,
|
| 483 |
+
-4.318,
|
| 484 |
+
-4.444,
|
| 485 |
+
-4.571,
|
| 486 |
+
-4.699,
|
| 487 |
+
-4.824,
|
| 488 |
+
-4.951,
|
| 489 |
+
-5.081,
|
| 490 |
+
-5.209,
|
| 491 |
+
-5.336,
|
| 492 |
+
-5.463,
|
| 493 |
+
-5.589,
|
| 494 |
+
-5.718,
|
| 495 |
+
-5.843,
|
| 496 |
+
-5.968,
|
| 497 |
+
-6.100,
|
| 498 |
+
-6.607,
|
| 499 |
+
-7.117,
|
| 500 |
+
-7.624,
|
| 501 |
+
-8.134,
|
| 502 |
+
-8.640,
|
| 503 |
+
-9.149,
|
| 504 |
+
-9.652,
|
| 505 |
+
-10.160,
|
| 506 |
+
-10.665,
|
| 507 |
+
-11.170,
|
| 508 |
+
-11.672,
|
| 509 |
+
-12.174,
|
| 510 |
+
-12.673,
|
| 511 |
+
-13.173,
|
| 512 |
+
-13.67,
|
| 513 |
+
-14.166,
|
| 514 |
+
-14.66,
|
| 515 |
+
-15.154,
|
| 516 |
+
-15.645,
|
| 517 |
+
-16.135,
|
| 518 |
+
-16.622,
|
| 519 |
+
-17.106,
|
| 520 |
+
-17.592,
|
| 521 |
+
-18.072,
|
| 522 |
+
-18.548,
|
| 523 |
+
-19.030,
|
| 524 |
+
-19.501,
|
| 525 |
+
-19.978,
|
| 526 |
+
-20.445,
|
| 527 |
+
-20.918,
|
| 528 |
+
-21.379,
|
| 529 |
+
-21.848,
|
| 530 |
+
-22.304,
|
| 531 |
+
-22.768,
|
| 532 |
+
-23.219,
|
| 533 |
+
-23.678,
|
| 534 |
+
-24.123,
|
| 535 |
+
-25.016,
|
| 536 |
+
]}
|
assets/lidar/sensors.yaml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
# Public sensor contracts. Per-sequence calibration remains authoritative for
|
| 5 |
+
# NCore-backed datasets; this file records the grids consumed by LidarVerse.
|
| 6 |
+
sensors:
|
| 7 |
+
nvidia_pai:
|
| 8 |
+
model: HESAI-AT128
|
| 9 |
+
grid: [128, 1200]
|
| 10 |
+
cadence_hz: 10
|
| 11 |
+
calibration: assets/lidar/lidar_model.yaml
|
| 12 |
+
pandaset:
|
| 13 |
+
model: HESAI-Pandar64
|
| 14 |
+
grid: [64, 1024]
|
| 15 |
+
cadence_hz: 10
|
| 16 |
+
calibration: tokenizer/training/datasets/lidar_datasets/pandaset.py
|
| 17 |
+
nuscenes:
|
| 18 |
+
model: HDL-32E
|
| 19 |
+
grid: [32, 1024]
|
| 20 |
+
native_cadence_hz: 20
|
| 21 |
+
world_model_cadence_hz: 2
|
| 22 |
+
calibration: per-sequence NCore metadata
|
| 23 |
+
waymo:
|
| 24 |
+
model: TOP
|
| 25 |
+
grid: [64, 1024]
|
| 26 |
+
cadence_hz: 10
|
| 27 |
+
calibration: per-sequence NCore metadata
|
diffusion/checkpointers/ema_fsdp_checkpointer.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import warnings
|
| 17 |
+
|
| 18 |
+
import attrs
|
| 19 |
+
|
| 20 |
+
from utils import log
|
| 21 |
+
from utils.config import CheckpointConfig as BaseCheckpointConfig
|
| 22 |
+
from utils.config import make_freezable
|
| 23 |
+
from utils.fsdp_checkpointer import FSDPCheckpointer as BaseFSDPCheckpointer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@make_freezable
|
| 27 |
+
@attrs.define(slots=False)
|
| 28 |
+
class CheckpointConfig(BaseCheckpointConfig):
|
| 29 |
+
load_ema_to_reg: bool = False
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class FSDPCheckpointer(BaseFSDPCheckpointer):
|
| 33 |
+
def __init__(self, *args, **kwargs):
|
| 34 |
+
super().__init__(*args, **kwargs)
|
| 35 |
+
if not isinstance(self.config_checkpoint, CheckpointConfig):
|
| 36 |
+
warnings.warn(
|
| 37 |
+
"The 'config_checkpoint' is not an instance of 'CheckpointConfig'. "
|
| 38 |
+
"This behavior is deprecated and will not be supported in future versions. "
|
| 39 |
+
"Please update 'config_checkpoint' to be of type 'CheckpointConfig'.",
|
| 40 |
+
DeprecationWarning,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
self.load_ema_to_reg = False
|
| 44 |
+
else:
|
| 45 |
+
self.load_ema_to_reg = self.config_checkpoint.load_ema_to_reg
|
| 46 |
+
|
| 47 |
+
log.critical(f"load_ema_to_reg: {self.load_ema_to_reg}", rank0_only=False)
|
| 48 |
+
|
| 49 |
+
def load_model_during_init(self, model, is_ema: bool = False, ema_id: int = 0):
|
| 50 |
+
if self.load_ema_to_reg and is_ema is False:
|
| 51 |
+
is_ema = True
|
| 52 |
+
ema_id = 0
|
| 53 |
+
log.critical("Loading EMA model to regular model during initialization.", rank0_only=False)
|
| 54 |
+
super().load_model_during_init(model, is_ema, ema_id)
|
diffusion/conditioner.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
from abc import ABC, abstractmethod
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from dataclasses import dataclass, fields
|
| 20 |
+
from enum import Enum
|
| 21 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn as nn
|
| 25 |
+
|
| 26 |
+
from utils import log
|
| 27 |
+
from utils.lazy_config import instantiate
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class BaseConditionEntry(nn.Module):
|
| 31 |
+
def __init__(self):
|
| 32 |
+
super().__init__()
|
| 33 |
+
|
| 34 |
+
self._dropout_rate = None
|
| 35 |
+
self._input_key = None
|
| 36 |
+
self._return_dict = False
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def dropout_rate(self) -> Union[float, torch.Tensor]:
|
| 40 |
+
return self._dropout_rate
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def input_key(self) -> str:
|
| 44 |
+
return self._input_key
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def is_return_dict(self) -> bool:
|
| 48 |
+
return self._return_dict
|
| 49 |
+
|
| 50 |
+
@dropout_rate.setter
|
| 51 |
+
def dropout_rate(self, value: Union[float, torch.Tensor]):
|
| 52 |
+
self._dropout_rate = value
|
| 53 |
+
|
| 54 |
+
@input_key.setter
|
| 55 |
+
def input_key(self, value: str):
|
| 56 |
+
self._input_key = value
|
| 57 |
+
|
| 58 |
+
@is_return_dict.setter
|
| 59 |
+
def is_return_dict(self, value: bool):
|
| 60 |
+
self._return_dict = value
|
| 61 |
+
|
| 62 |
+
@dropout_rate.deleter
|
| 63 |
+
def dropout_rate(self):
|
| 64 |
+
del self._dropout_rate
|
| 65 |
+
|
| 66 |
+
@input_key.deleter
|
| 67 |
+
def input_key(self):
|
| 68 |
+
del self._input_key
|
| 69 |
+
|
| 70 |
+
@is_return_dict.deleter
|
| 71 |
+
def is_return_dict(self):
|
| 72 |
+
del self._return_dict
|
| 73 |
+
|
| 74 |
+
def random_dropout_input(
|
| 75 |
+
self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None
|
| 76 |
+
) -> torch.Tensor:
|
| 77 |
+
del key
|
| 78 |
+
dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate
|
| 79 |
+
bernoulli = torch.bernoulli((1.0 - dropout_rate) * torch.ones(len(in_tensor))).type_as(in_tensor)
|
| 80 |
+
bernoulli_expand = bernoulli.view((-1,) + (1,) * (in_tensor.dim() - 1))
|
| 81 |
+
return bernoulli_expand * in_tensor
|
| 82 |
+
|
| 83 |
+
def summary(self) -> str:
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class DataType(Enum):
|
| 88 |
+
IMAGE = "image"
|
| 89 |
+
VIDEO = "video"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class TextAttr(BaseConditionEntry):
|
| 93 |
+
def __init__(self):
|
| 94 |
+
super().__init__()
|
| 95 |
+
|
| 96 |
+
def forward(self, token: torch.Tensor, mask: torch.Tensor):
|
| 97 |
+
return {"crossattn_emb": token, "crossattn_mask": mask}
|
| 98 |
+
|
| 99 |
+
def random_dropout_input(
|
| 100 |
+
self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None
|
| 101 |
+
) -> torch.Tensor:
|
| 102 |
+
if key is not None and "mask" in key:
|
| 103 |
+
return in_tensor
|
| 104 |
+
return super().random_dropout_input(in_tensor, dropout_rate, key)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@dataclass
|
| 108 |
+
class BaseVideoCondition:
|
| 109 |
+
crossattn_emb: torch.Tensor
|
| 110 |
+
crossattn_mask: torch.Tensor
|
| 111 |
+
data_type: DataType = DataType.VIDEO
|
| 112 |
+
padding_mask: Optional[torch.Tensor] = None
|
| 113 |
+
fps: Optional[torch.Tensor] = None
|
| 114 |
+
num_frames: Optional[torch.Tensor] = None
|
| 115 |
+
image_size: Optional[torch.Tensor] = None
|
| 116 |
+
scalar_feature: Optional[torch.Tensor] = None
|
| 117 |
+
frame_repeat: Optional[torch.Tensor] = None
|
| 118 |
+
|
| 119 |
+
def to_dict(self) -> Dict[str, Optional[torch.Tensor]]:
|
| 120 |
+
return {f.name: getattr(self, f.name) for f in fields(self)}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclass
|
| 124 |
+
class VideoExtendCondition(BaseVideoCondition):
|
| 125 |
+
video_cond_bool: Optional[torch.Tensor] = None # whether or not it conditioned on video
|
| 126 |
+
gt_latent: Optional[torch.Tensor] = None
|
| 127 |
+
condition_video_indicator: Optional[torch.Tensor] = None # 1 for condition region
|
| 128 |
+
|
| 129 |
+
# condition_video_input_mask will concat to the input of network, along channel dim;
|
| 130 |
+
# Will be concat with the input tensor
|
| 131 |
+
condition_video_input_mask: Optional[torch.Tensor] = None
|
| 132 |
+
# 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"
|
| 133 |
+
condition_video_augment_sigma: Optional[torch.Tensor] = None
|
| 134 |
+
# pose conditional input, will be concat with the input tensor
|
| 135 |
+
condition_video_pose: Optional[torch.Tensor] = None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@dataclass
|
| 139 |
+
class ViewConditionedVideoExtendCondition(VideoExtendCondition):
|
| 140 |
+
# view index indicating camera, used to index nn.Embedding
|
| 141 |
+
view_indices_B_T: Optional[torch.Tensor] = None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class GeneralConditioner(nn.Module, ABC):
|
| 145 |
+
"""
|
| 146 |
+
An abstract module designed to handle various embedding models with conditional and
|
| 147 |
+
unconditional configurations. This abstract base class initializes and manages a collection
|
| 148 |
+
of embedders that can dynamically adjust their dropout rates based on conditioning.
|
| 149 |
+
|
| 150 |
+
Attributes:
|
| 151 |
+
KEY2DIM (dict): A mapping from output keys to dimensions used for concatenation.
|
| 152 |
+
embedders (nn.ModuleDict): A dictionary containing all embedded models initialized and
|
| 153 |
+
configured based on the provided configurations.
|
| 154 |
+
|
| 155 |
+
Parameters:
|
| 156 |
+
emb_models (Union[List, Any]): A dictionary where keys are embedder names and values
|
| 157 |
+
are configurations for initializing the embedders.
|
| 158 |
+
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
KEY2DIM = {"crossattn_emb": 1, "crossattn_mask": 1}
|
| 162 |
+
|
| 163 |
+
def __init__(self, **emb_models: Union[List, Any]):
|
| 164 |
+
super().__init__()
|
| 165 |
+
self.embedders = nn.ModuleDict()
|
| 166 |
+
for n, (emb_name, embconfig) in enumerate(emb_models.items()):
|
| 167 |
+
embedder = instantiate(embconfig.obj)
|
| 168 |
+
assert isinstance(
|
| 169 |
+
embedder, BaseConditionEntry
|
| 170 |
+
), f"embedder model {embedder.__class__.__name__} has to inherit from BaseConditionEntry"
|
| 171 |
+
embedder.dropout_rate = getattr(embconfig, "dropout_rate", 0.0)
|
| 172 |
+
|
| 173 |
+
if hasattr(embconfig, "input_key"):
|
| 174 |
+
embedder.input_key = embconfig.input_key
|
| 175 |
+
elif hasattr(embconfig, "input_keys"):
|
| 176 |
+
embedder.input_keys = embconfig.input_keys
|
| 177 |
+
else:
|
| 178 |
+
raise KeyError(f"need either 'input_key' or 'input_keys' for embedder {embedder.__class__.__name__}")
|
| 179 |
+
|
| 180 |
+
log.debug(f"Initialized embedder #{n}-{emb_name}: \n {embedder.summary()}")
|
| 181 |
+
self.embedders[emb_name] = embedder
|
| 182 |
+
|
| 183 |
+
@abstractmethod
|
| 184 |
+
def forward(
|
| 185 |
+
self,
|
| 186 |
+
batch: Dict,
|
| 187 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 188 |
+
) -> Any:
|
| 189 |
+
"""Should be implemented in subclasses to handle conditon datatype"""
|
| 190 |
+
raise NotImplementedError
|
| 191 |
+
|
| 192 |
+
def _forward(
|
| 193 |
+
self,
|
| 194 |
+
batch: Dict,
|
| 195 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 196 |
+
) -> Dict:
|
| 197 |
+
"""
|
| 198 |
+
Processes the input batch through all configured embedders, applying conditional dropout rates if specified.
|
| 199 |
+
Output tensors for each key are concatenated along the dimensions specified in KEY2DIM.
|
| 200 |
+
|
| 201 |
+
Parameters:
|
| 202 |
+
batch (Dict): The input data batch to process.
|
| 203 |
+
override_dropout_rate (Optional[Dict[str, float]]): Optional dictionary to override default dropout rates
|
| 204 |
+
per embedder key.
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
Dict: A dictionary of output tensors concatenated by specified dimensions.
|
| 208 |
+
|
| 209 |
+
Note:
|
| 210 |
+
In case the network code is sensitive to the order of concatenation, you can either control the order via \
|
| 211 |
+
config file or make sure the embedders return a unique key for each output.
|
| 212 |
+
"""
|
| 213 |
+
output = defaultdict(list)
|
| 214 |
+
if override_dropout_rate is None:
|
| 215 |
+
override_dropout_rate = {}
|
| 216 |
+
|
| 217 |
+
# make sure emb_name in override_dropout_rate is valid
|
| 218 |
+
for emb_name in override_dropout_rate.keys():
|
| 219 |
+
assert emb_name in self.embedders, f"invalid name found {emb_name}"
|
| 220 |
+
|
| 221 |
+
for emb_name, embedder in self.embedders.items():
|
| 222 |
+
with torch.no_grad():
|
| 223 |
+
if hasattr(embedder, "input_key") and (embedder.input_key is not None):
|
| 224 |
+
emb_out = embedder(
|
| 225 |
+
embedder.random_dropout_input(
|
| 226 |
+
batch[embedder.input_key], override_dropout_rate.get(emb_name, None)
|
| 227 |
+
)
|
| 228 |
+
)
|
| 229 |
+
elif hasattr(embedder, "input_keys"):
|
| 230 |
+
emb_out = embedder(
|
| 231 |
+
*[
|
| 232 |
+
embedder.random_dropout_input(batch[k], override_dropout_rate.get(emb_name, None), k)
|
| 233 |
+
for k in embedder.input_keys
|
| 234 |
+
]
|
| 235 |
+
)
|
| 236 |
+
for k, v in emb_out.items():
|
| 237 |
+
output[k].append(v)
|
| 238 |
+
# Concatenate the outputs
|
| 239 |
+
return {k: torch.cat(v, dim=self.KEY2DIM.get(k, -1)) for k, v in output.items()}
|
| 240 |
+
|
| 241 |
+
def get_condition_uncondition(
|
| 242 |
+
self,
|
| 243 |
+
data_batch: Dict,
|
| 244 |
+
) -> Tuple[Any, Any]:
|
| 245 |
+
"""
|
| 246 |
+
Processes the provided data batch to generate conditioned and unconditioned outputs.
|
| 247 |
+
|
| 248 |
+
This method manipulates dropout rates to simulate two scenarios:
|
| 249 |
+
1. All conditions applied (conditioned)
|
| 250 |
+
2. Conditions removed/reduced to minimum (unconditioned)
|
| 251 |
+
|
| 252 |
+
This method sets dropout rates to zero for the conditioned scenario to fully apply
|
| 253 |
+
embedders' effects. For unconditioned, it sets rates to 1 (or 0 if initial rate is
|
| 254 |
+
insignificant) to minimize embedder influences.
|
| 255 |
+
|
| 256 |
+
Parameters:
|
| 257 |
+
data_batch (Dict): Input data batch containing all necessary information for
|
| 258 |
+
embedding processing.
|
| 259 |
+
|
| 260 |
+
Returns:
|
| 261 |
+
Tuple[Any, Any]: A tuple containing:
|
| 262 |
+
- Outputs with all embedders fully applied (conditioned)
|
| 263 |
+
- Outputs with embedders minimized/not applied (unconditioned)
|
| 264 |
+
"""
|
| 265 |
+
cond_dropout_rates, dropout_rates = {}, {}
|
| 266 |
+
for emb_name, embedder in self.embedders.items():
|
| 267 |
+
cond_dropout_rates[emb_name] = 0.0
|
| 268 |
+
dropout_rates[emb_name] = 1.0 if embedder.dropout_rate > 1e-4 else 0.0
|
| 269 |
+
|
| 270 |
+
condition: Any = self(data_batch, override_dropout_rate=cond_dropout_rates)
|
| 271 |
+
un_condition: Any = self(data_batch, override_dropout_rate=dropout_rates)
|
| 272 |
+
return condition, un_condition
|
| 273 |
+
|
| 274 |
+
def get_condition_with_negative_prompt(
|
| 275 |
+
self,
|
| 276 |
+
data_batch: Dict,
|
| 277 |
+
) -> Tuple[Any, Any]:
|
| 278 |
+
"""
|
| 279 |
+
Similar functionality as get_condition_uncondition
|
| 280 |
+
But use negative prompts for unconditon
|
| 281 |
+
"""
|
| 282 |
+
cond_dropout_rates, uncond_dropout_rates = {}, {}
|
| 283 |
+
for emb_name, embedder in self.embedders.items():
|
| 284 |
+
cond_dropout_rates[emb_name] = 0.0
|
| 285 |
+
if isinstance(embedder, TextAttr):
|
| 286 |
+
uncond_dropout_rates[emb_name] = 0.0
|
| 287 |
+
else:
|
| 288 |
+
uncond_dropout_rates[emb_name] = 1.0 if embedder.dropout_rate > 1e-4 else 0.0
|
| 289 |
+
|
| 290 |
+
data_batch_neg_prompt = copy.deepcopy(data_batch)
|
| 291 |
+
if "neg_t5_text_embeddings" in data_batch_neg_prompt:
|
| 292 |
+
if isinstance(data_batch_neg_prompt["neg_t5_text_embeddings"], torch.Tensor):
|
| 293 |
+
data_batch_neg_prompt["t5_text_embeddings"] = data_batch_neg_prompt["neg_t5_text_embeddings"]
|
| 294 |
+
data_batch_neg_prompt["t5_text_mask"] = data_batch_neg_prompt["neg_t5_text_mask"]
|
| 295 |
+
|
| 296 |
+
condition: Any = self(data_batch, override_dropout_rate=cond_dropout_rates)
|
| 297 |
+
un_condition: Any = self(data_batch_neg_prompt, override_dropout_rate=uncond_dropout_rates)
|
| 298 |
+
|
| 299 |
+
return condition, un_condition
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@dataclass
|
| 303 |
+
class CosmosCondition:
|
| 304 |
+
crossattn_emb: torch.Tensor
|
| 305 |
+
crossattn_mask: torch.Tensor
|
| 306 |
+
padding_mask: Optional[torch.Tensor] = None
|
| 307 |
+
scalar_feature: Optional[torch.Tensor] = None
|
| 308 |
+
|
| 309 |
+
def to_dict(self) -> Dict[str, Optional[torch.Tensor]]:
|
| 310 |
+
return {f.name: getattr(self, f.name) for f in fields(self)}
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class VideoConditioner(GeneralConditioner):
|
| 314 |
+
def forward(
|
| 315 |
+
self,
|
| 316 |
+
batch: Dict,
|
| 317 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 318 |
+
) -> BaseVideoCondition:
|
| 319 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 320 |
+
return BaseVideoCondition(**output)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class VideoExtendConditioner(GeneralConditioner):
|
| 324 |
+
def forward(
|
| 325 |
+
self,
|
| 326 |
+
batch: Dict,
|
| 327 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 328 |
+
) -> VideoExtendCondition:
|
| 329 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 330 |
+
return VideoExtendCondition(**output)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class ViewConditionedVideoExtendConditioner(GeneralConditioner):
|
| 334 |
+
def forward(
|
| 335 |
+
self,
|
| 336 |
+
batch: Dict,
|
| 337 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 338 |
+
) -> ViewConditionedVideoExtendCondition:
|
| 339 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 340 |
+
return ViewConditionedVideoExtendCondition(**output)
|
diffusion/config/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
diffusion/config/base/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
diffusion/config/base/conditioner.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Dict, List, Optional
|
| 17 |
+
|
| 18 |
+
import attrs
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from diffusion.conditioner import (
|
| 22 |
+
BaseConditionEntry,
|
| 23 |
+
TextAttr,
|
| 24 |
+
VideoConditioner,
|
| 25 |
+
VideoExtendConditioner,
|
| 26 |
+
ViewConditionedVideoExtendConditioner,
|
| 27 |
+
)
|
| 28 |
+
from utils.lazy_config import LazyCall as L
|
| 29 |
+
from utils.lazy_config import LazyDict
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@attrs.define(slots=False)
|
| 33 |
+
class TextConfig:
|
| 34 |
+
obj: LazyDict = L(TextAttr)() # No arguments
|
| 35 |
+
dropout_rate: float = 0.2
|
| 36 |
+
input_keys: List[str] = attrs.field(factory=lambda: ["t5_text_embeddings", "t5_text_mask"])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BooleanFlag(BaseConditionEntry):
|
| 40 |
+
def __init__(self, output_key: Optional[str] = None):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.output_key = output_key
|
| 43 |
+
|
| 44 |
+
def forward(self, *args, **kwargs) -> Dict[str, torch.Tensor]:
|
| 45 |
+
del args, kwargs
|
| 46 |
+
key = self.output_key if self.output_key else self.input_key
|
| 47 |
+
return {key: self.flag}
|
| 48 |
+
|
| 49 |
+
def random_dropout_input(
|
| 50 |
+
self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None
|
| 51 |
+
) -> torch.Tensor:
|
| 52 |
+
del key
|
| 53 |
+
dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate
|
| 54 |
+
self.flag = torch.bernoulli((1.0 - dropout_rate) * torch.ones(1)).bool().to(device=in_tensor.device)
|
| 55 |
+
return in_tensor
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ReMapkey(BaseConditionEntry):
|
| 59 |
+
def __init__(self, output_key: Optional[str] = None, dtype: Optional[str] = None):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.output_key = output_key
|
| 62 |
+
self.dtype = {
|
| 63 |
+
None: None,
|
| 64 |
+
"float": torch.float32,
|
| 65 |
+
"bfloat16": torch.bfloat16,
|
| 66 |
+
"half": torch.float16,
|
| 67 |
+
"float16": torch.float16,
|
| 68 |
+
"int": torch.int32,
|
| 69 |
+
"long": torch.int64,
|
| 70 |
+
}[dtype]
|
| 71 |
+
|
| 72 |
+
def forward(self, element: torch.Tensor) -> Dict[str, torch.Tensor]:
|
| 73 |
+
key = self.output_key if self.output_key else self.input_key
|
| 74 |
+
if isinstance(element, torch.Tensor):
|
| 75 |
+
element = element.to(dtype=self.dtype)
|
| 76 |
+
return {key: element}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class FrameRepeatAttr(BaseConditionEntry):
|
| 80 |
+
def __init__(self):
|
| 81 |
+
super().__init__()
|
| 82 |
+
|
| 83 |
+
def forward(self, frame_repeat: torch.Tensor) -> Dict[str, torch.Tensor]:
|
| 84 |
+
return {
|
| 85 |
+
"frame_repeat": frame_repeat / 10.0,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@attrs.define(slots=False)
|
| 90 |
+
class FPSConfig:
|
| 91 |
+
"""
|
| 92 |
+
Remap the key from the input dictionary to the output dictionary. For `fps`.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
obj: LazyDict = L(ReMapkey)(output_key="fps", dtype=None)
|
| 96 |
+
dropout_rate: float = 0.0
|
| 97 |
+
input_key: str = "fps"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@attrs.define(slots=False)
|
| 101 |
+
class PaddingMaskConfig:
|
| 102 |
+
"""
|
| 103 |
+
Remap the key from the input dictionary to the output dictionary. For `padding_mask`.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
obj: LazyDict = L(ReMapkey)(output_key="padding_mask", dtype=None)
|
| 107 |
+
dropout_rate: float = 0.0
|
| 108 |
+
input_key: str = "padding_mask"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@attrs.define(slots=False)
|
| 112 |
+
class ImageSizeConfig:
|
| 113 |
+
"""
|
| 114 |
+
Remap the key from the input dictionary to the output dictionary. For `image_size`.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
obj: LazyDict = L(ReMapkey)(output_key="image_size", dtype=None)
|
| 118 |
+
dropout_rate: float = 0.0
|
| 119 |
+
input_key: str = "image_size"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@attrs.define(slots=False)
|
| 123 |
+
class NumFramesConfig:
|
| 124 |
+
"""
|
| 125 |
+
Remap the key from the input dictionary to the output dictionary. For `num_frames`.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
obj: LazyDict = L(ReMapkey)(output_key="num_frames", dtype=None)
|
| 129 |
+
dropout_rate: float = 0.0
|
| 130 |
+
input_key: str = "num_frames"
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@attrs.define(slots=False)
|
| 134 |
+
class FrameRepeatConfig:
|
| 135 |
+
"""
|
| 136 |
+
Remap and process key from the input dictionary to the output dictionary. For `frame_repeat`.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
obj: LazyDict = L(FrameRepeatAttr)()
|
| 140 |
+
dropout_rate: float = 0.0
|
| 141 |
+
input_key: str = "frame_repeat"
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@attrs.define(slots=False)
|
| 145 |
+
class VideoCondBoolConfig:
|
| 146 |
+
obj: LazyDict = L(BooleanFlag)(output_key="video_cond_bool")
|
| 147 |
+
dropout_rate: float = 0.2
|
| 148 |
+
input_key: str = "fps" # This is a placeholder, we never use this value
|
| 149 |
+
# Config below are for long video generation only
|
| 150 |
+
compute_loss_for_condition_region: bool = False # Compute loss for condition region
|
| 151 |
+
|
| 152 |
+
# 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,
|
| 153 |
+
condition_location: str = "first_random_n"
|
| 154 |
+
random_conditon_rate: float = 0.5 # The rate to sample the condition region randomly
|
| 155 |
+
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"
|
| 156 |
+
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"
|
| 157 |
+
|
| 158 |
+
# How to dropout value of the conditional input frames
|
| 159 |
+
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
|
| 160 |
+
|
| 161 |
+
# How to corrupt the condition region
|
| 162 |
+
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)
|
| 163 |
+
# 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"
|
| 164 |
+
apply_corruption_to_condition_region_sigma_value: list[float] = [0.001, 0.2] + [
|
| 165 |
+
0.5
|
| 166 |
+
] * 10 # Sigma value for the corruption, used when apply_corruption_to_condition_region is "noise_with_sigma_fixed"
|
| 167 |
+
|
| 168 |
+
# Add augment_sigma condition to the network
|
| 169 |
+
condition_on_augment_sigma: bool = False
|
| 170 |
+
# The following arguments is to match with previous implementation where we use train sde to sample augment sigma (with adjust video noise turn on)
|
| 171 |
+
augment_sigma_sample_p_mean: float = 0.0 # Mean of the augment sigma
|
| 172 |
+
augment_sigma_sample_p_std: float = 1.0 # Std of the augment sigma
|
| 173 |
+
augment_sigma_sample_multiplier: float = 4.0 # Multipler of augment sigma
|
| 174 |
+
|
| 175 |
+
# Add pose condition to the network
|
| 176 |
+
add_pose_condition: bool = False
|
| 177 |
+
|
| 178 |
+
# Sample PPP... from IPPP... sequence
|
| 179 |
+
sample_tokens_start_from_p_or_i: bool = False
|
| 180 |
+
|
| 181 |
+
# Normalize the input condition latent
|
| 182 |
+
normalize_condition_latent: bool = False
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@attrs.define(slots=False)
|
| 186 |
+
class MVVideoCondBoolConfig(VideoCondBoolConfig):
|
| 187 |
+
n_cond_view_max: int = 1 # The max number of camera views as condition region
|
| 188 |
+
n_cond_view_min: int = 1 # The min number of camera views as condition region
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@attrs.define(slots=False)
|
| 192 |
+
class LatentConditionConfig:
|
| 193 |
+
"""
|
| 194 |
+
Remap the key from the input dictionary to the output dictionary. For `latent condition`.
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
obj: LazyDict = L(ReMapkey)(output_key="latent_condition", dtype=None)
|
| 198 |
+
dropout_rate: float = 0.0
|
| 199 |
+
input_key: str = "latent_condition"
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@attrs.define(slots=False)
|
| 203 |
+
class LatentConditionSigmaConfig:
|
| 204 |
+
"""
|
| 205 |
+
Remap the key from the input dictionary to the output dictionary. For `latent condition`.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
obj: LazyDict = L(ReMapkey)(output_key="latent_condition_sigma", dtype=None)
|
| 209 |
+
dropout_rate: float = 0.0
|
| 210 |
+
input_key: str = "latent_condition_sigma"
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
BaseVideoConditionerConfig: LazyDict = L(VideoConditioner)(
|
| 214 |
+
text=TextConfig(),
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
VideoConditionerFpsSizePaddingConfig: LazyDict = L(VideoConditioner)(
|
| 218 |
+
text=TextConfig(),
|
| 219 |
+
fps=FPSConfig(),
|
| 220 |
+
num_frames=NumFramesConfig(),
|
| 221 |
+
image_size=ImageSizeConfig(),
|
| 222 |
+
padding_mask=PaddingMaskConfig(),
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
VideoExtendConditionerConfig: LazyDict = L(VideoExtendConditioner)(
|
| 226 |
+
text=TextConfig(),
|
| 227 |
+
fps=FPSConfig(),
|
| 228 |
+
num_frames=NumFramesConfig(),
|
| 229 |
+
image_size=ImageSizeConfig(),
|
| 230 |
+
padding_mask=PaddingMaskConfig(),
|
| 231 |
+
video_cond_bool=VideoCondBoolConfig(),
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
VideoConditionerFpsSizePaddingFrameRepeatConfig: LazyDict = L(VideoConditioner)(
|
| 235 |
+
text=TextConfig(),
|
| 236 |
+
fps=FPSConfig(),
|
| 237 |
+
num_frames=NumFramesConfig(),
|
| 238 |
+
image_size=ImageSizeConfig(),
|
| 239 |
+
padding_mask=PaddingMaskConfig(),
|
| 240 |
+
frame_repeat=FrameRepeatConfig(),
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
VideoExtendConditionerFrameRepeatConfig: LazyDict = L(VideoExtendConditioner)(
|
| 244 |
+
text=TextConfig(),
|
| 245 |
+
fps=FPSConfig(),
|
| 246 |
+
num_frames=NumFramesConfig(),
|
| 247 |
+
image_size=ImageSizeConfig(),
|
| 248 |
+
padding_mask=PaddingMaskConfig(),
|
| 249 |
+
video_cond_bool=VideoCondBoolConfig(),
|
| 250 |
+
frame_repeat=FrameRepeatConfig(),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
ViewConditionedVideoExtendConditionerFrameRepeatConfig: LazyDict = L(ViewConditionedVideoExtendConditioner)(
|
| 254 |
+
text=TextConfig(),
|
| 255 |
+
fps=FPSConfig(),
|
| 256 |
+
num_frames=NumFramesConfig(),
|
| 257 |
+
image_size=ImageSizeConfig(),
|
| 258 |
+
padding_mask=PaddingMaskConfig(),
|
| 259 |
+
video_cond_bool=MVVideoCondBoolConfig(),
|
| 260 |
+
frame_repeat=FrameRepeatConfig(),
|
| 261 |
+
)
|
diffusion/functional/batch_ops.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
# Functions for performing operations with broadcasting to the right axis
|
| 17 |
+
#
|
| 18 |
+
# Example
|
| 19 |
+
# input1: tensor of size (N1, N2)
|
| 20 |
+
# input2: tensor of size (N1, N2, N3, N4)
|
| 21 |
+
# batch_mul(input1, input2) = input1[:, :, None, None] * input2
|
| 22 |
+
#
|
| 23 |
+
# If the common dimensions don't match, we raise an assertion error.
|
| 24 |
+
|
| 25 |
+
from torch import Tensor
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def common_broadcast(x: Tensor, y: Tensor) -> tuple[Tensor, Tensor]:
|
| 29 |
+
ndims1 = x.ndim
|
| 30 |
+
ndims2 = y.ndim
|
| 31 |
+
|
| 32 |
+
common_ndims = min(ndims1, ndims2)
|
| 33 |
+
for axis in range(common_ndims):
|
| 34 |
+
assert x.shape[axis] == y.shape[axis], "Dimensions not equal at axis {}".format(axis)
|
| 35 |
+
|
| 36 |
+
if ndims1 < ndims2:
|
| 37 |
+
x = x.reshape(x.shape + (1,) * (ndims2 - ndims1))
|
| 38 |
+
elif ndims2 < ndims1:
|
| 39 |
+
y = y.reshape(y.shape + (1,) * (ndims1 - ndims2))
|
| 40 |
+
|
| 41 |
+
return x, y
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def batch_add(x: Tensor, y: Tensor) -> Tensor:
|
| 45 |
+
x, y = common_broadcast(x, y)
|
| 46 |
+
return x + y
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def batch_mul(x: Tensor, y: Tensor) -> Tensor:
|
| 50 |
+
x, y = common_broadcast(x, y)
|
| 51 |
+
return x * y
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def batch_sub(x: Tensor, y: Tensor) -> Tensor:
|
| 55 |
+
x, y = common_broadcast(x, y)
|
| 56 |
+
return x - y
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def batch_div(x: Tensor, y: Tensor) -> Tensor:
|
| 60 |
+
x, y = common_broadcast(x, y)
|
| 61 |
+
return x / y
|
diffusion/functional/multi_step.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
Impl of multistep methods to solve the ODE in the diffusion model.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from typing import Callable, List, Tuple
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from diffusion.functional.runge_kutta import reg_x0_euler_step, res_x0_rk2_step
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def order2_fn(
|
| 28 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_s: torch.Tensor, x0_preds: torch.Tensor
|
| 29 |
+
) -> Tuple[torch.Tensor, List[torch.Tensor]]:
|
| 30 |
+
"""
|
| 31 |
+
impl the second order multistep method in https://arxiv.org/pdf/2308.02157
|
| 32 |
+
Adams Bashforth approach!
|
| 33 |
+
"""
|
| 34 |
+
if x0_preds:
|
| 35 |
+
x0_s1, s1 = x0_preds[0]
|
| 36 |
+
x_t = res_x0_rk2_step(x_s, t, s, x0_s, s1, x0_s1)
|
| 37 |
+
else:
|
| 38 |
+
x_t = reg_x0_euler_step(x_s, s, t, x0_s)[0]
|
| 39 |
+
return x_t, [(x0_s, s)]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# key: method name, value: method function
|
| 43 |
+
# key: order + algorithm name
|
| 44 |
+
MULTISTEP_FNs = {
|
| 45 |
+
"2ab": order2_fn,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_multi_step_fn(name: str) -> Callable:
|
| 50 |
+
if name in MULTISTEP_FNs:
|
| 51 |
+
return MULTISTEP_FNs[name]
|
| 52 |
+
methods = "\n\t".join(MULTISTEP_FNs.keys())
|
| 53 |
+
raise RuntimeError("Only support multistep method\n" + methods)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def is_multi_step_fn_supported(name: str) -> bool:
|
| 57 |
+
"""
|
| 58 |
+
Check if the multistep method is supported.
|
| 59 |
+
"""
|
| 60 |
+
return name in MULTISTEP_FNs
|
diffusion/functional/runge_kutta.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Callable, Tuple
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from diffusion.functional.batch_ops import batch_mul
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def phi1(t: torch.Tensor) -> torch.Tensor:
|
| 24 |
+
"""
|
| 25 |
+
Compute the first order phi function: (exp(t) - 1) / t.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
t: Input tensor.
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Tensor: Result of phi1 function.
|
| 32 |
+
"""
|
| 33 |
+
input_dtype = t.dtype
|
| 34 |
+
t = t.to(dtype=torch.float64)
|
| 35 |
+
return (torch.expm1(t) / t).to(dtype=input_dtype)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def phi2(t: torch.Tensor) -> torch.Tensor:
|
| 39 |
+
"""
|
| 40 |
+
Compute the second order phi function: (phi1(t) - 1) / t.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
t: Input tensor.
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Tensor: Result of phi2 function.
|
| 47 |
+
"""
|
| 48 |
+
input_dtype = t.dtype
|
| 49 |
+
t = t.to(dtype=torch.float64)
|
| 50 |
+
return ((phi1(t) - 1.0) / t).to(dtype=input_dtype)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def res_x0_rk2_step(
|
| 54 |
+
x_s: torch.Tensor,
|
| 55 |
+
t: torch.Tensor,
|
| 56 |
+
s: torch.Tensor,
|
| 57 |
+
x0_s: torch.Tensor,
|
| 58 |
+
s1: torch.Tensor,
|
| 59 |
+
x0_s1: torch.Tensor,
|
| 60 |
+
) -> torch.Tensor:
|
| 61 |
+
"""
|
| 62 |
+
Perform a residual-based 2nd order Runge-Kutta step.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
x_s: Current state tensor.
|
| 66 |
+
t: Target time tensor.
|
| 67 |
+
s: Current time tensor.
|
| 68 |
+
x0_s: Prediction at current time.
|
| 69 |
+
s1: Intermediate time tensor.
|
| 70 |
+
x0_s1: Prediction at intermediate time.
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
Tensor: Updated state tensor.
|
| 74 |
+
|
| 75 |
+
Raises:
|
| 76 |
+
AssertionError: If step size is too small.
|
| 77 |
+
"""
|
| 78 |
+
s = -torch.log(s)
|
| 79 |
+
t = -torch.log(t)
|
| 80 |
+
m = -torch.log(s1)
|
| 81 |
+
|
| 82 |
+
dt = t - s
|
| 83 |
+
assert not torch.any(torch.isclose(dt, torch.zeros_like(dt), atol=1e-6)), "Step size is too small"
|
| 84 |
+
assert not torch.any(torch.isclose(m - s, torch.zeros_like(dt), atol=1e-6)), "Step size is too small"
|
| 85 |
+
|
| 86 |
+
c2 = (m - s) / dt
|
| 87 |
+
phi1_val, phi2_val = phi1(-dt), phi2(-dt)
|
| 88 |
+
|
| 89 |
+
# Handle edge case where t = s = m
|
| 90 |
+
b1 = torch.nan_to_num(phi1_val - 1.0 / c2 * phi2_val, nan=0.0)
|
| 91 |
+
b2 = torch.nan_to_num(1.0 / c2 * phi2_val, nan=0.0)
|
| 92 |
+
|
| 93 |
+
return batch_mul(torch.exp(-dt), x_s) + batch_mul(dt, batch_mul(b1, x0_s) + batch_mul(b2, x0_s1))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def reg_x0_euler_step(
|
| 97 |
+
x_s: torch.Tensor,
|
| 98 |
+
s: torch.Tensor,
|
| 99 |
+
t: torch.Tensor,
|
| 100 |
+
x0_s: torch.Tensor,
|
| 101 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 102 |
+
"""
|
| 103 |
+
Perform a regularized Euler step based on x0 prediction.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
x_s: Current state tensor.
|
| 107 |
+
s: Current time tensor.
|
| 108 |
+
t: Target time tensor.
|
| 109 |
+
x0_s: Prediction at current time.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
Tuple[Tensor, Tensor]: Updated state tensor and current prediction.
|
| 113 |
+
"""
|
| 114 |
+
coef_x0 = (s - t) / s
|
| 115 |
+
coef_xs = t / s
|
| 116 |
+
return batch_mul(coef_x0, x0_s) + batch_mul(coef_xs, x_s), x0_s
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def reg_eps_euler_step(
|
| 120 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, eps_s: torch.Tensor
|
| 121 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 122 |
+
"""
|
| 123 |
+
Perform a regularized Euler step based on epsilon prediction.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
x_s: Current state tensor.
|
| 127 |
+
s: Current time tensor.
|
| 128 |
+
t: Target time tensor.
|
| 129 |
+
eps_s: Epsilon prediction at current time.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
Tuple[Tensor, Tensor]: Updated state tensor and current x0 prediction.
|
| 133 |
+
"""
|
| 134 |
+
return x_s + batch_mul(eps_s, t - s), x_s + batch_mul(eps_s, 0 - s)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def rk1_euler(
|
| 138 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable
|
| 139 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 140 |
+
"""
|
| 141 |
+
Perform a first-order Runge-Kutta (Euler) step.
|
| 142 |
+
|
| 143 |
+
Recommended for diffusion models with guidance or model undertrained
|
| 144 |
+
Usually more stable at the cost of a bit slower convergence.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
x_s: Current state tensor.
|
| 148 |
+
s: Current time tensor.
|
| 149 |
+
t: Target time tensor.
|
| 150 |
+
x0_fn: Function to compute x0 prediction.
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
Tuple[Tensor, Tensor]: Updated state tensor and x0 prediction.
|
| 154 |
+
"""
|
| 155 |
+
x0_s = x0_fn(x_s, s)
|
| 156 |
+
return reg_x0_euler_step(x_s, s, t, x0_s)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def rk2_mid_stable(
|
| 160 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable
|
| 161 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 162 |
+
"""
|
| 163 |
+
Perform a stable second-order Runge-Kutta (midpoint) step.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
x_s: Current state tensor.
|
| 167 |
+
s: Current time tensor.
|
| 168 |
+
t: Target time tensor.
|
| 169 |
+
x0_fn: Function to compute x0 prediction.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Tuple[Tensor, Tensor]: Updated state tensor and x0 prediction.
|
| 173 |
+
"""
|
| 174 |
+
s1 = torch.sqrt(s * t)
|
| 175 |
+
x_s1, _ = rk1_euler(x_s, s, s1, x0_fn)
|
| 176 |
+
|
| 177 |
+
x0_s1 = x0_fn(x_s1, s1)
|
| 178 |
+
return reg_x0_euler_step(x_s, s, t, x0_s1)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def rk2_mid(x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 182 |
+
"""
|
| 183 |
+
Perform a second-order Runge-Kutta (midpoint) step.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
x_s: Current state tensor.
|
| 187 |
+
s: Current time tensor.
|
| 188 |
+
t: Target time tensor.
|
| 189 |
+
x0_fn: Function to compute x0 prediction.
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
Tuple[Tensor, Tensor]: Updated state tensor and x0 prediction.
|
| 193 |
+
"""
|
| 194 |
+
s1 = torch.sqrt(s * t)
|
| 195 |
+
x_s1, x0_s = rk1_euler(x_s, s, s1, x0_fn)
|
| 196 |
+
|
| 197 |
+
x0_s1 = x0_fn(x_s1, s1)
|
| 198 |
+
|
| 199 |
+
return res_x0_rk2_step(x_s, t, s, x0_s, s1, x0_s1), x0_s1
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def rk_2heun_naive(
|
| 203 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable
|
| 204 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 205 |
+
"""
|
| 206 |
+
Perform a naive second-order Runge-Kutta (Heun's method) step.
|
| 207 |
+
Impl based on rho-rk-deis solvers, https://github.com/qsh-zh/deis
|
| 208 |
+
Recommended for diffusion models without guidance and relative large NFE
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
x_s: Current state tensor.
|
| 212 |
+
s: Current time tensor.
|
| 213 |
+
t: Target time tensor.
|
| 214 |
+
x0_fn: Function to compute x0 prediction.
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
Tuple[Tensor, Tensor]: Updated state tensor and current state.
|
| 218 |
+
"""
|
| 219 |
+
x_t, x0_s = rk1_euler(x_s, s, t, x0_fn)
|
| 220 |
+
eps_s = batch_mul(1.0 / s, x_t - x0_s)
|
| 221 |
+
x0_t = x0_fn(x_t, t)
|
| 222 |
+
eps_t = batch_mul(1.0 / t, x_t - x0_t)
|
| 223 |
+
|
| 224 |
+
avg_eps = (eps_s + eps_t) / 2
|
| 225 |
+
|
| 226 |
+
return reg_eps_euler_step(x_s, s, t, avg_eps)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def rk_2heun_edm(
|
| 230 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable
|
| 231 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 232 |
+
"""
|
| 233 |
+
Perform a naive second-order Runge-Kutta (Heun's method) step.
|
| 234 |
+
Impl based no EDM second order Heun method
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
x_s: Current state tensor.
|
| 238 |
+
s: Current time tensor.
|
| 239 |
+
t: Target time tensor.
|
| 240 |
+
x0_fn: Function to compute x0 prediction.
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
Tuple[Tensor, Tensor]: Updated state tensor and current state.
|
| 244 |
+
"""
|
| 245 |
+
x_t, x0_s = rk1_euler(x_s, s, t, x0_fn)
|
| 246 |
+
x0_t = x0_fn(x_t, t)
|
| 247 |
+
|
| 248 |
+
avg_x0 = (x0_s + x0_t) / 2
|
| 249 |
+
|
| 250 |
+
return reg_x0_euler_step(x_s, s, t, avg_x0)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def rk_3kutta_naive(
|
| 254 |
+
x_s: torch.Tensor, s: torch.Tensor, t: torch.Tensor, x0_fn: Callable
|
| 255 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 256 |
+
"""
|
| 257 |
+
Perform a naive third-order Runge-Kutta step.
|
| 258 |
+
Impl based on rho-rk-deis solvers, https://github.com/qsh-zh/deis
|
| 259 |
+
Recommended for diffusion models without guidance and relative large NFE
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
x_s: Current state tensor.
|
| 263 |
+
s: Current time tensor.
|
| 264 |
+
t: Target time tensor.
|
| 265 |
+
x0_fn: Function to compute x0 prediction.
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
Tuple[Tensor, Tensor]: Updated state tensor and current state.
|
| 269 |
+
"""
|
| 270 |
+
c2, c3 = 0.5, 1.0
|
| 271 |
+
a31, a32 = -1.0, 2.0
|
| 272 |
+
b1, b2, b3 = 1.0 / 6, 4.0 / 6, 1.0 / 6
|
| 273 |
+
|
| 274 |
+
delta = t - s
|
| 275 |
+
|
| 276 |
+
s1 = c2 * delta + s
|
| 277 |
+
s2 = c3 * delta + s
|
| 278 |
+
x_s1, x0_s = rk1_euler(x_s, s, s1, x0_fn)
|
| 279 |
+
eps_s = batch_mul(1.0 / s, x_s - x0_s)
|
| 280 |
+
x0_s1 = x0_fn(x_s1, s1)
|
| 281 |
+
eps_s1 = batch_mul(1.0 / s1, x_s1 - x0_s1)
|
| 282 |
+
|
| 283 |
+
_eps = a31 * eps_s + a32 * eps_s1
|
| 284 |
+
x_s2, _ = reg_eps_euler_step(x_s, s, s2, _eps)
|
| 285 |
+
|
| 286 |
+
x0_s2 = x0_fn(x_s2, s2)
|
| 287 |
+
eps_s2 = batch_mul(1.0 / s2, x_s2 - x0_s2)
|
| 288 |
+
|
| 289 |
+
avg_eps = b1 * eps_s + b2 * eps_s1 + b3 * eps_s2
|
| 290 |
+
return reg_eps_euler_step(x_s, s, t, avg_eps)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# key : order + name
|
| 294 |
+
RK_FNs = {
|
| 295 |
+
"1euler": rk1_euler,
|
| 296 |
+
"2mid": rk2_mid,
|
| 297 |
+
"2mid_stable": rk2_mid_stable,
|
| 298 |
+
"2heun_edm": rk_2heun_edm,
|
| 299 |
+
"2heun_naive": rk_2heun_naive,
|
| 300 |
+
"3kutta_naive": rk_3kutta_naive,
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def get_runge_kutta_fn(name: str) -> Callable:
|
| 305 |
+
"""
|
| 306 |
+
Get the specified Runge-Kutta function.
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
name: Name of the Runge-Kutta method.
|
| 310 |
+
|
| 311 |
+
Returns:
|
| 312 |
+
Callable: The specified Runge-Kutta function.
|
| 313 |
+
|
| 314 |
+
Raises:
|
| 315 |
+
RuntimeError: If the specified method is not supported.
|
| 316 |
+
"""
|
| 317 |
+
if name in RK_FNs:
|
| 318 |
+
return RK_FNs[name]
|
| 319 |
+
methods = "\n\t".join(RK_FNs.keys())
|
| 320 |
+
raise RuntimeError(f"Only support the following Runge-Kutta methods:\n\t{methods}")
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def is_runge_kutta_fn_supported(name: str) -> bool:
|
| 324 |
+
"""
|
| 325 |
+
Check if the specified Runge-Kutta function is supported.
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
name: Name of the Runge-Kutta method.
|
| 329 |
+
|
| 330 |
+
Returns:
|
| 331 |
+
bool: True if the method is supported, False otherwise.
|
| 332 |
+
"""
|
| 333 |
+
return name in RK_FNs
|
diffusion/inference/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""HDMap-conditioned LiDAR inference."""
|
diffusion/inference/causal.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Causal P1B4 sampling with clean K/V commits and streaming spatial memory."""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
from diffusion.inference.hdmap import _metric_ranges
|
| 10 |
+
from diffusion.inference.pai import SPATIAL_CACHE, make_batch, mode_spec
|
| 11 |
+
from diffusion.training.datasets.lidar_dataset.forecast_warp import TorchSpatialPointMap
|
| 12 |
+
from utils import misc
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _spatial_map(model, batch):
|
| 16 |
+
rays, elev, azim, row_off = model._stage2_spatial_map_geometry(batch["video"])
|
| 17 |
+
policy = {key: getattr(model.config, f"blockwise_spatial_map_{key}") for key in SPATIAL_CACHE}
|
| 18 |
+
policy["voxel_size_m"] = policy.pop("voxel_m")
|
| 19 |
+
return TorchSpatialPointMap(
|
| 20 |
+
ray_dirs=rays, row_elevations_rad=elev, column_azimuths_rad=azim,
|
| 21 |
+
row_azimuth_offsets_rad=row_off, device=rays.device,
|
| 22 |
+
min_range=2.5, max_range=100, min_value=-1, inverse_depth=False,
|
| 23 |
+
**policy,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _commit(model, latent, condition):
|
| 28 |
+
model._current_sfdmd_store_self_attn_kv = True
|
| 29 |
+
try:
|
| 30 |
+
velocity = model._rf_network_forward(
|
| 31 |
+
latent.to(**model.tensor_kwargs),
|
| 32 |
+
torch.zeros((1, latent.shape[2]), device=latent.device), condition,
|
| 33 |
+
)
|
| 34 |
+
if not torch.isfinite(velocity).all():
|
| 35 |
+
raise FloatingPointError("Clean K/V commit produced non-finite values")
|
| 36 |
+
finally:
|
| 37 |
+
model._current_sfdmd_store_self_attn_kv = False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def generate(model, sample, mode, args, seed, console):
|
| 41 |
+
spec = mode_spec(mode, args.stage)
|
| 42 |
+
length = spec["input_frames"] + spec["output_frames"]
|
| 43 |
+
# Complete P1+4N blocks using the extra supplied pose, then crop for display.
|
| 44 |
+
padded_length = 1 + ((length - 1 + 3) // 4) * 4
|
| 45 |
+
batch = make_batch(sample, mode, args.stage, length=padded_length)
|
| 46 |
+
video = batch["video"]
|
| 47 |
+
known = torch.arange(padded_length, device=video.device) < spec["input_frames"]
|
| 48 |
+
torch.manual_seed(seed)
|
| 49 |
+
model._current_stage2_data_batch = batch
|
| 50 |
+
model._current_stage2_geometry_source_mask = known
|
| 51 |
+
model._current_sensor_dataset_ids = batch["sensor_dataset_id"]
|
| 52 |
+
model._current_stage2_geometry_mode = "frozen_object" if mode == "resim" else "rolling_static"
|
| 53 |
+
model.factorized_static_only_geometry = False
|
| 54 |
+
model._hdmap_force_zero_latent = spec["hdmap"] == "null"
|
| 55 |
+
model._current_sfdmd_self_attn_kv_cache = model.new_teacher_forcing_kv_cache()
|
| 56 |
+
model._current_sfdmd_self_attn_kv_max_frames = args.kv_cache_frames
|
| 57 |
+
model._current_sfdmd_self_attn_kv_sink_frames = 1
|
| 58 |
+
model._current_sfdmd_store_self_attn_kv = False
|
| 59 |
+
model._current_sfdmd_detach_self_attn_kv = True
|
| 60 |
+
model._current_sfdmd_return_self_attn_kv = False
|
| 61 |
+
|
| 62 |
+
blocks = [(0, 1)] + [(start, start + 4) for start in range(1, padded_length, 4)]
|
| 63 |
+
spatial_map = _spatial_map(model, batch) if mode != "resim" else None
|
| 64 |
+
frozen = None
|
| 65 |
+
if mode == "resim":
|
| 66 |
+
# The training builder reads points only from the observed prefix.
|
| 67 |
+
# Target actor poses place the observed canonical object clouds.
|
| 68 |
+
frozen, _, _ = model._build_torch_spatial_map_history(video, batch["lidar_to_world"])
|
| 69 |
+
elif mode == "forecast":
|
| 70 |
+
# Prefill all supplied observations, then append only newly generated sweeps.
|
| 71 |
+
for start, end in blocks:
|
| 72 |
+
end = min(end, spec["input_frames"])
|
| 73 |
+
if start >= end:
|
| 74 |
+
break
|
| 75 |
+
spatial_map.append_token_block(
|
| 76 |
+
video[0, :, start:end], batch["lidar_to_world"][0, start:end], start,
|
| 77 |
+
input_has_prepend=False,
|
| 78 |
+
token_pose_sensor_start_end=batch["pose_sensor_start_end"][0, start:end],
|
| 79 |
+
)
|
| 80 |
+
observed = torch.zeros((1, 64, padded_length, 16, 128), device=video.device)
|
| 81 |
+
observed_cache = None
|
| 82 |
+
for t in range(spec["input_frames"]):
|
| 83 |
+
latent, observed_cache = model.encode_stream(
|
| 84 |
+
video[:, :, t:t + 1].float(), temporal_kv_cache=observed_cache, max_cache_frames=9,
|
| 85 |
+
)
|
| 86 |
+
if not torch.isfinite(latent).all():
|
| 87 |
+
raise FloatingPointError(f"Non-finite observed latent at frame {t}")
|
| 88 |
+
observed[:, :, t:t + 1] = latent.float()
|
| 89 |
+
del observed_cache
|
| 90 |
+
|
| 91 |
+
condition_cache = decoder_cache = None
|
| 92 |
+
decoded_blocks = []
|
| 93 |
+
try:
|
| 94 |
+
for block_index, (start, end) in enumerate(tqdm(
|
| 95 |
+
blocks, desc=f"{mode} causal sampling", unit="block", file=console,
|
| 96 |
+
leave=False, disable=not console.isatty(),
|
| 97 |
+
)):
|
| 98 |
+
poses = batch["lidar_to_world"][0, start:end]
|
| 99 |
+
motion = batch["pose_sensor_start_end"][0, start:end]
|
| 100 |
+
if spatial_map is not None:
|
| 101 |
+
geometry, _ = spatial_map.render(poses, target_pose_sensor_start_end=motion)
|
| 102 |
+
geometry = geometry[None]
|
| 103 |
+
else:
|
| 104 |
+
geometry = frozen[:, :, start:end]
|
| 105 |
+
active = dict(batch)
|
| 106 |
+
active.update(
|
| 107 |
+
video=torch.full_like(video[:, :, start:end], -1),
|
| 108 |
+
lidar_hdmap=batch["lidar_hdmap"][:, :, start:end],
|
| 109 |
+
lidar_blockwise_warped_history=geometry,
|
| 110 |
+
num_frames=batch["num_frames"].new_tensor([end - start]),
|
| 111 |
+
)
|
| 112 |
+
model._current_sfdmd_temporal_positions = torch.arange(start, end, device=video.device)
|
| 113 |
+
model._current_stage2_known_frame_mask = known[start:end]
|
| 114 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 115 |
+
condition, condition_cache = model.get_online_condition_stream(
|
| 116 |
+
active, temporal_kv_cache=condition_cache, max_cache_frames=9,
|
| 117 |
+
)
|
| 118 |
+
block_known = known[start:end]
|
| 119 |
+
known_latents = observed[:, :, start:end]
|
| 120 |
+
if bool(block_known.all()):
|
| 121 |
+
sampled = known_latents
|
| 122 |
+
else:
|
| 123 |
+
noise = misc.arch_invariant_rand(
|
| 124 |
+
(1, 64, end - start, 16, 128), torch.float32, "cuda", seed + block_index,
|
| 125 |
+
)
|
| 126 |
+
sampled = model._generate_sde(
|
| 127 |
+
latents=noise, condition=condition, uncondition=None,
|
| 128 |
+
guidance=1.0, use_cfg=False, B=1, num_steps=args.num_steps,
|
| 129 |
+
shift=5, seed=seed + block_index, sde_eta=args.sde_eta,
|
| 130 |
+
known_latents=known_latents if bool(block_known.any()) else None,
|
| 131 |
+
known_mask=block_known if bool(block_known.any()) else None,
|
| 132 |
+
known_latents_mode="clean_mask",
|
| 133 |
+
)
|
| 134 |
+
if not torch.isfinite(sampled).all():
|
| 135 |
+
raise FloatingPointError(f"Non-finite latents in block {block_index}")
|
| 136 |
+
if bool(block_known.any()) and not torch.equal(
|
| 137 |
+
sampled[:, :, block_known].float(), known_latents[:, :, block_known].float(),
|
| 138 |
+
):
|
| 139 |
+
raise RuntimeError(f"Clean-prefix replacement failed in block {block_index}")
|
| 140 |
+
# Commit once after denoising, synchronously, before the next block.
|
| 141 |
+
_commit(model, sampled, condition)
|
| 142 |
+
decoded, decoder_cache = model.decode_stream(
|
| 143 |
+
sampled.float(), temporal_kv_cache=decoder_cache, max_cache_frames=30,
|
| 144 |
+
)
|
| 145 |
+
if decoded.shape != video[:, :, start:end].shape or not torch.isfinite(decoded).all():
|
| 146 |
+
raise RuntimeError(f"Invalid decoded LiDAR in block {block_index}")
|
| 147 |
+
decoded = torch.where(block_known[None, None, :, None, None], video[:, :, start:end], decoded)
|
| 148 |
+
decoded_blocks.append(decoded)
|
| 149 |
+
new_start = max(start, spec["input_frames"])
|
| 150 |
+
if spatial_map is not None and new_start < end:
|
| 151 |
+
# No current-block or future GT points can enter its own condition.
|
| 152 |
+
offset = new_start - start
|
| 153 |
+
spatial_map.append_token_block(
|
| 154 |
+
decoded[0, :, offset:], poses[offset:], new_start, input_has_prepend=False,
|
| 155 |
+
token_pose_sensor_start_end=motion[offset:],
|
| 156 |
+
)
|
| 157 |
+
finally:
|
| 158 |
+
model._current_sfdmd_temporal_positions = None
|
| 159 |
+
model._current_sfdmd_self_attn_kv_cache = None
|
| 160 |
+
model._current_sfdmd_store_self_attn_kv = False
|
| 161 |
+
model._current_stage2_data_batch = None
|
| 162 |
+
return _metric_ranges(torch.cat(decoded_blocks, dim=2)[:, :, :length])
|
diffusion/inference/hdmap.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""HDMap-only diffusion loading, sampling, and output for native sensor grids."""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
from collections import Counter
|
| 12 |
+
from copy import deepcopy
|
| 13 |
+
from datetime import timedelta
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from tqdm import tqdm
|
| 19 |
+
|
| 20 |
+
from utils import inference as common
|
| 21 |
+
from utils.lidar_rangemap import unnormalize_and_reduce_channels
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# Dataset-ID order is a checkpoint contract, not inferred from grid dimensions.
|
| 25 |
+
SENSORS = {
|
| 26 |
+
0: ("pandar", 128, 1024, 10.0),
|
| 27 |
+
1: ("pandaset", 64, 1024, 10.0),
|
| 28 |
+
2: ("nuscenes", 32, 1024, 20.0),
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def resolve_checkpoint(path: Path) -> Path:
|
| 33 |
+
if path.is_file():
|
| 34 |
+
return path.resolve()
|
| 35 |
+
folder = path / "checkpoints" if (path / "checkpoints").is_dir() else path
|
| 36 |
+
marker = folder / "latest_checkpoint.txt"
|
| 37 |
+
stem = marker.read_text().strip().removesuffix(".pt")
|
| 38 |
+
if not stem.startswith("iter_") or not stem[5:].isdigit():
|
| 39 |
+
raise ValueError(f"Invalid checkpoint marker in {marker}: {stem!r}")
|
| 40 |
+
source = folder / f"{stem}_ema_model.pt"
|
| 41 |
+
if not source.is_file() or source.stat().st_size == 0:
|
| 42 |
+
raise FileNotFoundError(f"No complete EMA checkpoint: {source}")
|
| 43 |
+
# Match the research launcher: pin the EMA before training retention unlinks it.
|
| 44 |
+
snapshot_dir = folder.parent / "eval_snapshots"
|
| 45 |
+
snapshot_dir.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
snapshot = snapshot_dir / source.name
|
| 47 |
+
try:
|
| 48 |
+
os.link(source, snapshot)
|
| 49 |
+
except FileExistsError:
|
| 50 |
+
pass
|
| 51 |
+
return snapshot.resolve()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_model(checkpoint: Path, tokenizer_checkpoint: Path, latent_stats: Path):
|
| 55 |
+
from diffusion.training.config.base.lidarverse_vae import get_lidarverse_tokenizer
|
| 56 |
+
from diffusion.training.config.base.model import LidarModelConfig
|
| 57 |
+
from diffusion.training.config.text2world.registry import (
|
| 58 |
+
MININET_2B_Config, VideoConditionerFpsSizePaddingConfig,
|
| 59 |
+
)
|
| 60 |
+
from diffusion.training.models.hdmaptolidar_model_rf import HdmapToLidarRectifiedFlowModel
|
| 61 |
+
from utils.lazy_config import LazyDict
|
| 62 |
+
|
| 63 |
+
net = deepcopy(MININET_2B_Config)
|
| 64 |
+
net.update(
|
| 65 |
+
in_channels=128, out_channels=64, patch_spatial=(1, 1),
|
| 66 |
+
rope_scale_positions_by_patch=True, num_dataset_embeddings=3,
|
| 67 |
+
timestep_scale=0.001, rope_h_extrapolation_ratio=3.0,
|
| 68 |
+
rope_w_extrapolation_ratio=3.0, rope_t_extrapolation_ratio=1.0,
|
| 69 |
+
rope_enable_fps_modulation=False, use_wan_fp32_strategy=True,
|
| 70 |
+
)
|
| 71 |
+
net.sac_config.mode = "none"
|
| 72 |
+
vae = get_lidarverse_tokenizer()
|
| 73 |
+
vae.update(checkpoint_path=str(tokenizer_checkpoint), mean_std_fp=str(latent_stats),
|
| 74 |
+
strict_checkpoint=True, use_ema=False)
|
| 75 |
+
# No training experiment registration, dataloaders, FSDP, or extra EMA model.
|
| 76 |
+
config = LidarModelConfig(
|
| 77 |
+
net=net, vae=vae, conditioner=deepcopy(VideoConditionerFpsSizePaddingConfig),
|
| 78 |
+
ema=LazyDict(dict(enabled=False)), latent_shape=[64, 21, 16, 128],
|
| 79 |
+
hdmap_channels=3, additional_concat_ch=64, encode_hdmap_with_vae=True,
|
| 80 |
+
hdmap_dropout_prob=0.1, sigma_data=1.0, shift=5,
|
| 81 |
+
shift_clamp_percentiles=(0.5, 99.9), rf_prediction_type="velocity",
|
| 82 |
+
loss_reduce="mean", input_video_has_prepend=True,
|
| 83 |
+
)
|
| 84 |
+
model = HdmapToLidarRectifiedFlowModel(config)
|
| 85 |
+
model.model.to(dtype=torch.bfloat16)
|
| 86 |
+
# Local/trusted PyTorch checkpoints only. Load strictly: never adapt a head.
|
| 87 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=False)
|
| 88 |
+
state = payload.get("model", payload)
|
| 89 |
+
if isinstance(payload.get("ema"), dict):
|
| 90 |
+
state = payload["ema"]
|
| 91 |
+
model.model.load_state_dict(state, strict=True)
|
| 92 |
+
del state, payload
|
| 93 |
+
model.cuda().eval()
|
| 94 |
+
model.vae.float()
|
| 95 |
+
print(f"Loaded all diffusion weights strictly: {checkpoint}", flush=True)
|
| 96 |
+
return model
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def load_hdmap_sample(path: Path, num_frames: int) -> dict:
|
| 100 |
+
with np.load(path, allow_pickle=False) as payload:
|
| 101 |
+
sample = {key: payload[key] for key in payload.files}
|
| 102 |
+
for key in ("hdmap", "ray_directions", "sensor_dataset_id", "fps"):
|
| 103 |
+
if key not in sample:
|
| 104 |
+
raise ValueError(f"{path}: missing {key}; tokenizer-only NPZs have no HDMap condition")
|
| 105 |
+
dataset_id = int(sample["sensor_dataset_id"])
|
| 106 |
+
if dataset_id not in SENSORS:
|
| 107 |
+
raise ValueError(f"{path}: unknown sensor_dataset_id {dataset_id}")
|
| 108 |
+
sensor, height, width, fps = SENSORS[dataset_id]
|
| 109 |
+
hdmap = np.asarray(sample["hdmap"], dtype=np.float32)
|
| 110 |
+
if hdmap.shape != (num_frames, height, width):
|
| 111 |
+
raise ValueError(f"{path}: expected {num_frames} real {height}x{width} HDMap frames; got {hdmap.shape}")
|
| 112 |
+
if bool(sample.get("has_prepend", False)):
|
| 113 |
+
raise ValueError(f"{path}: store only real frames, not the duplicated VAE prefix")
|
| 114 |
+
if str(sample.get("dataset", sensor)) != sensor or float(sample["fps"]) != fps:
|
| 115 |
+
raise ValueError(f"{path}: sensor name/FPS does not match dataset ID {dataset_id}")
|
| 116 |
+
if float(sample.get("min_range_m", 2.5)) != 2.5 or float(sample.get("max_range_m", 100.0)) != 100.0:
|
| 117 |
+
raise ValueError(f"{path}: this checkpoint uses 2.5--100 m")
|
| 118 |
+
if not np.isfinite(hdmap).all() or hdmap.min() < -1 or hdmap.max() > 1:
|
| 119 |
+
raise ValueError(f"{path}: hdmap must be normalized to [-1,1], invalid cells=-1")
|
| 120 |
+
rays = np.asarray(sample["ray_directions"], dtype=np.float32)
|
| 121 |
+
if rays.shape not in ((height, width, 3), (num_frames, height, width, 3)):
|
| 122 |
+
raise ValueError(f"{path}: rays do not match the native HDMap grid: {rays.shape}")
|
| 123 |
+
if not np.isfinite(rays).all() or not np.allclose(np.linalg.norm(rays, axis=-1), 1, atol=1e-4):
|
| 124 |
+
raise ValueError(f"{path}: ray_directions must be finite unit vectors")
|
| 125 |
+
sample.update(hdmap=hdmap, ray_directions=rays, dataset=sensor,
|
| 126 |
+
visualization_yaw_deg=common.display_yaw(path, sensor))
|
| 127 |
+
return sample
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _metric_ranges(video):
|
| 131 |
+
# Same validity cutoff (including near/far buffers) as the working launcher.
|
| 132 |
+
ranges, valid = unnormalize_and_reduce_channels(
|
| 133 |
+
video, max_range=100.0, min_range=2.5, min_value=-1.0,
|
| 134 |
+
inverse_depth=False, process_output="mono",
|
| 135 |
+
)
|
| 136 |
+
return ranges[0].float().cpu().numpy(), valid[0].cpu().numpy()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _preview_frames(sample, generated, valid, output):
|
| 140 |
+
hdmap, hd_valid = _metric_ranges(torch.from_numpy(sample["hdmap"])[None, None])
|
| 141 |
+
rays = np.broadcast_to(sample["ray_directions"], hdmap.shape + (3,))
|
| 142 |
+
for index in range(len(generated)):
|
| 143 |
+
panels = []
|
| 144 |
+
clouds = [("hdmap", "HDMap", hdmap, hd_valid),
|
| 145 |
+
("generation", "Generated", generated, valid)]
|
| 146 |
+
for name, title, values, mask in clouds:
|
| 147 |
+
points = common.points_from_ranges(values[index], mask[index], rays[index])
|
| 148 |
+
common.write_ply(output / "ply" / f"{name}_{index:03d}.ply", points)
|
| 149 |
+
panels.append(common.label_image(
|
| 150 |
+
common.render_points(points, yaw_deg=sample["visualization_yaw_deg"]),
|
| 151 |
+
f"{sample['dataset']} | {title}",
|
| 152 |
+
))
|
| 153 |
+
yield np.concatenate(panels, axis=1)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _generate_sequence(model, sample, args, seed, console, label):
|
| 157 |
+
dataset_id = int(sample["sensor_dataset_id"])
|
| 158 |
+
torch.cuda.synchronize()
|
| 159 |
+
phase_started = time.perf_counter()
|
| 160 |
+
# The diffusion path sees HDMap + null text, never GT.
|
| 161 |
+
video = torch.from_numpy(sample["hdmap"])[None, None].cuda()
|
| 162 |
+
video = torch.cat([video[:, :, :1], video], dim=2)
|
| 163 |
+
_, _, _, height, width = video.shape
|
| 164 |
+
batch = {
|
| 165 |
+
# The shared preparation API encodes a target to obtain its latent shape.
|
| 166 |
+
# Supply an empty target, never GT. Its latent is not a sampling condition.
|
| 167 |
+
"video": torch.full_like(video, -1),
|
| 168 |
+
"lidar_hdmap": video,
|
| 169 |
+
"is_preprocessed": True,
|
| 170 |
+
"sensor_dataset_id": torch.tensor([dataset_id], device="cuda", dtype=torch.long),
|
| 171 |
+
"fps": torch.tensor([float(sample["fps"])], device="cuda"),
|
| 172 |
+
"num_frames": torch.tensor([args.sample_n_frames], device="cuda"),
|
| 173 |
+
"image_size": torch.tensor([[height, width]], device="cuda"),
|
| 174 |
+
"padding_mask": torch.zeros(1, 1, height, width, device="cuda"),
|
| 175 |
+
"t5_text_embeddings": torch.zeros(1, 512, 1024, device="cuda"),
|
| 176 |
+
"t5_text_mask": torch.zeros(1, 512, device="cuda"),
|
| 177 |
+
}
|
| 178 |
+
batch["t5_text_mask"][:, 0] = 1
|
| 179 |
+
# The VAE samples a Gaussian posterior even in eval mode. Seed preparation
|
| 180 |
+
# too, retaining the reference target-then-HDMap encode/RNG order.
|
| 181 |
+
torch.manual_seed(seed)
|
| 182 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 183 |
+
_, shape_latent, _ = model.get_data_and_condition(batch)
|
| 184 |
+
torch.cuda.synchronize()
|
| 185 |
+
encode_seconds = time.perf_counter() - phase_started
|
| 186 |
+
phase_started = time.perf_counter()
|
| 187 |
+
# Both supported samplers make one velocity query per step. Ordinary
|
| 188 |
+
# CFG makes two DiT forwards; CFG=0/1 makes one. The hook observes only
|
| 189 |
+
# completion and MUST return None so it cannot replace network outputs.
|
| 190 |
+
forwards_per_step = 1 if args.guidance in (0.0, 1.0) else 2
|
| 191 |
+
forwards = 0
|
| 192 |
+
with tqdm(total=args.num_steps, desc=f"{label} sampling", unit="step",
|
| 193 |
+
file=console, dynamic_ncols=True, leave=False,
|
| 194 |
+
disable=not console.isatty()) as progress:
|
| 195 |
+
def on_forward(_module, _inputs, _output):
|
| 196 |
+
nonlocal forwards
|
| 197 |
+
forwards += 1
|
| 198 |
+
if forwards % forwards_per_step == 0:
|
| 199 |
+
progress.update(1)
|
| 200 |
+
|
| 201 |
+
hook = model.net.register_forward_hook(on_forward)
|
| 202 |
+
try:
|
| 203 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 204 |
+
latent = model.generate_samples_from_batch(
|
| 205 |
+
batch, state_shape=shape_latent.shape[1:], n_sample=1,
|
| 206 |
+
guidance=args.guidance, seed=seed, num_steps=args.num_steps,
|
| 207 |
+
sampler=args.sampler, sde_eta=args.sde_eta,
|
| 208 |
+
)
|
| 209 |
+
torch.cuda.synchronize()
|
| 210 |
+
finally:
|
| 211 |
+
hook.remove()
|
| 212 |
+
sampling_seconds = time.perf_counter() - phase_started
|
| 213 |
+
phase_started = time.perf_counter()
|
| 214 |
+
decoded = model.decode(latent.float())
|
| 215 |
+
if decoded.shape != video.shape or not torch.isfinite(decoded).all():
|
| 216 |
+
raise RuntimeError(f"Invalid decoded range video: {tuple(decoded.shape)}")
|
| 217 |
+
generated, valid = _metric_ranges(decoded[:, :, 1:])
|
| 218 |
+
torch.cuda.synchronize()
|
| 219 |
+
decode_seconds = time.perf_counter() - phase_started
|
| 220 |
+
return generated, valid, {
|
| 221 |
+
"encode_seconds": encode_seconds,
|
| 222 |
+
"sampling_seconds": sampling_seconds,
|
| 223 |
+
"decode_seconds": decode_seconds,
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@torch.inference_mode()
|
| 228 |
+
def run(args, console, say, started):
|
| 229 |
+
sample_root, output_root = args.sample_path.resolve(), args.output_folder
|
| 230 |
+
# Count selected clips without decompressing their range videos. Preserve
|
| 231 |
+
# the original file order and per-sensor seed/index convention.
|
| 232 |
+
samples, selected_counts = [], Counter()
|
| 233 |
+
for path in common.sample_paths(sample_root):
|
| 234 |
+
with np.load(path, allow_pickle=False) as payload:
|
| 235 |
+
dataset_id = int(payload["sensor_dataset_id"])
|
| 236 |
+
if dataset_id not in SENSORS:
|
| 237 |
+
raise ValueError(f"{path}: unknown sensor_dataset_id {dataset_id}")
|
| 238 |
+
if selected_counts[dataset_id] < args.num_samples:
|
| 239 |
+
samples.append(path)
|
| 240 |
+
selected_counts[dataset_id] += 1
|
| 241 |
+
if not torch.cuda.is_available():
|
| 242 |
+
raise RuntimeError("A CUDA GPU is required; use the diffusion-capable container")
|
| 243 |
+
checkpoint = resolve_checkpoint(args.checkpoint.resolve())
|
| 244 |
+
model = load_model(checkpoint, args.tokenizer_checkpoint.resolve(), args.latent_stats.resolve())
|
| 245 |
+
torch.cuda.synchronize()
|
| 246 |
+
startup_seconds = time.perf_counter() - started
|
| 247 |
+
say(f"Ready in {startup_seconds:.1f}s | {checkpoint.name} | {len(samples)} clips, {args.sample_n_frames} frames each")
|
| 248 |
+
metadata = {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()}
|
| 249 |
+
metadata.update(resolved_checkpoint=str(checkpoint), shift=5, dataset_ids={k: v[0] for k, v in SENSORS.items()})
|
| 250 |
+
(output_root / "run.json").write_text(json.dumps(metadata, indent=2) + "\n")
|
| 251 |
+
counts = {key: 0 for key in SENSORS}
|
| 252 |
+
sensor_seconds = Counter()
|
| 253 |
+
records = []
|
| 254 |
+
timing_path = output_root / "timings.json"
|
| 255 |
+
for clip_index, path in enumerate(samples, 1):
|
| 256 |
+
clip_started = time.perf_counter()
|
| 257 |
+
sample = load_hdmap_sample(path, args.sample_n_frames)
|
| 258 |
+
dataset_id = int(sample["sensor_dataset_id"])
|
| 259 |
+
seed = args.seed + int(sample.get("sample_index", counts[dataset_id]))
|
| 260 |
+
counts[dataset_id] += 1
|
| 261 |
+
label = f"[{clip_index:02d}/{len(samples):02d}] {sample['dataset']}/{path.stem}"
|
| 262 |
+
say(f"{label} | encoding, {sample['hdmap'].shape[1]}x{sample['hdmap'].shape[2]}, seed {seed}")
|
| 263 |
+
generated, valid, generation_timing = _generate_sequence(
|
| 264 |
+
model, sample, args, seed, console, label
|
| 265 |
+
)
|
| 266 |
+
encode_seconds = generation_timing["encode_seconds"]
|
| 267 |
+
sampling_seconds = generation_timing["sampling_seconds"]
|
| 268 |
+
decode_seconds = generation_timing["decode_seconds"]
|
| 269 |
+
phase_started = time.perf_counter()
|
| 270 |
+
output = common.sample_output(path, sample_root, output_root)
|
| 271 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 272 |
+
saved = {key: sample[key] for key in (
|
| 273 |
+
"ray_directions", "fps", "sensor_dataset_id", "dataset", "clip_name",
|
| 274 |
+
"lidar_to_world", "pose_sensor_start_end", "frame_indices",
|
| 275 |
+
) if key in sample}
|
| 276 |
+
np.savez_compressed(output / "generation.npz", range_m=generated, valid_mask=valid,
|
| 277 |
+
seed=np.int64(seed), **saved)
|
| 278 |
+
save_seconds = time.perf_counter() - phase_started
|
| 279 |
+
phase_started = time.perf_counter()
|
| 280 |
+
if args.vis_pcd:
|
| 281 |
+
with tqdm(_preview_frames(sample, generated, valid, output), total=len(generated),
|
| 282 |
+
desc=f"{label} rendering", unit="frame", file=console,
|
| 283 |
+
dynamic_ncols=True, leave=False, disable=not console.isatty()) as preview:
|
| 284 |
+
common.write_video(output / "generation.mp4", preview, float(sample["fps"]))
|
| 285 |
+
render_seconds = time.perf_counter() - phase_started if args.vis_pcd else 0.0
|
| 286 |
+
total_seconds = time.perf_counter() - clip_started
|
| 287 |
+
sensor_seconds[dataset_id] += total_seconds
|
| 288 |
+
remaining = selected_counts[dataset_id] - counts[dataset_id]
|
| 289 |
+
eta = sensor_seconds[dataset_id] / counts[dataset_id] * remaining
|
| 290 |
+
generation_seconds = encode_seconds + sampling_seconds + decode_seconds
|
| 291 |
+
records.append(dict(sample=str(path), dataset=sample["dataset"], seed=seed,
|
| 292 |
+
encode_seconds=encode_seconds, sampling_seconds=sampling_seconds,
|
| 293 |
+
decode_seconds=decode_seconds, save_seconds=save_seconds,
|
| 294 |
+
render_seconds=render_seconds, total_seconds=total_seconds,
|
| 295 |
+
generation_fps=args.sample_n_frames / generation_seconds))
|
| 296 |
+
report = dict(startup_seconds=startup_seconds, elapsed_seconds=time.perf_counter() - started,
|
| 297 |
+
completed_clips=len(records), selected_clips=len(samples), samples=records)
|
| 298 |
+
timing_path.with_suffix(".json.tmp").write_text(json.dumps(report, indent=2) + "\n")
|
| 299 |
+
timing_path.with_suffix(".json.tmp").replace(timing_path)
|
| 300 |
+
say(f" Done {total_seconds:.1f}s | encode {encode_seconds:.1f}s | sample {sampling_seconds:.1f}s"
|
| 301 |
+
f" | decode {decode_seconds:.1f}s | save/render {save_seconds + render_seconds:.1f}s"
|
| 302 |
+
f" | {sample['dataset']} remaining ~{timedelta(seconds=round(eta))}")
|
| 303 |
+
model._store_hdmap_latent(None)
|
| 304 |
+
say(f"Finished {len(records)} clips in {timedelta(seconds=round(time.perf_counter() - started))} (including loading and rendering).")
|
| 305 |
+
say(f"Outputs: {output_root}\nTimings: {timing_path}")
|
diffusion/inference/pai.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Shared PAI package loading, conditioning, and quickstart outputs."""
|
| 5 |
+
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
from diffusion.inference.hdmap import _metric_ranges
|
| 16 |
+
from utils import inference as common
|
| 17 |
+
|
| 18 |
+
# No duplicate first frame: this DiT was trained on 21 unique sweeps.
|
| 19 |
+
MODES = {
|
| 20 |
+
"world": dict(input_frames=0, output_frames=20, geometry_frames=0,
|
| 21 |
+
hdmap="full", geometry="null"),
|
| 22 |
+
"forecast": dict(input_frames=10, output_frames=11, geometry_frames=10,
|
| 23 |
+
hdmap="null", geometry="frozen_static"),
|
| 24 |
+
"resim": dict(input_frames=15, output_frames=5, geometry_frames=15,
|
| 25 |
+
hdmap="null", geometry="frozen_object"),
|
| 26 |
+
}
|
| 27 |
+
SPATIAL_CACHE = dict(
|
| 28 |
+
voxel_policy="persistent_static", voxel_m=0.15, radius_m=100.0,
|
| 29 |
+
observation_unit="frame", static_min_observations=2, include_latest=False,
|
| 30 |
+
candidate_ttl_updates=1, free_space_clear=True, free_space_margin_m=0.75,
|
| 31 |
+
free_space_misses_to_remove=2,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def mode_spec(mode, stage=1):
|
| 36 |
+
spec = dict(MODES[mode])
|
| 37 |
+
if mode == "world" and stage != 1:
|
| 38 |
+
spec["output_frames"] = 21
|
| 39 |
+
spec["geometry"] = "rolling_generated"
|
| 40 |
+
if mode == "forecast" and stage != 1:
|
| 41 |
+
spec["geometry"] = "rolling_observed_then_generated"
|
| 42 |
+
return spec
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_package(checkpoint, stage):
|
| 46 |
+
config_path = checkpoint.with_name("config.json")
|
| 47 |
+
config = json.loads(config_path.read_text())
|
| 48 |
+
architecture = {1: "bidir", 2: "causal", 3: "sfdmd"}[stage]
|
| 49 |
+
expected = dict(
|
| 50 |
+
architecture=f"pai_factorized_{architecture}_p1x2", stage=f"stage{stage}",
|
| 51 |
+
weights="ema", input_channels=193, output_channels=64,
|
| 52 |
+
patch_spatial=[1, 2], model_channels=2048, num_blocks=28, num_heads=16,
|
| 53 |
+
num_dataset_embeddings=3, sensor_dataset_id=0, resolution=[128, 1024],
|
| 54 |
+
min_range_m=2.5, max_range_m=100, input_has_prepend=False,
|
| 55 |
+
shift=5, shift_clamp_percentiles=None, precision="bfloat16",
|
| 56 |
+
tokenizer="transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema",
|
| 57 |
+
tokenizer_encoder_dtype="bfloat16" if stage == 3 else "float32",
|
| 58 |
+
tokenizer_decoder_dtype="float32",
|
| 59 |
+
)
|
| 60 |
+
if stage != 1:
|
| 61 |
+
expected.update(temporal_block_size=4, temporal_prefix_frames=1)
|
| 62 |
+
if stage == 3:
|
| 63 |
+
encoder_dtype = config.get("tokenizer_encoder_dtype")
|
| 64 |
+
if encoder_dtype not in ("float32", "bfloat16"):
|
| 65 |
+
raise ValueError(f"{config_path}: unsupported tokenizer encoder dtype {encoder_dtype!r}")
|
| 66 |
+
spatial_cache = config.get("spatial_cache")
|
| 67 |
+
if not isinstance(spatial_cache, dict):
|
| 68 |
+
raise ValueError(f"{config_path}: missing spatial_cache configuration")
|
| 69 |
+
voxel_m = spatial_cache.get("voxel_m")
|
| 70 |
+
if not isinstance(voxel_m, (int, float)) or not np.isfinite(voxel_m) or voxel_m <= 0:
|
| 71 |
+
raise ValueError(f"{config_path}: voxel_m must be finite and positive")
|
| 72 |
+
expected.update(tokenizer_encoder_dtype=encoder_dtype,
|
| 73 |
+
spatial_cache={**SPATIAL_CACHE, "voxel_m": voxel_m}, stream_condition_vae_encode=True,
|
| 74 |
+
condition_vae_cache_frames=9, clean_x0_kv_commit=True)
|
| 75 |
+
for key, value in expected.items():
|
| 76 |
+
actual = config.get(key)
|
| 77 |
+
if key == "tokenizer" and actual == "transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema40k":
|
| 78 |
+
actual = value
|
| 79 |
+
if key not in config or actual != value:
|
| 80 |
+
raise ValueError(f"{config_path}: expected {key}={value!r}, got {config.get(key)!r}")
|
| 81 |
+
return config
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def load_model(checkpoint, tokenizer_checkpoint, latent_stats, stage=1, package=None):
|
| 85 |
+
package = load_package(checkpoint, stage) if package is None else package
|
| 86 |
+
from diffusion.training.config.base.lidarverse_vae import get_lidarverse_tokenizer
|
| 87 |
+
from diffusion.training.config.base.model import LidarModelConfig
|
| 88 |
+
from diffusion.training.config.text2world.registry import (
|
| 89 |
+
MININET_2B_Config, VideoConditionerFpsSizePaddingConfig,
|
| 90 |
+
)
|
| 91 |
+
from diffusion.training.models.hdmaptolidar_model_rf import (
|
| 92 |
+
HdmapToLidarFactorizedBidirectionalRFModel,
|
| 93 |
+
HdmapToLidarFactorizedTeacherForcingRFModel,
|
| 94 |
+
)
|
| 95 |
+
from tokenizer.training.configs.base.nets.lidarverse import PAI_TOKENIZER_NAME
|
| 96 |
+
from utils.lazy_config import LazyDict
|
| 97 |
+
|
| 98 |
+
net = deepcopy(MININET_2B_Config)
|
| 99 |
+
net.update(
|
| 100 |
+
in_channels=193, out_channels=64, patch_spatial=(1, 2),
|
| 101 |
+
num_dataset_embeddings=3, num_frame_type_embeddings=0,
|
| 102 |
+
temporal_block_size=0 if stage == 1 else 4,
|
| 103 |
+
temporal_prefix_frames=0 if stage == 1 else 1, side_condition_channels=0,
|
| 104 |
+
atten_backend="minimal_a2a" if stage == 1 else "torch-flex",
|
| 105 |
+
rope_scale_positions_by_patch=True, timestep_scale=0.001,
|
| 106 |
+
rope_h_extrapolation_ratio=3.0, rope_w_extrapolation_ratio=3.0,
|
| 107 |
+
rope_t_extrapolation_ratio=1.0, rope_enable_fps_modulation=False,
|
| 108 |
+
use_wan_fp32_strategy=True,
|
| 109 |
+
)
|
| 110 |
+
net.sac_config.mode = "none"
|
| 111 |
+
vae = get_lidarverse_tokenizer()
|
| 112 |
+
vae.update(
|
| 113 |
+
experiment_name=PAI_TOKENIZER_NAME, checkpoint_path=str(tokenizer_checkpoint),
|
| 114 |
+
mean_std_fp=str(latent_stats), strict_checkpoint=True, use_ema=False,
|
| 115 |
+
is_bf16=False, encoder_is_bf16=package["tokenizer_encoder_dtype"] == "bfloat16", decoder_is_bf16=False,
|
| 116 |
+
)
|
| 117 |
+
config = LidarModelConfig(
|
| 118 |
+
net=net, vae=vae, conditioner=deepcopy(VideoConditionerFpsSizePaddingConfig),
|
| 119 |
+
ema=LazyDict(dict(enabled=False)), fsdp_enabled=False,
|
| 120 |
+
latent_shape=[64, package.get("window_frames", 21), 16, 128], input_video_has_prepend=False,
|
| 121 |
+
hdmap_channels=1, additional_concat_ch=64, encode_hdmap_with_vae=True,
|
| 122 |
+
hdmap_dropout_prob=0.0, sigma_data=1.0, shift=5,
|
| 123 |
+
shift_clamp_percentiles=None, enable_shift_stretch=False,
|
| 124 |
+
rf_prediction_type="velocity", loss_reduce="mean",
|
| 125 |
+
diffusion_forcing_block_size=21 if stage == 1 else 4,
|
| 126 |
+
teacher_forcing_prefix_frames=0 if stage == 1 else 1,
|
| 127 |
+
factorized_bidirectional_stage1=stage == 1,
|
| 128 |
+
blockwise_warped_history_condition=True, blockwise_warped_history_concat=True,
|
| 129 |
+
blockwise_warped_history_backend="torch_spatial_map",
|
| 130 |
+
blockwise_spatial_map_max_range=100.0, blockwise_spatial_map_min_range=2.5,
|
| 131 |
+
**{f"blockwise_spatial_map_{key}": value for key, value in package.get("spatial_cache", SPATIAL_CACHE).items()},
|
| 132 |
+
blockwise_spatial_map_geometry_root_path="", blockwise_spatial_map_geometry_filter_list_path="",
|
| 133 |
+
stage2_known_mask_concat=True,
|
| 134 |
+
stage2_factorized_prefix_frames=[0, 1, 2, 4, 8, 10, 12, 16],
|
| 135 |
+
stage2_factorized_prefix_probs=[0.5] + [1 / 14] * 7,
|
| 136 |
+
stage2_factorized_hdmap_modes=["null", "full"], stage2_factorized_hdmap_probs=[0.5, 0.5],
|
| 137 |
+
stage2_factorized_geometry_modes_k0=["null", "rolling_static", "frozen_object"],
|
| 138 |
+
stage2_factorized_geometry_probs_k0=[0.1, 0.45, 0.45],
|
| 139 |
+
stage2_factorized_geometry_modes_known=["null", "rolling_static", "frozen_object"],
|
| 140 |
+
stage2_factorized_geometry_probs_known=[0.1, 0.45, 0.45],
|
| 141 |
+
factorized_decouple_geometry_observations=True,
|
| 142 |
+
factorized_geometry_observation_frames=[1, 2, 4, 8, 10, 12, 16, 20],
|
| 143 |
+
factorized_geometry_observation_probs=[0.125] * 8,
|
| 144 |
+
factorized_geometry_rolling_shutter=True, factorized_geometry_actor_box_time_mode="frame",
|
| 145 |
+
)
|
| 146 |
+
model_type = (HdmapToLidarFactorizedBidirectionalRFModel if stage == 1
|
| 147 |
+
else HdmapToLidarFactorizedTeacherForcingRFModel)
|
| 148 |
+
model = model_type(config)
|
| 149 |
+
model.model.to(dtype=torch.bfloat16)
|
| 150 |
+
payload = torch.load(str(checkpoint), map_location="cpu", weights_only=True, mmap=True)
|
| 151 |
+
model.model.load_state_dict(payload["model"], strict=True)
|
| 152 |
+
del payload
|
| 153 |
+
model.cuda().eval()
|
| 154 |
+
if stage != 1:
|
| 155 |
+
model.net.set_cached_inference_self_attention_backend("sdpa-flash")
|
| 156 |
+
print(f"Loaded PAI Stage {stage} EMA strictly: {checkpoint}", flush=True)
|
| 157 |
+
return model
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def load_sample(path, modes, stage=1):
|
| 161 |
+
with np.load(path, allow_pickle=False) as data:
|
| 162 |
+
sample = {key: data[key] for key in data.files}
|
| 163 |
+
ranges, valid, _, rays = common.load_sample(path)
|
| 164 |
+
sample.update(range_m=ranges, valid_mask=valid, ray_directions=rays)
|
| 165 |
+
frames = max(sum(mode_spec(mode, stage)[key] for key in ("input_frames", "output_frames")) for mode in modes)
|
| 166 |
+
if stage != 1:
|
| 167 |
+
frames = 1 + ((frames - 1 + 3) // 4) * 4
|
| 168 |
+
if sample["range_m"].shape[1:] != (128, 1024) or len(sample["range_m"]) < frames:
|
| 169 |
+
raise ValueError(f"{path}: need at least {frames} real 128x1024 sweeps")
|
| 170 |
+
if int(sample.get("sensor_dataset_id", -1)) != 0 or str(sample.get("dataset", "")) != "pandar":
|
| 171 |
+
raise ValueError(f"{path}: this checkpoint is NVIDIA PAI only (dataset ID 0)")
|
| 172 |
+
if float(sample.get("fps", 0)) != 10 or bool(sample.get("has_prepend", False)):
|
| 173 |
+
raise ValueError(f"{path}: expected 10 Hz real sweeps without a duplicated prefix")
|
| 174 |
+
if float(sample.get("min_range_m", 0)) != 2.5 or float(sample.get("max_range_m", 0)) != 100:
|
| 175 |
+
raise ValueError(f"{path}: expected range support [2.5,100] m")
|
| 176 |
+
rays = sample["ray_directions"]
|
| 177 |
+
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):
|
| 178 |
+
raise ValueError(f"{path}: expected a calibrated 128x1024 unit-ray grid")
|
| 179 |
+
if "world" in modes:
|
| 180 |
+
hdmap = sample.get("hdmap")
|
| 181 |
+
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:
|
| 182 |
+
raise ValueError(f"{path}: world generation needs aligned HDMap ranges normalized to [-1,1]")
|
| 183 |
+
poses = sample.get("pose_sensor_start_end")
|
| 184 |
+
if poses is None or poses.shape != (len(sample["range_m"]), 2, 4, 4) or not np.isfinite(poses).all():
|
| 185 |
+
raise ValueError(f"{path}: missing aligned sensor-to-world start/end poses")
|
| 186 |
+
if "resim" in modes or ("forecast" in modes and stage == 1):
|
| 187 |
+
for key in ("box_object_to_world", "box_lwh", "box_valid", "box_is_moving", "box_track_id"):
|
| 188 |
+
if key not in sample or len(sample[key]) != len(sample["range_m"]):
|
| 189 |
+
raise ValueError(f"{path}: forecast/resim need aligned {key}; use prepare_pai_bidir.py")
|
| 190 |
+
shape = sample["box_valid"].shape
|
| 191 |
+
if len(shape) != 2 or sample["box_track_id"].shape != shape or sample["box_is_moving"].shape != shape:
|
| 192 |
+
raise ValueError(f"{path}: box masks and track IDs must be (T,M)")
|
| 193 |
+
if sample["box_object_to_world"].shape != shape + (4, 4) or sample["box_lwh"].shape != shape + (3,):
|
| 194 |
+
raise ValueError(f"{path}: box poses/sizes do not match the mask")
|
| 195 |
+
active = sample["box_valid"].astype(bool)
|
| 196 |
+
if not np.isfinite(sample["box_object_to_world"][active]).all() or not np.isfinite(sample["box_lwh"][active]).all():
|
| 197 |
+
raise ValueError(f"{path}: non-finite actor annotations")
|
| 198 |
+
if (sample["box_lwh"][active] <= 0).any() or (sample["box_track_id"][active] < 0).any():
|
| 199 |
+
raise ValueError(f"{path}: actor sizes must be positive and track IDs nonnegative")
|
| 200 |
+
return sample
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def make_batch(sample, mode, stage=1, length=None):
|
| 204 |
+
from utils.pai_batch import make_pai_batch
|
| 205 |
+
|
| 206 |
+
spec = mode_spec(mode, stage)
|
| 207 |
+
length = spec["input_frames"] + spec["output_frames"] if length is None else length
|
| 208 |
+
return make_pai_batch(sample, length, input_frames=spec["input_frames"],
|
| 209 |
+
hdmap=spec["hdmap"] == "full",
|
| 210 |
+
boxes=mode == "resim" or (mode == "forecast" and stage == 1), device="cuda")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def generate_bidir(model, sample, mode, args, seed, console):
|
| 214 |
+
spec = MODES[mode]
|
| 215 |
+
model.stage2_factorized_force_prefix_k = spec["input_frames"]
|
| 216 |
+
model.stage2_factorized_force_hdmap_mode = spec["hdmap"]
|
| 217 |
+
# frozen_object + static_only is exactly the frozen_static builder branch.
|
| 218 |
+
model.stage2_factorized_force_geometry_mode = "null" if mode == "world" else "frozen_object"
|
| 219 |
+
model.factorized_static_only_geometry = mode == "forecast"
|
| 220 |
+
model.factorized_force_geometry_observations = spec["geometry_frames"] if mode != "world" else -1
|
| 221 |
+
torch.manual_seed(seed)
|
| 222 |
+
batch = make_batch(sample, mode)
|
| 223 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 224 |
+
_, latent, _ = model.get_data_and_condition(batch)
|
| 225 |
+
known_mask = model._current_stage2_known_frame_mask
|
| 226 |
+
kwargs = dict(known_latents=latent, known_mask=known_mask, known_latents_mode="clean_mask") if spec["input_frames"] else {}
|
| 227 |
+
with tqdm(total=args.num_steps, desc=f"{mode} sampling", file=console,
|
| 228 |
+
unit="step", leave=False, disable=not console.isatty()) as progress:
|
| 229 |
+
calls = 0
|
| 230 |
+
def on_forward(_module, _inputs, _output):
|
| 231 |
+
nonlocal calls
|
| 232 |
+
calls += 1
|
| 233 |
+
if calls % (1 if args.guidance in (0, 1) else 2) == 0:
|
| 234 |
+
progress.update(1)
|
| 235 |
+
hook = model.net.register_forward_hook(on_forward)
|
| 236 |
+
try:
|
| 237 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 238 |
+
result = model.generate_samples_from_batch(
|
| 239 |
+
batch, state_shape=latent.shape[1:], n_sample=1,
|
| 240 |
+
guidance=args.guidance, seed=seed, num_steps=args.num_steps,
|
| 241 |
+
sampler=args.sampler, sde_eta=args.sde_eta, **kwargs,
|
| 242 |
+
)
|
| 243 |
+
finally:
|
| 244 |
+
hook.remove()
|
| 245 |
+
if not torch.isfinite(result).all():
|
| 246 |
+
raise FloatingPointError("Sampling produced non-finite latents")
|
| 247 |
+
if spec["input_frames"] and not torch.equal(result[:, :, :spec["input_frames"]], latent[:, :, :spec["input_frames"]].float()):
|
| 248 |
+
raise RuntimeError("Clean-prefix latents were not preserved")
|
| 249 |
+
decoded = model.decode(result.float())
|
| 250 |
+
if decoded.shape != batch["video"].shape or not torch.isfinite(decoded).all():
|
| 251 |
+
raise RuntimeError("Invalid decoded LiDAR sequence")
|
| 252 |
+
return _metric_ranges(decoded)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _preview_label(image, title, frame, length, input_frames, is_input):
|
| 256 |
+
image = image.copy()
|
| 257 |
+
cv2.rectangle(image, (0, 0), (image.shape[1] - 1, 80), (255, 255, 255), -1)
|
| 258 |
+
color = (175, 90, 35) if is_input else (30, 30, 30)
|
| 259 |
+
cv2.putText(image, title, (20, 33), cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2, cv2.LINE_AA)
|
| 260 |
+
detail = f"Frame {frame} / {length - 1}"
|
| 261 |
+
if input_frames:
|
| 262 |
+
detail += f" | Input: 0-{input_frames - 1} | Generated: {input_frames}-{length - 1}"
|
| 263 |
+
cv2.putText(image, detail, (20, 64), cv2.FONT_HERSHEY_SIMPLEX, .7, (65, 65, 65), 1, cv2.LINE_AA)
|
| 264 |
+
return image
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def preview(sample, generated, valid, mode, output):
|
| 268 |
+
from utils.visualize.hdmap import render_hdmap
|
| 269 |
+
|
| 270 |
+
spec = MODES[mode]
|
| 271 |
+
length = len(generated)
|
| 272 |
+
if mode == "world":
|
| 273 |
+
source, source_valid = _metric_ranges(torch.from_numpy(sample["hdmap"][:length])[None, None])
|
| 274 |
+
source_title = "Input HDMap"
|
| 275 |
+
else:
|
| 276 |
+
source, source_valid = sample["range_m"][:length], sample["valid_mask"][:length]
|
| 277 |
+
for t in range(length):
|
| 278 |
+
is_input = t < spec["input_frames"]
|
| 279 |
+
if mode != "world":
|
| 280 |
+
source_title = "INPUT | Observed GT" if is_input else "GT | Reference only (not input)"
|
| 281 |
+
generated_title = "INPUT | Observed GT" if is_input else {
|
| 282 |
+
"world": "GENERATION | HDMap-conditioned",
|
| 283 |
+
"forecast": "GENERATION | Forecasting",
|
| 284 |
+
"resim": "GENERATION | Resimulation",
|
| 285 |
+
}[mode]
|
| 286 |
+
# Display the actual provided sweep, not its tokenizer reconstruction.
|
| 287 |
+
values, mask = (source[t], source_valid[t]) if is_input else (generated[t], valid[t])
|
| 288 |
+
clouds = (("input" if mode == "world" else "gt", source_title, source[t], source_valid[t]),
|
| 289 |
+
("generation", generated_title, values, mask))
|
| 290 |
+
panels = []
|
| 291 |
+
for name, title, ranges, hits in clouds:
|
| 292 |
+
points = common.points_from_ranges(ranges, hits, sample["ray_directions"])
|
| 293 |
+
common.write_ply(output / "ply" / f"{name}_{t:03d}.ply", points)
|
| 294 |
+
rendered = render_hdmap(sample, t) if mode == "world" and name == "input" else common.render_points(points, yaw_deg=0)
|
| 295 |
+
panels.append(_preview_label(rendered, title, t, length, spec["input_frames"], is_input))
|
| 296 |
+
yield np.concatenate(panels, axis=1)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
@torch.inference_mode()
|
| 300 |
+
def run(args, console, say):
|
| 301 |
+
package = load_package(args.checkpoint, args.stage)
|
| 302 |
+
modes = list(MODES) if args.mode == "all" else [args.mode]
|
| 303 |
+
paths = common.sample_paths(args.sample_path.resolve())[:args.num_samples]
|
| 304 |
+
if len(paths) < args.num_samples:
|
| 305 |
+
raise ValueError(f"Requested {args.num_samples} clips, found only {len(paths)}")
|
| 306 |
+
# Validate all requested annotations before allocating the diffusion model.
|
| 307 |
+
for path in paths:
|
| 308 |
+
sample = load_sample(path, modes, args.stage)
|
| 309 |
+
if args.raw_hdmap_condition_rasterize and "world" in modes:
|
| 310 |
+
from diffusion.inference.raw_hdmap import validate_raw_hdmap
|
| 311 |
+
validate_raw_hdmap(sample)
|
| 312 |
+
if args.vis_pcd and "world" in modes:
|
| 313 |
+
for key in ("map_vertices", "map_offsets", "map_kinds", "box_class"):
|
| 314 |
+
if key not in sample:
|
| 315 |
+
raise ValueError(f"{path}: missing {key}; rerun prepare_pai_bidir.py")
|
| 316 |
+
if not torch.cuda.is_available():
|
| 317 |
+
raise RuntimeError("Run this quickstart on a CUDA GPU in the diffusion environment")
|
| 318 |
+
model = load_model(args.checkpoint, args.tokenizer_checkpoint, args.latent_stats, args.stage, package)
|
| 319 |
+
generate = generate_bidir
|
| 320 |
+
if args.stage != 1:
|
| 321 |
+
from diffusion.inference.causal import generate
|
| 322 |
+
metadata = {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()}
|
| 323 |
+
metadata.update(checkpoint_config=package,
|
| 324 |
+
modes={mode: mode_spec(mode, args.stage) for mode in modes}, shift=5,
|
| 325 |
+
shift_clamp_percentiles=None, input_has_prepend=False,
|
| 326 |
+
tokenizer_encoder_dtype=package["tokenizer_encoder_dtype"], tokenizer_decoder_dtype="float32")
|
| 327 |
+
if args.stage != 1:
|
| 328 |
+
metadata.update(kv_cache_frames=args.kv_cache_frames, kv_sink_frames=1,
|
| 329 |
+
attention_backend="sdpa-flash",
|
| 330 |
+
kv_budget_includes_sink=True, clean_kv_commit="synchronous_blockwise",
|
| 331 |
+
condition_vae_cache_frames=9, decoder_cache_frames=30,
|
| 332 |
+
observed_latent_encoding="causal_observed_only_stream",
|
| 333 |
+
spatial_cache=package.get("spatial_cache", SPATIAL_CACHE))
|
| 334 |
+
(args.output_folder / "run.json").write_text(json.dumps(metadata, indent=2) + "\n")
|
| 335 |
+
for mode in modes:
|
| 336 |
+
for index, path in enumerate(paths):
|
| 337 |
+
seed = args.seed + index
|
| 338 |
+
say(f"{mode} [{index + 1}/{len(paths)}] {path.stem} | seed {seed}")
|
| 339 |
+
sample = load_sample(path, [mode], args.stage)
|
| 340 |
+
output = common.sample_output(path, args.sample_path.resolve(), args.output_folder / mode)
|
| 341 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 342 |
+
if args.raw_hdmap_condition_rasterize and mode == "world":
|
| 343 |
+
from diffusion.inference.raw_hdmap import rasterize_raw_hdmap
|
| 344 |
+
say(" Rasterizing raw map and boxes with rolling-shutter poses...")
|
| 345 |
+
condition, stats = rasterize_raw_hdmap(
|
| 346 |
+
sample, bbox_dilation=args.raw_hdmap_condition_bbox_dilation,
|
| 347 |
+
seg_interval=args.raw_hdmap_seg_interval,
|
| 348 |
+
)
|
| 349 |
+
sample["hdmap"] = condition
|
| 350 |
+
np.savez_compressed(output / "hdmap_condition.npz", normalized_range=condition,
|
| 351 |
+
frame_indices=sample["frame_indices"],
|
| 352 |
+
pose_sensor_start_end=sample["pose_sensor_start_end"],
|
| 353 |
+
ray_directions=sample["ray_directions"])
|
| 354 |
+
(output / "raw_hdmap_condition.json").write_text(json.dumps(stats, indent=2) + "\n")
|
| 355 |
+
say(f" HDMap coverage: {stats['original_hit_fraction']:.3%} -> {stats['condition_hit_fraction']:.3%}")
|
| 356 |
+
generated, valid = generate(model, sample, mode, args, seed, console)
|
| 357 |
+
length = len(generated)
|
| 358 |
+
np.savez_compressed(output / "generation.npz", range_m=generated, valid_mask=valid,
|
| 359 |
+
ray_directions=sample["ray_directions"], fps=np.float32(10),
|
| 360 |
+
pose_sensor_start_end=sample["pose_sensor_start_end"][:length],
|
| 361 |
+
frame_indices=sample["frame_indices"][:length], clip_name=sample["clip_name"],
|
| 362 |
+
known_frame_mask=np.arange(length) < MODES[mode]["input_frames"], seed=np.int64(seed))
|
| 363 |
+
if args.vis_pcd:
|
| 364 |
+
common.write_video(output / "generation.mp4", preview(sample, generated, valid, mode, output), 10)
|
| 365 |
+
say(f" Saved {output}")
|
| 366 |
+
say(f"Finished. Outputs: {args.output_folder}")
|
diffusion/inference/raw_hdmap.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Inference-only raw-vector HDMap conditioning for prepared PAI samples."""
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def validate_raw_hdmap(sample):
|
| 12 |
+
required = ("map_vertices", "map_offsets", "box_valid", "box_lwh", "box_object_to_world")
|
| 13 |
+
for key in required:
|
| 14 |
+
if key not in sample:
|
| 15 |
+
raise ValueError(f"Missing {key}; rerun scripts/data/prepare_pai_bidir.py")
|
| 16 |
+
vertices, offsets = sample["map_vertices"], sample["map_offsets"]
|
| 17 |
+
if vertices.ndim != 2 or vertices.shape[1:] != (3,) or not np.isfinite(vertices).all():
|
| 18 |
+
raise ValueError("Raw map vertices must be finite (N,3) world points")
|
| 19 |
+
if (offsets.ndim != 1 or len(offsets) < 2 or offsets.dtype.kind not in "iu"
|
| 20 |
+
or offsets[0] != 0 or offsets[-1] != len(vertices) or (np.diff(offsets) < 2).any()):
|
| 21 |
+
raise ValueError("Raw map offsets must delimit nonempty polylines of at least two vertices")
|
| 22 |
+
shape = sample["box_valid"].shape
|
| 23 |
+
if len(shape) != 2 or shape[0] != len(sample["range_m"]):
|
| 24 |
+
raise ValueError("Raw box masks must be (T,M), aligned with the real sweeps")
|
| 25 |
+
if sample["box_lwh"].shape != shape + (3,) or sample["box_object_to_world"].shape != shape + (4, 4):
|
| 26 |
+
raise ValueError("Raw box sizes/poses do not match the box mask")
|
| 27 |
+
active = sample["box_valid"].astype(bool)
|
| 28 |
+
if (not np.isfinite(sample["box_object_to_world"][active]).all()
|
| 29 |
+
or not np.isfinite(sample["box_lwh"][active]).all()
|
| 30 |
+
or (sample["box_lwh"][active] <= 0).any()):
|
| 31 |
+
raise ValueError("Active boxes must have finite poses and positive finite sizes")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _sample_polyline(vertices, spacing):
|
| 35 |
+
# Match LiDARGen's raw-MADS densification, including endpoint handling.
|
| 36 |
+
vertices = np.asarray(vertices, dtype=np.float64)
|
| 37 |
+
points = []
|
| 38 |
+
for start, end in zip(vertices[:-1], vertices[1:]):
|
| 39 |
+
distance = np.linalg.norm(end - start)
|
| 40 |
+
count = int(np.clip(np.floor(distance / spacing), 2, 10000))
|
| 41 |
+
fractions = np.linspace(0, 1, count)[:-1]
|
| 42 |
+
points.append(start + fractions[:, None] * (end - start))
|
| 43 |
+
points.append(vertices[-1:])
|
| 44 |
+
return np.concatenate(points).astype(np.float32)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _box_points(sample, frame, spacing):
|
| 48 |
+
signs = np.array([[1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1],
|
| 49 |
+
[1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1]], dtype=np.float64)
|
| 50 |
+
wireframe = [0, 1, 2, 3, 0, 4, 5, 6, 7, 4, 5, 1, 2, 6, 7, 3]
|
| 51 |
+
points = []
|
| 52 |
+
for index in np.flatnonzero(sample["box_valid"][frame]):
|
| 53 |
+
corners = signs * sample["box_lwh"][frame, index] / 2
|
| 54 |
+
pose = sample["box_object_to_world"][frame, index].astype(np.float64)
|
| 55 |
+
corners = corners @ pose[:3, :3].T + pose[:3, 3]
|
| 56 |
+
points.append(_sample_polyline(corners[wireframe], spacing))
|
| 57 |
+
return np.concatenate(points) if points else np.empty((0, 3), np.float32)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _dilate_nearest(normalized, kernel_size):
|
| 61 |
+
"""Widen bbox pixels without averaging ranges or filling empty neighborhoods."""
|
| 62 |
+
if kernel_size < 1 or kernel_size % 2 != 1:
|
| 63 |
+
raise ValueError("BBox dilation must be a positive odd integer")
|
| 64 |
+
if kernel_size == 1:
|
| 65 |
+
return normalized
|
| 66 |
+
valid = torch.isfinite(normalized) & (normalized > -1 + 1e-5)
|
| 67 |
+
work = normalized[:, None].masked_fill(~valid[:, None], torch.inf)
|
| 68 |
+
nearest = -F.max_pool2d(-work, kernel_size, stride=1, padding=kernel_size // 2)
|
| 69 |
+
return torch.where(torch.isfinite(nearest), nearest, -1.)[:, 0]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@torch.inference_mode()
|
| 73 |
+
def rasterize_raw_hdmap(sample, *, bbox_dilation=1, seg_interval=0.1):
|
| 74 |
+
"""Return a (T,H,W) normalized condition and provenance, without GT LiDAR."""
|
| 75 |
+
from diffusion.training.datasets.lidar_dataset.forecast_warp import (
|
| 76 |
+
TorchSpatialPointMap, compose_normalized_range_channels,
|
| 77 |
+
)
|
| 78 |
+
from diffusion.training.models.hdmaptolidar_model_rf import _sensor_tables_from_ray_directions
|
| 79 |
+
|
| 80 |
+
validate_raw_hdmap(sample)
|
| 81 |
+
if not np.isfinite(seg_interval) or seg_interval <= 0:
|
| 82 |
+
raise ValueError("Raw HDMap segment spacing must be positive and finite")
|
| 83 |
+
if bbox_dilation < 1 or bbox_dilation % 2 != 1:
|
| 84 |
+
raise ValueError("BBox dilation must be a positive odd integer")
|
| 85 |
+
rays = torch.as_tensor(sample["ray_directions"], dtype=torch.float32, device="cuda")
|
| 86 |
+
elevations, azimuths, offsets = _sensor_tables_from_ray_directions(rays, allow_approximate=True)
|
| 87 |
+
renderer = TorchSpatialPointMap(
|
| 88 |
+
ray_dirs=rays, row_elevations_rad=elevations, column_azimuths_rad=azimuths,
|
| 89 |
+
row_azimuth_offsets_rad=offsets, min_range=2.5, max_range=100,
|
| 90 |
+
min_value=-1, inverse_depth=False, radius_m=100, voxel_size_m=0.2, device="cuda",
|
| 91 |
+
)
|
| 92 |
+
vertices, offsets = sample["map_vertices"], sample["map_offsets"]
|
| 93 |
+
static_points = np.concatenate([_sample_polyline(vertices[a:b], seg_interval)
|
| 94 |
+
for a, b in zip(offsets[:-1], offsets[1:])])
|
| 95 |
+
poses = sample["pose_sensor_start_end"].astype(np.float32)
|
| 96 |
+
motions = np.linalg.inv(poses[:, 1]) @ poses[:, 0]
|
| 97 |
+
static, static_hit = renderer.render_points_world(
|
| 98 |
+
static_points, poses[:, 0], target_pose_sensor_start_end=motions,
|
| 99 |
+
)
|
| 100 |
+
boxes, box_hits = [], []
|
| 101 |
+
for t, pose in enumerate(poses):
|
| 102 |
+
ranges, hits = renderer.render_points_world(
|
| 103 |
+
_box_points(sample, t, seg_interval), pose[None, 0],
|
| 104 |
+
target_pose_sensor_start_end=motions[t:t + 1],
|
| 105 |
+
)
|
| 106 |
+
boxes.append(ranges[0, 0])
|
| 107 |
+
box_hits.append(hits[0])
|
| 108 |
+
thick_boxes = _dilate_nearest(torch.stack(boxes), bbox_dilation)
|
| 109 |
+
condition = compose_normalized_range_channels(
|
| 110 |
+
torch.stack((static[0], thick_boxes)), channel_dim=0, min_value=-1, inverse_depth=False,
|
| 111 |
+
)[0].cpu().numpy()
|
| 112 |
+
stats = dict(
|
| 113 |
+
source="prepared_raw_vectors", bbox_dilation_kernel=bbox_dilation,
|
| 114 |
+
map_dilation_kernel=1, segment_spacing_m=seg_interval,
|
| 115 |
+
rolling_shutter=True, min_range_m=2.5, max_range_m=100,
|
| 116 |
+
static_hit_fraction=float(static_hit.float().mean()),
|
| 117 |
+
bbox_hit_fraction_before_dilation=float(torch.stack(box_hits).float().mean()),
|
| 118 |
+
bbox_hit_fraction_after_dilation=float((thick_boxes > -1 + 1e-5).float().mean()),
|
| 119 |
+
original_hit_fraction=float((sample["hdmap"] > -1 + 1e-5).mean()),
|
| 120 |
+
condition_hit_fraction=float((condition > -1 + 1e-5).mean()),
|
| 121 |
+
)
|
| 122 |
+
return condition, stats
|
diffusion/module/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
diffusion/module/attention.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import List, Optional
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
import transformer_engine as te
|
| 21 |
+
from einops import rearrange
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.utils.checkpoint import checkpoint
|
| 24 |
+
from transformer_engine.pytorch.attention import DotProductAttention, apply_rotary_pos_emb
|
| 25 |
+
|
| 26 |
+
# ---------------------- Feed Forward Network -----------------------
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class FeedForward(nn.Module):
|
| 30 |
+
"""
|
| 31 |
+
Transformer FFN with optional gating
|
| 32 |
+
|
| 33 |
+
Parameters:
|
| 34 |
+
d_model (int): Dimensionality of input features.
|
| 35 |
+
d_ff (int): Dimensionality of the hidden layer.
|
| 36 |
+
dropout (float, optional): Dropout rate applied after the activation function. Defaults to 0.1.
|
| 37 |
+
activation (callable, optional): The activation function applied after the first linear layer.
|
| 38 |
+
Defaults to nn.ReLU().
|
| 39 |
+
is_gated (bool, optional): If set to True, incorporates gating mechanism to the feed-forward layer.
|
| 40 |
+
Defaults to False.
|
| 41 |
+
bias (bool, optional): If set to True, adds a bias to the linear layers. Defaults to True.
|
| 42 |
+
|
| 43 |
+
Example:
|
| 44 |
+
>>> ff = FeedForward(d_model=512, d_ff=2048)
|
| 45 |
+
>>> x = torch.randn(64, 10, 512) # Example input tensor
|
| 46 |
+
>>> output = ff(x)
|
| 47 |
+
>>> print(output.shape) # Expected shape: (64, 10, 512)
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
d_model: int,
|
| 53 |
+
d_ff: int,
|
| 54 |
+
dropout: float = 0.1,
|
| 55 |
+
activation=nn.ReLU(),
|
| 56 |
+
is_gated: bool = False,
|
| 57 |
+
bias: bool = False,
|
| 58 |
+
) -> None:
|
| 59 |
+
super().__init__()
|
| 60 |
+
|
| 61 |
+
self.layer1 = nn.Linear(d_model, d_ff, bias=bias)
|
| 62 |
+
self.layer2 = nn.Linear(d_ff, d_model, bias=bias)
|
| 63 |
+
|
| 64 |
+
self.dropout = nn.Dropout(dropout)
|
| 65 |
+
self.activation = activation
|
| 66 |
+
self.is_gated = is_gated
|
| 67 |
+
if is_gated:
|
| 68 |
+
self.linear_gate = nn.Linear(d_model, d_ff, bias=False)
|
| 69 |
+
|
| 70 |
+
def forward(self, x: torch.Tensor):
|
| 71 |
+
g = self.activation(self.layer1(x))
|
| 72 |
+
if self.is_gated:
|
| 73 |
+
x = g * self.linear_gate(x)
|
| 74 |
+
else:
|
| 75 |
+
x = g
|
| 76 |
+
assert self.dropout.p == 0.0, "we skip dropout"
|
| 77 |
+
return self.layer2(x)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class GPT2FeedForward(FeedForward):
|
| 81 |
+
def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1, bias: bool = False):
|
| 82 |
+
super().__init__(
|
| 83 |
+
d_model=d_model,
|
| 84 |
+
d_ff=d_ff,
|
| 85 |
+
dropout=dropout,
|
| 86 |
+
activation=nn.GELU(),
|
| 87 |
+
is_gated=False,
|
| 88 |
+
bias=bias,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def forward(self, x: torch.Tensor):
|
| 92 |
+
assert self.dropout.p == 0.0, "we skip dropout"
|
| 93 |
+
|
| 94 |
+
x = self.layer1(x)
|
| 95 |
+
|
| 96 |
+
def activation_layer2_forward(x):
|
| 97 |
+
x = self.activation(x)
|
| 98 |
+
x = self.layer2(x)
|
| 99 |
+
return x
|
| 100 |
+
|
| 101 |
+
x = checkpoint(activation_layer2_forward, x, use_reentrant=False)
|
| 102 |
+
return x
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ---------------------- Normalization Layer -----------------------
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def normalize(x: torch.Tensor, dim: Optional[List[int]] = None, eps: float = 0) -> torch.Tensor:
|
| 109 |
+
"""
|
| 110 |
+
Normalizes the input tensor along specified dimensions such that the average square norm of elements is adjusted.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
x (torch.Tensor): The input tensor to normalize.
|
| 114 |
+
dim (list, optional): The dimensions over which to normalize. If None, normalizes over all dimensions except the first.
|
| 115 |
+
eps (float, optional): A small constant to ensure numerical stability during division.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
torch.Tensor: The normalized tensor.
|
| 119 |
+
"""
|
| 120 |
+
if dim is None:
|
| 121 |
+
dim = list(range(1, x.ndim))
|
| 122 |
+
norm = torch.linalg.vector_norm(x, dim=dim, keepdim=True, dtype=torch.float32)
|
| 123 |
+
norm = torch.add(eps, norm, alpha=np.sqrt(norm.numel() / x.numel()))
|
| 124 |
+
return x / norm.to(x.dtype)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def get_normalization(name: str, channels: int):
|
| 128 |
+
if name == "I":
|
| 129 |
+
return nn.Identity()
|
| 130 |
+
elif name == "R":
|
| 131 |
+
return te.pytorch.RMSNorm(channels, eps=1e-6)
|
| 132 |
+
else:
|
| 133 |
+
raise ValueError(f"Normalization {name} not found")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class BaseAttentionOp(nn.Module):
|
| 137 |
+
def __init__(self):
|
| 138 |
+
super().__init__()
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class Attention(nn.Module):
|
| 142 |
+
"""
|
| 143 |
+
Generalized attention impl.
|
| 144 |
+
|
| 145 |
+
Allowing for both self-attention and cross-attention configurations depending on whether a `context_dim` is provided.
|
| 146 |
+
If `context_dim` is None, self-attention is assumed.
|
| 147 |
+
|
| 148 |
+
Parameters:
|
| 149 |
+
query_dim (int): Dimension of each query vector.
|
| 150 |
+
context_dim (int, optional): Dimension of each context vector. If None, self-attention is assumed.
|
| 151 |
+
heads (int, optional): Number of attention heads. Defaults to 8.
|
| 152 |
+
dim_head (int, optional): Dimension of each head. Defaults to 64.
|
| 153 |
+
dropout (float, optional): Dropout rate applied to the output of the attention block. Defaults to 0.0.
|
| 154 |
+
attn_op (BaseAttentionOp, optional): Custom attention operation to be used instead of the default.
|
| 155 |
+
qkv_bias (bool, optional): If True, adds a learnable bias to query, key, and value projections. Defaults to False.
|
| 156 |
+
out_bias (bool, optional): If True, adds a learnable bias to the output projection. Defaults to False.
|
| 157 |
+
qkv_norm (str, optional): A string representing normalization strategies for query, key, and value projections.
|
| 158 |
+
Defaults to "SSI".
|
| 159 |
+
qkv_norm_mode (str, optional): A string representing normalization mode for query, key, and value projections.
|
| 160 |
+
Defaults to 'per_head'. Only support 'per_head'.
|
| 161 |
+
|
| 162 |
+
Examples:
|
| 163 |
+
>>> attn = Attention(query_dim=128, context_dim=256, heads=4, dim_head=32, dropout=0.1)
|
| 164 |
+
>>> query = torch.randn(10, 128) # Batch size of 10
|
| 165 |
+
>>> context = torch.randn(10, 256) # Batch size of 10
|
| 166 |
+
>>> output = attn(query, context) # Perform the attention operation
|
| 167 |
+
|
| 168 |
+
Note:
|
| 169 |
+
https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/cosmos_predict1/attention.py#L223
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
def __init__(
|
| 173 |
+
self,
|
| 174 |
+
query_dim: int,
|
| 175 |
+
context_dim=None,
|
| 176 |
+
heads=8,
|
| 177 |
+
dim_head=64,
|
| 178 |
+
dropout=0.0,
|
| 179 |
+
attn_op: Optional[BaseAttentionOp] = None,
|
| 180 |
+
qkv_bias: bool = False,
|
| 181 |
+
out_bias: bool = False,
|
| 182 |
+
qkv_norm: str = "SSI",
|
| 183 |
+
qkv_norm_mode: str = "per_head",
|
| 184 |
+
backend: str = "transformer_engine",
|
| 185 |
+
qkv_format: str = "bshd",
|
| 186 |
+
) -> None:
|
| 187 |
+
super().__init__()
|
| 188 |
+
|
| 189 |
+
self.is_selfattn = context_dim is None # self attention
|
| 190 |
+
|
| 191 |
+
inner_dim = dim_head * heads
|
| 192 |
+
context_dim = query_dim if context_dim is None else context_dim
|
| 193 |
+
|
| 194 |
+
self.heads = heads
|
| 195 |
+
self.dim_head = dim_head
|
| 196 |
+
self.qkv_norm_mode = qkv_norm_mode
|
| 197 |
+
self.qkv_format = qkv_format
|
| 198 |
+
|
| 199 |
+
if self.qkv_norm_mode == "per_head":
|
| 200 |
+
norm_dim = dim_head
|
| 201 |
+
else:
|
| 202 |
+
raise ValueError(f"Normalization mode {self.qkv_norm_mode} not found, only support 'per_head'")
|
| 203 |
+
|
| 204 |
+
self.backend = backend
|
| 205 |
+
self.tp_size = 1 # TP is not included in this Attention implementation.
|
| 206 |
+
|
| 207 |
+
self.to_q = nn.Sequential(
|
| 208 |
+
nn.Linear(query_dim, inner_dim, bias=qkv_bias),
|
| 209 |
+
get_normalization(qkv_norm[0], norm_dim),
|
| 210 |
+
)
|
| 211 |
+
self.to_k = nn.Sequential(
|
| 212 |
+
nn.Linear(context_dim, inner_dim, bias=qkv_bias),
|
| 213 |
+
get_normalization(qkv_norm[1], norm_dim),
|
| 214 |
+
)
|
| 215 |
+
self.to_v = nn.Sequential(
|
| 216 |
+
nn.Linear(context_dim, inner_dim, bias=qkv_bias),
|
| 217 |
+
get_normalization(qkv_norm[2], norm_dim),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
self.to_out = nn.Sequential(
|
| 221 |
+
nn.Linear(inner_dim, query_dim, bias=out_bias),
|
| 222 |
+
nn.Dropout(dropout),
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if attn_op: # use what is given
|
| 226 |
+
self.attn_op = attn_op
|
| 227 |
+
elif self.backend == "transformer_engine":
|
| 228 |
+
self.attn_op: BaseAttentionOp = DotProductAttention(
|
| 229 |
+
self.heads,
|
| 230 |
+
self.dim_head,
|
| 231 |
+
num_gqa_groups=self.heads,
|
| 232 |
+
attention_dropout=0,
|
| 233 |
+
qkv_format=qkv_format,
|
| 234 |
+
attn_mask_type="no_mask",
|
| 235 |
+
tp_size=self.tp_size,
|
| 236 |
+
tp_group=None,
|
| 237 |
+
sequence_parallel=False,
|
| 238 |
+
)
|
| 239 |
+
elif self.backend == "torch":
|
| 240 |
+
self.attn_op = torch.nn.functional.scaled_dot_product_attention
|
| 241 |
+
else:
|
| 242 |
+
raise ValueError(f"Backend {backend} not found")
|
| 243 |
+
self.query_dim = query_dim
|
| 244 |
+
self.context_dim = context_dim
|
| 245 |
+
self.inner_dim = inner_dim
|
| 246 |
+
|
| 247 |
+
def cal_qkv(
|
| 248 |
+
self, x, context=None, mask=None, rope_emb=None, **kwargs
|
| 249 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 250 |
+
del kwargs
|
| 251 |
+
|
| 252 |
+
"""
|
| 253 |
+
self.to_q, self.to_k, self.to_v are nn.Sequential with projection + normalization layers.
|
| 254 |
+
Before 07/24/2024, these modules normalize across all heads.
|
| 255 |
+
After 07/24/2024, to support tensor parallelism and follow the common practice in the community,
|
| 256 |
+
we support to normalize per head.
|
| 257 |
+
To keep the checkpoint copatibility with the previous code,
|
| 258 |
+
we keep the nn.Sequential but call the projection and the normalization layers separately.
|
| 259 |
+
We use a flag `self.qkv_norm_mode` to control the normalization behavior.
|
| 260 |
+
The default value of `self.qkv_norm_mode` is "per_head", which means we normalize per head.
|
| 261 |
+
"""
|
| 262 |
+
if self.qkv_norm_mode == "per_head":
|
| 263 |
+
q = self.to_q[0](x)
|
| 264 |
+
context = x if context is None else context
|
| 265 |
+
k = self.to_k[0](context)
|
| 266 |
+
v = self.to_v[0](context)
|
| 267 |
+
q, k, v = map(
|
| 268 |
+
lambda t: rearrange(t, "b ... (n c) -> b ... n c", n=self.heads, c=self.dim_head),
|
| 269 |
+
(q, k, v),
|
| 270 |
+
)
|
| 271 |
+
else:
|
| 272 |
+
raise ValueError(f"Normalization mode {self.qkv_norm_mode} not found, only support 'per_head'")
|
| 273 |
+
|
| 274 |
+
q = self.to_q[1](q)
|
| 275 |
+
k = self.to_k[1](k)
|
| 276 |
+
v = self.to_v[1](v)
|
| 277 |
+
if self.is_selfattn and rope_emb is not None: # only apply to self-attention!
|
| 278 |
+
q = apply_rotary_pos_emb(q, rope_emb, tensor_format=self.qkv_format, fused=True)
|
| 279 |
+
k = apply_rotary_pos_emb(k, rope_emb, tensor_format=self.qkv_format, fused=True)
|
| 280 |
+
return q, k, v
|
| 281 |
+
|
| 282 |
+
def cal_attn(self, q, k, v, mask=None):
|
| 283 |
+
if self.backend == "transformer_engine":
|
| 284 |
+
seq_dim = self.qkv_format.index("s")
|
| 285 |
+
assert (
|
| 286 |
+
q.shape[seq_dim] > 1 and k.shape[seq_dim] > 1
|
| 287 |
+
), "Seqlen must be larger than 1 for TE Attention starting with 1.8 TE version."
|
| 288 |
+
out = self.attn_op(q, k, v, core_attention_bias_type="no_bias", core_attention_bias=None) # [B, Mq, H, V]
|
| 289 |
+
return self.to_out(out)
|
| 290 |
+
elif self.backend == "torch":
|
| 291 |
+
q = rearrange(q, "s b h d -> b h s d")
|
| 292 |
+
k = rearrange(k, "s b h d -> b h s d")
|
| 293 |
+
v = rearrange(v, "s b h d -> b h s d")
|
| 294 |
+
out = self.attn_op(q, k, v) # [B, Mq, H, V]
|
| 295 |
+
return self.to_out(rearrange(out, " b h s d -> s b (h d)"))
|
| 296 |
+
else:
|
| 297 |
+
raise ValueError(f"Backend {self.backend} not found")
|
| 298 |
+
|
| 299 |
+
def forward(
|
| 300 |
+
self,
|
| 301 |
+
x,
|
| 302 |
+
context=None,
|
| 303 |
+
mask=None,
|
| 304 |
+
rope_emb=None,
|
| 305 |
+
**kwargs,
|
| 306 |
+
):
|
| 307 |
+
"""
|
| 308 |
+
Args:
|
| 309 |
+
x (Tensor): The query tensor of shape [B, Mq, K]
|
| 310 |
+
context (Optional[Tensor]): The key tensor of shape [B, Mk, K] or use x as context [self attention] if None
|
| 311 |
+
"""
|
| 312 |
+
q, k, v = self.cal_qkv(x, context, mask, rope_emb=rope_emb, **kwargs)
|
| 313 |
+
return self.cal_attn(q, k, v, mask)
|
diffusion/module/blocks.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from einops import rearrange, repeat
|
| 22 |
+
from einops.layers.torch import Rearrange
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from diffusion.module.attention import Attention, GPT2FeedForward
|
| 26 |
+
from utils import log
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def modulate(x, shift, scale):
|
| 30 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Timesteps(nn.Module):
|
| 34 |
+
def __init__(self, num_channels):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.num_channels = num_channels
|
| 37 |
+
|
| 38 |
+
def forward(self, timesteps):
|
| 39 |
+
in_dype = timesteps.dtype
|
| 40 |
+
half_dim = self.num_channels // 2
|
| 41 |
+
exponent = -math.log(10000) * torch.arange(half_dim, dtype=torch.float32, device=timesteps.device)
|
| 42 |
+
exponent = exponent / (half_dim - 0.0)
|
| 43 |
+
|
| 44 |
+
emb = torch.exp(exponent)
|
| 45 |
+
emb = timesteps[:, None].float() * emb[None, :]
|
| 46 |
+
|
| 47 |
+
sin_emb = torch.sin(emb)
|
| 48 |
+
cos_emb = torch.cos(emb)
|
| 49 |
+
emb = torch.cat([cos_emb, sin_emb], dim=-1)
|
| 50 |
+
|
| 51 |
+
return emb.to(in_dype)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TimestepEmbedding(nn.Module):
|
| 55 |
+
def __init__(self, in_features: int, out_features: int, use_adaln_lora: bool = False):
|
| 56 |
+
super().__init__()
|
| 57 |
+
log.debug(
|
| 58 |
+
f"Using AdaLN LoRA Flag: {use_adaln_lora}. We enable bias if no AdaLN LoRA for backward compatibility."
|
| 59 |
+
)
|
| 60 |
+
self.linear_1 = nn.Linear(in_features, out_features, bias=not use_adaln_lora)
|
| 61 |
+
self.activation = nn.SiLU()
|
| 62 |
+
self.use_adaln_lora = use_adaln_lora
|
| 63 |
+
if use_adaln_lora:
|
| 64 |
+
self.linear_2 = nn.Linear(out_features, 3 * out_features, bias=False)
|
| 65 |
+
else:
|
| 66 |
+
self.linear_2 = nn.Linear(out_features, out_features, bias=True)
|
| 67 |
+
|
| 68 |
+
def forward(self, sample: torch.Tensor) -> torch.Tensor:
|
| 69 |
+
emb = self.linear_1(sample)
|
| 70 |
+
emb = self.activation(emb)
|
| 71 |
+
emb = self.linear_2(emb)
|
| 72 |
+
|
| 73 |
+
if self.use_adaln_lora:
|
| 74 |
+
adaln_lora_B_3D = emb
|
| 75 |
+
emb_B_D = sample
|
| 76 |
+
else:
|
| 77 |
+
emb_B_D = emb
|
| 78 |
+
adaln_lora_B_3D = None
|
| 79 |
+
|
| 80 |
+
return emb_B_D, adaln_lora_B_3D
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class FourierFeatures(nn.Module):
|
| 84 |
+
"""
|
| 85 |
+
Implements a layer that generates Fourier features from input tensors, based on randomly sampled
|
| 86 |
+
frequencies and phases. This can help in learning high-frequency functions in low-dimensional problems.
|
| 87 |
+
|
| 88 |
+
[B] -> [B, D]
|
| 89 |
+
|
| 90 |
+
Parameters:
|
| 91 |
+
num_channels (int): The number of Fourier features to generate.
|
| 92 |
+
bandwidth (float, optional): The scaling factor for the frequency of the Fourier features. Defaults to 1.
|
| 93 |
+
normalize (bool, optional): If set to True, the outputs are scaled by sqrt(2), usually to normalize
|
| 94 |
+
the variance of the features. Defaults to False.
|
| 95 |
+
|
| 96 |
+
Example:
|
| 97 |
+
>>> layer = FourierFeatures(num_channels=256, bandwidth=0.5, normalize=True)
|
| 98 |
+
>>> x = torch.randn(10, 256) # Example input tensor
|
| 99 |
+
>>> output = layer(x)
|
| 100 |
+
>>> print(output.shape) # Expected shape: (10, 256)
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(self, num_channels, bandwidth=1, normalize=False):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.register_buffer("freqs", 2 * np.pi * bandwidth * torch.randn(num_channels), persistent=True)
|
| 106 |
+
self.register_buffer("phases", 2 * np.pi * torch.rand(num_channels), persistent=True)
|
| 107 |
+
self.gain = np.sqrt(2) if normalize else 1
|
| 108 |
+
|
| 109 |
+
def forward(self, x, gain: float = 1.0):
|
| 110 |
+
"""
|
| 111 |
+
Apply the Fourier feature transformation to the input tensor.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
x (torch.Tensor): The input tensor.
|
| 115 |
+
gain (float, optional): An additional gain factor applied during the forward pass. Defaults to 1.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
torch.Tensor: The transformed tensor, with Fourier features applied.
|
| 119 |
+
"""
|
| 120 |
+
in_dtype = x.dtype
|
| 121 |
+
x = x.to(torch.float32).ger(self.freqs.to(torch.float32)).add(self.phases.to(torch.float32))
|
| 122 |
+
x = x.cos().mul(self.gain * gain).to(in_dtype)
|
| 123 |
+
return x
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class PatchEmbed(nn.Module):
|
| 127 |
+
"""
|
| 128 |
+
PatchEmbed is a module for embedding patches from an input tensor by applying either 3D or 2D convolutional layers,
|
| 129 |
+
depending on the . This module can process inputs with temporal (video) and spatial (image) dimensions,
|
| 130 |
+
making it suitable for video and image processing tasks. It supports dividing the input into patches
|
| 131 |
+
and embedding each patch into a vector of size `out_channels`.
|
| 132 |
+
|
| 133 |
+
Parameters:
|
| 134 |
+
- spatial_patch_size (int): The size of each spatial patch.
|
| 135 |
+
- temporal_patch_size (int): The size of each temporal patch.
|
| 136 |
+
- in_channels (int): Number of input channels. Default: 3.
|
| 137 |
+
- out_channels (int): The dimension of the embedding vector for each patch. Default: 768.
|
| 138 |
+
- bias (bool): If True, adds a learnable bias to the output of the convolutional layers. Default: True.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
spatial_patch_size,
|
| 144 |
+
temporal_patch_size,
|
| 145 |
+
in_channels=3,
|
| 146 |
+
out_channels=768,
|
| 147 |
+
bias=True,
|
| 148 |
+
):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.spatial_patch_size = spatial_patch_size
|
| 151 |
+
self.temporal_patch_size = temporal_patch_size
|
| 152 |
+
|
| 153 |
+
self.proj = nn.Sequential(
|
| 154 |
+
Rearrange(
|
| 155 |
+
"b c (t r) (h m) (w n) -> b t h w (c r m n)",
|
| 156 |
+
r=temporal_patch_size,
|
| 157 |
+
m=spatial_patch_size,
|
| 158 |
+
n=spatial_patch_size,
|
| 159 |
+
),
|
| 160 |
+
nn.Linear(
|
| 161 |
+
in_channels * spatial_patch_size * spatial_patch_size * temporal_patch_size, out_channels, bias=bias
|
| 162 |
+
),
|
| 163 |
+
)
|
| 164 |
+
self.out = nn.Identity()
|
| 165 |
+
|
| 166 |
+
def forward(self, x):
|
| 167 |
+
"""
|
| 168 |
+
Forward pass of the PatchEmbed module.
|
| 169 |
+
|
| 170 |
+
Parameters:
|
| 171 |
+
- x (torch.Tensor): The input tensor of shape (B, C, T, H, W) where
|
| 172 |
+
B is the batch size,
|
| 173 |
+
C is the number of channels,
|
| 174 |
+
T is the temporal dimension,
|
| 175 |
+
H is the height, and
|
| 176 |
+
W is the width of the input.
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
- torch.Tensor: The embedded patches as a tensor, with shape b t h w c.
|
| 180 |
+
"""
|
| 181 |
+
assert x.dim() == 5
|
| 182 |
+
_, _, T, H, W = x.shape
|
| 183 |
+
assert H % self.spatial_patch_size == 0 and W % self.spatial_patch_size == 0
|
| 184 |
+
assert T % self.temporal_patch_size == 0
|
| 185 |
+
x = self.proj(x)
|
| 186 |
+
return self.out(x)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class FinalLayer(nn.Module):
|
| 190 |
+
"""
|
| 191 |
+
The final layer of video DiT.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
hidden_size,
|
| 197 |
+
spatial_patch_size,
|
| 198 |
+
temporal_patch_size,
|
| 199 |
+
out_channels,
|
| 200 |
+
use_adaln_lora: bool = False,
|
| 201 |
+
adaln_lora_dim: int = 256,
|
| 202 |
+
):
|
| 203 |
+
super().__init__()
|
| 204 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 205 |
+
self.linear = nn.Linear(
|
| 206 |
+
hidden_size, spatial_patch_size * spatial_patch_size * temporal_patch_size * out_channels, bias=False
|
| 207 |
+
)
|
| 208 |
+
self.hidden_size = hidden_size
|
| 209 |
+
self.n_adaln_chunks = 2
|
| 210 |
+
self.use_adaln_lora = use_adaln_lora
|
| 211 |
+
if use_adaln_lora:
|
| 212 |
+
self.adaLN_modulation = nn.Sequential(
|
| 213 |
+
nn.SiLU(),
|
| 214 |
+
nn.Linear(hidden_size, adaln_lora_dim, bias=False),
|
| 215 |
+
nn.Linear(adaln_lora_dim, self.n_adaln_chunks * hidden_size, bias=False),
|
| 216 |
+
)
|
| 217 |
+
else:
|
| 218 |
+
self.adaLN_modulation = nn.Sequential(
|
| 219 |
+
nn.SiLU(), nn.Linear(hidden_size, self.n_adaln_chunks * hidden_size, bias=False)
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
def forward(
|
| 223 |
+
self,
|
| 224 |
+
x_BT_HW_D,
|
| 225 |
+
emb_B_D,
|
| 226 |
+
adaln_lora_B_3D: Optional[torch.Tensor] = None,
|
| 227 |
+
):
|
| 228 |
+
if self.use_adaln_lora:
|
| 229 |
+
assert adaln_lora_B_3D is not None
|
| 230 |
+
shift_B_D, scale_B_D = (self.adaLN_modulation(emb_B_D) + adaln_lora_B_3D[:, : 2 * self.hidden_size]).chunk(
|
| 231 |
+
2, dim=1
|
| 232 |
+
)
|
| 233 |
+
else:
|
| 234 |
+
shift_B_D, scale_B_D = self.adaLN_modulation(emb_B_D).chunk(2, dim=1)
|
| 235 |
+
|
| 236 |
+
B = emb_B_D.shape[0]
|
| 237 |
+
T = x_BT_HW_D.shape[0] // B
|
| 238 |
+
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)
|
| 239 |
+
x_BT_HW_D = modulate(self.norm_final(x_BT_HW_D), shift_BT_D, scale_BT_D)
|
| 240 |
+
|
| 241 |
+
x_BT_HW_D = self.linear(x_BT_HW_D)
|
| 242 |
+
return x_BT_HW_D
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class VideoAttn(nn.Module):
|
| 246 |
+
"""
|
| 247 |
+
Implements video attention with optional cross-attention capabilities.
|
| 248 |
+
|
| 249 |
+
This module processes video features while maintaining their spatio-temporal structure. It can perform
|
| 250 |
+
self-attention within the video features or cross-attention with external context features.
|
| 251 |
+
|
| 252 |
+
Parameters:
|
| 253 |
+
x_dim (int): Dimension of input feature vectors
|
| 254 |
+
context_dim (Optional[int]): Dimension of context features for cross-attention. None for self-attention
|
| 255 |
+
num_heads (int): Number of attention heads
|
| 256 |
+
bias (bool): Whether to include bias in attention projections. Default: False
|
| 257 |
+
qkv_norm_mode (str): Normalization mode for query/key/value projections. Must be "per_head". Default: "per_head"
|
| 258 |
+
x_format (str): Format of input tensor. Must be "BTHWD". Default: "BTHWD"
|
| 259 |
+
n_views (int): Extra parameter used in multi-view diffusion model. It indicated total number of view we model together.
|
| 260 |
+
|
| 261 |
+
Input shape:
|
| 262 |
+
- x: (T, H, W, B, D) video features
|
| 263 |
+
- context (optional): (M, B, D) context features for cross-attention
|
| 264 |
+
where:
|
| 265 |
+
T: temporal dimension
|
| 266 |
+
H: height
|
| 267 |
+
W: width
|
| 268 |
+
B: batch size
|
| 269 |
+
D: feature dimension
|
| 270 |
+
M: context sequence length
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def __init__(
|
| 274 |
+
self,
|
| 275 |
+
x_dim: int,
|
| 276 |
+
context_dim: Optional[int],
|
| 277 |
+
num_heads: int,
|
| 278 |
+
bias: bool = False,
|
| 279 |
+
qkv_norm_mode: str = "per_head",
|
| 280 |
+
x_format: str = "BTHWD",
|
| 281 |
+
n_views: int = 1,
|
| 282 |
+
) -> None:
|
| 283 |
+
super().__init__()
|
| 284 |
+
self.x_format = x_format
|
| 285 |
+
self.n_views = n_views
|
| 286 |
+
self.attn = Attention(
|
| 287 |
+
x_dim,
|
| 288 |
+
context_dim,
|
| 289 |
+
num_heads,
|
| 290 |
+
x_dim // num_heads,
|
| 291 |
+
qkv_bias=bias,
|
| 292 |
+
qkv_norm="RRI",
|
| 293 |
+
out_bias=bias,
|
| 294 |
+
qkv_norm_mode=qkv_norm_mode,
|
| 295 |
+
qkv_format="sbhd",
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
def forward(
|
| 299 |
+
self,
|
| 300 |
+
x: torch.Tensor,
|
| 301 |
+
context: Optional[torch.Tensor] = None,
|
| 302 |
+
crossattn_mask: Optional[torch.Tensor] = None,
|
| 303 |
+
rope_emb_L_1_1_D: Optional[torch.Tensor] = None,
|
| 304 |
+
) -> torch.Tensor:
|
| 305 |
+
"""
|
| 306 |
+
Forward pass for video attention.
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
x (Tensor): Input tensor of shape (B, T, H, W, D) or (T, H, W, B, D) representing batches of video data.
|
| 310 |
+
context (Tensor): Context tensor of shape (B, M, D) or (M, B, D),
|
| 311 |
+
where M is the sequence length of the context.
|
| 312 |
+
crossattn_mask (Optional[Tensor]): An optional mask for cross-attention mechanisms.
|
| 313 |
+
rope_emb_L_1_1_D (Optional[Tensor]):
|
| 314 |
+
Rotary positional embedding tensor of shape (L, 1, 1, D). L == THW for current video training.
|
| 315 |
+
|
| 316 |
+
Returns:
|
| 317 |
+
Tensor: The output tensor with applied attention, maintaining the input shape.
|
| 318 |
+
"""
|
| 319 |
+
if context is not None and self.n_views > 1:
|
| 320 |
+
x_T_H_W_B_D = rearrange(x, "(v t) h w b d -> t h w (v b) d", v=self.n_views)
|
| 321 |
+
context_M_B_D = rearrange(context, "(v m) b d -> m (v b) d", v=self.n_views)
|
| 322 |
+
else:
|
| 323 |
+
x_T_H_W_B_D = x
|
| 324 |
+
context_M_B_D = context
|
| 325 |
+
T, H, W, B, D = x_T_H_W_B_D.shape
|
| 326 |
+
x_THW_B_D = rearrange(x_T_H_W_B_D, "t h w b d -> (t h w) b d")
|
| 327 |
+
x_THW_B_D = self.attn(
|
| 328 |
+
x_THW_B_D,
|
| 329 |
+
context_M_B_D,
|
| 330 |
+
crossattn_mask,
|
| 331 |
+
rope_emb=rope_emb_L_1_1_D,
|
| 332 |
+
)
|
| 333 |
+
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)
|
| 334 |
+
if context is not None and self.n_views > 1:
|
| 335 |
+
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)
|
| 336 |
+
return x_T_H_W_B_D
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def adaln_norm_state(norm_state, x, scale, shift):
|
| 340 |
+
normalized = norm_state(x)
|
| 341 |
+
return normalized * (1 + scale) + shift
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class DITBuildingBlock(nn.Module):
|
| 345 |
+
"""
|
| 346 |
+
A building block for the DiT (Diffusion Transformer) architecture that supports different types of
|
| 347 |
+
attention and MLP operations with adaptive layer normalization.
|
| 348 |
+
|
| 349 |
+
Parameters:
|
| 350 |
+
block_type (str): Type of block - one of:
|
| 351 |
+
- "cross_attn"/"ca": Cross-attention
|
| 352 |
+
- "full_attn"/"fa": Full self-attention
|
| 353 |
+
- "mlp"/"ff": MLP/feedforward block
|
| 354 |
+
x_dim (int): Dimension of input features
|
| 355 |
+
context_dim (Optional[int]): Dimension of context features for cross-attention
|
| 356 |
+
num_heads (int): Number of attention heads
|
| 357 |
+
mlp_ratio (float): MLP hidden dimension multiplier. Default: 4.0
|
| 358 |
+
bias (bool): Whether to use bias in layers. Default: False
|
| 359 |
+
mlp_dropout (float): Dropout rate for MLP. Default: 0.0
|
| 360 |
+
qkv_norm_mode (str): QKV normalization mode. Default: "per_head"
|
| 361 |
+
x_format (str): Input tensor format. Default: "BTHWD"
|
| 362 |
+
use_adaln_lora (bool): Whether to use AdaLN-LoRA. Default: False
|
| 363 |
+
adaln_lora_dim (int): Dimension for AdaLN-LoRA. Default: 256
|
| 364 |
+
n_views (int): Extra parameter used in multi-view diffusion model. It indicated total number of view we model together.
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
def __init__(
|
| 368 |
+
self,
|
| 369 |
+
block_type: str,
|
| 370 |
+
x_dim: int,
|
| 371 |
+
context_dim: Optional[int],
|
| 372 |
+
num_heads: int,
|
| 373 |
+
mlp_ratio: float = 4.0,
|
| 374 |
+
bias: bool = False,
|
| 375 |
+
mlp_dropout: float = 0.0,
|
| 376 |
+
qkv_norm_mode: str = "per_head",
|
| 377 |
+
x_format: str = "BTHWD",
|
| 378 |
+
use_adaln_lora: bool = False,
|
| 379 |
+
adaln_lora_dim: int = 256,
|
| 380 |
+
n_views: int = 1,
|
| 381 |
+
) -> None:
|
| 382 |
+
block_type = block_type.lower()
|
| 383 |
+
|
| 384 |
+
super().__init__()
|
| 385 |
+
self.x_format = x_format
|
| 386 |
+
if block_type in ["cross_attn", "ca"]:
|
| 387 |
+
self.block = VideoAttn(
|
| 388 |
+
x_dim,
|
| 389 |
+
context_dim,
|
| 390 |
+
num_heads,
|
| 391 |
+
bias=bias,
|
| 392 |
+
qkv_norm_mode=qkv_norm_mode,
|
| 393 |
+
x_format=self.x_format,
|
| 394 |
+
n_views=n_views,
|
| 395 |
+
)
|
| 396 |
+
elif block_type in ["full_attn", "fa"]:
|
| 397 |
+
self.block = VideoAttn(
|
| 398 |
+
x_dim, None, num_heads, bias=bias, qkv_norm_mode=qkv_norm_mode, x_format=self.x_format
|
| 399 |
+
)
|
| 400 |
+
elif block_type in ["mlp", "ff"]:
|
| 401 |
+
self.block = GPT2FeedForward(x_dim, int(x_dim * mlp_ratio), dropout=mlp_dropout, bias=bias)
|
| 402 |
+
else:
|
| 403 |
+
raise ValueError(f"Unknown block type: {block_type}")
|
| 404 |
+
|
| 405 |
+
self.block_type = block_type
|
| 406 |
+
self.use_adaln_lora = use_adaln_lora
|
| 407 |
+
|
| 408 |
+
self.norm_state = nn.LayerNorm(x_dim, elementwise_affine=False, eps=1e-6)
|
| 409 |
+
self.n_adaln_chunks = 3
|
| 410 |
+
if use_adaln_lora:
|
| 411 |
+
self.adaLN_modulation = nn.Sequential(
|
| 412 |
+
nn.SiLU(),
|
| 413 |
+
nn.Linear(x_dim, adaln_lora_dim, bias=False),
|
| 414 |
+
nn.Linear(adaln_lora_dim, self.n_adaln_chunks * x_dim, bias=False),
|
| 415 |
+
)
|
| 416 |
+
else:
|
| 417 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(x_dim, self.n_adaln_chunks * x_dim, bias=False))
|
| 418 |
+
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
x: torch.Tensor,
|
| 422 |
+
emb_B_D: torch.Tensor,
|
| 423 |
+
crossattn_emb: torch.Tensor,
|
| 424 |
+
crossattn_mask: Optional[torch.Tensor] = None,
|
| 425 |
+
rope_emb_L_1_1_D: Optional[torch.Tensor] = None,
|
| 426 |
+
adaln_lora_B_3D: Optional[torch.Tensor] = None,
|
| 427 |
+
) -> torch.Tensor:
|
| 428 |
+
"""
|
| 429 |
+
Forward pass for dynamically configured blocks with adaptive normalization.
|
| 430 |
+
|
| 431 |
+
Args:
|
| 432 |
+
x (Tensor): Input tensor of shape (B, T, H, W, D) or (T, H, W, B, D).
|
| 433 |
+
emb_B_D (Tensor): Embedding tensor for adaptive layer normalization modulation.
|
| 434 |
+
crossattn_emb (Tensor): Tensor for cross-attention blocks.
|
| 435 |
+
crossattn_mask (Optional[Tensor]): Optional mask for cross-attention.
|
| 436 |
+
rope_emb_L_1_1_D (Optional[Tensor]):
|
| 437 |
+
Rotary positional embedding tensor of shape (L, 1, 1, D). L == THW for current video training.
|
| 438 |
+
|
| 439 |
+
Returns:
|
| 440 |
+
Tensor: The output tensor after processing through the configured block and adaptive normalization.
|
| 441 |
+
"""
|
| 442 |
+
if self.use_adaln_lora:
|
| 443 |
+
shift_B_D, scale_B_D, gate_B_D = (self.adaLN_modulation(emb_B_D) + adaln_lora_B_3D).chunk(
|
| 444 |
+
self.n_adaln_chunks, dim=1
|
| 445 |
+
)
|
| 446 |
+
else:
|
| 447 |
+
shift_B_D, scale_B_D, gate_B_D = self.adaLN_modulation(emb_B_D).chunk(self.n_adaln_chunks, dim=1)
|
| 448 |
+
|
| 449 |
+
shift_1_1_1_B_D, scale_1_1_1_B_D, gate_1_1_1_B_D = (
|
| 450 |
+
shift_B_D.unsqueeze(0).unsqueeze(0).unsqueeze(0),
|
| 451 |
+
scale_B_D.unsqueeze(0).unsqueeze(0).unsqueeze(0),
|
| 452 |
+
gate_B_D.unsqueeze(0).unsqueeze(0).unsqueeze(0),
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
if self.block_type in ["mlp", "ff"]:
|
| 456 |
+
x = x + gate_1_1_1_B_D * self.block(
|
| 457 |
+
adaln_norm_state(self.norm_state, x, scale_1_1_1_B_D, shift_1_1_1_B_D),
|
| 458 |
+
)
|
| 459 |
+
elif self.block_type in ["full_attn", "fa"]:
|
| 460 |
+
x = x + gate_1_1_1_B_D * self.block(
|
| 461 |
+
adaln_norm_state(self.norm_state, x, scale_1_1_1_B_D, shift_1_1_1_B_D),
|
| 462 |
+
context=None,
|
| 463 |
+
rope_emb_L_1_1_D=rope_emb_L_1_1_D,
|
| 464 |
+
)
|
| 465 |
+
elif self.block_type in ["cross_attn", "ca"]:
|
| 466 |
+
x = x + gate_1_1_1_B_D * self.block(
|
| 467 |
+
adaln_norm_state(self.norm_state, x, scale_1_1_1_B_D, shift_1_1_1_B_D),
|
| 468 |
+
context=crossattn_emb,
|
| 469 |
+
crossattn_mask=crossattn_mask,
|
| 470 |
+
rope_emb_L_1_1_D=rope_emb_L_1_1_D,
|
| 471 |
+
)
|
| 472 |
+
else:
|
| 473 |
+
raise ValueError(f"Unknown block type: {self.block_type}")
|
| 474 |
+
|
| 475 |
+
return x
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class GeneralDITTransformerBlock(nn.Module):
|
| 479 |
+
"""
|
| 480 |
+
A wrapper module that manages a sequence of DITBuildingBlocks to form a complete transformer layer.
|
| 481 |
+
Each block in the sequence is specified by a block configuration string.
|
| 482 |
+
|
| 483 |
+
Parameters:
|
| 484 |
+
x_dim (int): Dimension of input features
|
| 485 |
+
context_dim (int): Dimension of context features for cross-attention blocks
|
| 486 |
+
num_heads (int): Number of attention heads
|
| 487 |
+
block_config (str): String specifying block sequence (e.g. "ca-fa-mlp" for cross-attention,
|
| 488 |
+
full-attention, then MLP)
|
| 489 |
+
mlp_ratio (float): MLP hidden dimension multiplier. Default: 4.0
|
| 490 |
+
x_format (str): Input tensor format. Default: "BTHWD"
|
| 491 |
+
use_adaln_lora (bool): Whether to use AdaLN-LoRA. Default: False
|
| 492 |
+
adaln_lora_dim (int): Dimension for AdaLN-LoRA. Default: 256
|
| 493 |
+
n_views (int): Extra parameter used in multi-view diffusion model. Default: 1
|
| 494 |
+
|
| 495 |
+
The block_config string uses "-" to separate block types:
|
| 496 |
+
- "ca"/"cross_attn": Cross-attention block
|
| 497 |
+
- "fa"/"full_attn": Full self-attention block
|
| 498 |
+
- "mlp"/"ff": MLP/feedforward block
|
| 499 |
+
|
| 500 |
+
Example:
|
| 501 |
+
block_config = "ca-fa-mlp" creates a sequence of:
|
| 502 |
+
1. Cross-attention block
|
| 503 |
+
2. Full self-attention block
|
| 504 |
+
3. MLP block
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
def __init__(
|
| 508 |
+
self,
|
| 509 |
+
x_dim: int,
|
| 510 |
+
context_dim: int,
|
| 511 |
+
num_heads: int,
|
| 512 |
+
block_config: str,
|
| 513 |
+
mlp_ratio: float = 4.0,
|
| 514 |
+
x_format: str = "BTHWD",
|
| 515 |
+
use_adaln_lora: bool = False,
|
| 516 |
+
adaln_lora_dim: int = 256,
|
| 517 |
+
n_views: int = 1,
|
| 518 |
+
):
|
| 519 |
+
super().__init__()
|
| 520 |
+
self.blocks = nn.ModuleList()
|
| 521 |
+
self.x_format = x_format
|
| 522 |
+
for block_type in block_config.split("-"):
|
| 523 |
+
self.blocks.append(
|
| 524 |
+
DITBuildingBlock(
|
| 525 |
+
block_type,
|
| 526 |
+
x_dim,
|
| 527 |
+
context_dim,
|
| 528 |
+
num_heads,
|
| 529 |
+
mlp_ratio,
|
| 530 |
+
x_format=self.x_format,
|
| 531 |
+
use_adaln_lora=use_adaln_lora,
|
| 532 |
+
adaln_lora_dim=adaln_lora_dim,
|
| 533 |
+
n_views=n_views,
|
| 534 |
+
)
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
def forward(
|
| 538 |
+
self,
|
| 539 |
+
x: torch.Tensor,
|
| 540 |
+
emb_B_D: torch.Tensor,
|
| 541 |
+
crossattn_emb: torch.Tensor,
|
| 542 |
+
crossattn_mask: Optional[torch.Tensor] = None,
|
| 543 |
+
rope_emb_L_1_1_D: Optional[torch.Tensor] = None,
|
| 544 |
+
adaln_lora_B_3D: Optional[torch.Tensor] = None,
|
| 545 |
+
extra_per_block_pos_emb: Optional[torch.Tensor] = None,
|
| 546 |
+
) -> torch.Tensor:
|
| 547 |
+
if extra_per_block_pos_emb is not None:
|
| 548 |
+
x = x + extra_per_block_pos_emb
|
| 549 |
+
for block in self.blocks:
|
| 550 |
+
x = block(
|
| 551 |
+
x,
|
| 552 |
+
emb_B_D,
|
| 553 |
+
crossattn_emb,
|
| 554 |
+
crossattn_mask,
|
| 555 |
+
rope_emb_L_1_1_D=rope_emb_L_1_1_D,
|
| 556 |
+
adaln_lora_B_3D=adaln_lora_B_3D,
|
| 557 |
+
)
|
| 558 |
+
return x
|
diffusion/modules/denoiser_scaling.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Tuple
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class EDMScaling:
|
| 22 |
+
def __init__(self, sigma_data: float = 0.5):
|
| 23 |
+
self.sigma_data = sigma_data
|
| 24 |
+
|
| 25 |
+
def __call__(self, sigma: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 26 |
+
c_skip = self.sigma_data**2 / (sigma**2 + self.sigma_data**2)
|
| 27 |
+
c_out = sigma * self.sigma_data / (sigma**2 + self.sigma_data**2) ** 0.5
|
| 28 |
+
c_in = 1 / (sigma**2 + self.sigma_data**2) ** 0.5
|
| 29 |
+
c_noise = 0.25 * sigma.log()
|
| 30 |
+
return c_skip, c_out, c_in, c_noise
|
diffusion/modules/res_sampler.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
A general framework for various sampling algorithm from a diffusion model.
|
| 18 |
+
Impl based on
|
| 19 |
+
* Refined Exponential Solver (RES) in https://arxiv.org/pdf/2308.02157
|
| 20 |
+
* also clude other impl, DDIM, DEIS, DPM-Solver, EDM sampler.
|
| 21 |
+
Most of sampling algorihtm, Runge-Kutta, Multi-step, etc, can be impl in this framework by \
|
| 22 |
+
adding new step function in get_runge_kutta_fn or get_multi_step_fn.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import math
|
| 26 |
+
from typing import Any, Callable, List, Literal, Optional, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import attrs
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from diffusion.functional.multi_step import get_multi_step_fn, is_multi_step_fn_supported
|
| 32 |
+
from diffusion.functional.runge_kutta import get_runge_kutta_fn, is_runge_kutta_fn_supported
|
| 33 |
+
from utils.config import make_freezable
|
| 34 |
+
|
| 35 |
+
COMMON_SOLVER_OPTIONS = Literal["2ab", "2mid", "1euler"]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@make_freezable
|
| 39 |
+
@attrs.define(slots=False)
|
| 40 |
+
class SolverConfig:
|
| 41 |
+
is_multi: bool = False
|
| 42 |
+
rk: str = "2mid"
|
| 43 |
+
multistep: str = "2ab"
|
| 44 |
+
# following parameters control stochasticity, see EDM paper
|
| 45 |
+
# BY default, we use deterministic with no stochasticity
|
| 46 |
+
s_churn: float = 0.0
|
| 47 |
+
s_t_max: float = float("inf")
|
| 48 |
+
s_t_min: float = 0.05
|
| 49 |
+
s_noise: float = 1.0
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@make_freezable
|
| 53 |
+
@attrs.define(slots=False)
|
| 54 |
+
class SolverTimestampConfig:
|
| 55 |
+
nfe: int = 50
|
| 56 |
+
t_min: float = 0.002
|
| 57 |
+
t_max: float = 80.0
|
| 58 |
+
order: float = 7.0
|
| 59 |
+
is_forward: bool = False # whether generate forward or backward timestamps
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@make_freezable
|
| 63 |
+
@attrs.define(slots=False)
|
| 64 |
+
class SamplerConfig:
|
| 65 |
+
solver: SolverConfig = attrs.field(factory=SolverConfig)
|
| 66 |
+
timestamps: SolverTimestampConfig = attrs.field(factory=SolverTimestampConfig)
|
| 67 |
+
sample_clean: bool = True # whether run one last step to generate clean image
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_rev_ts(
|
| 71 |
+
t_min: float, t_max: float, num_steps: int, ts_order: Union[int, float], is_forward: bool = False
|
| 72 |
+
) -> torch.Tensor:
|
| 73 |
+
"""
|
| 74 |
+
Generate a sequence of reverse time steps.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
t_min (float): The minimum time value.
|
| 78 |
+
t_max (float): The maximum time value.
|
| 79 |
+
num_steps (int): The number of time steps to generate.
|
| 80 |
+
ts_order (Union[int, float]): The order of the time step progression.
|
| 81 |
+
is_forward (bool, optional): If True, returns the sequence in forward order. Defaults to False.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
torch.Tensor: A tensor containing the generated time steps in reverse or forward order.
|
| 85 |
+
|
| 86 |
+
Raises:
|
| 87 |
+
ValueError: If `t_min` is not less than `t_max`.
|
| 88 |
+
TypeError: If `ts_order` is not an integer or float.
|
| 89 |
+
"""
|
| 90 |
+
if t_min >= t_max:
|
| 91 |
+
raise ValueError("t_min must be less than t_max")
|
| 92 |
+
|
| 93 |
+
if not isinstance(ts_order, (int, float)):
|
| 94 |
+
raise TypeError("ts_order must be an integer or float")
|
| 95 |
+
|
| 96 |
+
step_indices = torch.arange(num_steps + 1, dtype=torch.float64)
|
| 97 |
+
time_steps = (
|
| 98 |
+
t_max ** (1 / ts_order) + step_indices / num_steps * (t_min ** (1 / ts_order) - t_max ** (1 / ts_order))
|
| 99 |
+
) ** ts_order
|
| 100 |
+
|
| 101 |
+
if is_forward:
|
| 102 |
+
return time_steps.flip(dims=(0,))
|
| 103 |
+
|
| 104 |
+
return time_steps
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class Sampler(torch.nn.Module):
|
| 108 |
+
def __init__(self, cfg: Optional[SamplerConfig] = None):
|
| 109 |
+
super().__init__()
|
| 110 |
+
if cfg is None:
|
| 111 |
+
cfg = SamplerConfig()
|
| 112 |
+
self.cfg = cfg
|
| 113 |
+
|
| 114 |
+
@torch.no_grad()
|
| 115 |
+
def forward(
|
| 116 |
+
self,
|
| 117 |
+
x0_fn: Callable,
|
| 118 |
+
x_sigma_max: torch.Tensor,
|
| 119 |
+
num_steps: int = 35,
|
| 120 |
+
sigma_min: float = 0.002,
|
| 121 |
+
sigma_max: float = 80,
|
| 122 |
+
rho: float = 7,
|
| 123 |
+
S_churn: float = 0,
|
| 124 |
+
S_min: float = 0,
|
| 125 |
+
S_max: float = float("inf"),
|
| 126 |
+
S_noise: float = 1,
|
| 127 |
+
solver_option: str = "2ab",
|
| 128 |
+
) -> torch.Tensor:
|
| 129 |
+
in_dtype = x_sigma_max.dtype
|
| 130 |
+
|
| 131 |
+
def float64_x0_fn(x_B_StateShape: torch.Tensor, t_B: torch.Tensor) -> torch.Tensor:
|
| 132 |
+
return x0_fn(x_B_StateShape.to(in_dtype), t_B.to(in_dtype)).to(torch.float64)
|
| 133 |
+
|
| 134 |
+
is_multistep = is_multi_step_fn_supported(solver_option)
|
| 135 |
+
is_rk = is_runge_kutta_fn_supported(solver_option)
|
| 136 |
+
assert is_multistep or is_rk, f"Only support multistep or Runge-Kutta method, got {solver_option}"
|
| 137 |
+
|
| 138 |
+
solver_cfg = SolverConfig(
|
| 139 |
+
s_churn=S_churn,
|
| 140 |
+
s_t_max=S_max,
|
| 141 |
+
s_t_min=S_min,
|
| 142 |
+
s_noise=S_noise,
|
| 143 |
+
is_multi=is_multistep,
|
| 144 |
+
rk=solver_option,
|
| 145 |
+
multistep=solver_option,
|
| 146 |
+
)
|
| 147 |
+
timestamps_cfg = SolverTimestampConfig(nfe=num_steps, t_min=sigma_min, t_max=sigma_max, order=rho)
|
| 148 |
+
sampler_cfg = SamplerConfig(solver=solver_cfg, timestamps=timestamps_cfg, sample_clean=True)
|
| 149 |
+
|
| 150 |
+
return self._forward_impl(float64_x0_fn, x_sigma_max, sampler_cfg).to(in_dtype)
|
| 151 |
+
|
| 152 |
+
@torch.no_grad()
|
| 153 |
+
def _forward_impl(
|
| 154 |
+
self,
|
| 155 |
+
denoiser_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
|
| 156 |
+
noisy_input_B_StateShape: torch.Tensor,
|
| 157 |
+
sampler_cfg: Optional[SamplerConfig] = None,
|
| 158 |
+
callback_fns: Optional[List[Callable]] = None,
|
| 159 |
+
) -> torch.Tensor:
|
| 160 |
+
"""
|
| 161 |
+
Internal implementation of the forward pass.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
denoiser_fn: Function to denoise the input.
|
| 165 |
+
noisy_input_B_StateShape: Input tensor with noise.
|
| 166 |
+
sampler_cfg: Configuration for the sampler.
|
| 167 |
+
callback_fns: List of callback functions to be called during sampling.
|
| 168 |
+
|
| 169 |
+
Returns:
|
| 170 |
+
torch.Tensor: Denoised output tensor.
|
| 171 |
+
"""
|
| 172 |
+
sampler_cfg = self.cfg if sampler_cfg is None else sampler_cfg
|
| 173 |
+
solver_order = 1 if sampler_cfg.solver.is_multi else int(sampler_cfg.solver.rk[0])
|
| 174 |
+
num_timestamps = sampler_cfg.timestamps.nfe // solver_order
|
| 175 |
+
|
| 176 |
+
sigmas_L = get_rev_ts(
|
| 177 |
+
sampler_cfg.timestamps.t_min, sampler_cfg.timestamps.t_max, num_timestamps, sampler_cfg.timestamps.order
|
| 178 |
+
).to(noisy_input_B_StateShape.device)
|
| 179 |
+
|
| 180 |
+
denoised_output = differential_equation_solver(
|
| 181 |
+
denoiser_fn, sigmas_L, sampler_cfg.solver, callback_fns=callback_fns
|
| 182 |
+
)(noisy_input_B_StateShape)
|
| 183 |
+
|
| 184 |
+
if sampler_cfg.sample_clean:
|
| 185 |
+
# Override denoised_output with fully denoised version
|
| 186 |
+
ones = torch.ones(denoised_output.size(0), device=denoised_output.device, dtype=denoised_output.dtype)
|
| 187 |
+
denoised_output = denoiser_fn(denoised_output, sigmas_L[-1] * ones)
|
| 188 |
+
|
| 189 |
+
return denoised_output
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def fori_loop(lower: int, upper: int, body_fun: Callable[[int, Any], Any], init_val: Any) -> Any:
|
| 193 |
+
"""
|
| 194 |
+
Implements a for loop with a function.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
lower: Lower bound of the loop (inclusive).
|
| 198 |
+
upper: Upper bound of the loop (exclusive).
|
| 199 |
+
body_fun: Function to be applied in each iteration.
|
| 200 |
+
init_val: Initial value for the loop.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
The final result after all iterations.
|
| 204 |
+
"""
|
| 205 |
+
val = init_val
|
| 206 |
+
for i in range(lower, upper):
|
| 207 |
+
val = body_fun(i, val)
|
| 208 |
+
return val
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def differential_equation_solver(
|
| 212 |
+
x0_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
|
| 213 |
+
sigmas_L: torch.Tensor,
|
| 214 |
+
solver_cfg: SolverConfig,
|
| 215 |
+
callback_fns: Optional[List[Callable]] = None,
|
| 216 |
+
) -> Callable[[torch.Tensor], torch.Tensor]:
|
| 217 |
+
"""
|
| 218 |
+
Creates a differential equation solver function.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
x0_fn: Function to compute x0 prediction.
|
| 222 |
+
sigmas_L: Tensor of sigma values with shape [L,].
|
| 223 |
+
solver_cfg: Configuration for the solver.
|
| 224 |
+
callback_fns: Optional list of callback functions.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
A function that solves the differential equation.
|
| 228 |
+
"""
|
| 229 |
+
num_step = len(sigmas_L) - 1
|
| 230 |
+
|
| 231 |
+
if solver_cfg.is_multi:
|
| 232 |
+
update_step_fn = get_multi_step_fn(solver_cfg.multistep)
|
| 233 |
+
else:
|
| 234 |
+
update_step_fn = get_runge_kutta_fn(solver_cfg.rk)
|
| 235 |
+
|
| 236 |
+
eta = min(solver_cfg.s_churn / (num_step + 1), math.sqrt(1.2) - 1)
|
| 237 |
+
|
| 238 |
+
def sample_fn(input_xT_B_StateShape: torch.Tensor) -> torch.Tensor:
|
| 239 |
+
"""
|
| 240 |
+
Samples from the differential equation.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
input_xT_B_StateShape: Input tensor with shape [B, StateShape].
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
Output tensor with shape [B, StateShape].
|
| 247 |
+
"""
|
| 248 |
+
ones_B = torch.ones(input_xT_B_StateShape.size(0), device=input_xT_B_StateShape.device, dtype=torch.float64)
|
| 249 |
+
|
| 250 |
+
def step_fn(
|
| 251 |
+
i_th: int, state: Tuple[torch.Tensor, Optional[List[torch.Tensor]]]
|
| 252 |
+
) -> Tuple[torch.Tensor, Optional[List[torch.Tensor]]]:
|
| 253 |
+
input_x_B_StateShape, x0_preds = state
|
| 254 |
+
sigma_cur_0, sigma_next_0 = sigmas_L[i_th], sigmas_L[i_th + 1]
|
| 255 |
+
|
| 256 |
+
# algorithm 2: line 4-6
|
| 257 |
+
if solver_cfg.s_t_min < sigma_cur_0 < solver_cfg.s_t_max:
|
| 258 |
+
hat_sigma_cur_0 = sigma_cur_0 + eta * sigma_cur_0
|
| 259 |
+
input_x_B_StateShape = input_x_B_StateShape + (
|
| 260 |
+
hat_sigma_cur_0**2 - sigma_cur_0**2
|
| 261 |
+
).sqrt() * solver_cfg.s_noise * torch.randn_like(input_x_B_StateShape)
|
| 262 |
+
sigma_cur_0 = hat_sigma_cur_0
|
| 263 |
+
|
| 264 |
+
if solver_cfg.is_multi:
|
| 265 |
+
x0_pred_B_StateShape = x0_fn(input_x_B_StateShape, sigma_cur_0 * ones_B)
|
| 266 |
+
output_x_B_StateShape, x0_preds = update_step_fn(
|
| 267 |
+
input_x_B_StateShape, sigma_cur_0 * ones_B, sigma_next_0 * ones_B, x0_pred_B_StateShape, x0_preds
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
output_x_B_StateShape, x0_preds = update_step_fn(
|
| 271 |
+
input_x_B_StateShape, sigma_cur_0 * ones_B, sigma_next_0 * ones_B, x0_fn
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if callback_fns:
|
| 275 |
+
for callback_fn in callback_fns:
|
| 276 |
+
callback_fn(**locals())
|
| 277 |
+
|
| 278 |
+
return output_x_B_StateShape, x0_preds
|
| 279 |
+
|
| 280 |
+
x_at_eps, _ = fori_loop(0, num_step, step_fn, [input_xT_B_StateShape, None])
|
| 281 |
+
return x_at_eps
|
| 282 |
+
|
| 283 |
+
return sample_fn
|
diffusion/training/conditioner.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass, fields
|
| 17 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
|
| 22 |
+
from diffusion.conditioner import DataType, GeneralConditioner
|
| 23 |
+
from diffusion.functional.batch_ops import batch_mul
|
| 24 |
+
from diffusion.training.context_parallel import split_inputs_cp
|
| 25 |
+
from utils.misc import count_params
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class AbstractEmbModel(nn.Module):
|
| 29 |
+
def __init__(self):
|
| 30 |
+
super().__init__()
|
| 31 |
+
|
| 32 |
+
self._is_trainable = None
|
| 33 |
+
self._dropout_rate = None
|
| 34 |
+
self._input_key = None
|
| 35 |
+
self._return_dict = False
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def is_trainable(self) -> bool:
|
| 39 |
+
return self._is_trainable
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def dropout_rate(self) -> Union[float, torch.Tensor]:
|
| 43 |
+
return self._dropout_rate
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def input_key(self) -> str:
|
| 47 |
+
return self._input_key
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def is_return_dict(self) -> bool:
|
| 51 |
+
return self._return_dict
|
| 52 |
+
|
| 53 |
+
@is_trainable.setter
|
| 54 |
+
def is_trainable(self, value: bool):
|
| 55 |
+
self._is_trainable = value
|
| 56 |
+
|
| 57 |
+
@dropout_rate.setter
|
| 58 |
+
def dropout_rate(self, value: Union[float, torch.Tensor]):
|
| 59 |
+
self._dropout_rate = value
|
| 60 |
+
|
| 61 |
+
@input_key.setter
|
| 62 |
+
def input_key(self, value: str):
|
| 63 |
+
self._input_key = value
|
| 64 |
+
|
| 65 |
+
@is_return_dict.setter
|
| 66 |
+
def is_return_dict(self, value: bool):
|
| 67 |
+
self._return_dict = value
|
| 68 |
+
|
| 69 |
+
@is_trainable.deleter
|
| 70 |
+
def is_trainable(self):
|
| 71 |
+
del self._is_trainable
|
| 72 |
+
|
| 73 |
+
@dropout_rate.deleter
|
| 74 |
+
def dropout_rate(self):
|
| 75 |
+
del self._dropout_rate
|
| 76 |
+
|
| 77 |
+
@input_key.deleter
|
| 78 |
+
def input_key(self):
|
| 79 |
+
del self._input_key
|
| 80 |
+
|
| 81 |
+
@is_return_dict.deleter
|
| 82 |
+
def is_return_dict(self):
|
| 83 |
+
del self._return_dict
|
| 84 |
+
|
| 85 |
+
def random_dropout_input(
|
| 86 |
+
self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None
|
| 87 |
+
) -> torch.Tensor:
|
| 88 |
+
del key
|
| 89 |
+
dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate
|
| 90 |
+
return batch_mul(
|
| 91 |
+
torch.bernoulli((1.0 - dropout_rate) * torch.ones(in_tensor.shape[0])).type_as(in_tensor),
|
| 92 |
+
in_tensor,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def details(self) -> str:
|
| 96 |
+
return ""
|
| 97 |
+
|
| 98 |
+
def summary(self) -> str:
|
| 99 |
+
input_key = self.input_key if self.input_key is not None else getattr(self, "input_keys", None)
|
| 100 |
+
return (
|
| 101 |
+
f"{self.__class__.__name__} \n\tinput key: {input_key}"
|
| 102 |
+
f"\n\tParam count: {count_params(self, False)} \n\tTrainable: {self.is_trainable}"
|
| 103 |
+
f"\n\tDropout rate: {self.dropout_rate}"
|
| 104 |
+
f"\n\t{self.details()}"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class TrajectoryAttr(AbstractEmbModel):
|
| 109 |
+
def __init__(self, traj_dim: int):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.traj_dim = traj_dim
|
| 112 |
+
|
| 113 |
+
def forward(self, traj: torch.Tensor) -> Dict[str, torch.Tensor]:
|
| 114 |
+
return {
|
| 115 |
+
"trajectory": traj,
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
def details(self) -> str:
|
| 119 |
+
return f"Traj dim : {self.traj_dim} \n\tOutput key: [trajectory]"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class FrameRepeatAttr(AbstractEmbModel):
|
| 123 |
+
def __init__(self):
|
| 124 |
+
super().__init__()
|
| 125 |
+
|
| 126 |
+
def forward(self, frame_repeat: torch.Tensor) -> Dict[str, torch.Tensor]:
|
| 127 |
+
return {
|
| 128 |
+
"frame_repeat": frame_repeat / 10.0,
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
def details(self) -> str:
|
| 132 |
+
return "Frame repeat, Output key: [frame_repeat]"
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@dataclass
|
| 136 |
+
class BaseVideoCondition:
|
| 137 |
+
crossattn_emb: torch.Tensor
|
| 138 |
+
crossattn_mask: torch.Tensor
|
| 139 |
+
data_type: DataType = DataType.VIDEO
|
| 140 |
+
padding_mask: Optional[torch.Tensor] = None
|
| 141 |
+
fps: Optional[torch.Tensor] = None
|
| 142 |
+
num_frames: Optional[torch.Tensor] = None
|
| 143 |
+
image_size: Optional[torch.Tensor] = None
|
| 144 |
+
scalar_feature: Optional[torch.Tensor] = None
|
| 145 |
+
trajectory: Optional[torch.Tensor] = None
|
| 146 |
+
frame_repeat: Optional[torch.Tensor] = None
|
| 147 |
+
|
| 148 |
+
def to_dict(self) -> Dict[str, Optional[torch.Tensor]]:
|
| 149 |
+
return {f.name: getattr(self, f.name) for f in fields(self)}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@dataclass
|
| 153 |
+
class VideoExtendCondition(BaseVideoCondition):
|
| 154 |
+
video_cond_bool: Optional[torch.Tensor] = None # whether or not it conditioned on video
|
| 155 |
+
gt_latent: Optional[torch.Tensor] = None
|
| 156 |
+
condition_video_indicator: Optional[torch.Tensor] = None # 1 for condition region
|
| 157 |
+
|
| 158 |
+
# condition_video_input_mask will concat to the input of network, along channel dim;
|
| 159 |
+
# Will be concat with the input tensor
|
| 160 |
+
condition_video_input_mask: Optional[torch.Tensor] = None
|
| 161 |
+
# 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"
|
| 162 |
+
condition_video_augment_sigma: Optional[torch.Tensor] = None
|
| 163 |
+
# pose conditional input, will be concat with the input tensor
|
| 164 |
+
condition_video_pose: Optional[torch.Tensor] = None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dataclass
|
| 168 |
+
class ViewConditionedVideoExtendCondition(VideoExtendCondition):
|
| 169 |
+
# view index indicating camera, used to index nn.Embedding
|
| 170 |
+
view_indices_B_T: Optional[torch.Tensor] = None
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@dataclass
|
| 174 |
+
class VideoLatentDiffusionDecoderCondition(BaseVideoCondition):
|
| 175 |
+
# latent_condition will concat to the input of network, along channel dim;
|
| 176 |
+
# cfg will make latent_condition all zero padding.
|
| 177 |
+
latent_condition: Optional[torch.Tensor] = None
|
| 178 |
+
latent_condition_sigma: Optional[torch.Tensor] = None
|
| 179 |
+
|
| 180 |
+
def get_condition_for_cp(self, cp_group):
|
| 181 |
+
self.latent_condition = split_inputs_cp(x=self.latent_condition, seq_dim=2, cp_group=cp_group)
|
| 182 |
+
self.latent_condition_sigma = split_inputs_cp(x=self.latent_condition_sigma, seq_dim=2, cp_group=cp_group)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class VideoConditioner(GeneralConditioner):
|
| 186 |
+
def forward(
|
| 187 |
+
self,
|
| 188 |
+
batch: Dict,
|
| 189 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 190 |
+
) -> BaseVideoCondition:
|
| 191 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 192 |
+
return BaseVideoCondition(**output)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class VideoDiffusionDecoderConditioner(GeneralConditioner):
|
| 196 |
+
def forward(
|
| 197 |
+
self,
|
| 198 |
+
batch: Dict,
|
| 199 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 200 |
+
) -> VideoLatentDiffusionDecoderCondition:
|
| 201 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 202 |
+
return VideoLatentDiffusionDecoderCondition(**output)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class VideoExtendConditioner(GeneralConditioner):
|
| 206 |
+
def forward(
|
| 207 |
+
self,
|
| 208 |
+
batch: Dict,
|
| 209 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 210 |
+
) -> VideoExtendCondition:
|
| 211 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 212 |
+
return VideoExtendCondition(**output)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class ViewConditionedVideoExtendConditioner(GeneralConditioner):
|
| 216 |
+
def forward(
|
| 217 |
+
self,
|
| 218 |
+
batch: Dict,
|
| 219 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 220 |
+
) -> ViewConditionedVideoExtendCondition:
|
| 221 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 222 |
+
return ViewConditionedVideoExtendCondition(**output)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class VideoConditionerWithTraingOnlyEmb(GeneralConditioner):
|
| 226 |
+
def get_condition_uncondition(
|
| 227 |
+
self,
|
| 228 |
+
data_batch: Dict,
|
| 229 |
+
) -> Tuple[Any, Any]:
|
| 230 |
+
"""
|
| 231 |
+
Processes the provided data batch to generate two sets of outputs: conditioned and unconditioned. This method
|
| 232 |
+
manipulates the dropout rates of embedders to simulate two scenarios — one where all conditions are applied
|
| 233 |
+
(conditioned), and one where they are removed or reduced to the minimum (unconditioned).
|
| 234 |
+
|
| 235 |
+
This method first sets the dropout rates to zero for the conditioned scenario to fully apply the embedders' effects.
|
| 236 |
+
For the unconditioned scenario, it sets the dropout rates to 1 (or to 0 if the initial unconditional dropout rate
|
| 237 |
+
is insignificant) to minimize the embedders' influences, simulating an unconditioned generation.
|
| 238 |
+
|
| 239 |
+
Parameters:
|
| 240 |
+
data_batch (Dict): The input data batch that contains all necessary information for embedding processing. The
|
| 241 |
+
data is expected to match the required format and keys expected by the embedders.
|
| 242 |
+
|
| 243 |
+
Returns:
|
| 244 |
+
Tuple[Any, Any]: A tuple containing two condition:
|
| 245 |
+
- The first one contains the outputs with all embedders fully applied (conditioned outputs).
|
| 246 |
+
- The second one contains the outputs with embedders minimized or not applied (unconditioned outputs).
|
| 247 |
+
"""
|
| 248 |
+
cond_dropout_rates, dropout_rates = {}, {}
|
| 249 |
+
for emb_name, embedder in self.embedders.items():
|
| 250 |
+
if isinstance(embedder, FrameRepeatAttr):
|
| 251 |
+
cond_dropout_rates[emb_name] = 1.0
|
| 252 |
+
else:
|
| 253 |
+
cond_dropout_rates[emb_name] = 0.0
|
| 254 |
+
dropout_rates[emb_name] = 1.0 if embedder.dropout_rate > 1e-4 else 0.0
|
| 255 |
+
|
| 256 |
+
condition: Any = self(data_batch, override_dropout_rate=cond_dropout_rates)
|
| 257 |
+
un_condition: Any = self(data_batch, override_dropout_rate=dropout_rates)
|
| 258 |
+
return condition, un_condition
|
| 259 |
+
|
| 260 |
+
def forward(
|
| 261 |
+
self,
|
| 262 |
+
batch: Dict,
|
| 263 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 264 |
+
) -> BaseVideoCondition:
|
| 265 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 266 |
+
return BaseVideoCondition(**output)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class VideoExtendConditionerWithTraingOnlyEmb(VideoConditionerWithTraingOnlyEmb):
|
| 270 |
+
def forward(
|
| 271 |
+
self,
|
| 272 |
+
batch: Dict,
|
| 273 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 274 |
+
) -> VideoExtendCondition:
|
| 275 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 276 |
+
return VideoExtendCondition(**output)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@dataclass
|
| 280 |
+
class BaseWithCtrlCondition(VideoExtendCondition):
|
| 281 |
+
control_input_canny: Optional[torch.Tensor] = None
|
| 282 |
+
control_input_blur: Optional[torch.Tensor] = None
|
| 283 |
+
control_input_canny_blur: Optional[torch.Tensor] = None
|
| 284 |
+
control_input_depth: Optional[torch.Tensor] = None
|
| 285 |
+
control_input_segmentation: Optional[torch.Tensor] = None
|
| 286 |
+
control_input_depth_segmentation: Optional[torch.Tensor] = None
|
| 287 |
+
control_input_mask: Optional[torch.Tensor] = None
|
| 288 |
+
control_input_human_kpts: Optional[torch.Tensor] = None
|
| 289 |
+
control_input_upscale: Optional[torch.Tensor] = None
|
| 290 |
+
control_input_identity: Optional[torch.Tensor] = None
|
| 291 |
+
control_input_multi: Optional[torch.Tensor] = None
|
| 292 |
+
base_model: Optional[torch.nn.Module] = None
|
| 293 |
+
hint_key: Optional[str] = None
|
| 294 |
+
control_weight: Optional[float] = 1.0
|
| 295 |
+
num_layers_to_use: Optional[int] = -1
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class VideoConditionerWithCtrl(VideoExtendConditioner):
|
| 299 |
+
def forward(
|
| 300 |
+
self,
|
| 301 |
+
batch: Dict,
|
| 302 |
+
override_dropout_rate: Optional[Dict[str, float]] = None,
|
| 303 |
+
) -> BaseWithCtrlCondition:
|
| 304 |
+
output = super()._forward(batch, override_dropout_rate)
|
| 305 |
+
output["hint_key"] = batch["hint_key"]
|
| 306 |
+
if "control_weight" in batch:
|
| 307 |
+
output["control_weight"] = batch["control_weight"]
|
| 308 |
+
if "num_layers_to_use" in batch:
|
| 309 |
+
output["num_layers_to_use"] = batch["num_layers_to_use"]
|
| 310 |
+
return BaseWithCtrlCondition(**output)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class BooleanFlag(AbstractEmbModel):
|
| 314 |
+
def __init__(self, output_key: Optional[str] = None):
|
| 315 |
+
super().__init__()
|
| 316 |
+
self.output_key = output_key
|
| 317 |
+
|
| 318 |
+
def forward(self, *args, **kwargs) -> Dict[str, torch.Tensor]:
|
| 319 |
+
del args, kwargs
|
| 320 |
+
key = self.output_key if self.output_key else self.input_key
|
| 321 |
+
return {key: self.flag}
|
| 322 |
+
|
| 323 |
+
def random_dropout_input(
|
| 324 |
+
self, in_tensor: torch.Tensor, dropout_rate: Optional[float] = None, key: Optional[str] = None
|
| 325 |
+
) -> torch.Tensor:
|
| 326 |
+
del key
|
| 327 |
+
dropout_rate = dropout_rate if dropout_rate is not None else self.dropout_rate
|
| 328 |
+
self.flag = torch.bernoulli((1.0 - dropout_rate) * torch.ones(1)).bool().to(device=in_tensor.device)
|
| 329 |
+
return in_tensor
|
| 330 |
+
|
| 331 |
+
def details(self) -> str:
|
| 332 |
+
key = self.output_key if self.output_key else self.input_key
|
| 333 |
+
return f"Output key: {key} \n\t This is a boolean flag"
|
diffusion/training/config/base/ema.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from utils.ema import EMAModelTracker, PowerEMATracker
|
| 17 |
+
from utils.lazy_config import PLACEHOLDER
|
| 18 |
+
from utils.lazy_config import LazyCall as L
|
| 19 |
+
from utils.lazy_config import LazyDict
|
| 20 |
+
|
| 21 |
+
PowerEMAConfig: LazyDict = L(PowerEMATracker.initialize_multi_rank_ema)(
|
| 22 |
+
model=PLACEHOLDER, enabled=True, rate=0.10, num=3
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
RegEMAConfig: LazyDict = L(EMAModelTracker.initialize_multi_rank_ema)(
|
| 26 |
+
model=PLACEHOLDER, enabled=True, rate=0.999, num=1
|
| 27 |
+
)
|
diffusion/training/config/base/lidarverse_vae.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Released LidarVerse tokenizer wrapper for diffusion training/inference."""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import omegaconf
|
| 9 |
+
|
| 10 |
+
from diffusion.training.module.pretrained_vae_base import ConfigBasedVideoVAE
|
| 11 |
+
from utils.lazy_config import LazyCall as L
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_lidarverse_tokenizer(
|
| 15 |
+
resolution: str = "native",
|
| 16 |
+
chunk_duration: int = 21,
|
| 17 |
+
) -> omegaconf.dictconfig.DictConfig:
|
| 18 |
+
del resolution, chunk_duration
|
| 19 |
+
return L(ConfigBasedVideoVAE)(
|
| 20 |
+
experiment_name=(
|
| 21 |
+
"transformer_vae_8x8x1_z64_cross_dataset3_pandar_pandaset_"
|
| 22 |
+
"nuscenes32_gridrope_mask_pts_scratch_200k"
|
| 23 |
+
),
|
| 24 |
+
checkpoint_path=os.environ.get(
|
| 25 |
+
"LIDARVERSE_TOKENIZER_CHECKPOINT",
|
| 26 |
+
"checkpoints/lidarverse-tokenizer/ckpt.pt",
|
| 27 |
+
),
|
| 28 |
+
mean_std_fp=os.environ.get(
|
| 29 |
+
"LIDARVERSE_TOKENIZER_LATENT_STATS",
|
| 30 |
+
"checkpoints/lidarverse-tokenizer/latent_stats.pt",
|
| 31 |
+
),
|
| 32 |
+
latent_ch=64,
|
| 33 |
+
is_bf16=False,
|
| 34 |
+
spatial_compression=8,
|
| 35 |
+
apply_validity_mask=True,
|
| 36 |
+
# The public checkpoint has EMA weights materialized as network.*.
|
| 37 |
+
use_ema=False,
|
| 38 |
+
)
|
diffusion/training/config/base/model.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import List, Optional
|
| 17 |
+
|
| 18 |
+
import attrs
|
| 19 |
+
|
| 20 |
+
from diffusion.training.config.base.ema import PowerEMAConfig
|
| 21 |
+
from diffusion.training.modules.edm_sde import EDMSDE
|
| 22 |
+
from utils.lazy_config import LazyCall as L
|
| 23 |
+
from utils.lazy_config import LazyDict
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@attrs.define(slots=False)
|
| 27 |
+
class FSDPConfig:
|
| 28 |
+
policy: str = "block"
|
| 29 |
+
checkpoint: bool = False
|
| 30 |
+
min_num_params: int = 1024
|
| 31 |
+
sharding_group_size: int = 8
|
| 32 |
+
sharding_strategy: str = "full"
|
| 33 |
+
use_orig_params: bool = False
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@attrs.define(slots=False)
|
| 37 |
+
class DefaultModelConfig:
|
| 38 |
+
vae: LazyDict = None
|
| 39 |
+
conditioner: LazyDict = None
|
| 40 |
+
net: LazyDict = None
|
| 41 |
+
ema: LazyDict = PowerEMAConfig
|
| 42 |
+
sde: LazyDict = L(EDMSDE)(
|
| 43 |
+
p_mean=0.0,
|
| 44 |
+
p_std=1.0,
|
| 45 |
+
sigma_max=80,
|
| 46 |
+
sigma_min=0.0002,
|
| 47 |
+
)
|
| 48 |
+
sigma_data: float = 0.5
|
| 49 |
+
camera_sample_weight: LazyDict = LazyDict(
|
| 50 |
+
dict(
|
| 51 |
+
enabled=False,
|
| 52 |
+
weight=5.0,
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
aesthetic_finetuning: LazyDict = LazyDict(
|
| 56 |
+
dict(
|
| 57 |
+
enabled=False,
|
| 58 |
+
)
|
| 59 |
+
)
|
| 60 |
+
loss_mask_enabled: bool = False
|
| 61 |
+
loss_masking: LazyDict = None
|
| 62 |
+
loss_add_logvar: bool = True
|
| 63 |
+
precision: str = "bfloat16"
|
| 64 |
+
input_data_key: str = "video" # key to fetch input data from data_batch
|
| 65 |
+
input_image_key: str = "images_1024" # key to fetch input image from data_batch
|
| 66 |
+
loss_reduce: str = "sum"
|
| 67 |
+
loss_scale: float = 1.0
|
| 68 |
+
latent_shape: List[int] = [16, 24, 44, 80] # 24 corresponig to 136 frames
|
| 69 |
+
fsdp_enabled: bool = False
|
| 70 |
+
use_torch_compile: bool = False
|
| 71 |
+
fsdp: FSDPConfig = attrs.field(factory=FSDPConfig)
|
| 72 |
+
use_dummy_temporal_dim: bool = False # Whether to use dummy temporal dimension in data
|
| 73 |
+
adjust_video_noise: bool = False # whether or not adjust video noise accroding to the video length
|
| 74 |
+
peft_control: LazyDict | None = None
|
| 75 |
+
num_latents_to_drop: int = 0 # number of P-latents to discard after encoding
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@attrs.define(slots=False)
|
| 79 |
+
class MultiviewModelConfig(DefaultModelConfig):
|
| 80 |
+
n_views: int = 6
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@attrs.define(slots=False)
|
| 84 |
+
class LidarModelConfig(DefaultModelConfig):
|
| 85 |
+
# Optional second tokenizer for an aligned per-return LiDAR attribute.
|
| 86 |
+
# The primary VAE continues to encode range and HDMap inputs; when present,
|
| 87 |
+
# this VAE encodes only the intensity channel.
|
| 88 |
+
intensity_vae: LazyDict = None
|
| 89 |
+
n_views: int = 4
|
| 90 |
+
rgb_latent_shape: List[int] = [88, 160]
|
| 91 |
+
lidar_latent_shape: List[int] = [64, 224]
|
| 92 |
+
rgb_shape: List[int] = [704, 1280]
|
| 93 |
+
lidar_shape: List[int] = [512, 1792]
|
| 94 |
+
# Image-conditioned mininet RF (ImageToLidarMininetRectifiedFlowModel):
|
| 95 |
+
# number of RGB conditioning views temporal-concatenated onto the lidar
|
| 96 |
+
# latent, their dataset view keys, and the RGB image-VAE latent channel
|
| 97 |
+
# count (zero-padded up to the lidar latent ch before the temporal stack).
|
| 98 |
+
n_rgb_views: int = 0
|
| 99 |
+
rgb_view_keys: List[int] = attrs.field(factory=list)
|
| 100 |
+
image_latent_ch: int = 16
|
| 101 |
+
# Classifier-free guidance on the RGB condition: per-sample probability of
|
| 102 |
+
# zeroing ALL RGB condition frames during training (learns the RGB-
|
| 103 |
+
# unconditional branch). 0.0 = always conditional (no image CFG).
|
| 104 |
+
rgb_dropout_prob: float = 0.0
|
| 105 |
+
# VIDEO image-conditioned mininet RF (VideoImageToLidarMininetRectifiedFlowModel):
|
| 106 |
+
# per-frame counts on the joint temporal axis, RGB pixel-time stride (RGB
|
| 107 |
+
# temporal compression / lidar temporal compression), RGB input resize
|
| 108 |
+
# (HxW) before the Wan encode, and the per-sample probability of dropping a
|
| 109 |
+
# random suffix of RGB future frames (lidar extrapolation training).
|
| 110 |
+
lidar_latent_t: int = 1
|
| 111 |
+
rgb_latent_t: int = 1
|
| 112 |
+
rgb_temporal_stride: int = 4
|
| 113 |
+
rgb_resize_hw: List[int] = attrs.field(factory=lambda: [256, 448])
|
| 114 |
+
# Encode each RGB frame as an independent T=1 clip (no VAE temporal
|
| 115 |
+
# compression) -> Tr == #RGB input frames -> 1:1 with lidar frames.
|
| 116 |
+
rgb_per_frame_encode: bool = False
|
| 117 |
+
# Prepend a duplicate of RGB latent frame 0 per view (mirrors the lidar VAE
|
| 118 |
+
# frame-0 prepend) -> Tr+1 RGB frames matching lidar Tl, exact 1:1 RoPE
|
| 119 |
+
# pixel-time alignment (no off-by-one).
|
| 120 |
+
rgb_prepend_first_frame: bool = False
|
| 121 |
+
# PV-VAE-style RGB future-frame dropping (mirrors the lidar VAE's
|
| 122 |
+
# frame_drop_{prob,min_latent,max_latent}): with prob ``future_frame_drop_prob``
|
| 123 |
+
# drop the trailing ``k ~ U[min, max]`` RGB latent frames (same cut across
|
| 124 |
+
# views). ``max < 0`` => Tr-1 (keep only the first frame); ``min=0`` =>
|
| 125 |
+
# sometimes keep all. 0 prob = no future-frame dropping.
|
| 126 |
+
future_frame_drop_prob: float = 0.0
|
| 127 |
+
future_frame_drop_min: int = 0
|
| 128 |
+
future_frame_drop_max: int = -1
|
| 129 |
+
# Cross-attn RGB conditioning: spatial avg-pool factor applied to the RGB
|
| 130 |
+
# latent HxW before tokenizing into image-context K/V (keeps h/w structure,
|
| 131 |
+
# trims token count). 1 = no pooling.
|
| 132 |
+
rgb_context_pool: int = 1
|
| 133 |
+
hdmap_channels: int = 0
|
| 134 |
+
additional_concat_ch: int = 0
|
| 135 |
+
skip_hdmap_proj: bool = False
|
| 136 |
+
encode_hdmap_with_vae: bool = False
|
| 137 |
+
# BEV-native hdmap conditioning: pool the multi-channel BEV hdmap raster
|
| 138 |
+
# (one channel per semantic class, solid box footprints) down to the latent
|
| 139 |
+
# grid with a learnable conv encoder and channel-concat it. Mutually
|
| 140 |
+
# exclusive with encode_hdmap_with_vae / skip_hdmap_proj.
|
| 141 |
+
bev_hdmap_pool: bool = False
|
| 142 |
+
bev_hdmap_channels: int = 7
|
| 143 |
+
bev_hdmap_size: int = 256
|
| 144 |
+
bev_hdmap_out_size: int = 32
|
| 145 |
+
bev_hdmap_base_channels: int = 64
|
| 146 |
+
# BEV-native hdmap conditioning via a FROZEN pretrained Wan2.2 RGB VAE:
|
| 147 |
+
# render the BEV raster to a 3-ch image and encode it (16x spatial, z=48),
|
| 148 |
+
# then channel-concat that latent (no learnable projection). Mutually
|
| 149 |
+
# exclusive with bev_hdmap_pool / encode_hdmap_with_vae / skip_hdmap_proj.
|
| 150 |
+
# ``bev_hdmap_render_mode``: "colored" (per-class palette) or "occupancy".
|
| 151 |
+
bev_hdmap_wan_encode: bool = False
|
| 152 |
+
bev_hdmap_wan_ckpt: str = "checkpoints/wan_vae_pretrained/Wan2.2_VAE.pth"
|
| 153 |
+
bev_hdmap_render_mode: str = "colored"
|
| 154 |
+
hdmap_dropout_prob: float = 0.0
|
| 155 |
+
# Mixture of training-time hdmap dropout regimes. When dropout fires for
|
| 156 |
+
# a sample (prob = hdmap_dropout_prob), one mode from this list is drawn
|
| 157 |
+
# uniformly:
|
| 158 |
+
# "full" -- zero the entire hdmap latent (CFG-style)
|
| 159 |
+
# "frame_bernoulli" -- independently zero each frame at
|
| 160 |
+
# hdmap_frame_dropout_rate
|
| 161 |
+
# "keep_first_k" -- zero all frames except the first
|
| 162 |
+
# hdmap_keep_first_k frames
|
| 163 |
+
# Default = ("full",) preserves the legacy CFG-only behavior, so all
|
| 164 |
+
# pre-existing configs train exactly as before. Only video-mode hdmap
|
| 165 |
+
# latents (5-D, with a temporal axis) honor frame-wise modes; image-mode
|
| 166 |
+
# latents (4-D, T=1) fall back to "full" silently.
|
| 167 |
+
hdmap_dropout_modes: List[str] = attrs.field(factory=lambda: ["full"])
|
| 168 |
+
hdmap_frame_dropout_rate: float = 0.5
|
| 169 |
+
hdmap_keep_first_k: int = 1
|
| 170 |
+
# ArtiFixer stage-2 conditioning dropout. One decision is shared across the
|
| 171 |
+
# batch: with probability ``hdmap_dropout_prob`` drop every latent frame;
|
| 172 |
+
# otherwise retain a uniformly sampled non-empty prefix. This is applied in
|
| 173 |
+
# latent space because LiDAR HDMap conditioning has no separate opacity mask.
|
| 174 |
+
hdmap_artifixer_dropout: bool = False
|
| 175 |
+
shift: float = 1.0
|
| 176 |
+
# LTX training stretch (Fig. 10): map shifted-t percentiles (0.5, 99.9) to [0,1].
|
| 177 |
+
# None = shift only (legacy). Not the same as inference ``enable_shift_stretch``.
|
| 178 |
+
shift_clamp_percentiles: Optional[tuple] = None
|
| 179 |
+
# LTX stretch (inference only): remap schedule clean end to this t (e.g. 0.1).
|
| 180 |
+
enable_shift_stretch: bool = False
|
| 181 |
+
shift_stretch_terminal: float = 0.1
|
| 182 |
+
train_time_distribution: str = "uniform"
|
| 183 |
+
train_time_weight: str = "uniform"
|
| 184 |
+
# RF prediction parameterization. "velocity" (default, legacy): the net
|
| 185 |
+
# regresses the flow velocity v = noise - clean. "clean": the net regresses
|
| 186 |
+
# the clean latent x0 directly (VGGT-World z-prediction); the sampler
|
| 187 |
+
# converts x0_hat -> velocity via v = (x_t - x0_hat)/sigma. Loss is then a
|
| 188 |
+
# clean-target MSE ||x0_hat - x0||^2 (uniform-weighted, VGGT eq. 12 style).
|
| 189 |
+
rf_prediction_type: str = "velocity"
|
| 190 |
+
# Paired single-frame autoregressive baselines. Sensor2Sensor concatenates
|
| 191 |
+
# one previous-frame latent; LaGen-SDE concatenates previous, foreground,
|
| 192 |
+
# and background latents and FiLM-modulates the previous latent by the
|
| 193 |
+
# relative ego pose.
|
| 194 |
+
autoregressive_condition_count: int = 0
|
| 195 |
+
autoregressive_pose_film: bool = False
|
| 196 |
+
autoregressive_pose_film_hidden_channels: int = 256
|
| 197 |
+
autoregressive_noise_modulation_max: float = 0.0
|
| 198 |
+
autoregressive_ego_action_only: bool = False
|
| 199 |
+
autoregressive_geometry_root_path: str = ""
|
| 200 |
+
autoregressive_geometry_filter_list: str = ""
|
| 201 |
+
autoregressive_min_range: float = 2.5
|
| 202 |
+
autoregressive_max_range: float = 75.0
|
| 203 |
+
autoregressive_min_value: float = -1.0
|
| 204 |
+
autoregressive_inverse_depth: bool = False
|
| 205 |
+
# Blockwise Diffusion Forcing (HDMap->LiDAR or forecast RF). A positive
|
| 206 |
+
# block size samples one independent RF time per temporal block and pairs it
|
| 207 |
+
# with a block-causal DiT mask of the same size. Zero preserves the legacy single
|
| 208 |
+
# time per full clip. The current 8-frame Waymo recipe has latent T=9
|
| 209 |
+
# (prepend + 8 real frames), so block_size=3 gives three causal blocks.
|
| 210 |
+
diffusion_forcing_block_size: int = 0
|
| 211 |
+
# Match ArtiFixer's stage-2 Diffusion Forcing time sampler and weighting:
|
| 212 |
+
# 1000 discrete uniform base-sigma levels, shift-only reparameterization,
|
| 213 |
+
# and the reference bell-shaped per-timestep loss weights.
|
| 214 |
+
diffusion_forcing_artifixer_matching: bool = False
|
| 215 |
+
# Causal teacher-forcing variants optimize only the denoiser, replay clean
|
| 216 |
+
# prefix K/V, and optionally rescale the RF objective.
|
| 217 |
+
optimizer_net_only: bool = False
|
| 218 |
+
teacher_forcing_prefix_frames: int = 0
|
| 219 |
+
teacher_forcing_detach_clean_kv: bool = False
|
| 220 |
+
teacher_forcing_loss_scale: float = 1.0
|
| 221 |
+
# Imaginaire causal-training mixture over the number of leading clean
|
| 222 |
+
# latent frames. Dedicated Imaginaire models supply their reference
|
| 223 |
+
# defaults when these lists are empty; other model classes ignore them.
|
| 224 |
+
imaginaire_conditioned_prefix_frames: List[int] = attrs.field(
|
| 225 |
+
factory=list
|
| 226 |
+
)
|
| 227 |
+
imaginaire_conditioned_prefix_probs: List[float] = attrs.field(
|
| 228 |
+
factory=list
|
| 229 |
+
)
|
| 230 |
+
# Existing LiDAR video datasets prepend a duplicate of frame 0 before VAE
|
| 231 |
+
# encoding. Imaginaire-style training instead consumes unique frames and
|
| 232 |
+
# treats the actual frame 0 as its singleton temporal prefix.
|
| 233 |
+
input_video_has_prepend: bool = True
|
| 234 |
+
# Optional second geometry condition for block-causal HDMap->LiDAR RF.
|
| 235 |
+
# The dataloader accumulates only lidar sweeps from blocks preceding each
|
| 236 |
+
# target block, renders them at each target pose, and the model encodes the
|
| 237 |
+
# resulting range video with the frozen lidar VAE. The latent enters through
|
| 238 |
+
# the network's zero-initialized side patch projection; False is a no-op.
|
| 239 |
+
blockwise_warped_history_condition: bool = False
|
| 240 |
+
# Concatenate the VAE-encoded geometry after the LiDAR and HDMap slots
|
| 241 |
+
# instead of using the side patch projection. This is opt-in so faithful
|
| 242 |
+
# ArtiFixer and Imaginaire recipes keep their upstream architecture.
|
| 243 |
+
blockwise_warped_history_concat: bool = False
|
| 244 |
+
# Source of the blockwise warped-history range video. "dataloader" keeps
|
| 245 |
+
# the legacy worker-side NumPy all-history union. "torch_spatial_map"
|
| 246 |
+
# constructs a causal per-sample TorchSpatialPointMap on the training device.
|
| 247 |
+
blockwise_warped_history_backend: str = "dataloader"
|
| 248 |
+
blockwise_spatial_map_radius_m: float = 75.0
|
| 249 |
+
blockwise_spatial_map_voxel_m: float = 0.2
|
| 250 |
+
blockwise_spatial_map_voxel_policy: str = "newest"
|
| 251 |
+
# "frame" counts distinct frame hits inside each committed block; map
|
| 252 |
+
# visibility and candidate expiry remain block-boundary operations.
|
| 253 |
+
blockwise_spatial_map_observation_unit: str = "block"
|
| 254 |
+
blockwise_spatial_map_static_min_observations: int = 2
|
| 255 |
+
blockwise_spatial_map_candidate_ttl_updates: int = 1
|
| 256 |
+
blockwise_spatial_map_include_latest: bool = True
|
| 257 |
+
# Per-global-microstep chance of rebuilding the training map from one
|
| 258 |
+
# detached terminal-sigma Euler prediction instead of ground-truth sweeps.
|
| 259 |
+
# The decision is synchronized because this path adds an FSDP forward.
|
| 260 |
+
blockwise_spatial_map_self_prediction_prob: float = 0.0
|
| 261 |
+
blockwise_spatial_map_free_space_clear: bool = False
|
| 262 |
+
blockwise_spatial_map_free_space_margin_m: float = 0.75
|
| 263 |
+
blockwise_spatial_map_free_space_misses_to_remove: int = 2
|
| 264 |
+
blockwise_spatial_map_geometry_root_path: str = ""
|
| 265 |
+
blockwise_spatial_map_geometry_filter_list_path: str = ""
|
| 266 |
+
blockwise_spatial_map_geometry_resample_width: int = -1
|
| 267 |
+
blockwise_spatial_map_min_range: float = 2.5
|
| 268 |
+
blockwise_spatial_map_max_range: float = 75.0
|
| 269 |
+
blockwise_spatial_map_min_value: float = -1.0
|
| 270 |
+
blockwise_spatial_map_inverse_depth: bool = False
|
| 271 |
+
# Replace the Gaussian RF endpoint with a confidence-weighted soft
|
| 272 |
+
# geometry proposal. Its confidence-composited range render also enters
|
| 273 |
+
# through the DiT side projection.
|
| 274 |
+
blockwise_geometry_source: bool = False
|
| 275 |
+
blockwise_geometry_source_noise_floor: float = 0.2
|
| 276 |
+
# Composite uncertain projected pixels against empty range before the
|
| 277 |
+
# nonlinear VAE encode. Latent confidence/noise blending still applies.
|
| 278 |
+
blockwise_geometry_source_preencode_confidence: bool = False
|
| 279 |
+
blockwise_geometry_source_dropout_prob: float = 0.0
|
| 280 |
+
blockwise_geometry_source_density_kernel: int = 5
|
| 281 |
+
blockwise_geometry_source_density_saturation_hits: float = 5.0
|
| 282 |
+
# Isolated Stage-2 multi-task conditioning experiment. One mode is sampled
|
| 283 |
+
# for the full distributed step so every rank follows the same model path.
|
| 284 |
+
stage2_multitask_modes: List[str] = attrs.field(factory=list)
|
| 285 |
+
stage2_multitask_probs: List[float] = attrs.field(factory=list)
|
| 286 |
+
stage2_multitask_sampling: str = "categorical"
|
| 287 |
+
stage2_multitask_known_mask_concat: bool = False
|
| 288 |
+
stage2_multitask_forecast_observed_frames: int = 6
|
| 289 |
+
stage2_multitask_resim_known_min_per_block: int = 1
|
| 290 |
+
stage2_multitask_resim_known_max_per_block: int = 2
|
| 291 |
+
stage2_multitask_resim_drop_block_prob: float = 0.1
|
| 292 |
+
stage2_multitask_world_hdmap_dropout_prob: float = 0.1
|
| 293 |
+
stage2_multitask_hdmap_bbox_channel_start: int = 4
|
| 294 |
+
# Factorized Stage-2 conditioning. Prefix length, HDMap form, and geometry
|
| 295 |
+
# provenance are sampled without task labels or task embeddings.
|
| 296 |
+
stage2_known_mask_concat: bool = False
|
| 297 |
+
stage2_factorized_prefix_frames: List[int] = attrs.field(factory=list)
|
| 298 |
+
stage2_factorized_prefix_probs: List[float] = attrs.field(factory=list)
|
| 299 |
+
stage2_factorized_hdmap_modes: List[str] = attrs.field(factory=list)
|
| 300 |
+
stage2_factorized_hdmap_probs: List[float] = attrs.field(factory=list)
|
| 301 |
+
stage2_factorized_geometry_modes_k0: List[str] = attrs.field(factory=list)
|
| 302 |
+
stage2_factorized_geometry_probs_k0: List[float] = attrs.field(
|
| 303 |
+
factory=list
|
| 304 |
+
)
|
| 305 |
+
stage2_factorized_geometry_modes_known: List[str] = attrs.field(
|
| 306 |
+
factory=list
|
| 307 |
+
)
|
| 308 |
+
stage2_factorized_geometry_probs_known: List[float] = attrs.field(
|
| 309 |
+
factory=list
|
| 310 |
+
)
|
| 311 |
+
factorized_geometry_block_size: int = 4
|
| 312 |
+
factorized_geometry_prefix_frames: int = 1
|
| 313 |
+
# Deskew source sweeps before factorized geometry accumulation and
|
| 314 |
+
# re-skew each rendered condition into the target sweep convention.
|
| 315 |
+
factorized_geometry_rolling_shutter: bool = False
|
| 316 |
+
# ``frame`` preserves the legacy one-box-pose-per-sweep behavior.
|
| 317 |
+
# The other modes interpolate adjacent actor boxes by approximate ray time.
|
| 318 |
+
factorized_geometry_actor_box_time_mode: str = "frame"
|
| 319 |
+
# When enabled, frozen geometry samples its own observed-prefix length G
|
| 320 |
+
# instead of reusing the clean-latent prefix length K.
|
| 321 |
+
factorized_decouple_geometry_observations: bool = False
|
| 322 |
+
factorized_geometry_observation_frames: List[int] = attrs.field(
|
| 323 |
+
factory=list
|
| 324 |
+
)
|
| 325 |
+
factorized_geometry_observation_probs: List[float] = attrs.field(
|
| 326 |
+
factory=list
|
| 327 |
+
)
|
| 328 |
+
factorized_force_geometry_observations: int = -1
|
| 329 |
+
factorized_bidirectional_stage1: bool = False
|
| 330 |
+
stage2_factorized_hdmap_bbox_channel_start: int = 4
|
| 331 |
+
stage2_factorized_force_prefix_k: int = -1
|
| 332 |
+
stage2_factorized_force_hdmap_mode: str = ""
|
| 333 |
+
stage2_factorized_force_geometry_mode: str = ""
|
| 334 |
+
# Teacher-forcing discrete consistency distillation. The frozen teacher is
|
| 335 |
+
# the causal Stage-2 network; earlier blocks are replayed as clean context
|
| 336 |
+
# while one selected block follows an adjacent shifted RF ladder interval.
|
| 337 |
+
tfdcm_total_steps: int = 48
|
| 338 |
+
tfdcm_skipping_interval_steps: int = 1
|
| 339 |
+
tfdcm_timestep_shift: float = 5.0
|
| 340 |
+
tfdcm_teacher_guidance: float = 1.0
|
| 341 |
+
tfdcm_teacher_checkpoint: str = ""
|
| 342 |
+
tfdcm_loss_scale: float = 100.0
|
| 343 |
+
# Self-Forcing DMD (HDMap->LiDAR DF only). Defaults keep every existing
|
| 344 |
+
# experiment unchanged; the dedicated SF-DMD model validates/populates all
|
| 345 |
+
# fields before use.
|
| 346 |
+
sfdmd_num_real_frames: int = 41
|
| 347 |
+
sfdmd_window_frames: int = 8
|
| 348 |
+
sfdmd_fake_updates_per_cycle: int = 5
|
| 349 |
+
sfdmd_kv_cache_frames: int = 6
|
| 350 |
+
# Optional permanent prefix retained when the bounded DiT K/V cache rolls.
|
| 351 |
+
# ArtiFixer's three-frame adaptation uses sink3 + recent3 as persistent
|
| 352 |
+
# history, then appends the current three-frame query for nine total frames.
|
| 353 |
+
sfdmd_kv_sink_frames: int = 0
|
| 354 |
+
# Number of generated three-frame blocks linked by autograd during student
|
| 355 |
+
# replay before cached K/V is detached (truncated BPTT).
|
| 356 |
+
sfdmd_tbptt_blocks: int = 1
|
| 357 |
+
# Keep canonical ArtiFixer on full-rollout BPTT unless an isolated,
|
| 358 |
+
# memory-bounded handoff explicitly opts into truncation.
|
| 359 |
+
sfdmd_allow_truncated_bptt: bool = False
|
| 360 |
+
sfdmd_kv_equivalence_atol: float = 2.0e-2
|
| 361 |
+
sfdmd_run_kv_equivalence_gate: bool = True
|
| 362 |
+
# Skip bias-free text cross-attention only after a runtime assertion that
|
| 363 |
+
# the supplied text embedding is exactly zero.
|
| 364 |
+
sfdmd_skip_zero_crossattn: bool = False
|
| 365 |
+
sfdmd_stream_condition_vae_encode: bool = False
|
| 366 |
+
sfdmd_condition_vae_cache_frames: int = 6
|
| 367 |
+
sfdmd_accumulated_geometry_warp: bool = False
|
| 368 |
+
sfdmd_geometry_source: bool = False
|
| 369 |
+
sfdmd_geometry_source_noise_floor: float = 0.1
|
| 370 |
+
sfdmd_geometry_source_preencode_confidence: bool = False
|
| 371 |
+
sfdmd_geometry_source_density_kernel: int = 5
|
| 372 |
+
sfdmd_geometry_source_density_saturation_hits: float = 5.0
|
| 373 |
+
sfdmd_spatial_map_radius_m: float = 75.0
|
| 374 |
+
sfdmd_spatial_map_voxel_m: float = 0.2
|
| 375 |
+
sfdmd_spatial_map_voxel_policy: str = "newest"
|
| 376 |
+
# Kept separate so Stage 4 must explicitly match its input checkpoint.
|
| 377 |
+
sfdmd_spatial_map_observation_unit: str = "block"
|
| 378 |
+
sfdmd_spatial_map_static_min_observations: int = 2
|
| 379 |
+
sfdmd_spatial_map_candidate_ttl_updates: int = 1
|
| 380 |
+
sfdmd_spatial_map_include_latest: bool = True
|
| 381 |
+
sfdmd_spatial_map_free_space_clear: bool = False
|
| 382 |
+
sfdmd_spatial_map_free_space_margin_m: float = 0.75
|
| 383 |
+
sfdmd_spatial_map_free_space_misses_to_remove: int = 2
|
| 384 |
+
sfdmd_num_steps: int = 4
|
| 385 |
+
sfdmd_sde_eta: float = 1.0
|
| 386 |
+
# ArtiFixer-compatible DMD mode: randomly select one denoising exit step,
|
| 387 |
+
# use fresh-noise SDE transitions, train one full-rollout critic update per
|
| 388 |
+
# iteration, and update the student every ``student_update_freq`` iterations.
|
| 389 |
+
sfdmd_artifixer_matching: bool = False
|
| 390 |
+
sfdmd_imaginaire_matching: bool = False
|
| 391 |
+
sfdmd_clean_x0_kv_commit: bool = False
|
| 392 |
+
# Preserve the task-free Stage-2 prefix/HDMap/geometry distribution during
|
| 393 |
+
# ArtiFixer-style self-forcing rollouts.
|
| 394 |
+
sfdmd_factorized_conditioning: bool = False
|
| 395 |
+
# Training-only controls for isolating temporal and spatial self-forcing.
|
| 396 |
+
# Existing experiments retain generated history by default.
|
| 397 |
+
sfdmd_temporal_history_source: str = "generated"
|
| 398 |
+
sfdmd_geometry_history_source: str = "generated"
|
| 399 |
+
sfdmd_temporal_prefix_frames: int = 0
|
| 400 |
+
sfdmd_student_update_freq: int = 5
|
| 401 |
+
sfdmd_ema_start_cycle: int = 0
|
| 402 |
+
sfdmd_teacher_guidance: float = 1.0
|
| 403 |
+
sfdmd_critic_min_sigma: float = 0.02
|
| 404 |
+
sfdmd_critic_max_sigma: float = 0.98
|
| 405 |
+
sfdmd_max_grad_norm: float = 1.0
|
| 406 |
+
sfdmd_teacher_checkpoint: str = ""
|
| 407 |
+
sfdmd_teacher_net: LazyDict | None = None
|
| 408 |
+
sfdmd_geometry_root_path: str = ""
|
| 409 |
+
sfdmd_geometry_filter_list_path: str = ""
|
| 410 |
+
sfdmd_geometry_resample_width: int = -1
|
| 411 |
+
sfdmd_min_range: float = 2.5
|
| 412 |
+
sfdmd_max_range: float = 75.0
|
| 413 |
+
sfdmd_min_value: float = -1.0
|
| 414 |
+
sfdmd_inverse_depth: bool = False
|
| 415 |
+
# ---- lidar point-cloud forecasting (LidarForecastRectifiedFlowModel) ----
|
| 416 |
+
# Number of clean PAST context frames in a forecasting clip (the remaining
|
| 417 |
+
# sample_n_frames - n_past frames are the FUTURE frames to predict). Only
|
| 418 |
+
# consumed by the forecasting model; harmless default for other configs.
|
| 419 |
+
n_past: int = 0
|
| 420 |
+
# Per-sample prob of dropping (zeroing) the ego-pose conditioning during
|
| 421 |
+
# training so the model learns a pose-unconditional branch -> pose CFG.
|
| 422 |
+
pose_dropout_prob: float = 0.0
|
| 423 |
+
# Per-sample prob of "history dropout": hide the k OLDEST past frames
|
| 424 |
+
# (structured prefix drop, k~U{1..n_past-1}) by zeroing their latent content
|
| 425 |
+
# + pose (mask stays 1 = "present but empty context"). Teaches the generative
|
| 426 |
+
# forecaster to work with less history than a deterministic model needs.
|
| 427 |
+
history_dropout_prob: float = 0.0
|
| 428 |
+
# Forecasting only: Vista-style anchor concat. When True, broadcast the clean
|
| 429 |
+
# most-recent past (t=0) latent across all T frames and channel-concat it to
|
| 430 |
+
# the noised input (requires net.in_channels = 2*latent_ch). Gives future
|
| 431 |
+
# frames a direct input-level view of the anchor instead of relying purely on
|
| 432 |
+
# temporal attention. Default False -> existing configs unchanged.
|
| 433 |
+
anchor_concat: bool = False
|
| 434 |
+
# Forecasting only: replace the broadcast anchor with a per-frame latent
|
| 435 |
+
# encoded from observed lidar sweeps warped into each target ego pose.
|
| 436 |
+
# Shares the same extra latent_ch input slot as anchor_concat.
|
| 437 |
+
warped_history_concat: bool = False
|
| 438 |
+
# Dataloader rasterization mode for warped_history_concat.
|
| 439 |
+
# "latest" uses only the newest observed sweep; "all" z-buffers all past.
|
| 440 |
+
warped_history_mode: str = "all"
|
| 441 |
+
# Whether to also use the legacy flattened-SE(3) ego_pose_head. Geometry-only
|
| 442 |
+
# conditioning sets this False and net.ego_pose_dim=0.
|
| 443 |
+
use_pose_condition: bool = True
|
| 444 |
+
# Forecasting DF only: route the VAE-encoded observed-history warp through
|
| 445 |
+
# the block-causal checkpoint's independently projected side condition.
|
| 446 |
+
warped_history_side_condition: bool = False
|
| 447 |
+
# Forecasting DF only: append this many always-zero channels in the legacy
|
| 448 |
+
# HDMap concat slot, preserving the warm-start x_embedder shape while the
|
| 449 |
+
# lidar-only warp enters through the side projection.
|
| 450 |
+
forecast_null_concat_channels: int = 0
|
| 451 |
+
# Selects the prefix-aware block-causal forecast model in inference tools.
|
| 452 |
+
forecast_diffusion_forcing: bool = False
|
| 453 |
+
# Forecasting only: Vista-style anchor CFG. Per-sample prob of dropping
|
| 454 |
+
# (zeroing) the anchor concat during training so it becomes a CFG target
|
| 455 |
+
# (uncond pass zeros the concat). 0.0 -> anchor is always-on context (no
|
| 456 |
+
# anchor CFG). Vista uses 0.15.
|
| 457 |
+
anchor_dropout_prob: float = 0.0
|
diffusion/training/config/base/optim.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from diffusion.training.functional.lr_scheduler import LambdaLinearScheduler
|
| 17 |
+
from diffusion.training.utils.optim_instantiate import get_base_optimizer
|
| 18 |
+
from utils.lazy_config import PLACEHOLDER
|
| 19 |
+
from utils.lazy_config import LazyCall as L
|
| 20 |
+
from utils.lazy_config import LazyDict
|
| 21 |
+
|
| 22 |
+
FusedAdamWConfig: LazyDict = L(get_base_optimizer)(
|
| 23 |
+
model=PLACEHOLDER,
|
| 24 |
+
lr=1e-4,
|
| 25 |
+
weight_decay=0.3,
|
| 26 |
+
betas=[0.9, 0.999],
|
| 27 |
+
optim_type="fusedadam",
|
| 28 |
+
eps=1e-8,
|
| 29 |
+
sharding=False,
|
| 30 |
+
master_weights=True,
|
| 31 |
+
capturable=True,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
LambdaLinearSchedulerConfig: LazyDict = L(LambdaLinearScheduler)(
|
| 35 |
+
warm_up_steps=[1000],
|
| 36 |
+
cycle_lengths=[10000000000000],
|
| 37 |
+
f_start=[1.0e-6],
|
| 38 |
+
f_max=[1.0],
|
| 39 |
+
f_min=[1.0],
|
| 40 |
+
)
|
diffusion/training/config/config_lidar.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Minimal configuration entry point for public LidarVerse experiments."""
|
| 5 |
+
|
| 6 |
+
import importlib
|
| 7 |
+
from typing import Any, List
|
| 8 |
+
|
| 9 |
+
import attrs
|
| 10 |
+
|
| 11 |
+
from diffusion.training.config.base.model import LidarModelConfig
|
| 12 |
+
from diffusion.training.config.text2world.registry import (
|
| 13 |
+
register_configs as register_configs_text2world,
|
| 14 |
+
)
|
| 15 |
+
from diffusion.training.models.model import DiffusionModel
|
| 16 |
+
from diffusion.training.trainer import Trainer
|
| 17 |
+
from utils import config
|
| 18 |
+
from utils.lazy_config import PLACEHOLDER
|
| 19 |
+
from utils.lazy_config import LazyCall as L
|
| 20 |
+
from utils.lazy_config import LazyDict
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@attrs.define(slots=False)
|
| 24 |
+
class Config(config.Config):
|
| 25 |
+
defaults: List[Any] = attrs.field(
|
| 26 |
+
factory=lambda: [
|
| 27 |
+
"_self_",
|
| 28 |
+
{"data_train": None},
|
| 29 |
+
{"data_val": None},
|
| 30 |
+
{"optimizer": "fusedadamw"},
|
| 31 |
+
{"scheduler": "lambdalinear"},
|
| 32 |
+
{"callbacks": None},
|
| 33 |
+
{"net": "mininet_2b"},
|
| 34 |
+
{"conditioner": "add_fps_image_size_padding_mask"},
|
| 35 |
+
{"fsdp": None},
|
| 36 |
+
{"ema": "power"},
|
| 37 |
+
{"vae": "lidarverse_tokenizer"},
|
| 38 |
+
{"checkpoint": "local"},
|
| 39 |
+
{"ckpt_klass": "fsdp"},
|
| 40 |
+
{"experiment": None},
|
| 41 |
+
]
|
| 42 |
+
)
|
| 43 |
+
model_obj: LazyDict = L(DiffusionModel)(config=PLACEHOLDER)
|
| 44 |
+
optimizer_fake: LazyDict | None = None
|
| 45 |
+
scheduler_fake: LazyDict | None = None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
_PUBLIC_EXPERIMENT_MODULE = (
|
| 49 |
+
"diffusion.training.config.text2world_hdmaptolidar."
|
| 50 |
+
"experiment_lidarverse"
|
| 51 |
+
)
|
| 52 |
+
_PUBLIC_EXPERIMENTS = {
|
| 53 |
+
"lidarverse_stage1_bidir_21f",
|
| 54 |
+
"lidarverse_stage2_causal_9f",
|
| 55 |
+
"lidarverse_stage3_sfdmd_9f",
|
| 56 |
+
"lidarverse_pai_stage1_finetune",
|
| 57 |
+
"lidarverse_pai_stage2_finetune",
|
| 58 |
+
"lidarverse_pai_stage3_finetune",
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _register_lidarverse_experiments() -> None:
|
| 63 |
+
from hydra.core.config_store import ConfigStore
|
| 64 |
+
|
| 65 |
+
importlib.import_module(_PUBLIC_EXPERIMENT_MODULE).register_experiments(
|
| 66 |
+
ConfigStore.instance()
|
| 67 |
+
)
|
| 68 |
+
importlib.import_module(
|
| 69 |
+
"diffusion.training.config.text2world_hdmaptolidar.experiment_pai_release"
|
| 70 |
+
).register_experiments(ConfigStore.instance())
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def make_config(experiment_name: str | None = None):
|
| 74 |
+
if experiment_name is not None and experiment_name not in _PUBLIC_EXPERIMENTS:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"unknown public LidarVerse experiment {experiment_name!r}; "
|
| 77 |
+
f"choose one of {sorted(_PUBLIC_EXPERIMENTS)}"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
c = Config(
|
| 81 |
+
model=LidarModelConfig(),
|
| 82 |
+
optimizer=None,
|
| 83 |
+
scheduler=None,
|
| 84 |
+
dataloader_train=None,
|
| 85 |
+
dataloader_val=None,
|
| 86 |
+
)
|
| 87 |
+
c.job.project = "lidarverse"
|
| 88 |
+
c.job.group = "training"
|
| 89 |
+
c.job.name = "delete_${now:%Y-%m-%d}_${now:%H-%M-%S}"
|
| 90 |
+
c.trainer.type = Trainer
|
| 91 |
+
c.trainer.max_iter = 400_000
|
| 92 |
+
c.trainer.logging_iter = 10
|
| 93 |
+
c.trainer.validation_iter = 100
|
| 94 |
+
c.trainer.run_validation = False
|
| 95 |
+
c.trainer.callbacks = None
|
| 96 |
+
c.checkpoint = None
|
| 97 |
+
|
| 98 |
+
register_configs_text2world()
|
| 99 |
+
_register_lidarverse_experiments()
|
| 100 |
+
return c
|
diffusion/training/config/text2world/registry.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Minimal shared Hydra registry for LidarVerse diffusion models."""
|
| 5 |
+
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
from typing import Dict
|
| 8 |
+
|
| 9 |
+
from hydra.core.config_store import ConfigStore
|
| 10 |
+
|
| 11 |
+
from diffusion.checkpointers.ema_fsdp_checkpointer import (
|
| 12 |
+
CheckpointConfig,
|
| 13 |
+
FSDPCheckpointer,
|
| 14 |
+
)
|
| 15 |
+
from diffusion.config.base.conditioner import (
|
| 16 |
+
FPSConfig,
|
| 17 |
+
ImageSizeConfig,
|
| 18 |
+
NumFramesConfig,
|
| 19 |
+
PaddingMaskConfig,
|
| 20 |
+
TextConfig,
|
| 21 |
+
)
|
| 22 |
+
from diffusion.training.conditioner import VideoConditioner
|
| 23 |
+
from diffusion.training.config.base.lidarverse_vae import (
|
| 24 |
+
get_lidarverse_tokenizer,
|
| 25 |
+
)
|
| 26 |
+
from diffusion.training.config.base.optim import (
|
| 27 |
+
FusedAdamWConfig,
|
| 28 |
+
LambdaLinearSchedulerConfig,
|
| 29 |
+
)
|
| 30 |
+
from diffusion.training.networks.lvg_dit import LVGDiTForLidar
|
| 31 |
+
from diffusion.training.networks.minimal_v4_dit import SACConfig
|
| 32 |
+
from utils.ema import PowerEMATracker
|
| 33 |
+
from utils.lazy_config import PLACEHOLDER
|
| 34 |
+
from utils.lazy_config import LazyCall as L
|
| 35 |
+
from utils.lazy_config import LazyDict
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
FSDP_CHECKPOINTER: Dict[str, str] = L(FSDPCheckpointer)()
|
| 39 |
+
|
| 40 |
+
VideoConditionerFpsSizePaddingConfig: LazyDict = L(VideoConditioner)(
|
| 41 |
+
text=TextConfig(),
|
| 42 |
+
fps=FPSConfig(),
|
| 43 |
+
num_frames=NumFramesConfig(),
|
| 44 |
+
image_size=ImageSizeConfig(),
|
| 45 |
+
padding_mask=PaddingMaskConfig(),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
MININET_2B_Config: LazyDict = L(LVGDiTForLidar)(
|
| 49 |
+
max_img_h=240,
|
| 50 |
+
max_img_w=240,
|
| 51 |
+
max_frames=128,
|
| 52 |
+
in_channels=16,
|
| 53 |
+
out_channels=16,
|
| 54 |
+
patch_spatial=2,
|
| 55 |
+
patch_temporal=1,
|
| 56 |
+
model_channels=2048,
|
| 57 |
+
num_blocks=28,
|
| 58 |
+
num_heads=16,
|
| 59 |
+
concat_padding_mask=True,
|
| 60 |
+
pos_emb_cls="rope3d",
|
| 61 |
+
pos_emb_learnable=True,
|
| 62 |
+
pos_emb_interpolation="crop",
|
| 63 |
+
use_adaln_lora=True,
|
| 64 |
+
adaln_lora_dim=256,
|
| 65 |
+
atten_backend="minimal_a2a",
|
| 66 |
+
extra_per_block_abs_pos_emb=False,
|
| 67 |
+
rope_h_extrapolation_ratio=1.0,
|
| 68 |
+
rope_w_extrapolation_ratio=1.0,
|
| 69 |
+
rope_t_extrapolation_ratio=1.0,
|
| 70 |
+
sac_config=L(SACConfig)(),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
PowerEMAConfig: LazyDict = L(PowerEMATracker.initialize_multi_rank_ema)(
|
| 74 |
+
model=PLACEHOLDER,
|
| 75 |
+
enabled=True,
|
| 76 |
+
rate=0.10,
|
| 77 |
+
num=3,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def register_configs() -> None:
|
| 82 |
+
cs = ConfigStore.instance()
|
| 83 |
+
cs.store(
|
| 84 |
+
group="optimizer",
|
| 85 |
+
package="optimizer",
|
| 86 |
+
name="fusedadamw",
|
| 87 |
+
node=FusedAdamWConfig,
|
| 88 |
+
)
|
| 89 |
+
cs.store(
|
| 90 |
+
group="scheduler",
|
| 91 |
+
package="scheduler",
|
| 92 |
+
name="lambdalinear",
|
| 93 |
+
node=LambdaLinearSchedulerConfig,
|
| 94 |
+
)
|
| 95 |
+
cs.store(
|
| 96 |
+
group="net",
|
| 97 |
+
package="model.net",
|
| 98 |
+
name="mininet_2b",
|
| 99 |
+
node=deepcopy(MININET_2B_Config),
|
| 100 |
+
)
|
| 101 |
+
cs.store(
|
| 102 |
+
group="conditioner",
|
| 103 |
+
package="model.conditioner",
|
| 104 |
+
name="add_fps_image_size_padding_mask",
|
| 105 |
+
node=VideoConditionerFpsSizePaddingConfig,
|
| 106 |
+
)
|
| 107 |
+
cs.store(
|
| 108 |
+
group="vae",
|
| 109 |
+
package="model.vae",
|
| 110 |
+
name="lidarverse_tokenizer",
|
| 111 |
+
node=get_lidarverse_tokenizer(),
|
| 112 |
+
)
|
| 113 |
+
cs.store(
|
| 114 |
+
group="ema",
|
| 115 |
+
package="model.ema",
|
| 116 |
+
name="power",
|
| 117 |
+
node=PowerEMAConfig,
|
| 118 |
+
)
|
| 119 |
+
cs.store(
|
| 120 |
+
group="checkpoint",
|
| 121 |
+
package="checkpoint",
|
| 122 |
+
name="local",
|
| 123 |
+
node=CheckpointConfig(
|
| 124 |
+
save_iter=1000,
|
| 125 |
+
load_path="",
|
| 126 |
+
load_training_state=False,
|
| 127 |
+
strict_resume=True,
|
| 128 |
+
),
|
| 129 |
+
)
|
| 130 |
+
cs.store(
|
| 131 |
+
group="ckpt_klass",
|
| 132 |
+
package="checkpoint.type",
|
| 133 |
+
name="fsdp",
|
| 134 |
+
node=FSDP_CHECKPOINTER,
|
| 135 |
+
)
|
| 136 |
+
|
diffusion/training/config/text2world_hdmaptolidar/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
diffusion/training/config/text2world_hdmaptolidar/experiment_lidarverse.py
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 6 |
+
Stage 1 starts directly from an adapted Cosmos-Predict2 2B checkpoint. Stage 2
|
| 7 |
+
trains the causal four-frame student with teacher forcing, and Stage 3 applies
|
| 8 |
+
self-forcing distribution matching on nine-frame self-rollouts.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from copy import deepcopy
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
from hydra.core.config_store import ConfigStore
|
| 15 |
+
|
| 16 |
+
from diffusion.training.config.base.optim import (
|
| 17 |
+
FusedAdamWConfig,
|
| 18 |
+
LambdaLinearSchedulerConfig,
|
| 19 |
+
)
|
| 20 |
+
from diffusion.training.config.text2world.registry import MININET_2B_Config
|
| 21 |
+
from diffusion.training.datasets.lidar_dataset.hdmaptolidar_dataloader import (
|
| 22 |
+
CrossDatasetHdmapLidarDataset,
|
| 23 |
+
HomogeneousMultiHdmapDataLoader,
|
| 24 |
+
)
|
| 25 |
+
from diffusion.training.models.hdmaptolidar_model_rf import (
|
| 26 |
+
FSDPHdmapToLidarFactorizedBidirectionalRFModel,
|
| 27 |
+
FSDPHdmapToLidarFactorizedTeacherForcingRFModel,
|
| 28 |
+
)
|
| 29 |
+
from diffusion.training.models.hdmaptolidar_model_sf_dmd import (
|
| 30 |
+
FSDPHdmapToLidarSFDMDModel,
|
| 31 |
+
)
|
| 32 |
+
from diffusion.training.networks.minimal_v4_dit import SACConfig
|
| 33 |
+
from diffusion.training.trainer_sf_dmd import SFDMDTrainer
|
| 34 |
+
from utils.lazy_config import PLACEHOLDER
|
| 35 |
+
from utils.lazy_config import LazyCall as L
|
| 36 |
+
from utils.lazy_config import LazyDict
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
STAGE1_NAME = "lidarverse_stage1_bidir_21f"
|
| 40 |
+
STAGE2_NAME = "lidarverse_stage2_causal_9f"
|
| 41 |
+
STAGE3_NAME = "lidarverse_stage3_sfdmd_9f"
|
| 42 |
+
|
| 43 |
+
_LATENT_CHANNELS = 64
|
| 44 |
+
_STAGE1_FRAMES = 21
|
| 45 |
+
_CAUSAL_FRAMES = 9
|
| 46 |
+
_DATASET_NAMES = ("nvidia_pai", "nuscenes")
|
| 47 |
+
_PREFIX_FRAMES_21 = [0, 1, 2, 4, 8, 10, 12, 16]
|
| 48 |
+
_PREFIX_PROBS_21 = [0.5] + [0.5 / 7.0] * 7
|
| 49 |
+
_GEOMETRY_FRAMES_21 = [1, 2, 4, 8, 10, 12, 16, 20]
|
| 50 |
+
_PREFIX_FRAMES_9 = [0, 1, 2, 4, 8]
|
| 51 |
+
_PREFIX_PROBS_9 = [0.5] + [0.125] * 4
|
| 52 |
+
_GEOMETRY_FRAMES_9 = [1, 2, 4, 8]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _checkpoint(env_name: str, default: str) -> str:
|
| 56 |
+
return os.environ.get(env_name, default)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _build_cross_dataset_dataloader(
|
| 60 |
+
*,
|
| 61 |
+
validation: bool,
|
| 62 |
+
sample_n_frames: int,
|
| 63 |
+
num_workers: int = 16,
|
| 64 |
+
):
|
| 65 |
+
suffix = "val" if validation else "train"
|
| 66 |
+
dataset_names = [
|
| 67 |
+
f"lidarverse_nvidia_pai_{suffix}",
|
| 68 |
+
f"lidarverse_nuscenes_{suffix}",
|
| 69 |
+
]
|
| 70 |
+
shared = {
|
| 71 |
+
"sample_n_frames": sample_n_frames,
|
| 72 |
+
"frame_sampling_method": "sequential",
|
| 73 |
+
"process_input": "mono",
|
| 74 |
+
"is_video_tokenizer": False,
|
| 75 |
+
"blockwise_warped_history_condition": False,
|
| 76 |
+
"hdmap_multichannel": False,
|
| 77 |
+
"return_hdmap_semantic": False,
|
| 78 |
+
"return_moving_boxes": True,
|
| 79 |
+
"resolve_moving_box_track_ids": False,
|
| 80 |
+
"return_full_lidar_metadata": True,
|
| 81 |
+
"load_intensity": False,
|
| 82 |
+
}
|
| 83 |
+
per_dataset = {
|
| 84 |
+
f"lidarverse_nvidia_pai_{suffix}": {
|
| 85 |
+
"min_range": 2.5,
|
| 86 |
+
"max_range": 100.0,
|
| 87 |
+
"sensor_fps": 10.0,
|
| 88 |
+
"frame_sampling_every_n_frames": 1,
|
| 89 |
+
"moving_box_root": os.environ.get(
|
| 90 |
+
"LIDARVERSE_NVIDIA_PAI_ROOT", "data/nvidia_pai"
|
| 91 |
+
),
|
| 92 |
+
},
|
| 93 |
+
f"lidarverse_nuscenes_{suffix}": {
|
| 94 |
+
"min_range": 2.5,
|
| 95 |
+
"max_range": 100.0,
|
| 96 |
+
"hdmap_map_max_dist": 100.0,
|
| 97 |
+
"sensor_fps": 2.0,
|
| 98 |
+
"frame_sampling_every_n_frames": 10,
|
| 99 |
+
"repeat_row": 1,
|
| 100 |
+
"lidar_size": [32, 1024],
|
| 101 |
+
},
|
| 102 |
+
}
|
| 103 |
+
return HomogeneousMultiHdmapDataLoader(
|
| 104 |
+
dataset=CrossDatasetHdmapLidarDataset(
|
| 105 |
+
dataset_names=dataset_names,
|
| 106 |
+
shared_overrides=shared,
|
| 107 |
+
per_dataset_overrides=per_dataset,
|
| 108 |
+
),
|
| 109 |
+
batch_size=1,
|
| 110 |
+
validation=validation,
|
| 111 |
+
dataset_sampling_weights=[0.5, 0.5],
|
| 112 |
+
drop_last=True,
|
| 113 |
+
pin_memory=True,
|
| 114 |
+
num_workers=num_workers,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _dataloader(*, validation: bool, sample_n_frames: int):
|
| 119 |
+
return L(_build_cross_dataset_dataloader)(
|
| 120 |
+
validation=validation,
|
| 121 |
+
sample_n_frames=sample_n_frames,
|
| 122 |
+
num_workers=int(os.environ.get("LIDARVERSE_DATALOADER_WORKERS", "16")),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _factorized_model_config(num_frames: int) -> dict:
|
| 127 |
+
prefix_frames = (
|
| 128 |
+
_PREFIX_FRAMES_21 if num_frames == _STAGE1_FRAMES else _PREFIX_FRAMES_9
|
| 129 |
+
)
|
| 130 |
+
prefix_probs = (
|
| 131 |
+
_PREFIX_PROBS_21 if num_frames == _STAGE1_FRAMES else _PREFIX_PROBS_9
|
| 132 |
+
)
|
| 133 |
+
geometry_frames = (
|
| 134 |
+
_GEOMETRY_FRAMES_21
|
| 135 |
+
if num_frames == _STAGE1_FRAMES
|
| 136 |
+
else _GEOMETRY_FRAMES_9
|
| 137 |
+
)
|
| 138 |
+
return {
|
| 139 |
+
# Spatial dimensions are a shape hint only. Native-grid batches carry
|
| 140 |
+
# their own H/W; T is checked by the bidirectional/SF-DMD contracts.
|
| 141 |
+
"latent_shape": [_LATENT_CHANNELS, num_frames, 16, 150],
|
| 142 |
+
"hdmap_channels": 1,
|
| 143 |
+
"additional_concat_ch": _LATENT_CHANNELS,
|
| 144 |
+
"skip_hdmap_proj": False,
|
| 145 |
+
"encode_hdmap_with_vae": True,
|
| 146 |
+
"hdmap_dropout_prob": 0.0,
|
| 147 |
+
"loss_reduce": "mean",
|
| 148 |
+
"sigma_data": 1.0,
|
| 149 |
+
"shift": 5,
|
| 150 |
+
"train_time_distribution": "logitnormal",
|
| 151 |
+
"train_time_weight": "uniform",
|
| 152 |
+
"input_video_has_prepend": False,
|
| 153 |
+
"blockwise_warped_history_condition": True,
|
| 154 |
+
"blockwise_warped_history_concat": True,
|
| 155 |
+
"blockwise_warped_history_backend": "dataloader",
|
| 156 |
+
"blockwise_spatial_map_self_prediction_prob": 0.0,
|
| 157 |
+
"stage2_known_mask_concat": True,
|
| 158 |
+
"imaginaire_conditioned_prefix_frames": prefix_frames,
|
| 159 |
+
"imaginaire_conditioned_prefix_probs": prefix_probs,
|
| 160 |
+
"stage2_factorized_prefix_frames": prefix_frames,
|
| 161 |
+
"stage2_factorized_prefix_probs": prefix_probs,
|
| 162 |
+
"stage2_factorized_hdmap_modes": ["null", "full"],
|
| 163 |
+
"stage2_factorized_hdmap_probs": [0.5, 0.5],
|
| 164 |
+
"stage2_factorized_geometry_modes_k0": [
|
| 165 |
+
"null",
|
| 166 |
+
"rolling_static",
|
| 167 |
+
"frozen_object",
|
| 168 |
+
],
|
| 169 |
+
"stage2_factorized_geometry_probs_k0": [0.1, 0.45, 0.45],
|
| 170 |
+
"stage2_factorized_geometry_modes_known": [
|
| 171 |
+
"null",
|
| 172 |
+
"rolling_static",
|
| 173 |
+
"frozen_object",
|
| 174 |
+
],
|
| 175 |
+
"stage2_factorized_geometry_probs_known": [0.1, 0.45, 0.45],
|
| 176 |
+
"stage2_factorized_hdmap_bbox_channel_start": 4,
|
| 177 |
+
"stage2_factorized_force_prefix_k": -1,
|
| 178 |
+
"stage2_factorized_force_hdmap_mode": "",
|
| 179 |
+
"stage2_factorized_force_geometry_mode": "",
|
| 180 |
+
"factorized_decouple_geometry_observations": True,
|
| 181 |
+
"factorized_geometry_observation_frames": geometry_frames,
|
| 182 |
+
"factorized_geometry_observation_probs": [
|
| 183 |
+
1.0 / len(geometry_frames)
|
| 184 |
+
] * len(geometry_frames),
|
| 185 |
+
"factorized_force_geometry_observations": -1,
|
| 186 |
+
"factorized_geometry_block_size": 4,
|
| 187 |
+
"factorized_geometry_prefix_frames": 1,
|
| 188 |
+
"factorized_geometry_rolling_shutter": True,
|
| 189 |
+
"factorized_geometry_actor_box_time_mode": "frame",
|
| 190 |
+
"ema": {"enabled": True},
|
| 191 |
+
"fsdp_enabled": True,
|
| 192 |
+
"fsdp": {
|
| 193 |
+
"policy": "block",
|
| 194 |
+
"checkpoint": False,
|
| 195 |
+
"min_num_params": 1024,
|
| 196 |
+
"sharding_group_size": 8,
|
| 197 |
+
"sharding_strategy": "hybrid",
|
| 198 |
+
},
|
| 199 |
+
"net": {
|
| 200 |
+
"in_channels": _LATENT_CHANNELS * 3 + 1,
|
| 201 |
+
"out_channels": _LATENT_CHANNELS,
|
| 202 |
+
"side_condition_channels": 0,
|
| 203 |
+
"num_frame_type_embeddings": 0,
|
| 204 |
+
"num_dataset_embeddings": len(_DATASET_NAMES),
|
| 205 |
+
"timestep_scale": 0.001,
|
| 206 |
+
"rope_h_extrapolation_ratio": 3.0,
|
| 207 |
+
"rope_w_extrapolation_ratio": 3.0,
|
| 208 |
+
"rope_t_extrapolation_ratio": 1.0,
|
| 209 |
+
"rope_enable_fps_modulation": False,
|
| 210 |
+
"use_wan_fp32_strategy": True,
|
| 211 |
+
},
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
stage1_config = LazyDict(
|
| 216 |
+
{
|
| 217 |
+
"defaults": [
|
| 218 |
+
{"override /net": "mininet_2b"},
|
| 219 |
+
{"override /ckpt_klass": "fsdp"},
|
| 220 |
+
{"override /checkpoint": "local"},
|
| 221 |
+
{"override /vae": "lidarverse_tokenizer"},
|
| 222 |
+
{"override /conditioner": "add_fps_image_size_padding_mask"},
|
| 223 |
+
"_self_",
|
| 224 |
+
],
|
| 225 |
+
"job": {
|
| 226 |
+
"project": "posttraining",
|
| 227 |
+
"group": "lidarverse",
|
| 228 |
+
"name": STAGE1_NAME,
|
| 229 |
+
},
|
| 230 |
+
"optimizer": {
|
| 231 |
+
"lr": 2 ** (-14.3),
|
| 232 |
+
"weight_decay": 0.1,
|
| 233 |
+
"betas": [0.9, 0.99],
|
| 234 |
+
"eps": 1.0e-10,
|
| 235 |
+
},
|
| 236 |
+
"checkpoint": {
|
| 237 |
+
"save_iter": 200,
|
| 238 |
+
"save_at_iters": [2000, 4000, 6000, 8000, 10000, 15000, 20000],
|
| 239 |
+
"keep_last_checkpoints": 2,
|
| 240 |
+
"broadcast_via_filesystem": False,
|
| 241 |
+
"load_path": _checkpoint(
|
| 242 |
+
"LIDARVERSE_COSMOS_WARMSTART",
|
| 243 |
+
"checkpoints/cosmos-predict2/cosmos2_2b_lidar_warmstart.pt",
|
| 244 |
+
),
|
| 245 |
+
"load_training_state": False,
|
| 246 |
+
"strict_resume": False,
|
| 247 |
+
"keys_not_to_resume": [],
|
| 248 |
+
},
|
| 249 |
+
"trainer": {
|
| 250 |
+
"max_iter": 20000,
|
| 251 |
+
"distributed_parallelism": "fsdp",
|
| 252 |
+
"logging_iter": 10,
|
| 253 |
+
"grad_accum_iter": 1,
|
| 254 |
+
"run_validation": True,
|
| 255 |
+
"validation_iter": 1000,
|
| 256 |
+
"max_val_iter": 20,
|
| 257 |
+
},
|
| 258 |
+
"model_parallel": {
|
| 259 |
+
"sequence_parallel": False,
|
| 260 |
+
"tensor_model_parallel_size": 1,
|
| 261 |
+
"context_parallel_size": 1,
|
| 262 |
+
},
|
| 263 |
+
"model": _factorized_model_config(_STAGE1_FRAMES),
|
| 264 |
+
"model_obj": L(FSDPHdmapToLidarFactorizedBidirectionalRFModel)(
|
| 265 |
+
config=PLACEHOLDER,
|
| 266 |
+
fsdp_checkpointer=PLACEHOLDER,
|
| 267 |
+
),
|
| 268 |
+
"scheduler": {
|
| 269 |
+
"warm_up_steps": [2500],
|
| 270 |
+
"cycle_lengths": [20000],
|
| 271 |
+
"f_start": [1.0e-6],
|
| 272 |
+
"f_max": [1.0],
|
| 273 |
+
"f_min": [1.0],
|
| 274 |
+
},
|
| 275 |
+
"dataloader_train": _dataloader(
|
| 276 |
+
validation=False, sample_n_frames=_STAGE1_FRAMES
|
| 277 |
+
),
|
| 278 |
+
"dataloader_val": _dataloader(
|
| 279 |
+
validation=True, sample_n_frames=_STAGE1_FRAMES
|
| 280 |
+
),
|
| 281 |
+
},
|
| 282 |
+
# Derived stages store the trainer class directly in trainer.type.
|
| 283 |
+
flags={"allow_objects": True},
|
| 284 |
+
)
|
| 285 |
+
stage1_config["model"].update(
|
| 286 |
+
diffusion_forcing_block_size=_STAGE1_FRAMES,
|
| 287 |
+
teacher_forcing_prefix_frames=0,
|
| 288 |
+
factorized_bidirectional_stage1=True,
|
| 289 |
+
)
|
| 290 |
+
stage1_config["model"]["net"].update(
|
| 291 |
+
atten_backend="minimal_a2a",
|
| 292 |
+
temporal_block_size=0,
|
| 293 |
+
temporal_prefix_frames=0,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
stage2_config = deepcopy(stage1_config)
|
| 298 |
+
stage2_config["job"]["name"] = STAGE2_NAME
|
| 299 |
+
stage2_config["checkpoint"].update(
|
| 300 |
+
save_iter=200,
|
| 301 |
+
save_at_iters=[2000, 4000, 6000, 8000, 10000],
|
| 302 |
+
load_path=_checkpoint(
|
| 303 |
+
"LIDARVERSE_STAGE1_CHECKPOINT",
|
| 304 |
+
"checkpoints/lidarverse-stage1/iter_000020000_ema_model.pt",
|
| 305 |
+
),
|
| 306 |
+
load_ema_to_reg=False,
|
| 307 |
+
load_training_state=False,
|
| 308 |
+
strict_resume=False,
|
| 309 |
+
)
|
| 310 |
+
stage2_config["trainer"].update(
|
| 311 |
+
max_iter=10000,
|
| 312 |
+
validation_iter=1000,
|
| 313 |
+
)
|
| 314 |
+
stage2_config["scheduler"].update(
|
| 315 |
+
warm_up_steps=[1000],
|
| 316 |
+
cycle_lengths=[10000],
|
| 317 |
+
)
|
| 318 |
+
stage2_config["model"] = _factorized_model_config(_CAUSAL_FRAMES)
|
| 319 |
+
stage2_config["model"].update(
|
| 320 |
+
diffusion_forcing_block_size=4,
|
| 321 |
+
teacher_forcing_prefix_frames=1,
|
| 322 |
+
factorized_bidirectional_stage1=False,
|
| 323 |
+
)
|
| 324 |
+
stage2_config["model"]["net"].update(
|
| 325 |
+
atten_backend="torch-flex",
|
| 326 |
+
temporal_block_size=4,
|
| 327 |
+
temporal_prefix_frames=1,
|
| 328 |
+
# FlexAttention supports full-block recomputation, not selective caching.
|
| 329 |
+
sac_config=L(SACConfig)(mode="block_wise"),
|
| 330 |
+
)
|
| 331 |
+
stage2_config["model_obj"] = L(
|
| 332 |
+
FSDPHdmapToLidarFactorizedTeacherForcingRFModel
|
| 333 |
+
)(
|
| 334 |
+
config=PLACEHOLDER,
|
| 335 |
+
fsdp_checkpointer=PLACEHOLDER,
|
| 336 |
+
)
|
| 337 |
+
stage2_config["dataloader_train"] = _dataloader(
|
| 338 |
+
validation=False, sample_n_frames=_CAUSAL_FRAMES
|
| 339 |
+
)
|
| 340 |
+
stage2_config["dataloader_val"] = _dataloader(
|
| 341 |
+
validation=True, sample_n_frames=_CAUSAL_FRAMES
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _score_net_config():
|
| 346 |
+
net = deepcopy(MININET_2B_Config)
|
| 347 |
+
net.in_channels = _LATENT_CHANNELS * 3 + 1
|
| 348 |
+
net.out_channels = _LATENT_CHANNELS
|
| 349 |
+
net.patch_spatial = stage2_config["model"]["net"].get(
|
| 350 |
+
"patch_spatial", MININET_2B_Config.patch_spatial
|
| 351 |
+
)
|
| 352 |
+
net.side_condition_channels = 0
|
| 353 |
+
net.num_frame_type_embeddings = 0
|
| 354 |
+
net.num_dataset_embeddings = len(_DATASET_NAMES)
|
| 355 |
+
net.timestep_scale = 0.001
|
| 356 |
+
net.rope_h_extrapolation_ratio = 3.0
|
| 357 |
+
net.rope_w_extrapolation_ratio = 3.0
|
| 358 |
+
net.rope_t_extrapolation_ratio = 1.0
|
| 359 |
+
net.rope_enable_fps_modulation = False
|
| 360 |
+
net.use_wan_fp32_strategy = True
|
| 361 |
+
net.atten_backend = "minimal_a2a"
|
| 362 |
+
net.temporal_block_size = 0
|
| 363 |
+
net.temporal_prefix_frames = 0
|
| 364 |
+
net.sac_config = L(SACConfig)(mode="none")
|
| 365 |
+
return net
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
stage3_config = deepcopy(stage2_config)
|
| 369 |
+
stage3_config["job"]["name"] = STAGE3_NAME
|
| 370 |
+
stage3_config["checkpoint"].update(
|
| 371 |
+
save_iter=250,
|
| 372 |
+
save_at_iters=[500, 1000, 1500, 2000],
|
| 373 |
+
load_path=_checkpoint(
|
| 374 |
+
"LIDARVERSE_STAGE2_CHECKPOINT",
|
| 375 |
+
"checkpoints/lidarverse-stage2/iter_000010000.pt",
|
| 376 |
+
),
|
| 377 |
+
load_ema_to_reg=True,
|
| 378 |
+
load_training_state=False,
|
| 379 |
+
strict_resume=True,
|
| 380 |
+
)
|
| 381 |
+
stage3_config["trainer"].update(
|
| 382 |
+
type=SFDMDTrainer,
|
| 383 |
+
max_iter=2000,
|
| 384 |
+
logging_iter=1,
|
| 385 |
+
run_validation=False,
|
| 386 |
+
grad_accum_iter=1,
|
| 387 |
+
)
|
| 388 |
+
stage3_config["optimizer"].update(
|
| 389 |
+
lr=2.0e-6,
|
| 390 |
+
weight_decay=0.01,
|
| 391 |
+
betas=[0.9, 0.999],
|
| 392 |
+
eps=1.0e-8,
|
| 393 |
+
)
|
| 394 |
+
fake_optimizer = deepcopy(FusedAdamWConfig)
|
| 395 |
+
fake_optimizer.lr = 4.0e-7
|
| 396 |
+
fake_optimizer.weight_decay = 0.01
|
| 397 |
+
fake_optimizer.betas = [0.9, 0.999]
|
| 398 |
+
fake_optimizer.eps = 1.0e-8
|
| 399 |
+
stage3_config["optimizer_fake"] = fake_optimizer
|
| 400 |
+
fake_scheduler = deepcopy(LambdaLinearSchedulerConfig)
|
| 401 |
+
fake_scheduler.warm_up_steps = [0]
|
| 402 |
+
fake_scheduler.cycle_lengths = [10000000000000]
|
| 403 |
+
fake_scheduler.f_start = [1.0]
|
| 404 |
+
fake_scheduler.f_max = [1.0]
|
| 405 |
+
fake_scheduler.f_min = [1.0]
|
| 406 |
+
stage3_config["scheduler_fake"] = fake_scheduler
|
| 407 |
+
stage3_config["scheduler"].update(
|
| 408 |
+
warm_up_steps=[0],
|
| 409 |
+
cycle_lengths=[10000000000000],
|
| 410 |
+
f_start=[1.0],
|
| 411 |
+
f_max=[1.0],
|
| 412 |
+
f_min=[1.0],
|
| 413 |
+
)
|
| 414 |
+
stage3_config["model"].update(
|
| 415 |
+
sfdmd_num_real_frames=_CAUSAL_FRAMES,
|
| 416 |
+
sfdmd_window_frames=_CAUSAL_FRAMES,
|
| 417 |
+
sfdmd_fake_updates_per_cycle=1,
|
| 418 |
+
sfdmd_student_update_freq=5,
|
| 419 |
+
sfdmd_num_steps=4,
|
| 420 |
+
sfdmd_sde_eta=1.0,
|
| 421 |
+
sfdmd_kv_cache_frames=9,
|
| 422 |
+
sfdmd_kv_sink_frames=1,
|
| 423 |
+
sfdmd_tbptt_blocks=2,
|
| 424 |
+
sfdmd_allow_truncated_bptt=True,
|
| 425 |
+
sfdmd_run_kv_equivalence_gate=False,
|
| 426 |
+
sfdmd_skip_zero_crossattn=True,
|
| 427 |
+
sfdmd_stream_condition_vae_encode=True,
|
| 428 |
+
sfdmd_condition_vae_cache_frames=9,
|
| 429 |
+
sfdmd_accumulated_geometry_warp=False,
|
| 430 |
+
sfdmd_geometry_source=False,
|
| 431 |
+
sfdmd_spatial_map_radius_m=100.0,
|
| 432 |
+
sfdmd_spatial_map_voxel_m=0.15,
|
| 433 |
+
sfdmd_spatial_map_voxel_policy="persistent_static",
|
| 434 |
+
sfdmd_spatial_map_observation_unit="block",
|
| 435 |
+
sfdmd_spatial_map_static_min_observations=3,
|
| 436 |
+
sfdmd_spatial_map_candidate_ttl_updates=1,
|
| 437 |
+
sfdmd_spatial_map_include_latest=False,
|
| 438 |
+
sfdmd_spatial_map_free_space_clear=True,
|
| 439 |
+
sfdmd_spatial_map_free_space_margin_m=0.75,
|
| 440 |
+
sfdmd_spatial_map_free_space_misses_to_remove=2,
|
| 441 |
+
sfdmd_artifixer_matching=True,
|
| 442 |
+
sfdmd_imaginaire_matching=False,
|
| 443 |
+
sfdmd_clean_x0_kv_commit=True,
|
| 444 |
+
sfdmd_factorized_conditioning=True,
|
| 445 |
+
sfdmd_temporal_history_source="generated",
|
| 446 |
+
sfdmd_geometry_history_source="generated",
|
| 447 |
+
sfdmd_temporal_prefix_frames=1,
|
| 448 |
+
sfdmd_ema_start_cycle=200,
|
| 449 |
+
sfdmd_teacher_guidance=3.0,
|
| 450 |
+
sfdmd_critic_min_sigma=0.02,
|
| 451 |
+
sfdmd_critic_max_sigma=0.98,
|
| 452 |
+
sfdmd_max_grad_norm=10.0,
|
| 453 |
+
sfdmd_teacher_checkpoint=_checkpoint(
|
| 454 |
+
"LIDARVERSE_STAGE2_EMA_CHECKPOINT",
|
| 455 |
+
"checkpoints/lidarverse-stage2/iter_000010000_ema_model.pt",
|
| 456 |
+
),
|
| 457 |
+
sfdmd_teacher_net=_score_net_config(),
|
| 458 |
+
sfdmd_min_range=1.0,
|
| 459 |
+
sfdmd_max_range=100.0,
|
| 460 |
+
sfdmd_min_value=-1.0,
|
| 461 |
+
sfdmd_inverse_depth=False,
|
| 462 |
+
train_time_distribution="uniform",
|
| 463 |
+
shift_clamp_percentiles=None,
|
| 464 |
+
)
|
| 465 |
+
stage3_config["model"]["net"].update(
|
| 466 |
+
temporal_block_size=4,
|
| 467 |
+
temporal_prefix_frames=1,
|
| 468 |
+
side_condition_channels=0,
|
| 469 |
+
sac_config=L(SACConfig)(mode="none"),
|
| 470 |
+
)
|
| 471 |
+
stage3_config["model"]["fsdp"]["use_orig_params"] = True
|
| 472 |
+
stage3_config["model"]["ema"].update(beta=0.99, num=1)
|
| 473 |
+
stage3_config["model"]["vae"] = {
|
| 474 |
+
"use_ema": False,
|
| 475 |
+
"encoder_is_bf16": True,
|
| 476 |
+
"decoder_is_bf16": False,
|
| 477 |
+
}
|
| 478 |
+
stage3_config["model_obj"] = L(FSDPHdmapToLidarSFDMDModel)(
|
| 479 |
+
config=PLACEHOLDER,
|
| 480 |
+
fsdp_checkpointer=PLACEHOLDER,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def register_experiments(cs: ConfigStore) -> None:
|
| 485 |
+
for name, node in (
|
| 486 |
+
(STAGE1_NAME, stage1_config),
|
| 487 |
+
(STAGE2_NAME, stage2_config),
|
| 488 |
+
(STAGE3_NAME, stage3_config),
|
| 489 |
+
):
|
| 490 |
+
cs.store(
|
| 491 |
+
group="experiment",
|
| 492 |
+
package="_global_",
|
| 493 |
+
name=name,
|
| 494 |
+
node=node,
|
| 495 |
+
)
|
diffusion/training/config/text2world_hdmaptolidar/experiment_pai_release.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""PAI post-training from processed release weights; no internal dataset roots."""
|
| 5 |
+
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
from diffusion.training.config.text2world_hdmaptolidar.experiment_lidarverse import (
|
| 10 |
+
stage1_config, stage2_config, stage3_config, _factorized_model_config,
|
| 11 |
+
)
|
| 12 |
+
from utils.processed_pai import loader_config
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def register_experiments(cs):
|
| 16 |
+
for stage, base, package in ((1, stage1_config, "bidir"), (2, stage2_config, "causal"), (3, stage3_config, "sfdmd")):
|
| 17 |
+
node = deepcopy(base)
|
| 18 |
+
name = f"lidarverse_pai_stage{stage}_finetune"
|
| 19 |
+
node.job.name = name
|
| 20 |
+
node.checkpoint.update(load_path=os.environ.get(f"LIDARVERSE_STAGE{stage}_CHECKPOINT",
|
| 21 |
+
f"checkpoints/lidarverse-{package}-pai/ema_model.pt"), load_training_state=False,
|
| 22 |
+
load_ema_to_reg=False, strict_resume=True, save_iter=200, save_at_iters=[])
|
| 23 |
+
node.trainer.update(max_iter=2000, run_validation=False)
|
| 24 |
+
node.scheduler.update(warm_up_steps=[0], cycle_lengths=[2000], f_start=[1.], f_max=[1.], f_min=[1.])
|
| 25 |
+
node.dataloader_train = loader_config()
|
| 26 |
+
node.dataloader_val = loader_config(validation=True)
|
| 27 |
+
model = node.model
|
| 28 |
+
factors = _factorized_model_config(21)
|
| 29 |
+
for key, value in factors.items():
|
| 30 |
+
if key.startswith(("stage2_factorized", "imaginaire_conditioned", "factorized_geometry_observation")):
|
| 31 |
+
model[key] = value
|
| 32 |
+
model.update(latent_shape=[64, 13 if stage == 3 else 21, 16, 128],
|
| 33 |
+
precision="bfloat16", enable_shift_stretch=False, shift_clamp_percentiles=None,
|
| 34 |
+
blockwise_warped_history_backend="torch_spatial_map",
|
| 35 |
+
blockwise_spatial_map_geometry_root_path="", blockwise_spatial_map_geometry_filter_list_path="",
|
| 36 |
+
blockwise_spatial_map_min_range=2.5, blockwise_spatial_map_max_range=100.,
|
| 37 |
+
blockwise_spatial_map_voxel_m=.10 if stage == 3 else .15, blockwise_spatial_map_radius_m=100.,
|
| 38 |
+
blockwise_spatial_map_voxel_policy="persistent_static",
|
| 39 |
+
blockwise_spatial_map_observation_unit="frame", blockwise_spatial_map_static_min_observations=2,
|
| 40 |
+
blockwise_spatial_map_include_latest=False, blockwise_spatial_map_candidate_ttl_updates=1,
|
| 41 |
+
blockwise_spatial_map_free_space_clear=True, blockwise_spatial_map_free_space_margin_m=.75,
|
| 42 |
+
blockwise_spatial_map_free_space_misses_to_remove=2)
|
| 43 |
+
model.net.update(patch_spatial=[1, 2], num_dataset_embeddings=3, rope_scale_positions_by_patch=True)
|
| 44 |
+
model.vae = dict(experiment_name="transformer_lidar_video_tokenizer_8x8x1_z64_pandar_2p5to100_1024_ema40k",
|
| 45 |
+
checkpoint_path=os.environ.get("LIDARVERSE_TOKENIZER_CHECKPOINT", "checkpoints/lidarverse-tokenizer-pai/ckpt.pt"),
|
| 46 |
+
mean_std_fp=os.environ.get("LIDARVERSE_TOKENIZER_LATENT_STATS", "checkpoints/lidarverse-tokenizer-pai/latent_stats.pt"),
|
| 47 |
+
use_ema=False, strict_checkpoint=True, is_bf16=False,
|
| 48 |
+
encoder_is_bf16=False, decoder_is_bf16=False)
|
| 49 |
+
if stage == 3:
|
| 50 |
+
model.update(sfdmd_num_real_frames=21, sfdmd_window_frames=13, sfdmd_min_range=2.5,
|
| 51 |
+
sfdmd_spatial_map_voxel_m=.10,
|
| 52 |
+
sfdmd_teacher_checkpoint=os.environ.get("LIDARVERSE_SCORE_CHECKPOINT",
|
| 53 |
+
"checkpoints/lidarverse-causal-pai/ema_model.pt"))
|
| 54 |
+
model.sfdmd_teacher_net.update(patch_spatial=[1, 2], num_dataset_embeddings=3,
|
| 55 |
+
rope_scale_positions_by_patch=True)
|
| 56 |
+
cs.store(group="experiment", package="_global_", name=name, node=node)
|
diffusion/training/context_parallel.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from torch.distributed import ProcessGroup, all_gather, get_process_group_ranks, get_world_size
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def split_inputs_cp(x: Tensor, seq_dim: int, cp_group: ProcessGroup) -> Tensor:
|
| 22 |
+
"""
|
| 23 |
+
Split input tensor along the sequence dimension for checkpoint parallelism.
|
| 24 |
+
|
| 25 |
+
This function divides the input tensor into equal parts along the specified
|
| 26 |
+
sequence dimension, based on the number of ranks in the checkpoint parallelism group.
|
| 27 |
+
It then selects the part corresponding to the current rank.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
x: Input tensor to be split.
|
| 31 |
+
seq_dim: The dimension along which to split the input (sequence dimension).
|
| 32 |
+
cp_group: The process group for checkpoint parallelism.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
A slice of the input tensor corresponding to the current rank.
|
| 36 |
+
|
| 37 |
+
Raises:
|
| 38 |
+
AssertionError: If the sequence dimension is not divisible by the number of ranks.
|
| 39 |
+
"""
|
| 40 |
+
cp_ranks = get_process_group_ranks(cp_group)
|
| 41 |
+
cp_size = len(cp_ranks)
|
| 42 |
+
|
| 43 |
+
assert x.shape[seq_dim] % cp_size == 0, f"{x.shape[seq_dim]} cannot divide cp_size {cp_size}"
|
| 44 |
+
x = x.view(*x.shape[:seq_dim], cp_size, x.shape[seq_dim] // cp_size, *x.shape[(seq_dim + 1) :])
|
| 45 |
+
seq_idx = torch.tensor([cp_group.rank()], device=x.device)
|
| 46 |
+
x = x.index_select(seq_dim, seq_idx)
|
| 47 |
+
# Note that the new sequence length is the original sequence length / cp_size
|
| 48 |
+
x = x.view(*x.shape[:seq_dim], -1, *x.shape[(seq_dim + 2) :])
|
| 49 |
+
return x
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def cat_outputs_cp(x: Tensor, seq_dim: int, cp_group: ProcessGroup) -> Tensor:
|
| 53 |
+
"""
|
| 54 |
+
Concatenate outputs from different ranks in the checkpoint parallelism group.
|
| 55 |
+
|
| 56 |
+
This function gathers tensors from all ranks in the checkpoint parallelism group
|
| 57 |
+
and concatenates them along the specified sequence dimension.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
x: Input tensor to be concatenated.
|
| 61 |
+
seq_dim: The dimension along which to concatenate the tensors (sequence dimension).
|
| 62 |
+
cp_group: The process group for checkpoint parallelism.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
A tensor that is the concatenation of tensors from all ranks in the cp_group.
|
| 66 |
+
|
| 67 |
+
Raises:
|
| 68 |
+
RuntimeError: If the gather operation fails.
|
| 69 |
+
"""
|
| 70 |
+
# Get the world size (number of processes in the group)
|
| 71 |
+
world_size = get_world_size(cp_group)
|
| 72 |
+
|
| 73 |
+
# Create a list to store tensors from all ranks
|
| 74 |
+
gathered_tensors = [torch.zeros_like(x) for _ in range(world_size)]
|
| 75 |
+
|
| 76 |
+
# Gather tensors from all ranks
|
| 77 |
+
try:
|
| 78 |
+
all_gather(gathered_tensors, x, group=cp_group)
|
| 79 |
+
except RuntimeError as e:
|
| 80 |
+
raise RuntimeError(f"Failed to gather tensors: {e}")
|
| 81 |
+
|
| 82 |
+
# Concatenate the gathered tensors along the specified dimension
|
| 83 |
+
return torch.cat(gathered_tensors, dim=seq_dim)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def cat_outputs_cp_with_grad(x: Tensor, seq_dim: int, cp_group: ProcessGroup) -> Tensor:
|
| 87 |
+
"""
|
| 88 |
+
Concatenate outputs from different ranks in the context parallelism group.
|
| 89 |
+
|
| 90 |
+
This function gathers tensors from all ranks in the checkpoint parallelism group
|
| 91 |
+
and concatenates them along the specified sequence dimension.
|
| 92 |
+
|
| 93 |
+
It retains computational graph locally for each rank by replacing the portion of the tensor with original output.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
x: Input tensor to be concatenated.
|
| 97 |
+
seq_dim: The dimension along which to concatenate the tensors (sequence dimension).
|
| 98 |
+
cp_group: The process group for checkpoint parallelism.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
A tensor that is the concatenation of tensors from all ranks in the cp_group.
|
| 102 |
+
|
| 103 |
+
Raises:
|
| 104 |
+
RuntimeError: If the gather operation fails.
|
| 105 |
+
"""
|
| 106 |
+
# Get the world size (number of processes in the group)
|
| 107 |
+
cp_size = cp_group.size()
|
| 108 |
+
assert cp_size > 0, "cp_size should be greater than 0"
|
| 109 |
+
|
| 110 |
+
# Create a list to store tensors from all ranks
|
| 111 |
+
gathered_tensors = [torch.zeros_like(x) for _ in range(cp_size)]
|
| 112 |
+
|
| 113 |
+
# Gather tensors from all ranks
|
| 114 |
+
try:
|
| 115 |
+
all_gather(gathered_tensors, x, group=cp_group)
|
| 116 |
+
except RuntimeError as e:
|
| 117 |
+
raise RuntimeError(f"Failed to gather tensors: {e}")
|
| 118 |
+
|
| 119 |
+
rank = cp_group.rank()
|
| 120 |
+
gathered_tensors[rank] = x
|
| 121 |
+
# Concatenate the gathered tensors along the specified dimension
|
| 122 |
+
return torch.cat(gathered_tensors, dim=seq_dim)
|
diffusion/training/datasets/lidar_dataset/configs.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 4 |
+
|
| 5 |
+
"""Public HDMap-to-LiDAR dataset contracts for LidarVerse.
|
| 6 |
+
|
| 7 |
+
The released training recipe uses NVIDIA PAI and nuScenes. The Waymo entries
|
| 8 |
+
are a generic NCore adapter for users who independently prepare that dataset;
|
| 9 |
+
they are not part of the released checkpoint's training lineage.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _path(name: str, default: str) -> str:
|
| 16 |
+
return os.path.expanduser(os.environ.get(name, default))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _base_hdmap_video(
|
| 20 |
+
*,
|
| 21 |
+
data_name: str,
|
| 22 |
+
root: str,
|
| 23 |
+
split: str,
|
| 24 |
+
hdmap_root: str,
|
| 25 |
+
backend: str,
|
| 26 |
+
height: int,
|
| 27 |
+
width: int,
|
| 28 |
+
lidar_length: int,
|
| 29 |
+
sensor_fps: float,
|
| 30 |
+
sensor_name: str,
|
| 31 |
+
) -> dict:
|
| 32 |
+
custom_folders = [root, root] if backend == "radym" else [root]
|
| 33 |
+
return {
|
| 34 |
+
"data_name": data_name,
|
| 35 |
+
"root_path": root,
|
| 36 |
+
"filter_list_path": split,
|
| 37 |
+
"t5_embedding_path": "",
|
| 38 |
+
"custom_folders": custom_folders,
|
| 39 |
+
"custom_fields": ["lidar", "hdmap"],
|
| 40 |
+
"metadata_folder": "",
|
| 41 |
+
"max_range": 100.0,
|
| 42 |
+
"min_range": 2.5,
|
| 43 |
+
"downsample_factor_row": 1,
|
| 44 |
+
"downsample_factor_col": 1,
|
| 45 |
+
"repeat_row": 1,
|
| 46 |
+
"repeat_col": 1,
|
| 47 |
+
"repeat_temporal": 1,
|
| 48 |
+
"lidar_crop_size": [-1, -1],
|
| 49 |
+
"rgb_crop_size": [-1, -1],
|
| 50 |
+
"rgb_resize_size": [-1, -1],
|
| 51 |
+
"lidar_size": [height, width],
|
| 52 |
+
"lidar_resize_size": [-1, -1],
|
| 53 |
+
"downsample_method": "scatter_min",
|
| 54 |
+
"min_value": -1.0,
|
| 55 |
+
"num_views": 0,
|
| 56 |
+
"sample_n_frames": 21,
|
| 57 |
+
"lidar_length": lidar_length,
|
| 58 |
+
"frame_sampling_method": "sequential",
|
| 59 |
+
"frame_sampling_every_n_frames": 1,
|
| 60 |
+
"sample_lidar_prob": 1.0,
|
| 61 |
+
"is_video_tokenizer": False,
|
| 62 |
+
"load_lidar_only": True,
|
| 63 |
+
"load_rgb_only": False,
|
| 64 |
+
"load_lidar_and_rgb": False,
|
| 65 |
+
"load_lidar_or_rgb": False,
|
| 66 |
+
"RGB_FPS": 30,
|
| 67 |
+
"LIDAR_FPS": int(round(sensor_fps)),
|
| 68 |
+
"load_t5_embeddings": False,
|
| 69 |
+
"inverse_depth": False,
|
| 70 |
+
"process_input": "mono",
|
| 71 |
+
"load_intensity": False,
|
| 72 |
+
"dataset_backend": backend,
|
| 73 |
+
"resample_width": width if backend.endswith("_ncore") else -1,
|
| 74 |
+
"center_vehicle_forward": backend == "nuscenes_ncore",
|
| 75 |
+
"hdmap_root": hdmap_root,
|
| 76 |
+
"hdmap_multichannel": False,
|
| 77 |
+
"hdmap_moving_only": False,
|
| 78 |
+
"hdmap_include_boxes": True,
|
| 79 |
+
"hdmap_map_max_dist": 100.0,
|
| 80 |
+
"hdmap_pose_for_lidar_to_world": backend == "nuscenes_ncore",
|
| 81 |
+
"sensor_fps": sensor_fps,
|
| 82 |
+
"sensor_dataset_name": sensor_name,
|
| 83 |
+
"sensor_dataset_id": -1,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
_PAI_ROOT = _path("LIDARVERSE_NVIDIA_PAI_ROOT", "data/nvidia_pai")
|
| 88 |
+
_NUSCENES_ROOT = _path("LIDARVERSE_NUSCENES_ROOT", "data/nuscenes_ncore")
|
| 89 |
+
_WAYMO_TRAIN_ROOT = _path(
|
| 90 |
+
"LIDARVERSE_WAYMO_ROOT", "data/waymo_ncore/training"
|
| 91 |
+
)
|
| 92 |
+
_WAYMO_VAL_ROOT = _path(
|
| 93 |
+
"LIDARVERSE_WAYMO_VAL_ROOT", "data/waymo_ncore/validation"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
COMMONDATA_CONFIG = {
|
| 97 |
+
"lidarverse_nvidia_pai_train": _base_hdmap_video(
|
| 98 |
+
data_name="mads_range_map",
|
| 99 |
+
root=_PAI_ROOT,
|
| 100 |
+
split=_path(
|
| 101 |
+
"LIDARVERSE_NVIDIA_PAI_TRAIN_LIST",
|
| 102 |
+
"data/splits/nvidia_pai_train.lst",
|
| 103 |
+
),
|
| 104 |
+
hdmap_root=_PAI_ROOT,
|
| 105 |
+
backend="radym",
|
| 106 |
+
height=128,
|
| 107 |
+
width=1200,
|
| 108 |
+
lidar_length=200,
|
| 109 |
+
sensor_fps=10.0,
|
| 110 |
+
sensor_name="nvidia_pai",
|
| 111 |
+
),
|
| 112 |
+
"lidarverse_nuscenes_train": _base_hdmap_video(
|
| 113 |
+
data_name="nuscenes_lidar_range_map",
|
| 114 |
+
root=_NUSCENES_ROOT,
|
| 115 |
+
split=_path(
|
| 116 |
+
"LIDARVERSE_NUSCENES_TRAIN_LIST",
|
| 117 |
+
"data/splits/nuscenes_train.lst",
|
| 118 |
+
),
|
| 119 |
+
hdmap_root=_path(
|
| 120 |
+
"LIDARVERSE_NUSCENES_HDMAP_ROOT", "data/nuscenes_hdmap"
|
| 121 |
+
),
|
| 122 |
+
backend="nuscenes_ncore",
|
| 123 |
+
height=32,
|
| 124 |
+
width=1024,
|
| 125 |
+
lidar_length=380,
|
| 126 |
+
sensor_fps=2.0,
|
| 127 |
+
sensor_name="nuscenes",
|
| 128 |
+
),
|
| 129 |
+
"lidarverse_waymo_train": _base_hdmap_video(
|
| 130 |
+
data_name="waymo_lidar_range_map",
|
| 131 |
+
root=_WAYMO_TRAIN_ROOT,
|
| 132 |
+
split=_path(
|
| 133 |
+
"LIDARVERSE_WAYMO_TRAIN_LIST", "data/splits/waymo_train.lst"
|
| 134 |
+
),
|
| 135 |
+
hdmap_root=_path(
|
| 136 |
+
"LIDARVERSE_WAYMO_HDMAP_ROOT", "data/waymo_hdmap/training"
|
| 137 |
+
),
|
| 138 |
+
backend="waymo_ncore",
|
| 139 |
+
height=64,
|
| 140 |
+
width=1024,
|
| 141 |
+
lidar_length=199,
|
| 142 |
+
sensor_fps=10.0,
|
| 143 |
+
sensor_name="waymo",
|
| 144 |
+
),
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
for dataset, env_name, default in (
|
| 148 |
+
(
|
| 149 |
+
"nvidia_pai",
|
| 150 |
+
"LIDARVERSE_NVIDIA_PAI_VAL_LIST",
|
| 151 |
+
"data/splits/nvidia_pai_val.lst",
|
| 152 |
+
),
|
| 153 |
+
(
|
| 154 |
+
"nuscenes",
|
| 155 |
+
"LIDARVERSE_NUSCENES_VAL_LIST",
|
| 156 |
+
"data/splits/nuscenes_val.lst",
|
| 157 |
+
),
|
| 158 |
+
):
|
| 159 |
+
source = f"lidarverse_{dataset}_train"
|
| 160 |
+
target = f"lidarverse_{dataset}_val"
|
| 161 |
+
COMMONDATA_CONFIG[target] = dict(COMMONDATA_CONFIG[source])
|
| 162 |
+
COMMONDATA_CONFIG[target]["filter_list_path"] = _path(env_name, default)
|
| 163 |
+
|
| 164 |
+
COMMONDATA_CONFIG["lidarverse_waymo_val"] = _base_hdmap_video(
|
| 165 |
+
data_name="waymo_lidar_range_map",
|
| 166 |
+
root=_WAYMO_VAL_ROOT,
|
| 167 |
+
split=_path(
|
| 168 |
+
"LIDARVERSE_WAYMO_VAL_LIST", "data/splits/waymo_val.lst"
|
| 169 |
+
),
|
| 170 |
+
hdmap_root=_path(
|
| 171 |
+
"LIDARVERSE_WAYMO_VAL_HDMAP_ROOT", "data/waymo_hdmap/validation"
|
| 172 |
+
),
|
| 173 |
+
backend="waymo_ncore",
|
| 174 |
+
height=64,
|
| 175 |
+
width=1024,
|
| 176 |
+
lidar_length=199,
|
| 177 |
+
sensor_fps=10.0,
|
| 178 |
+
sensor_name="waymo",
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# Native PAI columns are reduced to the trained 1200-column grid.
|
| 182 |
+
for split in ("train", "val"):
|
| 183 |
+
config = COMMONDATA_CONFIG[f"lidarverse_nvidia_pai_{split}"]
|
| 184 |
+
config["metadata_folder"] = _path(
|
| 185 |
+
"LIDARVERSE_NVIDIA_PAI_METADATA", "data/nvidia_pai/metadata"
|
| 186 |
+
)
|
| 187 |
+
config["downsample_factor_col"] = 3
|
diffusion/training/datasets/lidar_dataset/forecast_warp.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffusion/training/datasets/lidar_dataset/hdmaptolidar_dataloader.py
ADDED
|
@@ -0,0 +1,960 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Dataloader for hdmap-to-lidar diffusion training.
|
| 5 |
+
|
| 6 |
+
Loads lidar range-map + HD-map conditioning, reusing the diffusion
|
| 7 |
+
``LidarRangeMapSampler`` infrastructure and adding the metadata fields
|
| 8 |
+
expected by the Cosmos diffusion training loop (t5 embeddings, fps, etc.).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import gc
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
from omegaconf import OmegaConf
|
| 18 |
+
from torch.utils.data import DataLoader, Dataset, Sampler
|
| 19 |
+
|
| 20 |
+
from diffusion.training.datasets.lidar_dataset.configs import COMMONDATA_CONFIG
|
| 21 |
+
from diffusion.training.datasets.lidar_dataset.imagetolidar_dataloader import (
|
| 22 |
+
LidarRangeMapSampler,
|
| 23 |
+
dict_collation_fn,
|
| 24 |
+
frames_as_batch_collation_fn,
|
| 25 |
+
)
|
| 26 |
+
from diffusion.training.datasets.lidar_dataset.forecast_warp import (
|
| 27 |
+
compose_normalized_range_channels,
|
| 28 |
+
warp_blockwise_history_to_video,
|
| 29 |
+
)
|
| 30 |
+
from diffusion.training.datasets.lidar_dataset.waymo_track_ids import (
|
| 31 |
+
resolve_waymo_box_track_ids_from_ncore,
|
| 32 |
+
)
|
| 33 |
+
from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField
|
| 34 |
+
from tokenizer.training.datasets.lidar_datasets.waymo_ncore import (
|
| 35 |
+
load_waymo_lidar_geometry,
|
| 36 |
+
)
|
| 37 |
+
from utils import log
|
| 38 |
+
from utils.lazy_config import LazyCall as L
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
from megatron.core import parallel_state
|
| 42 |
+
except ImportError:
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class HdmapLidarSampler(LidarRangeMapSampler):
|
| 47 |
+
"""Dataset that returns lidar range-map + HD-map with diffusion metadata.
|
| 48 |
+
|
| 49 |
+
Inherits all lidar/hdmap loading logic from the existing
|
| 50 |
+
``LidarRangeMapSampler`` and adds the metadata fields required by the
|
| 51 |
+
Cosmos diffusion training loop.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
blockwise_warped_history_condition: bool = False,
|
| 57 |
+
blockwise_warped_history_block_size: int = 3,
|
| 58 |
+
blockwise_warped_history_mode: str = "all",
|
| 59 |
+
autoregressive_pair: bool = False,
|
| 60 |
+
autoregressive_previous_root: str = "",
|
| 61 |
+
autoregressive_generated_previous_prob: float = 0.0,
|
| 62 |
+
autoregressive_include_static_boxes: bool = False,
|
| 63 |
+
synthesize_null_hdmap: bool = False,
|
| 64 |
+
return_hdmap_semantic: bool = False,
|
| 65 |
+
return_moving_boxes: bool = False,
|
| 66 |
+
resolve_moving_box_track_ids: bool = False,
|
| 67 |
+
return_full_lidar_metadata: bool = False,
|
| 68 |
+
moving_box_limit: int = 256,
|
| 69 |
+
moving_box_root: str = "",
|
| 70 |
+
sensor_fps: float = 24.0,
|
| 71 |
+
emit_sensor_metadata: bool = False,
|
| 72 |
+
sensor_dataset_id: int = -1,
|
| 73 |
+
sensor_dataset_name: str = "",
|
| 74 |
+
**kwargs,
|
| 75 |
+
):
|
| 76 |
+
self.sensor_fps = float(sensor_fps)
|
| 77 |
+
if self.sensor_fps <= 0.0:
|
| 78 |
+
raise ValueError(
|
| 79 |
+
f"sensor_fps must be positive, got {self.sensor_fps}"
|
| 80 |
+
)
|
| 81 |
+
self.emit_sensor_metadata = bool(emit_sensor_metadata)
|
| 82 |
+
self.sensor_dataset_id = int(sensor_dataset_id)
|
| 83 |
+
self.sensor_dataset_name = str(
|
| 84 |
+
sensor_dataset_name or kwargs.get("data_name", "")
|
| 85 |
+
)
|
| 86 |
+
self._sensor_root_path = kwargs.get("root_path")
|
| 87 |
+
self._sensor_filter_list_path = kwargs.get("filter_list_path")
|
| 88 |
+
self._sensor_center_vehicle_forward = bool(
|
| 89 |
+
kwargs.get("center_vehicle_forward", True)
|
| 90 |
+
)
|
| 91 |
+
self._sensor_ray_directions = None
|
| 92 |
+
self.autoregressive_pair = bool(autoregressive_pair)
|
| 93 |
+
self.autoregressive_target_frames = int(
|
| 94 |
+
kwargs.get("sample_n_frames", 1)
|
| 95 |
+
)
|
| 96 |
+
if self.autoregressive_pair:
|
| 97 |
+
if self.autoregressive_target_frames != 1:
|
| 98 |
+
raise ValueError(
|
| 99 |
+
"autoregressive_pair currently requires "
|
| 100 |
+
"sample_n_frames=1"
|
| 101 |
+
)
|
| 102 |
+
if bool(kwargs.get("is_video_tokenizer", False)):
|
| 103 |
+
raise ValueError(
|
| 104 |
+
"autoregressive_pair requires a per-frame tokenizer"
|
| 105 |
+
)
|
| 106 |
+
kwargs["sample_n_frames"] = 2
|
| 107 |
+
if kwargs.get("dataset_backend", "radym") == "radym":
|
| 108 |
+
custom_folders = kwargs.get("custom_folders")
|
| 109 |
+
custom_fields = kwargs.get("custom_fields")
|
| 110 |
+
if (
|
| 111 |
+
custom_folders is not None
|
| 112 |
+
and custom_fields is not None
|
| 113 |
+
and len(custom_folders) != len(custom_fields)
|
| 114 |
+
):
|
| 115 |
+
raise ValueError(
|
| 116 |
+
"Radym custom_folders and custom_fields must have the "
|
| 117 |
+
"same length, got "
|
| 118 |
+
f"{len(custom_folders)} and {len(custom_fields)}"
|
| 119 |
+
)
|
| 120 |
+
super().__init__(**kwargs)
|
| 121 |
+
self.autoregressive_previous_root = str(
|
| 122 |
+
autoregressive_previous_root
|
| 123 |
+
)
|
| 124 |
+
self.autoregressive_generated_previous_prob = float(
|
| 125 |
+
autoregressive_generated_previous_prob
|
| 126 |
+
)
|
| 127 |
+
self.autoregressive_include_static_boxes = bool(
|
| 128 |
+
autoregressive_include_static_boxes
|
| 129 |
+
)
|
| 130 |
+
if not 0.0 <= self.autoregressive_generated_previous_prob <= 1.0:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
"autoregressive_generated_previous_prob must be in [0,1]"
|
| 133 |
+
)
|
| 134 |
+
if (
|
| 135 |
+
self.autoregressive_generated_previous_prob > 0.0
|
| 136 |
+
and not self.autoregressive_previous_root
|
| 137 |
+
):
|
| 138 |
+
raise ValueError(
|
| 139 |
+
"generated previous-frame sampling requires "
|
| 140 |
+
"autoregressive_previous_root"
|
| 141 |
+
)
|
| 142 |
+
self.synthesize_null_hdmap = bool(synthesize_null_hdmap)
|
| 143 |
+
self.return_hdmap_semantic = bool(return_hdmap_semantic)
|
| 144 |
+
self.return_moving_boxes = bool(return_moving_boxes)
|
| 145 |
+
self.resolve_moving_box_track_ids = bool(
|
| 146 |
+
resolve_moving_box_track_ids
|
| 147 |
+
)
|
| 148 |
+
self.return_full_lidar_metadata = bool(
|
| 149 |
+
return_full_lidar_metadata
|
| 150 |
+
)
|
| 151 |
+
self.moving_box_limit = int(moving_box_limit)
|
| 152 |
+
self.moving_box_root = str(moving_box_root)
|
| 153 |
+
if (
|
| 154 |
+
self.return_hdmap_semantic
|
| 155 |
+
and self.dataset_backend != "waymo_ncore"
|
| 156 |
+
):
|
| 157 |
+
raise ValueError(
|
| 158 |
+
"semantic HDMap output requires "
|
| 159 |
+
"dataset_backend='waymo_ncore'"
|
| 160 |
+
)
|
| 161 |
+
if self.return_hdmap_semantic and not bool(
|
| 162 |
+
self._hdmap_kwargs["hdmap_multichannel"]
|
| 163 |
+
):
|
| 164 |
+
raise ValueError(
|
| 165 |
+
"return_hdmap_semantic requires hdmap_multichannel=True"
|
| 166 |
+
)
|
| 167 |
+
if self.return_moving_boxes and self.moving_box_limit <= 0:
|
| 168 |
+
raise ValueError("moving_box_limit must be positive")
|
| 169 |
+
if (
|
| 170 |
+
self.return_moving_boxes
|
| 171 |
+
and self.dataset_backend == "radym"
|
| 172 |
+
and not self.moving_box_root
|
| 173 |
+
):
|
| 174 |
+
raise ValueError(
|
| 175 |
+
"radym moving-box output requires moving_box_root"
|
| 176 |
+
)
|
| 177 |
+
if (
|
| 178 |
+
self.resolve_moving_box_track_ids
|
| 179 |
+
and self.dataset_backend != "waymo_ncore"
|
| 180 |
+
):
|
| 181 |
+
raise ValueError(
|
| 182 |
+
"NCore track-ID resolution is only defined for Waymo"
|
| 183 |
+
)
|
| 184 |
+
if self.synthesize_null_hdmap:
|
| 185 |
+
# Preserve the LiDAR + HDMap conditioner view count even though the
|
| 186 |
+
# underlying NCore reader was asked to load only LiDAR.
|
| 187 |
+
self.plus = 2
|
| 188 |
+
self.blockwise_warped_history_condition = bool(
|
| 189 |
+
blockwise_warped_history_condition
|
| 190 |
+
)
|
| 191 |
+
self.blockwise_warped_history_block_size = int(
|
| 192 |
+
blockwise_warped_history_block_size
|
| 193 |
+
)
|
| 194 |
+
self.blockwise_warped_history_mode = str(
|
| 195 |
+
blockwise_warped_history_mode
|
| 196 |
+
)
|
| 197 |
+
self._blockwise_warp_geometry = None
|
| 198 |
+
self._blockwise_warp_geometry_args = None
|
| 199 |
+
if self.blockwise_warped_history_condition:
|
| 200 |
+
if self.dataset_backend != "waymo_ncore":
|
| 201 |
+
raise ValueError(
|
| 202 |
+
"blockwise warped-history conditioning requires "
|
| 203 |
+
f"dataset_backend='waymo_ncore', got {self.dataset_backend!r}"
|
| 204 |
+
)
|
| 205 |
+
if self.process_input != "mono":
|
| 206 |
+
raise ValueError(
|
| 207 |
+
"blockwise warped-history conditioning requires "
|
| 208 |
+
f"process_input='mono', got {self.process_input!r}"
|
| 209 |
+
)
|
| 210 |
+
if not self.is_video_tokenizer:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"blockwise warped-history conditioning requires a video "
|
| 213 |
+
"tokenizer with frame-0 prepend"
|
| 214 |
+
)
|
| 215 |
+
if self.blockwise_warped_history_block_size <= 0:
|
| 216 |
+
raise ValueError(
|
| 217 |
+
"blockwise_warped_history_block_size must be positive"
|
| 218 |
+
)
|
| 219 |
+
if self.blockwise_warped_history_mode not in ("latest", "all"):
|
| 220 |
+
raise ValueError(
|
| 221 |
+
"blockwise_warped_history_mode must be 'latest' or 'all', "
|
| 222 |
+
f"got {self.blockwise_warped_history_mode!r}"
|
| 223 |
+
)
|
| 224 |
+
self._blockwise_warp_geometry_args = dict(
|
| 225 |
+
root_path=kwargs["root_path"],
|
| 226 |
+
filter_list_path=kwargs.get("filter_list_path"),
|
| 227 |
+
resample_width=int(kwargs.get("resample_width", -1)),
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
def get_sensor_metadata(self, height: int, width: int) -> dict:
|
| 231 |
+
"""Return the calibrated native ray grid for cross-dataset training."""
|
| 232 |
+
if not self.emit_sensor_metadata:
|
| 233 |
+
return {}
|
| 234 |
+
if self._sensor_ray_directions is None:
|
| 235 |
+
if self.dataset_backend == "waymo_ncore":
|
| 236 |
+
from tokenizer.training.datasets.lidar_datasets.waymo_ncore import (
|
| 237 |
+
load_waymo_ray_directions,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
rays = load_waymo_ray_directions(
|
| 241 |
+
root_path=self._sensor_root_path,
|
| 242 |
+
filter_list_path=self._sensor_filter_list_path,
|
| 243 |
+
lidar_id="lidar_top",
|
| 244 |
+
resample_width=self.resample_width,
|
| 245 |
+
)
|
| 246 |
+
elif self.dataset_backend == "nuscenes_ncore":
|
| 247 |
+
from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import (
|
| 248 |
+
load_nuscenes_ray_directions,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
rays = load_nuscenes_ray_directions(
|
| 252 |
+
root_path=self._sensor_root_path,
|
| 253 |
+
filter_list_path=self._sensor_filter_list_path,
|
| 254 |
+
lidar_id="lidar_top",
|
| 255 |
+
resample_width=self.resample_width,
|
| 256 |
+
center_vehicle_forward=self._sensor_center_vehicle_forward,
|
| 257 |
+
)
|
| 258 |
+
else:
|
| 259 |
+
from utils.lidar_rangemap import (
|
| 260 |
+
load_pandar128_elevations,
|
| 261 |
+
range_map_to_ray_directions,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
elevations = torch.tensor(
|
| 265 |
+
load_pandar128_elevations(), dtype=torch.float32
|
| 266 |
+
)
|
| 267 |
+
rays = range_map_to_ray_directions(
|
| 268 |
+
width // self.repeat_col, elevations
|
| 269 |
+
)
|
| 270 |
+
rays = torch.as_tensor(rays, dtype=torch.float32)
|
| 271 |
+
rays = rays.repeat_interleave(self.repeat_row, dim=0)
|
| 272 |
+
rays = rays.repeat_interleave(self.repeat_col, dim=1)
|
| 273 |
+
if tuple(rays.shape) != (height, width, 3):
|
| 274 |
+
raise ValueError(
|
| 275 |
+
"sensor rays must match the repeated native grid: "
|
| 276 |
+
f"rays={tuple(rays.shape)}, sample={(height, width, 3)}"
|
| 277 |
+
)
|
| 278 |
+
self._sensor_ray_directions = rays.contiguous()
|
| 279 |
+
return {
|
| 280 |
+
"sensor_ray_directions": self._sensor_ray_directions,
|
| 281 |
+
"sensor_depth_bounds": torch.tensor(
|
| 282 |
+
[self.min_distance, self.max_distance], dtype=torch.float32
|
| 283 |
+
),
|
| 284 |
+
"sensor_dataset_id": self.sensor_dataset_id,
|
| 285 |
+
"sensor_dataset_name": self.sensor_dataset_name,
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
def _radym_moving_box_arrays(self, example):
|
| 289 |
+
key = str(example["__key__"])
|
| 290 |
+
frame_names = []
|
| 291 |
+
for value in example["rgb_frame_indices"]:
|
| 292 |
+
frame_name = str(value)
|
| 293 |
+
if frame_name.isdigit():
|
| 294 |
+
frame_name = f"{int(frame_name):06d}"
|
| 295 |
+
frame_names.append(frame_name)
|
| 296 |
+
tar_handle = self.dataset._get_tar_handle(
|
| 297 |
+
self.moving_box_root, "all_object_info", key
|
| 298 |
+
)
|
| 299 |
+
frame_payloads = []
|
| 300 |
+
actor_names = set()
|
| 301 |
+
for frame_name in frame_names:
|
| 302 |
+
member_name = (
|
| 303 |
+
f"{key}.{frame_name}.all_object_info.json"
|
| 304 |
+
)
|
| 305 |
+
member = tar_handle.extractfile(member_name)
|
| 306 |
+
if member is None:
|
| 307 |
+
raise FileNotFoundError(
|
| 308 |
+
f"missing moving-box metadata {member_name}"
|
| 309 |
+
)
|
| 310 |
+
payload = json.load(member)
|
| 311 |
+
frame_payloads.append(payload)
|
| 312 |
+
actor_names.update(payload)
|
| 313 |
+
ordered_names = sorted(
|
| 314 |
+
actor_names,
|
| 315 |
+
key=lambda value: (
|
| 316 |
+
0, int(value)
|
| 317 |
+
) if str(value).isdigit() else (1, str(value)),
|
| 318 |
+
)
|
| 319 |
+
track_ids = {
|
| 320 |
+
actor_name: index
|
| 321 |
+
for index, actor_name in enumerate(ordered_names)
|
| 322 |
+
}
|
| 323 |
+
type_ids = {"Car": 0, "Pedestrian": 1, "Cyclist": 2}
|
| 324 |
+
box_frame = []
|
| 325 |
+
box_o2w = []
|
| 326 |
+
box_lwh = []
|
| 327 |
+
box_type = []
|
| 328 |
+
box_moving = []
|
| 329 |
+
box_track_id = []
|
| 330 |
+
for local_frame, payload in enumerate(frame_payloads):
|
| 331 |
+
for actor_name, actor in payload.items():
|
| 332 |
+
box_frame.append(local_frame)
|
| 333 |
+
box_o2w.append(actor["object_to_world"])
|
| 334 |
+
box_lwh.append(actor["object_lwh"])
|
| 335 |
+
box_type.append(type_ids.get(actor["object_type"], -1))
|
| 336 |
+
box_moving.append(bool(actor["object_is_moving"]))
|
| 337 |
+
box_track_id.append(track_ids[actor_name])
|
| 338 |
+
if box_frame:
|
| 339 |
+
return (
|
| 340 |
+
np.asarray(box_frame, dtype=np.int64),
|
| 341 |
+
np.asarray(box_o2w, dtype=np.float32),
|
| 342 |
+
np.asarray(box_lwh, dtype=np.float32),
|
| 343 |
+
np.asarray(box_type, dtype=np.int64),
|
| 344 |
+
np.asarray(box_moving, dtype=bool),
|
| 345 |
+
np.asarray(box_track_id, dtype=np.int64),
|
| 346 |
+
np.arange(len(frame_names), dtype=np.int64),
|
| 347 |
+
)
|
| 348 |
+
return (
|
| 349 |
+
np.zeros((0,), dtype=np.int64),
|
| 350 |
+
np.zeros((0, 4, 4), dtype=np.float32),
|
| 351 |
+
np.zeros((0, 3), dtype=np.float32),
|
| 352 |
+
np.zeros((0,), dtype=np.int64),
|
| 353 |
+
np.zeros((0,), dtype=bool),
|
| 354 |
+
np.zeros((0,), dtype=np.int64),
|
| 355 |
+
np.arange(len(frame_names), dtype=np.int64),
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
def _moving_boxes_for_sample(self, example):
|
| 359 |
+
if self.dataset_backend == "radym":
|
| 360 |
+
(
|
| 361 |
+
box_frame,
|
| 362 |
+
box_o2w,
|
| 363 |
+
box_lwh,
|
| 364 |
+
box_type,
|
| 365 |
+
box_moving,
|
| 366 |
+
track_ids,
|
| 367 |
+
frame_indices,
|
| 368 |
+
) = self._radym_moving_box_arrays(example)
|
| 369 |
+
else:
|
| 370 |
+
composer = self.dataset.composers.get(example["__key__"])
|
| 371 |
+
if composer is None:
|
| 372 |
+
raise RuntimeError(
|
| 373 |
+
"moving-box output requires a cached HDMap composer"
|
| 374 |
+
)
|
| 375 |
+
track_ids = getattr(
|
| 376 |
+
composer, "_resolved_box_track_ids", None
|
| 377 |
+
)
|
| 378 |
+
if track_ids is None and self.resolve_moving_box_track_ids:
|
| 379 |
+
loader = self.dataset._get_loader(example["__key__"])
|
| 380 |
+
lidar_sensor = loader.get_lidar_sensor(
|
| 381 |
+
self.dataset.lidar_id
|
| 382 |
+
)
|
| 383 |
+
track_ids, metadata = (
|
| 384 |
+
resolve_waymo_box_track_ids_from_ncore(
|
| 385 |
+
hdmap_composer=composer,
|
| 386 |
+
sequence_loader=loader,
|
| 387 |
+
lidar_sensor=lidar_sensor,
|
| 388 |
+
)
|
| 389 |
+
)
|
| 390 |
+
composer._resolved_box_track_ids = track_ids
|
| 391 |
+
composer._resolved_box_track_id_metadata = metadata
|
| 392 |
+
if track_ids is None:
|
| 393 |
+
track_ids = composer.box_track_id
|
| 394 |
+
box_frame = np.asarray(composer.box_frame, dtype=np.int64)
|
| 395 |
+
box_o2w = np.asarray(composer.box_o2w, dtype=np.float32)
|
| 396 |
+
box_lwh = np.asarray(composer.box_lwh, dtype=np.float32)
|
| 397 |
+
box_type = np.asarray(composer.box_type, dtype=np.int64)
|
| 398 |
+
box_moving = np.asarray(composer.box_moving, dtype=bool)
|
| 399 |
+
track_ids = np.asarray(track_ids, dtype=np.int64)
|
| 400 |
+
frame_indices = np.asarray(
|
| 401 |
+
example["rgb_frame_indices"], dtype=np.int64
|
| 402 |
+
)
|
| 403 |
+
if bool((box_moving & (track_ids < 0)).any()):
|
| 404 |
+
raise ValueError(
|
| 405 |
+
"moving actors have no persistent track IDs; refresh the "
|
| 406 |
+
"dataset's HDMap/box metadata"
|
| 407 |
+
)
|
| 408 |
+
moving_rows = box_moving
|
| 409 |
+
dynamic_track_ids = np.unique(track_ids[moving_rows])
|
| 410 |
+
dynamic_rows = np.isin(track_ids, dynamic_track_ids)
|
| 411 |
+
selected_rows = (
|
| 412 |
+
np.ones_like(dynamic_rows)
|
| 413 |
+
if self.autoregressive_include_static_boxes
|
| 414 |
+
else dynamic_rows
|
| 415 |
+
)
|
| 416 |
+
num_frames = int(frame_indices.shape[0])
|
| 417 |
+
object_to_world = np.zeros(
|
| 418 |
+
(num_frames, self.moving_box_limit, 4, 4),
|
| 419 |
+
dtype=np.float32,
|
| 420 |
+
)
|
| 421 |
+
lwh = np.zeros(
|
| 422 |
+
(num_frames, self.moving_box_limit, 3), dtype=np.float32
|
| 423 |
+
)
|
| 424 |
+
valid = np.zeros(
|
| 425 |
+
(num_frames, self.moving_box_limit), dtype=bool
|
| 426 |
+
)
|
| 427 |
+
sampled_track_ids = np.full(
|
| 428 |
+
(num_frames, self.moving_box_limit), -1, dtype=np.int64
|
| 429 |
+
)
|
| 430 |
+
sampled_box_types = np.full(
|
| 431 |
+
(num_frames, self.moving_box_limit), -1, dtype=np.int64
|
| 432 |
+
)
|
| 433 |
+
truncated = 0
|
| 434 |
+
for local_idx, frame_idx in enumerate(frame_indices):
|
| 435 |
+
indices = np.nonzero(
|
| 436 |
+
(box_frame == int(frame_idx))
|
| 437 |
+
& selected_rows
|
| 438 |
+
)[0]
|
| 439 |
+
truncated += max(0, int(indices.shape[0]) - self.moving_box_limit)
|
| 440 |
+
indices = indices[: self.moving_box_limit]
|
| 441 |
+
count = int(indices.shape[0])
|
| 442 |
+
if count == 0:
|
| 443 |
+
continue
|
| 444 |
+
object_to_world[local_idx, :count] = box_o2w[indices]
|
| 445 |
+
lwh[local_idx, :count] = box_lwh[indices]
|
| 446 |
+
sampled_track_ids[local_idx, :count] = track_ids[indices]
|
| 447 |
+
sampled_box_types[local_idx, :count] = box_type[indices]
|
| 448 |
+
valid[local_idx, :count] = True
|
| 449 |
+
return (
|
| 450 |
+
torch.from_numpy(object_to_world),
|
| 451 |
+
torch.from_numpy(lwh),
|
| 452 |
+
torch.from_numpy(valid),
|
| 453 |
+
torch.from_numpy(sampled_track_ids),
|
| 454 |
+
torch.from_numpy(sampled_box_types),
|
| 455 |
+
truncated,
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
def _generated_previous_frame(
|
| 459 |
+
self, clip_key: str, native_frame_idx: int
|
| 460 |
+
) -> torch.Tensor:
|
| 461 |
+
path = os.path.join(
|
| 462 |
+
self.autoregressive_previous_root, f"{clip_key}.npz"
|
| 463 |
+
)
|
| 464 |
+
if not os.path.isfile(path):
|
| 465 |
+
raise FileNotFoundError(
|
| 466 |
+
f"missing DAgger rollout for {clip_key!r}: {path}"
|
| 467 |
+
)
|
| 468 |
+
with np.load(path, allow_pickle=False) as payload:
|
| 469 |
+
frames = np.asarray(payload["range"], dtype=np.float32)
|
| 470 |
+
frame_indices = np.asarray(
|
| 471 |
+
payload["frame_indices"], dtype=np.int64
|
| 472 |
+
)
|
| 473 |
+
matches = np.nonzero(frame_indices == int(native_frame_idx))[0]
|
| 474 |
+
if matches.shape[0] != 1:
|
| 475 |
+
raise RuntimeError(
|
| 476 |
+
f"{path} must contain native frame {native_frame_idx} "
|
| 477 |
+
f"exactly once, found {matches.shape[0]}"
|
| 478 |
+
)
|
| 479 |
+
frame = frames[int(matches[0])]
|
| 480 |
+
if frame.shape != tuple(self.lidar_size):
|
| 481 |
+
raise ValueError(
|
| 482 |
+
f"DAgger frame shape {frame.shape} does not match "
|
| 483 |
+
f"lidar_size={tuple(self.lidar_size)}"
|
| 484 |
+
)
|
| 485 |
+
return torch.from_numpy(frame)[None, None]
|
| 486 |
+
|
| 487 |
+
def _sample_generated_previous_frame(
|
| 488 |
+
self, clip_key: str
|
| 489 |
+
) -> tuple[int, torch.Tensor]:
|
| 490 |
+
path = os.path.join(
|
| 491 |
+
self.autoregressive_previous_root, f"{clip_key}.npz"
|
| 492 |
+
)
|
| 493 |
+
if not os.path.isfile(path):
|
| 494 |
+
raise FileNotFoundError(
|
| 495 |
+
f"missing DAgger rollout for {clip_key!r}: {path}"
|
| 496 |
+
)
|
| 497 |
+
with np.load(path, allow_pickle=False) as payload:
|
| 498 |
+
frames = np.asarray(payload["range"], dtype=np.float32)
|
| 499 |
+
frame_indices = np.asarray(
|
| 500 |
+
payload["frame_indices"], dtype=np.int64
|
| 501 |
+
)
|
| 502 |
+
if frames.shape[0] != frame_indices.shape[0] or frames.shape[0] == 0:
|
| 503 |
+
raise ValueError(
|
| 504 |
+
f"invalid DAgger bank shapes in {path}: "
|
| 505 |
+
f"range={frames.shape}, frame_indices={frame_indices.shape}"
|
| 506 |
+
)
|
| 507 |
+
selected = int(np.random.randint(0, frames.shape[0]))
|
| 508 |
+
frame = frames[selected]
|
| 509 |
+
if frame.shape != tuple(self.lidar_size):
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"DAgger frame shape {frame.shape} does not match "
|
| 512 |
+
f"lidar_size={tuple(self.lidar_size)}"
|
| 513 |
+
)
|
| 514 |
+
return int(frame_indices[selected]), torch.from_numpy(frame)[None, None]
|
| 515 |
+
|
| 516 |
+
def __getitem__(self, idx):
|
| 517 |
+
# Deterministic parity mode: caller-provided (clip_idx, native rows) via
|
| 518 |
+
# ``self._explicit_windows`` (set e.g. by scripts/dump_hdmap_gen_ncore.py
|
| 519 |
+
# to align with an r2flow manifest). Mirrors the base
|
| 520 |
+
# ``LidarRangeMapSampler.__getitem__`` -- this override otherwise drops
|
| 521 |
+
# the explicit-windows branch and silently falls back to the random /
|
| 522 |
+
# frame-index path, ignoring the requested (clip, frame).
|
| 523 |
+
if self._explicit_windows is not None:
|
| 524 |
+
lidar_data_idx, lidar_frame_indices = self._explicit_windows[idx]
|
| 525 |
+
lidar_frame_indices = np.asarray(lidar_frame_indices, dtype=np.int64)
|
| 526 |
+
else:
|
| 527 |
+
lidar_data_idx = (idx % self.n_data_per_node) + self.data_start_idx
|
| 528 |
+
lidar_frame_indices = self.sample_frame_indices(load_lidar=True)
|
| 529 |
+
use_generated_previous = (
|
| 530 |
+
self.autoregressive_pair
|
| 531 |
+
and self.autoregressive_generated_previous_prob > 0.0
|
| 532 |
+
and np.random.random()
|
| 533 |
+
< self.autoregressive_generated_previous_prob
|
| 534 |
+
)
|
| 535 |
+
generated_previous = None
|
| 536 |
+
if use_generated_previous:
|
| 537 |
+
if self._explicit_windows is None:
|
| 538 |
+
clip_key = self.dataset.filter_set[lidar_data_idx]
|
| 539 |
+
(
|
| 540 |
+
generated_frame_idx,
|
| 541 |
+
generated_previous,
|
| 542 |
+
) = self._sample_generated_previous_frame(clip_key)
|
| 543 |
+
lidar_frame_indices = np.asarray(
|
| 544 |
+
[generated_frame_idx, generated_frame_idx + 1],
|
| 545 |
+
dtype=np.int64,
|
| 546 |
+
)
|
| 547 |
+
else:
|
| 548 |
+
generated_previous = self._generated_previous_frame(
|
| 549 |
+
self.dataset.filter_set[lidar_data_idx],
|
| 550 |
+
int(lidar_frame_indices[0]),
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
# When cameras are requested, additionally pull RGB + intrinsics +
|
| 554 |
+
# Camera-to-LiDAR transforms supplied by the configured dataset root.
|
| 555 |
+
data_fields = ["custom"]
|
| 556 |
+
if self.load_lidar_and_rgb:
|
| 557 |
+
data_fields = [
|
| 558 |
+
"custom",
|
| 559 |
+
DataField.CAMERA_C2LIDAR_TRANSFORM,
|
| 560 |
+
DataField.CAMERA_INTRINSICS,
|
| 561 |
+
DataField.IMAGE_RGB,
|
| 562 |
+
]
|
| 563 |
+
|
| 564 |
+
try:
|
| 565 |
+
example = self.dataset._read_rgb_and_lidar(
|
| 566 |
+
lidar_data_idx, lidar_frame_indices, data_fields
|
| 567 |
+
)
|
| 568 |
+
except Exception as e:
|
| 569 |
+
log.info(f"Error loading data for index {idx}: {e}", rank0_only=False)
|
| 570 |
+
return self.__getitem__(np.random.randint(0, self.__len__()))
|
| 571 |
+
|
| 572 |
+
lidar_rangemap = self.get_lidar(example)
|
| 573 |
+
if lidar_rangemap is None:
|
| 574 |
+
log.info(f"Lidar rangemap missing for index {idx}, retrying", rank0_only=False)
|
| 575 |
+
return self.__getitem__(np.random.randint(0, self.__len__()))
|
| 576 |
+
|
| 577 |
+
lidar_hdmap = self.get_lidar_hdmap(example)
|
| 578 |
+
if lidar_hdmap is None:
|
| 579 |
+
if self.synthesize_null_hdmap:
|
| 580 |
+
lidar_hdmap = torch.full_like(
|
| 581 |
+
lidar_rangemap[:1], self.min_value
|
| 582 |
+
)
|
| 583 |
+
else:
|
| 584 |
+
log.info(
|
| 585 |
+
f"HDmap missing for index {idx}, retrying",
|
| 586 |
+
rank0_only=False,
|
| 587 |
+
)
|
| 588 |
+
return self.__getitem__(np.random.randint(0, self.__len__()))
|
| 589 |
+
autoregressive_previous = None
|
| 590 |
+
autoregressive_lidar_to_world = None
|
| 591 |
+
autoregressive_frame_indices = None
|
| 592 |
+
if self.autoregressive_pair:
|
| 593 |
+
if lidar_rangemap.shape[1] != 2 or lidar_hdmap.shape[1] != 2:
|
| 594 |
+
raise RuntimeError(
|
| 595 |
+
"autoregressive pair must load exactly two frames, got "
|
| 596 |
+
f"lidar={tuple(lidar_rangemap.shape)}, "
|
| 597 |
+
f"hdmap={tuple(lidar_hdmap.shape)}"
|
| 598 |
+
)
|
| 599 |
+
autoregressive_previous = lidar_rangemap[:, :1].clone()
|
| 600 |
+
autoregressive_lidar_to_world = np.asarray(
|
| 601 |
+
example["lidar_to_world"], dtype=np.float32
|
| 602 |
+
)
|
| 603 |
+
autoregressive_frame_indices = np.asarray(
|
| 604 |
+
example["rgb_frame_indices"], dtype=np.int64
|
| 605 |
+
)
|
| 606 |
+
if generated_previous is not None:
|
| 607 |
+
autoregressive_previous = generated_previous
|
| 608 |
+
lidar_rangemap = lidar_rangemap[:, 1:2]
|
| 609 |
+
lidar_hdmap = lidar_hdmap[:, 1:2]
|
| 610 |
+
lidar_hdmap_semantic = None
|
| 611 |
+
if lidar_hdmap.shape[0] > 1:
|
| 612 |
+
lidar_hdmap_semantic = lidar_hdmap
|
| 613 |
+
lidar_hdmap = compose_normalized_range_channels(
|
| 614 |
+
lidar_hdmap_semantic,
|
| 615 |
+
channel_dim=0,
|
| 616 |
+
min_value=self.min_value,
|
| 617 |
+
inverse_depth=self.inverse_depth,
|
| 618 |
+
)
|
| 619 |
+
if self.return_hdmap_semantic and lidar_hdmap_semantic is None:
|
| 620 |
+
raise RuntimeError(
|
| 621 |
+
"semantic HDMap output requested but the reader returned a "
|
| 622 |
+
"single composited channel"
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
try:
|
| 626 |
+
t5_embed = self.prepare_t5_embeddings(example, lidar_frame_indices)
|
| 627 |
+
except (FileNotFoundError, RuntimeError) as e:
|
| 628 |
+
log.warning(
|
| 629 |
+
f"T5 embedding load failed for index {idx} "
|
| 630 |
+
f"(key={example['__key__']}): {e}; retrying with new index",
|
| 631 |
+
rank0_only=False,
|
| 632 |
+
)
|
| 633 |
+
return self.__getitem__(np.random.randint(0, self.__len__()))
|
| 634 |
+
|
| 635 |
+
bev_hdmap = self.get_lidar_hdmap_bev(example)
|
| 636 |
+
|
| 637 |
+
metadata_slice = (
|
| 638 |
+
slice(None)
|
| 639 |
+
if self.return_full_lidar_metadata
|
| 640 |
+
else slice(-1, None)
|
| 641 |
+
)
|
| 642 |
+
sample = {
|
| 643 |
+
"video": lidar_rangemap,
|
| 644 |
+
"lidar_hdmap": lidar_hdmap,
|
| 645 |
+
"__key__": example["__key__"],
|
| 646 |
+
"clip_name": "%s-%s-%d" % (self.data_name, example["__key__"], idx),
|
| 647 |
+
"data_type": "lidar",
|
| 648 |
+
"num_frames": (
|
| 649 |
+
self.autoregressive_target_frames
|
| 650 |
+
if self.autoregressive_pair
|
| 651 |
+
else self.sample_n_frames
|
| 652 |
+
),
|
| 653 |
+
"is_preprocessed": True,
|
| 654 |
+
"image_size": torch.tensor(self.lidar_size),
|
| 655 |
+
"padding_mask": torch.zeros(1, self.lidar_size[0], self.lidar_size[1]),
|
| 656 |
+
"fps": self.sensor_fps,
|
| 657 |
+
"sensor_dataset_id": int(self.sensor_dataset_id),
|
| 658 |
+
"sensor_dataset_name": str(self.sensor_dataset_name),
|
| 659 |
+
"t5_text_embeddings": t5_embed["t5_text_embeddings"],
|
| 660 |
+
"t5_text_mask": t5_embed["t5_text_mask"],
|
| 661 |
+
# Sweep-start (and start/end) ego poses for the *actually sampled*
|
| 662 |
+
# frames (sequential sampling uses a random start_idx) -- forwarded
|
| 663 |
+
# so --save_poses dumps poses aligned to the dumped range maps
|
| 664 |
+
# instead of re-deriving from metadata assuming start frame 0.
|
| 665 |
+
"lidar_to_world": np.asarray(
|
| 666 |
+
example["lidar_to_world"][metadata_slice],
|
| 667 |
+
dtype=np.float32,
|
| 668 |
+
),
|
| 669 |
+
"pose_sensor_start_end": np.asarray(
|
| 670 |
+
example["pose_sensor_start_end"][metadata_slice],
|
| 671 |
+
dtype=np.float32,
|
| 672 |
+
),
|
| 673 |
+
# Actual sampled lidar frame indices (post frame-sampling). Mirrors
|
| 674 |
+
# the base image sampler; consumed by verification viz that re-reads
|
| 675 |
+
# the raw cloud/camera for the SAME frames (viz_waymo_cam5_overlay).
|
| 676 |
+
"rgb_frame_indices": np.asarray(
|
| 677 |
+
example["rgb_frame_indices"][metadata_slice],
|
| 678 |
+
dtype=np.int64,
|
| 679 |
+
),
|
| 680 |
+
}
|
| 681 |
+
sample.update(
|
| 682 |
+
self.get_sensor_metadata(*lidar_rangemap.shape[-2:])
|
| 683 |
+
)
|
| 684 |
+
if self.autoregressive_pair:
|
| 685 |
+
sample["autoregressive_previous_video"] = (
|
| 686 |
+
autoregressive_previous
|
| 687 |
+
)
|
| 688 |
+
sample["autoregressive_lidar_to_world"] = (
|
| 689 |
+
autoregressive_lidar_to_world
|
| 690 |
+
)
|
| 691 |
+
sample["autoregressive_frame_indices"] = (
|
| 692 |
+
autoregressive_frame_indices
|
| 693 |
+
)
|
| 694 |
+
if bev_hdmap is not None:
|
| 695 |
+
sample["bev_hdmap"] = bev_hdmap
|
| 696 |
+
if self.return_hdmap_semantic:
|
| 697 |
+
sample["lidar_hdmap_semantic"] = lidar_hdmap_semantic
|
| 698 |
+
if self.return_moving_boxes:
|
| 699 |
+
(
|
| 700 |
+
moving_box_object_to_world,
|
| 701 |
+
moving_box_lwh,
|
| 702 |
+
moving_box_valid,
|
| 703 |
+
moving_box_track_id,
|
| 704 |
+
moving_box_type,
|
| 705 |
+
moving_box_truncated,
|
| 706 |
+
) = self._moving_boxes_for_sample(example)
|
| 707 |
+
sample["moving_box_object_to_world"] = (
|
| 708 |
+
moving_box_object_to_world
|
| 709 |
+
)
|
| 710 |
+
sample["moving_box_lwh"] = moving_box_lwh
|
| 711 |
+
sample["moving_box_valid"] = moving_box_valid
|
| 712 |
+
sample["moving_box_track_id"] = moving_box_track_id
|
| 713 |
+
sample["moving_box_type"] = moving_box_type
|
| 714 |
+
sample["moving_box_truncated"] = moving_box_truncated
|
| 715 |
+
|
| 716 |
+
if self.blockwise_warped_history_condition:
|
| 717 |
+
if self._blockwise_warp_geometry is None:
|
| 718 |
+
self._blockwise_warp_geometry = load_waymo_lidar_geometry(
|
| 719 |
+
**self._blockwise_warp_geometry_args
|
| 720 |
+
)
|
| 721 |
+
ray_dirs, elev, azim, row_off = self._blockwise_warp_geometry
|
| 722 |
+
warped, _ = warp_blockwise_history_to_video(
|
| 723 |
+
video=sample["video"],
|
| 724 |
+
lidar_to_world=sample["lidar_to_world"],
|
| 725 |
+
block_size=self.blockwise_warped_history_block_size,
|
| 726 |
+
ray_dirs=ray_dirs,
|
| 727 |
+
row_elevations_rad=elev,
|
| 728 |
+
column_azimuths_rad=azim,
|
| 729 |
+
row_azimuth_offsets_rad=row_off,
|
| 730 |
+
min_range=self.min_distance,
|
| 731 |
+
max_range=self.max_distance,
|
| 732 |
+
min_value=self.min_value,
|
| 733 |
+
inverse_depth=self.inverse_depth,
|
| 734 |
+
history_mode=self.blockwise_warped_history_mode,
|
| 735 |
+
)
|
| 736 |
+
sample["lidar_blockwise_warped_history"] = torch.from_numpy(warped)
|
| 737 |
+
|
| 738 |
+
if self.load_lidar_and_rgb:
|
| 739 |
+
# image_rgb_<v> / camera_intrinsics_<v> / camera_c2lidar_transform_<v>
|
| 740 |
+
for getter in (
|
| 741 |
+
self.get_rgb,
|
| 742 |
+
self.get_camera_intrinsics,
|
| 743 |
+
self.get_camera_c2lidar_transform,
|
| 744 |
+
):
|
| 745 |
+
cam_dict = getter(example)
|
| 746 |
+
if cam_dict is not None:
|
| 747 |
+
sample.update(cam_dict)
|
| 748 |
+
|
| 749 |
+
del example
|
| 750 |
+
gc.collect()
|
| 751 |
+
return sample
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class HdmapLidarDataset:
|
| 755 |
+
"""Lazy-constructable dataset config that builds ``HdmapLidarSampler``."""
|
| 756 |
+
|
| 757 |
+
def __init__(self, dataset_name: str, **kwargs):
|
| 758 |
+
self.dataset_name = dataset_name
|
| 759 |
+
self.dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name])
|
| 760 |
+
self.extra_config = OmegaConf.create(kwargs)
|
| 761 |
+
|
| 762 |
+
def build_dataset(self):
|
| 763 |
+
if self.extra_config:
|
| 764 |
+
merged_config = OmegaConf.merge(self.dataset_config, self.extra_config)
|
| 765 |
+
else:
|
| 766 |
+
merged_config = self.dataset_config
|
| 767 |
+
config_dict = OmegaConf.to_container(merged_config, resolve=True)
|
| 768 |
+
return HdmapLidarSampler(**config_dict)
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
class HdmapLidarDataLoader(DataLoader):
|
| 772 |
+
def __init__(self, dataset, batch_size: int = 1, *args, **kw):
|
| 773 |
+
dataset_obj = dataset.build_dataset()
|
| 774 |
+
if "dataloaders" in kw:
|
| 775 |
+
kw.pop("dataloaders")
|
| 776 |
+
super().__init__(dataset_obj, batch_size, collate_fn=dict_collation_fn, *args, **kw)
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
class CrossDatasetHdmapLidarDataset:
|
| 780 |
+
"""Lazy native-grid HDMap/LiDAR mixture with homogeneous batches."""
|
| 781 |
+
|
| 782 |
+
def __init__(
|
| 783 |
+
self,
|
| 784 |
+
dataset_names,
|
| 785 |
+
shared_overrides=None,
|
| 786 |
+
per_dataset_overrides=None,
|
| 787 |
+
):
|
| 788 |
+
self.dataset_names = list(dataset_names)
|
| 789 |
+
self.shared_overrides = dict(shared_overrides or {})
|
| 790 |
+
self.per_dataset_overrides = dict(per_dataset_overrides or {})
|
| 791 |
+
|
| 792 |
+
def build_dataset(self):
|
| 793 |
+
children = []
|
| 794 |
+
for dataset_id, dataset_name in enumerate(self.dataset_names):
|
| 795 |
+
dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name])
|
| 796 |
+
overrides = OmegaConf.create(
|
| 797 |
+
{
|
| 798 |
+
**self.shared_overrides,
|
| 799 |
+
**self.per_dataset_overrides.get(dataset_name, {}),
|
| 800 |
+
"emit_sensor_metadata": True,
|
| 801 |
+
"sensor_dataset_id": dataset_id,
|
| 802 |
+
"sensor_dataset_name": dataset_name,
|
| 803 |
+
}
|
| 804 |
+
)
|
| 805 |
+
config_dict = OmegaConf.to_container(
|
| 806 |
+
OmegaConf.merge(dataset_config, overrides), resolve=True
|
| 807 |
+
)
|
| 808 |
+
children.append(HdmapLidarSampler(**config_dict))
|
| 809 |
+
return HomogeneousMultiHdmapDataset(children)
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
class HomogeneousMultiHdmapDataset(Dataset):
|
| 813 |
+
def __init__(self, children):
|
| 814 |
+
self.children = list(children)
|
| 815 |
+
if not self.children:
|
| 816 |
+
raise ValueError("At least one child dataset is required")
|
| 817 |
+
|
| 818 |
+
def __len__(self):
|
| 819 |
+
return sum(len(child) for child in self.children)
|
| 820 |
+
|
| 821 |
+
def __getitem__(self, index):
|
| 822 |
+
dataset_id, local_index = index
|
| 823 |
+
return self.children[dataset_id][local_index]
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
class HomogeneousHdmapBatchSampler(Sampler):
|
| 827 |
+
def __init__(
|
| 828 |
+
self,
|
| 829 |
+
dataset,
|
| 830 |
+
batch_size,
|
| 831 |
+
validation=False,
|
| 832 |
+
mix_datasets_across_ranks=False,
|
| 833 |
+
dataset_sampling_weights=None,
|
| 834 |
+
seed=0,
|
| 835 |
+
):
|
| 836 |
+
self.dataset = dataset
|
| 837 |
+
self.batch_size = int(batch_size)
|
| 838 |
+
self.validation = bool(validation)
|
| 839 |
+
self.mix_datasets_across_ranks = bool(mix_datasets_across_ranks)
|
| 840 |
+
self.seed = int(seed)
|
| 841 |
+
if "parallel_state" in globals() and parallel_state.is_initialized():
|
| 842 |
+
self.rank = parallel_state.get_data_parallel_rank()
|
| 843 |
+
self.world_size = parallel_state.get_data_parallel_world_size()
|
| 844 |
+
elif torch.distributed.is_initialized():
|
| 845 |
+
self.rank = torch.distributed.get_rank()
|
| 846 |
+
self.world_size = torch.distributed.get_world_size()
|
| 847 |
+
else:
|
| 848 |
+
self.rank = 0
|
| 849 |
+
self.world_size = 1
|
| 850 |
+
self.dataset_sampling_weights = None
|
| 851 |
+
if dataset_sampling_weights is not None:
|
| 852 |
+
weights = torch.as_tensor(
|
| 853 |
+
dataset_sampling_weights, dtype=torch.float64
|
| 854 |
+
)
|
| 855 |
+
if weights.numel() != len(dataset.children):
|
| 856 |
+
raise ValueError(
|
| 857 |
+
"dataset_sampling_weights must have one value per dataset; "
|
| 858 |
+
f"got {weights.numel()} values for {len(dataset.children)}"
|
| 859 |
+
)
|
| 860 |
+
if (
|
| 861 |
+
not torch.isfinite(weights).all()
|
| 862 |
+
or (weights < 0).any()
|
| 863 |
+
or weights.sum() <= 0
|
| 864 |
+
):
|
| 865 |
+
raise ValueError(
|
| 866 |
+
"dataset_sampling_weights must be finite, non-negative, "
|
| 867 |
+
"and sum positive"
|
| 868 |
+
)
|
| 869 |
+
if self.mix_datasets_across_ranks and not torch.allclose(
|
| 870 |
+
weights, weights.new_full(weights.shape, weights.mean())
|
| 871 |
+
):
|
| 872 |
+
raise ValueError(
|
| 873 |
+
"Non-uniform dataset sampling is incompatible with "
|
| 874 |
+
"mix_datasets_across_ranks=True"
|
| 875 |
+
)
|
| 876 |
+
self.dataset_sampling_weights = weights / weights.sum()
|
| 877 |
+
self.num_batches = max(
|
| 878 |
+
1,
|
| 879 |
+
sum(len(child) for child in dataset.children)
|
| 880 |
+
// (self.batch_size * self.world_size),
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
def __len__(self):
|
| 884 |
+
return self.num_batches
|
| 885 |
+
|
| 886 |
+
def __iter__(self):
|
| 887 |
+
generator = torch.Generator().manual_seed(self.seed)
|
| 888 |
+
cursors = [0] * len(self.dataset.children)
|
| 889 |
+
for step in range(self.num_batches):
|
| 890 |
+
if self.validation:
|
| 891 |
+
dataset_id = step % len(self.dataset.children)
|
| 892 |
+
elif self.mix_datasets_across_ranks:
|
| 893 |
+
dataset_id = (self.rank + step) % len(self.dataset.children)
|
| 894 |
+
elif self.dataset_sampling_weights is None:
|
| 895 |
+
dataset_id = int(
|
| 896 |
+
torch.randint(
|
| 897 |
+
len(self.dataset.children), (1,), generator=generator
|
| 898 |
+
).item()
|
| 899 |
+
)
|
| 900 |
+
else:
|
| 901 |
+
dataset_id = int(
|
| 902 |
+
torch.multinomial(
|
| 903 |
+
self.dataset_sampling_weights,
|
| 904 |
+
1,
|
| 905 |
+
generator=generator,
|
| 906 |
+
).item()
|
| 907 |
+
)
|
| 908 |
+
child_len = len(self.dataset.children[dataset_id])
|
| 909 |
+
start = cursors[dataset_id] + self.rank * self.batch_size
|
| 910 |
+
batch = [
|
| 911 |
+
(dataset_id, (start + offset) % child_len)
|
| 912 |
+
for offset in range(self.batch_size)
|
| 913 |
+
]
|
| 914 |
+
cursors[dataset_id] = (
|
| 915 |
+
cursors[dataset_id] + self.world_size * self.batch_size
|
| 916 |
+
) % child_len
|
| 917 |
+
yield batch
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
class HomogeneousMultiHdmapDataLoader(DataLoader):
|
| 921 |
+
def __init__(
|
| 922 |
+
self,
|
| 923 |
+
dataset,
|
| 924 |
+
batch_size=1,
|
| 925 |
+
validation=False,
|
| 926 |
+
mix_datasets_across_ranks=False,
|
| 927 |
+
dataset_sampling_weights=None,
|
| 928 |
+
seed=0,
|
| 929 |
+
*args,
|
| 930 |
+
**kwargs,
|
| 931 |
+
):
|
| 932 |
+
dataset_obj = dataset.build_dataset()
|
| 933 |
+
batch_sampler = HomogeneousHdmapBatchSampler(
|
| 934 |
+
dataset_obj,
|
| 935 |
+
batch_size=batch_size,
|
| 936 |
+
validation=validation,
|
| 937 |
+
mix_datasets_across_ranks=mix_datasets_across_ranks,
|
| 938 |
+
dataset_sampling_weights=dataset_sampling_weights,
|
| 939 |
+
seed=seed,
|
| 940 |
+
)
|
| 941 |
+
if "dataloaders" in kwargs:
|
| 942 |
+
kwargs.pop("dataloaders")
|
| 943 |
+
if "drop_last" in kwargs:
|
| 944 |
+
kwargs.pop("drop_last")
|
| 945 |
+
super().__init__(
|
| 946 |
+
dataset_obj,
|
| 947 |
+
batch_sampler=batch_sampler,
|
| 948 |
+
collate_fn=dict_collation_fn,
|
| 949 |
+
*args,
|
| 950 |
+
**kwargs,
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def get_hdmap_lidar_dataset(dataset_name: str, **kwargs):
|
| 955 |
+
"""Build the raw dataset (no DataLoader wrapping)."""
|
| 956 |
+
dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name])
|
| 957 |
+
if kwargs:
|
| 958 |
+
dataset_config = OmegaConf.merge(dataset_config, OmegaConf.create(kwargs))
|
| 959 |
+
config_dict = OmegaConf.to_container(dataset_config, resolve=True)
|
| 960 |
+
return HdmapLidarSampler(**config_dict)
|
diffusion/training/datasets/lidar_dataset/imagetolidar_dataloader.py
ADDED
|
@@ -0,0 +1,969 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
import os
|
| 22 |
+
import pickle
|
| 23 |
+
|
| 24 |
+
import einops
|
| 25 |
+
import omegaconf
|
| 26 |
+
import torchvision.transforms as transforms
|
| 27 |
+
|
| 28 |
+
from utils.lazy_config import LazyCall as L
|
| 29 |
+
from utils import log
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
from megatron.core import parallel_state
|
| 33 |
+
USE_MEGATRON = True
|
| 34 |
+
except ImportError:
|
| 35 |
+
USE_MEGATRON = False
|
| 36 |
+
|
| 37 |
+
from omegaconf import OmegaConf
|
| 38 |
+
from torch.utils.data import DataLoader, Dataset
|
| 39 |
+
|
| 40 |
+
from tokenizer.training.datasets.lidar_datasets.datasets import RadymLidar
|
| 41 |
+
from tokenizer.training.datasets.lidar_datasets.data_fileds import DataField
|
| 42 |
+
from utils.lidar_rangemap import RangeMapDownsampler, normalize_range_map
|
| 43 |
+
|
| 44 |
+
from diffusion.training.datasets.lidar_dataset.configs import COMMONDATA_CONFIG
|
| 45 |
+
|
| 46 |
+
def dict_collation_fn(samples, combine_tensors=True, combine_scalars=True, ignore_keys=None):
|
| 47 |
+
"""Take a list of samples (as dictionary) and create a batch, preserving the keys.
|
| 48 |
+
If `tensors` is True, `ndarray` objects are combined into
|
| 49 |
+
tensor batches.
|
| 50 |
+
:param dict samples: list of samples
|
| 51 |
+
:param bool tensors: whether to turn lists of ndarrays into a single ndarray
|
| 52 |
+
:returns: single sample consisting of a batch
|
| 53 |
+
:rtype: dict
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
batched = {key: [] for key in samples[0]}
|
| 57 |
+
# assert isinstance(samples[0][first_key], (list, tuple)), type(samples[first_key])
|
| 58 |
+
|
| 59 |
+
for s in samples:
|
| 60 |
+
[batched[key].append(s[key]) for key in batched if not (ignore_keys is not None and key in ignore_keys)]
|
| 61 |
+
|
| 62 |
+
result = {}
|
| 63 |
+
for key in batched:
|
| 64 |
+
if ignore_keys and key in ignore_keys:
|
| 65 |
+
continue
|
| 66 |
+
try:
|
| 67 |
+
if isinstance(batched[key][0], bool):
|
| 68 |
+
assert key == "is_preprocessed"
|
| 69 |
+
result[key] = batched[key][0] # this is a hack to align with cosmos data
|
| 70 |
+
elif isinstance(batched[key][0], (int, float)):
|
| 71 |
+
if combine_scalars:
|
| 72 |
+
result[key] = torch.from_numpy(np.array(list(batched[key])))
|
| 73 |
+
elif isinstance(batched[key][0], torch.Tensor):
|
| 74 |
+
if combine_tensors:
|
| 75 |
+
result[key] = torch.stack(list(batched[key]))
|
| 76 |
+
elif isinstance(batched[key][0], np.ndarray):
|
| 77 |
+
if combine_tensors:
|
| 78 |
+
result[key] = np.array(list(batched[key]))
|
| 79 |
+
elif isinstance(batched[key][0], list) and isinstance(batched[key][0][0], int):
|
| 80 |
+
result[key] = [torch.Tensor(elems).long() for elems in zip(*batched[key])]
|
| 81 |
+
else:
|
| 82 |
+
result[key] = list(batched[key])
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(key)
|
| 85 |
+
raise e
|
| 86 |
+
# result.append(b)
|
| 87 |
+
del batched
|
| 88 |
+
return result
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def frames_as_batch_collation_fn(
|
| 92 |
+
samples, combine_tensors=True, combine_scalars=True, ignore_keys=None,
|
| 93 |
+
video_key="video", hdmap_key="lidar_hdmap",
|
| 94 |
+
):
|
| 95 |
+
"""Flatten the per-sample temporal dim (N>1) into the batch dim.
|
| 96 |
+
|
| 97 |
+
This is intended for image-style training (``is_video_tokenizer=False``)
|
| 98 |
+
where each ``__getitem__`` call returns a tensor of shape ``[C, N, H, W]``
|
| 99 |
+
representing N independent frames from the same clip. After the normal
|
| 100 |
+
collation produces ``[B, C, N, H, W]`` for video/hdmap, we reshape to
|
| 101 |
+
``[B*N, C, 1, H, W]`` so every frame becomes its own training example, and
|
| 102 |
+
repeat per-sample metadata N times so alignment is preserved.
|
| 103 |
+
|
| 104 |
+
If N == 1 this is a no-op and the output is identical to ``dict_collation_fn``.
|
| 105 |
+
"""
|
| 106 |
+
batch = dict_collation_fn(samples, combine_tensors, combine_scalars, ignore_keys)
|
| 107 |
+
|
| 108 |
+
vid = batch.get(video_key)
|
| 109 |
+
if not (isinstance(vid, torch.Tensor) and vid.ndim == 5):
|
| 110 |
+
return batch
|
| 111 |
+
|
| 112 |
+
B, C, N, H, W = vid.shape
|
| 113 |
+
if N <= 1:
|
| 114 |
+
return batch
|
| 115 |
+
|
| 116 |
+
def _flatten_frames(t: torch.Tensor) -> torch.Tensor:
|
| 117 |
+
Bt, Ct, Nt, Ht, Wt = t.shape
|
| 118 |
+
return t.permute(0, 2, 1, 3, 4).reshape(Bt * Nt, Ct, 1, Ht, Wt).contiguous()
|
| 119 |
+
|
| 120 |
+
batch[video_key] = _flatten_frames(vid)
|
| 121 |
+
_flatten_keys = {video_key, hdmap_key, "bev_hdmap"}
|
| 122 |
+
for fk in (hdmap_key, "bev_hdmap"):
|
| 123 |
+
if isinstance(batch.get(fk), torch.Tensor) and batch[fk].ndim == 5:
|
| 124 |
+
batch[fk] = _flatten_frames(batch[fk])
|
| 125 |
+
|
| 126 |
+
for key, v in list(batch.items()):
|
| 127 |
+
if key in _flatten_keys:
|
| 128 |
+
continue
|
| 129 |
+
if isinstance(v, bool):
|
| 130 |
+
continue
|
| 131 |
+
if isinstance(v, torch.Tensor) and v.ndim >= 1 and v.shape[0] == B:
|
| 132 |
+
batch[key] = v.repeat_interleave(N, dim=0)
|
| 133 |
+
elif isinstance(v, np.ndarray) and v.ndim >= 1 and v.shape[0] == B:
|
| 134 |
+
batch[key] = np.repeat(v, N, axis=0)
|
| 135 |
+
elif isinstance(v, list) and len(v) == B:
|
| 136 |
+
expanded = []
|
| 137 |
+
for item in v:
|
| 138 |
+
expanded.extend([item] * N)
|
| 139 |
+
batch[key] = expanded
|
| 140 |
+
|
| 141 |
+
return batch
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class MyDataLoader(DataLoader):
|
| 145 |
+
def __init__(self, dataset, batch_size: int = 1, *args, **kw):
|
| 146 |
+
dataset_obj = dataset.build_dataset()
|
| 147 |
+
print("dl", kw.get("dataloaders"))
|
| 148 |
+
if "dataloaders" in kw:
|
| 149 |
+
kw.pop("dataloaders") # HACK?
|
| 150 |
+
print("dl2", kw.get("dataloaders"))
|
| 151 |
+
super().__init__(dataset_obj, batch_size, collate_fn=dict_collation_fn, *args, **kw)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class LidarRangeMapDataset:
|
| 155 |
+
def __init__(self, dataset_name, filter_list_path=None, **kwargs):
|
| 156 |
+
self.dataset_name = dataset_name
|
| 157 |
+
self.dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name])
|
| 158 |
+
self.extra_config = OmegaConf.create(kwargs)
|
| 159 |
+
|
| 160 |
+
if filter_list_path is not None:
|
| 161 |
+
self.dataset_config["filter_list_path"] = filter_list_path
|
| 162 |
+
|
| 163 |
+
def build_dataset(self):
|
| 164 |
+
config_dict = OmegaConf.to_container(self.dataset_config, resolve=True)
|
| 165 |
+
return LidarRangeMapSampler(**config_dict)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def get_lidar_dataset(dataset_name, filter_list_path=None):
|
| 169 |
+
dataset_config = OmegaConf.create(COMMONDATA_CONFIG[dataset_name])
|
| 170 |
+
|
| 171 |
+
if filter_list_path is not None:
|
| 172 |
+
dataset_config["filter_list_path"] = filter_list_path
|
| 173 |
+
|
| 174 |
+
config_dict = OmegaConf.to_container(dataset_config, resolve=True)
|
| 175 |
+
return LidarRangeMapSampler(**config_dict)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class LidarRangeMapSampler(Dataset):
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
data_name,
|
| 182 |
+
root_path,
|
| 183 |
+
filter_list_path,
|
| 184 |
+
t5_embedding_path,
|
| 185 |
+
custom_folders,
|
| 186 |
+
custom_fields,
|
| 187 |
+
metadata_folder,
|
| 188 |
+
max_range,
|
| 189 |
+
min_range,
|
| 190 |
+
downsample_factor_row,
|
| 191 |
+
downsample_factor_col,
|
| 192 |
+
repeat_row,
|
| 193 |
+
repeat_col,
|
| 194 |
+
repeat_temporal,
|
| 195 |
+
lidar_crop_size,
|
| 196 |
+
rgb_crop_size,
|
| 197 |
+
rgb_resize_size,
|
| 198 |
+
lidar_size,
|
| 199 |
+
downsample_method, # for range map
|
| 200 |
+
min_value,
|
| 201 |
+
num_views, # the number of RGB cameras
|
| 202 |
+
sample_n_frames,
|
| 203 |
+
lidar_length,
|
| 204 |
+
frame_sampling_method,
|
| 205 |
+
frame_sampling_every_n_frames,
|
| 206 |
+
sample_lidar_prob,
|
| 207 |
+
is_video_tokenizer,
|
| 208 |
+
sequential_start_idx=0,
|
| 209 |
+
load_lidar_only=True,
|
| 210 |
+
load_rgb_only=False,
|
| 211 |
+
load_lidar_and_rgb=False, # load both lidar and rgb
|
| 212 |
+
load_lidar_or_rgb=False,
|
| 213 |
+
RGB_FPS=30,
|
| 214 |
+
LIDAR_FPS=10,
|
| 215 |
+
load_t5_embeddings=False,
|
| 216 |
+
inverse_depth=False,
|
| 217 |
+
to_three_channels="repeat", # legacy: "repeat" or "concat" (3 channels)
|
| 218 |
+
process_input=None, # if set, overrides to_three_channels. One of "repeat", "concat", "mono".
|
| 219 |
+
load_intensity=False, # if True, append per-frame intensity as an extra channel (dual tokenizer)
|
| 220 |
+
intensity_transform="legacy",
|
| 221 |
+
intensity_raw_max=1.0,
|
| 222 |
+
inv_depth_threshold=20,
|
| 223 |
+
# Optional fixed-size resize of the final range map to [H, W] (use -1 to
|
| 224 |
+
# keep a dim), done with nearest-exact interpolation (NOT bilinear) so
|
| 225 |
+
# depth values are resampled, never blended across depth discontinuities.
|
| 226 |
+
# Mirrors the tokenizer dataset's resize -- use it to feed a VAE at its
|
| 227 |
+
# exact training resolution when downsample_factor_col can't hit it.
|
| 228 |
+
lidar_resize_size=(-1, -1),
|
| 229 |
+
view_indices=None,
|
| 230 |
+
# Which frame of the sampled clip drives the T5 "chunk_id" lookup
|
| 231 |
+
# in prepare_t5_embeddings. The current on-disk layout is one
|
| 232 |
+
# `<__key__>.pkl` per clip (chunk-agnostic), so all three options
|
| 233 |
+
# resolve to the same pickle today, but this kwarg lets us pin
|
| 234 |
+
# the semantic intent ("the caption that describes the first
|
| 235 |
+
# frame of the window") so we get correct behavior if per-chunk
|
| 236 |
+
# pickles ever ship under `<__key__>_<chunk_id>.pkl`.
|
| 237 |
+
# "middle" (default) -- frame_indices[len(...)//2] (legacy)
|
| 238 |
+
# "first" -- frame_indices[0]
|
| 239 |
+
# "last" -- frame_indices[-1]
|
| 240 |
+
t5_chunk_anchor="middle",
|
| 241 |
+
# --- backend dispatch (mirrors the tokenizer LidarRangeMapSampler) --- #
|
| 242 |
+
# "radym" (LidarGEN tar) or "waymo_ncore" (NCore .itar). The waymo backend
|
| 243 |
+
# reads the native 64x2650 grid + rasterizes hdmap on the fly.
|
| 244 |
+
dataset_backend="radym",
|
| 245 |
+
resample_width=-1, # waymo_ncore only: rebin azimuth to this width; <=0 native
|
| 246 |
+
center_vehicle_forward=False,
|
| 247 |
+
# waymo_ncore hdmap (on-the-fly rasterized from dump_waymo_hdmap NPZs)
|
| 248 |
+
hdmap_root=None,
|
| 249 |
+
hdmap_multichannel=False,
|
| 250 |
+
hdmap_moving_only=False,
|
| 251 |
+
hdmap_include_boxes=True,
|
| 252 |
+
hdmap_box_edge_spacing=0.15,
|
| 253 |
+
hdmap_map_max_dist=None,
|
| 254 |
+
# BEV multi-channel hdmap raster (for BEV-latent conditioning).
|
| 255 |
+
hdmap_bev=False,
|
| 256 |
+
hdmap_bev_size=(256, 256),
|
| 257 |
+
hdmap_bev_pc_range=(-75.0, 75.0, -75.0, 75.0, -3.0, 5.0),
|
| 258 |
+
hdmap_sensor_template="native",
|
| 259 |
+
hdmap_template_root_path=None,
|
| 260 |
+
hdmap_template_filter_list_path=None,
|
| 261 |
+
hdmap_virtual_sensor_height_m=None,
|
| 262 |
+
hdmap_virtual_sensor_yaw_deg=0.0,
|
| 263 |
+
canonical_lidar_mode="native",
|
| 264 |
+
hdmap_pose_for_lidar_to_world=False,
|
| 265 |
+
):
|
| 266 |
+
super().__init__()
|
| 267 |
+
self.data_name = data_name
|
| 268 |
+
self.load_intensity = load_intensity
|
| 269 |
+
self.intensity_transform = str(intensity_transform)
|
| 270 |
+
if self.intensity_transform not in ("legacy", "log1p"):
|
| 271 |
+
raise ValueError(
|
| 272 |
+
f"Unknown intensity_transform: {self.intensity_transform!r}"
|
| 273 |
+
)
|
| 274 |
+
self.intensity_raw_max = float(intensity_raw_max)
|
| 275 |
+
if self.intensity_raw_max <= 0.0:
|
| 276 |
+
raise ValueError("intensity_raw_max must be positive")
|
| 277 |
+
self.dataset_backend = dataset_backend
|
| 278 |
+
self.resample_width = resample_width
|
| 279 |
+
# waymo_ncore hdmap rasterization knobs (consumed in _build_dataset).
|
| 280 |
+
self._hdmap_kwargs = dict(
|
| 281 |
+
hdmap_root=hdmap_root,
|
| 282 |
+
min_range=min_range,
|
| 283 |
+
max_range=max_range,
|
| 284 |
+
hdmap_multichannel=hdmap_multichannel,
|
| 285 |
+
hdmap_moving_only=hdmap_moving_only,
|
| 286 |
+
hdmap_include_boxes=hdmap_include_boxes,
|
| 287 |
+
hdmap_box_edge_spacing=hdmap_box_edge_spacing,
|
| 288 |
+
hdmap_map_max_dist=hdmap_map_max_dist,
|
| 289 |
+
hdmap_bev=hdmap_bev,
|
| 290 |
+
hdmap_bev_size=hdmap_bev_size,
|
| 291 |
+
hdmap_bev_pc_range=hdmap_bev_pc_range,
|
| 292 |
+
)
|
| 293 |
+
self._nuscenes_canonical_kwargs = dict(
|
| 294 |
+
hdmap_sensor_template=hdmap_sensor_template,
|
| 295 |
+
hdmap_template_root_path=hdmap_template_root_path,
|
| 296 |
+
hdmap_template_filter_list_path=hdmap_template_filter_list_path,
|
| 297 |
+
hdmap_virtual_sensor_height_m=hdmap_virtual_sensor_height_m,
|
| 298 |
+
hdmap_virtual_sensor_yaw_deg=hdmap_virtual_sensor_yaw_deg,
|
| 299 |
+
canonical_lidar_mode=canonical_lidar_mode,
|
| 300 |
+
center_vehicle_forward=bool(center_vehicle_forward),
|
| 301 |
+
hdmap_pose_for_lidar_to_world=bool(hdmap_pose_for_lidar_to_world),
|
| 302 |
+
)
|
| 303 |
+
# waymo_ncore only: open the per-view camera zarrs when RGB is requested
|
| 304 |
+
# (the radym backend ignores this; it reads RGB from separate tars).
|
| 305 |
+
self._load_cameras = bool(
|
| 306 |
+
load_lidar_and_rgb or load_rgb_only or load_lidar_or_rgb
|
| 307 |
+
)
|
| 308 |
+
# build the dataset
|
| 309 |
+
self.dataset = self._build_dataset(
|
| 310 |
+
root_path=root_path,
|
| 311 |
+
filter_list_path=filter_list_path,
|
| 312 |
+
num_views=num_views,
|
| 313 |
+
metadata_folder=metadata_folder,
|
| 314 |
+
custom_folders=custom_folders,
|
| 315 |
+
custom_fields=custom_fields,
|
| 316 |
+
view_indices=view_indices,
|
| 317 |
+
load_intensity=load_intensity,
|
| 318 |
+
)
|
| 319 |
+
self.plus = 1 if "hdmap" not in self.dataset.custom_fields else 2
|
| 320 |
+
self.num_views = num_views
|
| 321 |
+
|
| 322 |
+
self.LIDAR_FPS = LIDAR_FPS
|
| 323 |
+
self.RGB_FPS = RGB_FPS
|
| 324 |
+
|
| 325 |
+
self.sample_n_frames = sample_n_frames # the "actual" target sequence length
|
| 326 |
+
self.lidar_length = lidar_length
|
| 327 |
+
self.rgb_length = lidar_length * (RGB_FPS // LIDAR_FPS)
|
| 328 |
+
self.frame_sampling_method = frame_sampling_method
|
| 329 |
+
assert self.frame_sampling_method in ["random", "sequential", "sequential_from_zero"]
|
| 330 |
+
self.frame_sampling_every_n_frames = frame_sampling_every_n_frames
|
| 331 |
+
# Chunk offset for sequential_from_zero: render frames [start, start+n).
|
| 332 |
+
# Default 0 preserves existing behavior bit-for-bit. Mirrors the tokenizer
|
| 333 |
+
# LidarRangeMapSampler; used by infer_diffusion.py --chunk_start tiling.
|
| 334 |
+
self.sequential_start_idx = int(sequential_start_idx)
|
| 335 |
+
# Optional deterministic-window override: list of (clip_idx, frame_rows).
|
| 336 |
+
# When set, __getitem__/__len__ use it instead of the random clip+start
|
| 337 |
+
# logic, so an external driver can request the EXACT (clip, native rows)
|
| 338 |
+
# window it needs (used by the parity eval that mirrors waymo_ncore).
|
| 339 |
+
self._explicit_windows = None
|
| 340 |
+
|
| 341 |
+
self.inverse_depth = inverse_depth
|
| 342 |
+
self.min_distance = min_range
|
| 343 |
+
self.max_distance = max_range
|
| 344 |
+
self.max_range = max_range if not inverse_depth else 1 / min_range
|
| 345 |
+
self.min_range = min_range if not inverse_depth else 1 / max_range
|
| 346 |
+
|
| 347 |
+
self.min_value = min_value # min value after normalisation, if 0 then [0, 1],if -1, then [-1, 1]
|
| 348 |
+
|
| 349 |
+
self.repeat_row = repeat_row
|
| 350 |
+
self.repeat_col = repeat_col
|
| 351 |
+
self.repeat_temporal = repeat_temporal
|
| 352 |
+
self.lidar_resize_size = lidar_resize_size
|
| 353 |
+
self.to_three_channels = to_three_channels
|
| 354 |
+
assert self.to_three_channels in ["repeat", "concat"]
|
| 355 |
+
# process_input takes precedence over the legacy to_three_channels arg.
|
| 356 |
+
# "mono" produces a single-channel range map; required for the dual
|
| 357 |
+
# (range + intensity) tokenizer.
|
| 358 |
+
self.process_input = process_input if process_input is not None else to_three_channels
|
| 359 |
+
assert self.process_input in ["repeat", "concat", "mono"], (
|
| 360 |
+
f"Unsupported process_input={self.process_input!r}; "
|
| 361 |
+
"expected one of 'repeat', 'concat', 'mono'."
|
| 362 |
+
)
|
| 363 |
+
if self.load_intensity and self.process_input != "mono":
|
| 364 |
+
log.warning(
|
| 365 |
+
f"[lidar dataset] load_intensity=True with process_input="
|
| 366 |
+
f"{self.process_input!r}; intensity will be appended as an extra "
|
| 367 |
+
f"channel, but this combination is unusual. "
|
| 368 |
+
f"Use process_input='mono' for the dual tokenizer.",
|
| 369 |
+
rank0_only=True,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
self.lidar_size = lidar_size
|
| 373 |
+
self.lidar_crop_size = lidar_crop_size
|
| 374 |
+
self.rgb_crop_size = rgb_crop_size
|
| 375 |
+
self.rgb_resize_size = rgb_resize_size
|
| 376 |
+
|
| 377 |
+
self.sample_lidar_prob = sample_lidar_prob if not load_rgb_only else -1
|
| 378 |
+
self.load_lidar_only = load_lidar_only
|
| 379 |
+
self.load_rgb_only = load_rgb_only
|
| 380 |
+
self.load_lidar_and_rgb = load_lidar_and_rgb
|
| 381 |
+
self.load_lidar_or_rgb = load_lidar_or_rgb
|
| 382 |
+
|
| 383 |
+
assert sum([self.load_lidar_only, self.load_rgb_only, self.load_lidar_and_rgb, self.load_lidar_or_rgb]) == 1
|
| 384 |
+
|
| 385 |
+
# t5 text embedding
|
| 386 |
+
self.load_t5_embeddings = load_t5_embeddings
|
| 387 |
+
self.t5_embedding_path = t5_embedding_path
|
| 388 |
+
if t5_chunk_anchor not in ("first", "middle", "last"):
|
| 389 |
+
raise ValueError(
|
| 390 |
+
f"t5_chunk_anchor must be one of 'first'/'middle'/'last', "
|
| 391 |
+
f"got {t5_chunk_anchor!r}."
|
| 392 |
+
)
|
| 393 |
+
self.t5_chunk_anchor = t5_chunk_anchor
|
| 394 |
+
# One-shot probe flag so prepare_t5_embeddings logs the first real
|
| 395 |
+
# embedding it loads (per dataloader-worker process). Each fork gets
|
| 396 |
+
# its own copy, so we'll see one probe line per worker.
|
| 397 |
+
self._t5_probe_logged = False
|
| 398 |
+
|
| 399 |
+
self.length = self.dataset.size_of_filter_set()
|
| 400 |
+
log.critical(f"load_lidar_only: {self.load_lidar_only}")
|
| 401 |
+
log.critical(f"dataset size: {self.length}")
|
| 402 |
+
log.critical(f"load_t5_embeddings: {self.load_t5_embeddings}")
|
| 403 |
+
if self.load_t5_embeddings:
|
| 404 |
+
log.critical(f"t5_embedding_path: {self.t5_embedding_path}")
|
| 405 |
+
if not os.path.isdir(self.t5_embedding_path):
|
| 406 |
+
log.warning(
|
| 407 |
+
f"[t5] embedding directory does NOT exist: "
|
| 408 |
+
f"{self.t5_embedding_path} -- prepare_t5_embeddings "
|
| 409 |
+
f"will fall back to zero embeddings",
|
| 410 |
+
rank0_only=False,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
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
|
| 414 |
+
if self.is_video_tokenizer:
|
| 415 |
+
assert self.frame_sampling_method == "sequential" or self.frame_sampling_method == "sequential_from_zero"
|
| 416 |
+
|
| 417 |
+
self.range_map_downsampler = RangeMapDownsampler(row_factor = downsample_factor_row, col_factor = downsample_factor_col, method = downsample_method)
|
| 418 |
+
|
| 419 |
+
# image transform
|
| 420 |
+
self.img_transform = transforms.Compose(
|
| 421 |
+
[
|
| 422 |
+
transforms.Resize(
|
| 423 |
+
self.rgb_resize_size, interpolation=transforms.InterpolationMode.BILINEAR, antialias=True
|
| 424 |
+
),
|
| 425 |
+
transforms.CenterCrop(self.rgb_crop_size),
|
| 426 |
+
]
|
| 427 |
+
)
|
| 428 |
+
self.norm_image = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
| 429 |
+
|
| 430 |
+
# Prepare infinite dataset logic
|
| 431 |
+
self.n_data = self.length
|
| 432 |
+
if parallel_state.is_initialized():
|
| 433 |
+
dp_group_id = parallel_state.get_data_parallel_rank()
|
| 434 |
+
dp_world_size = parallel_state.get_data_parallel_world_size()
|
| 435 |
+
log.critical(
|
| 436 |
+
f"Using parallelism size CP :{parallel_state.get_context_parallel_world_size()}, "
|
| 437 |
+
+ f"TP :{parallel_state.get_tensor_model_parallel_world_size()} for video dataset, "
|
| 438 |
+
+ f"DP: {dp_group_id}, DP World size: {dp_world_size}"
|
| 439 |
+
)
|
| 440 |
+
else:
|
| 441 |
+
dp_world_size = 1
|
| 442 |
+
dp_group_id = 0
|
| 443 |
+
|
| 444 |
+
# Data partitioning
|
| 445 |
+
self.n_data_per_node = self.n_data // dp_world_size
|
| 446 |
+
self.data_start_idx = dp_group_id * self.n_data_per_node
|
| 447 |
+
self.dp_group_id = dp_group_id
|
| 448 |
+
|
| 449 |
+
# Infinite loop multiplier. Guard against n_data_per_node == 0, which
|
| 450 |
+
# happens when a (tiny, e.g. overfit) filter set has fewer clips than
|
| 451 |
+
# dp_world_size (n_data // dp_world_size == 0). Such datasets are only
|
| 452 |
+
# ever eagerly constructed at registry import and never iterated by the
|
| 453 |
+
# current experiment, so a 0 multiplier (=> len 0) is harmless; without
|
| 454 |
+
# the guard the bare division kills every job that imports the registry
|
| 455 |
+
# at higher GPU counts.
|
| 456 |
+
maximum_iter = 2000000 # hack to create infinite loop
|
| 457 |
+
self.multiplier = maximum_iter // max(1, self.n_data_per_node)
|
| 458 |
+
# self.multiplier = 1
|
| 459 |
+
|
| 460 |
+
def __len__(self):
|
| 461 |
+
"""
|
| 462 |
+
Return the artificially multiplied length
|
| 463 |
+
"""
|
| 464 |
+
if self._explicit_windows is not None:
|
| 465 |
+
return len(self._explicit_windows)
|
| 466 |
+
return self.multiplier * self.n_data_per_node
|
| 467 |
+
|
| 468 |
+
def sample_random_frames(self, n_frames, total_frames):
|
| 469 |
+
# sample self.sample_n_frames frames from the video
|
| 470 |
+
# return the frame indices
|
| 471 |
+
frame_indices = np.random.randint(0, total_frames, size=n_frames)
|
| 472 |
+
return frame_indices
|
| 473 |
+
|
| 474 |
+
def sample_sequential_frames(self, n_frames, total_frames):
|
| 475 |
+
# sample every self.frame_sampling_every_n_frames frames
|
| 476 |
+
if self.frame_sampling_method == "sequential_from_zero":
|
| 477 |
+
start_idx = self.sequential_start_idx
|
| 478 |
+
else:
|
| 479 |
+
start_idx = np.random.randint(0, total_frames - n_frames * self.frame_sampling_every_n_frames)
|
| 480 |
+
frame_indices = np.arange(start_idx, start_idx + n_frames * self.frame_sampling_every_n_frames, self.frame_sampling_every_n_frames)
|
| 481 |
+
return frame_indices
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def sample_frame_indices(self, load_lidar):
|
| 485 |
+
if load_lidar:
|
| 486 |
+
if self.frame_sampling_method == "random":
|
| 487 |
+
frame_indices = self.sample_random_frames(self.sample_n_frames, self.lidar_length)
|
| 488 |
+
else:
|
| 489 |
+
frame_indices = self.sample_sequential_frames(
|
| 490 |
+
self.sample_n_frames // self.repeat_temporal, self.lidar_length
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
else: # load rgb
|
| 494 |
+
if self.frame_sampling_method == "random":
|
| 495 |
+
frame_indices = self.sample_random_frames(self.sample_n_frames, self.rgb_length)
|
| 496 |
+
else:
|
| 497 |
+
frame_indices = self.sample_sequential_frames(
|
| 498 |
+
self.sample_n_frames + 1, self.rgb_length
|
| 499 |
+
) # + 1 because the video tokenizer will need one more additional frame
|
| 500 |
+
return frame_indices
|
| 501 |
+
|
| 502 |
+
def normalise_and_convert_range_map_to_three_channels(self, range_maps):
|
| 503 |
+
"""Normalize the range map and lift to ``[N, C, H, W]``.
|
| 504 |
+
|
| 505 |
+
``C`` is 3 for ``repeat``/``concat`` (legacy 3-channel paths) and 1 for
|
| 506 |
+
``mono`` (used by the dual range+intensity tokenizer).
|
| 507 |
+
"""
|
| 508 |
+
if self.process_input == "repeat":
|
| 509 |
+
range_maps = normalize_range_map(
|
| 510 |
+
range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth
|
| 511 |
+
) # shape: [N, H, W]
|
| 512 |
+
range_maps = range_maps[:, None, :, :].repeat(3, axis=1) # shape: [N, 3, H, W]
|
| 513 |
+
elif self.process_input == "mono":
|
| 514 |
+
range_maps = normalize_range_map(
|
| 515 |
+
range_maps, self.max_distance, self.min_distance, self.min_value, self.inverse_depth
|
| 516 |
+
) # shape: [N, H, W]
|
| 517 |
+
range_maps = range_maps[:, None, :, :] # shape: [N, 1, H, W]
|
| 518 |
+
elif self.process_input == "concat":
|
| 519 |
+
inverse_depth = normalize_range_map(
|
| 520 |
+
range_maps, self.max_distance, self.min_distance, self.min_value, True
|
| 521 |
+
) # shape: [N, H, W]
|
| 522 |
+
depth = normalize_range_map(
|
| 523 |
+
range_maps, self.max_distance, self.min_distance, self.min_value, False
|
| 524 |
+
) # shape: [N, H, W]
|
| 525 |
+
range_maps = np.concatenate(
|
| 526 |
+
[inverse_depth[:, None, :, :], depth[:, None, :, :], depth[:, None, :, :]], axis=1
|
| 527 |
+
) # shape: [N, 3, H, W]
|
| 528 |
+
|
| 529 |
+
return range_maps
|
| 530 |
+
|
| 531 |
+
def _normalize_intensity(self, intensity_maps):
|
| 532 |
+
"""Apply the intensity tokenizer's input transform."""
|
| 533 |
+
intensity_maps = intensity_maps.copy()
|
| 534 |
+
if self.intensity_transform == "log1p":
|
| 535 |
+
intensity_maps = np.clip(
|
| 536 |
+
intensity_maps / self.intensity_raw_max, 0.0, 1.0
|
| 537 |
+
)
|
| 538 |
+
intensity_maps = np.log1p(intensity_maps) / np.log(2.0)
|
| 539 |
+
intensity_maps = intensity_maps * 2.0 - 1.0
|
| 540 |
+
return intensity_maps[:, None, :, :]
|
| 541 |
+
if self.min_value == -1:
|
| 542 |
+
intensity_maps = intensity_maps * 2 - 1
|
| 543 |
+
return intensity_maps[:, None, :, :] # [N, 1, H, W]
|
| 544 |
+
|
| 545 |
+
def _build_dataset(self, **kwargs):
|
| 546 |
+
"""Construct the low-level reader. Defaults to the LidarGEN tar-backed
|
| 547 |
+
``RadymLidar``; ``dataset_backend='waymo_ncore'`` swaps in the NCore
|
| 548 |
+
reader (native 64x2650 grid + on-the-fly hdmap rasterization). Mirrors
|
| 549 |
+
the tokenizer ``LidarRangeMapSampler._build_dataset``."""
|
| 550 |
+
if self.dataset_backend == "waymo_ncore":
|
| 551 |
+
from tokenizer.training.datasets.lidar_datasets.waymo_ncore import (
|
| 552 |
+
WaymoNCoreLidar,
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
return WaymoNCoreLidar(
|
| 556 |
+
resample_width=self.resample_width,
|
| 557 |
+
load_cameras=self._load_cameras,
|
| 558 |
+
**self._hdmap_kwargs,
|
| 559 |
+
**kwargs,
|
| 560 |
+
)
|
| 561 |
+
if self.dataset_backend == "nuscenes_ncore":
|
| 562 |
+
from tokenizer.training.datasets.lidar_datasets.nuscenes_ncore import (
|
| 563 |
+
NuScenesNCoreLidar,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
return NuScenesNCoreLidar(
|
| 567 |
+
resample_width=self.resample_width,
|
| 568 |
+
load_cameras=self._load_cameras,
|
| 569 |
+
**self._hdmap_kwargs,
|
| 570 |
+
**self._nuscenes_canonical_kwargs,
|
| 571 |
+
**kwargs,
|
| 572 |
+
)
|
| 573 |
+
return RadymLidar(**kwargs)
|
| 574 |
+
|
| 575 |
+
def process_lidar(self, range_maps, intensity_maps=None):
|
| 576 |
+
"""Downsample, normalize, optionally append intensity, then repeat/crop/temporal-pad.
|
| 577 |
+
|
| 578 |
+
When ``intensity_maps`` is provided it is downsampled jointly with the range
|
| 579 |
+
map (so the same valid pixels are kept), normalized, and concatenated as an
|
| 580 |
+
extra channel after ``normalise_and_convert_range_map_to_three_channels``.
|
| 581 |
+
"""
|
| 582 |
+
if intensity_maps is not None:
|
| 583 |
+
range_maps, [intensity_maps] = self.range_map_downsampler.downsample(
|
| 584 |
+
range_maps, [intensity_maps]
|
| 585 |
+
) # range_maps: [N, H, W]; intensity: [N, H, W]
|
| 586 |
+
else:
|
| 587 |
+
range_maps = self.range_map_downsampler.downsample(range_maps) # [N, H, W]
|
| 588 |
+
|
| 589 |
+
range_maps = self.normalise_and_convert_range_map_to_three_channels(
|
| 590 |
+
range_maps
|
| 591 |
+
) # [N, C, H, W] with C=3 (repeat/concat) or C=1 (mono)
|
| 592 |
+
|
| 593 |
+
if intensity_maps is not None:
|
| 594 |
+
intensity_np = self._normalize_intensity(intensity_maps) # [N, 1, H, W]
|
| 595 |
+
range_maps = np.concatenate([range_maps, intensity_np], axis=1) # [N, C+1, H, W]
|
| 596 |
+
|
| 597 |
+
range_maps = range_maps.repeat(self.repeat_row, axis=2)
|
| 598 |
+
range_maps = range_maps.repeat(self.repeat_col, axis=3)
|
| 599 |
+
|
| 600 |
+
# only crop along the column dimension
|
| 601 |
+
if self.lidar_crop_size[1] != -1:
|
| 602 |
+
if self.lidar_crop_size[1] > 1600: # we do center crop
|
| 603 |
+
start_col_idx = (range_maps.shape[-1] - self.lidar_crop_size[1]) // 2
|
| 604 |
+
range_maps = range_maps[:, :, :, start_col_idx : start_col_idx + self.lidar_crop_size[1]]
|
| 605 |
+
else:
|
| 606 |
+
start_col_idx = np.random.randint(0, range_maps.shape[-1] - self.lidar_crop_size[1])
|
| 607 |
+
range_maps = range_maps[:, :, :, start_col_idx : start_col_idx + self.lidar_crop_size[1]]
|
| 608 |
+
|
| 609 |
+
# if it comes from sequential sampling, then we need to repeat the range maps for sequence
|
| 610 |
+
if self.frame_sampling_method in ("sequential", "sequential_from_zero") and self.is_video_tokenizer:
|
| 611 |
+
first_range_map = range_maps[
|
| 612 |
+
0
|
| 613 |
+
] # let's just repeat the first frame to make task easier. This is the same practice as when I evaluate the tokenizer
|
| 614 |
+
range_maps = range_maps.repeat(self.repeat_temporal, axis=0)
|
| 615 |
+
range_maps = np.concatenate(
|
| 616 |
+
[first_range_map[None], range_maps], axis=0
|
| 617 |
+
) # this one will be repeated later on in the encoder
|
| 618 |
+
|
| 619 |
+
# to torch tensor
|
| 620 |
+
range_maps = torch.from_numpy(range_maps).float() # [N, C(+1), H, W]
|
| 621 |
+
|
| 622 |
+
# Optional fixed-size resize (nearest-exact). Applied to [N, C, H, W] so
|
| 623 |
+
# depth values are resampled, never blended. Matches the tokenizer's
|
| 624 |
+
# ``lidar_resize_size`` so a VAE can be fed at its training resolution.
|
| 625 |
+
if self.lidar_resize_size is not None and (
|
| 626 |
+
self.lidar_resize_size[0] != -1 or self.lidar_resize_size[1] != -1
|
| 627 |
+
):
|
| 628 |
+
_, _, H, W = range_maps.shape
|
| 629 |
+
target_h = self.lidar_resize_size[0] if self.lidar_resize_size[0] != -1 else H
|
| 630 |
+
target_w = self.lidar_resize_size[1] if self.lidar_resize_size[1] != -1 else W
|
| 631 |
+
if (target_h, target_w) != (H, W):
|
| 632 |
+
range_maps = torch.nn.functional.interpolate(
|
| 633 |
+
range_maps, size=(target_h, target_w), mode="nearest-exact"
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
return range_maps
|
| 637 |
+
|
| 638 |
+
def process_lidar_multichannel(self, range_maps):
|
| 639 |
+
"""Process ``(N,K,H,W)`` semantic range maps without mixing K."""
|
| 640 |
+
if range_maps.ndim != 4:
|
| 641 |
+
raise ValueError(
|
| 642 |
+
"multi-channel HDMap must be (N,K,H,W), got "
|
| 643 |
+
f"{tuple(range_maps.shape)}"
|
| 644 |
+
)
|
| 645 |
+
if self.process_input != "mono":
|
| 646 |
+
raise ValueError(
|
| 647 |
+
"multi-channel HDMap processing requires process_input='mono'"
|
| 648 |
+
)
|
| 649 |
+
num_frames, num_channels = range_maps.shape[:2]
|
| 650 |
+
flat = range_maps.reshape(
|
| 651 |
+
num_frames * num_channels, *range_maps.shape[2:]
|
| 652 |
+
)
|
| 653 |
+
flat = self.range_map_downsampler.downsample(flat)
|
| 654 |
+
flat = self.normalise_and_convert_range_map_to_three_channels(flat)
|
| 655 |
+
if flat.shape[1] != 1:
|
| 656 |
+
raise RuntimeError(
|
| 657 |
+
"semantic HDMap normalization must preserve one depth channel"
|
| 658 |
+
)
|
| 659 |
+
range_maps = flat.reshape(
|
| 660 |
+
num_frames, num_channels, *flat.shape[2:]
|
| 661 |
+
)
|
| 662 |
+
range_maps = range_maps.repeat(self.repeat_row, axis=2)
|
| 663 |
+
range_maps = range_maps.repeat(self.repeat_col, axis=3)
|
| 664 |
+
|
| 665 |
+
if self.lidar_crop_size[1] != -1:
|
| 666 |
+
crop_width = self.lidar_crop_size[1]
|
| 667 |
+
if crop_width > 1600:
|
| 668 |
+
start_col_idx = (range_maps.shape[-1] - crop_width) // 2
|
| 669 |
+
else:
|
| 670 |
+
start_col_idx = np.random.randint(
|
| 671 |
+
0, range_maps.shape[-1] - crop_width
|
| 672 |
+
)
|
| 673 |
+
range_maps = range_maps[
|
| 674 |
+
:, :, :, start_col_idx : start_col_idx + crop_width
|
| 675 |
+
]
|
| 676 |
+
|
| 677 |
+
if (
|
| 678 |
+
self.frame_sampling_method
|
| 679 |
+
in ("sequential", "sequential_from_zero")
|
| 680 |
+
and self.is_video_tokenizer
|
| 681 |
+
):
|
| 682 |
+
first_range_map = range_maps[0]
|
| 683 |
+
range_maps = range_maps.repeat(self.repeat_temporal, axis=0)
|
| 684 |
+
range_maps = np.concatenate(
|
| 685 |
+
[first_range_map[None], range_maps], axis=0
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
range_maps = torch.from_numpy(range_maps).float()
|
| 689 |
+
if self.lidar_resize_size is not None and (
|
| 690 |
+
self.lidar_resize_size[0] != -1
|
| 691 |
+
or self.lidar_resize_size[1] != -1
|
| 692 |
+
):
|
| 693 |
+
n, k, height, width = range_maps.shape
|
| 694 |
+
target_h = (
|
| 695 |
+
self.lidar_resize_size[0]
|
| 696 |
+
if self.lidar_resize_size[0] != -1
|
| 697 |
+
else height
|
| 698 |
+
)
|
| 699 |
+
target_w = (
|
| 700 |
+
self.lidar_resize_size[1]
|
| 701 |
+
if self.lidar_resize_size[1] != -1
|
| 702 |
+
else width
|
| 703 |
+
)
|
| 704 |
+
if (target_h, target_w) != (height, width):
|
| 705 |
+
range_maps = torch.nn.functional.interpolate(
|
| 706 |
+
range_maps.reshape(n * k, 1, height, width),
|
| 707 |
+
size=(target_h, target_w),
|
| 708 |
+
mode="nearest-exact",
|
| 709 |
+
).reshape(n, k, target_h, target_w)
|
| 710 |
+
return range_maps
|
| 711 |
+
|
| 712 |
+
def process_rgb(self, rgb_images):
|
| 713 |
+
rgb_images = self.img_transform(rgb_images)
|
| 714 |
+
rgb_images = self.norm_image(rgb_images) # N C H W
|
| 715 |
+
return rgb_images
|
| 716 |
+
|
| 717 |
+
def prepare_dummy_data(self):
|
| 718 |
+
data = {}
|
| 719 |
+
dummy_text_embedding = torch.zeros(512, 1024)
|
| 720 |
+
dummy_text_mask = torch.zeros(512)
|
| 721 |
+
dummy_text_mask[0] = 1
|
| 722 |
+
data["t5_text_embeddings"] = dummy_text_embedding
|
| 723 |
+
data["t5_text_mask"] = dummy_text_mask
|
| 724 |
+
|
| 725 |
+
return data
|
| 726 |
+
|
| 727 |
+
def prepare_t5_embeddings(self, example, frame_indices):
|
| 728 |
+
# determine which chunk to use based on the frame indices
|
| 729 |
+
if self.t5_chunk_anchor == "first":
|
| 730 |
+
anchor_indice = frame_indices[0]
|
| 731 |
+
elif self.t5_chunk_anchor == "last":
|
| 732 |
+
anchor_indice = frame_indices[-1]
|
| 733 |
+
else: # "middle" (legacy default)
|
| 734 |
+
anchor_indice = frame_indices[len(frame_indices) // 2]
|
| 735 |
+
chunk_id = anchor_indice // int(self.lidar_length / 5)
|
| 736 |
+
|
| 737 |
+
if self.load_t5_embeddings:
|
| 738 |
+
# t5_embed_path = os.path.join(self.t5_embedding_path, example["__key__"] + f"_{chunk_id}.pkl")
|
| 739 |
+
t5_embed_path = os.path.join(self.t5_embedding_path, example["__key__"] + ".pkl")
|
| 740 |
+
if not os.path.exists(t5_embed_path):
|
| 741 |
+
# Mirror the lidar/hdmap behavior: signal __getitem__ to draw a
|
| 742 |
+
# different sample instead of silently feeding zero embeddings.
|
| 743 |
+
raise FileNotFoundError(
|
| 744 |
+
f"t5 embedding missing for {example['__key__']}: {t5_embed_path}"
|
| 745 |
+
)
|
| 746 |
+
# Truncated/corrupt .pkl files exist in the wild. Re-raise so the
|
| 747 |
+
# caller can retry with a different index (same pattern as
|
| 748 |
+
# hdmap/lidar load failures).
|
| 749 |
+
try:
|
| 750 |
+
with open(t5_embed_path, "rb") as fh:
|
| 751 |
+
t5_embed_pickle = pickle.load(fh)
|
| 752 |
+
text_embedding = t5_embed_pickle["pickle"]["ground_truth"]["embeddings"]["t5_xxl"]
|
| 753 |
+
except (EOFError, pickle.UnpicklingError, OSError, KeyError) as e:
|
| 754 |
+
raise RuntimeError(
|
| 755 |
+
f"[t5] failed to load {t5_embed_path} "
|
| 756 |
+
f"({type(e).__name__}: {e})"
|
| 757 |
+
) from e
|
| 758 |
+
|
| 759 |
+
t5_embed = {}
|
| 760 |
+
dummy_text_embedding = torch.zeros(512, 1024)
|
| 761 |
+
dummy_text_mask = torch.zeros(512)
|
| 762 |
+
n_text = text_embedding.shape[0] # 512
|
| 763 |
+
dummy_text_embedding[:n_text] = torch.from_numpy(text_embedding)
|
| 764 |
+
dummy_text_mask[:n_text] = 1
|
| 765 |
+
t5_embed["t5_text_embeddings"] = dummy_text_embedding
|
| 766 |
+
t5_embed["t5_text_mask"] = dummy_text_mask
|
| 767 |
+
# One-shot probe: confirm to the training log that real
|
| 768 |
+
# (non-zero) T5 embeddings are flowing through this worker.
|
| 769 |
+
if not self._t5_probe_logged:
|
| 770 |
+
nz_rows = int(
|
| 771 |
+
(dummy_text_embedding.abs().sum(dim=-1) > 0).sum()
|
| 772 |
+
)
|
| 773 |
+
log.critical(
|
| 774 |
+
f"[t5 probe] pid={os.getpid()} loaded {t5_embed_path} "
|
| 775 |
+
f"shape={tuple(text_embedding.shape)} "
|
| 776 |
+
f"nonzero_rows={nz_rows}/{dummy_text_embedding.shape[0]}",
|
| 777 |
+
rank0_only=False,
|
| 778 |
+
)
|
| 779 |
+
self._t5_probe_logged = True
|
| 780 |
+
del t5_embed_pickle
|
| 781 |
+
else:
|
| 782 |
+
t5_embed = self.prepare_dummy_data()
|
| 783 |
+
|
| 784 |
+
if self.num_views > 1:
|
| 785 |
+
t5_embed["t5_text_embeddings"] = torch.cat([t5_embed["t5_text_embeddings"]] * (self.num_views+self.plus), dim=0)
|
| 786 |
+
t5_embed["t5_text_mask"] = torch.cat([t5_embed["t5_text_mask"]] * (self.num_views+self.plus), dim=0)
|
| 787 |
+
|
| 788 |
+
return t5_embed
|
| 789 |
+
|
| 790 |
+
def get_lidar(self, example, lidar_key = "lidar"):
|
| 791 |
+
if lidar_key in example["custom"]:
|
| 792 |
+
range_maps = example["custom"][lidar_key] # shape: [N, 128, 3600]
|
| 793 |
+
intensity_maps = (
|
| 794 |
+
example["custom"].get("lidar_intensity") if self.load_intensity else None
|
| 795 |
+
)
|
| 796 |
+
range_maps = self.process_lidar(range_maps, intensity_maps=intensity_maps)
|
| 797 |
+
range_maps = range_maps.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W]
|
| 798 |
+
else:
|
| 799 |
+
range_maps = None
|
| 800 |
+
|
| 801 |
+
return range_maps
|
| 802 |
+
|
| 803 |
+
def get_lidar_hdmap(self, example, hdmap_key = "hdmap"):
|
| 804 |
+
if hdmap_key in example["custom"]:
|
| 805 |
+
hdmap = example["custom"][hdmap_key] # shape: [N, 128, 3600]
|
| 806 |
+
if hdmap.ndim == 4:
|
| 807 |
+
hdmap = self.process_lidar_multichannel(hdmap)
|
| 808 |
+
else:
|
| 809 |
+
hdmap = self.process_lidar(hdmap)
|
| 810 |
+
hdmap = hdmap.permute(1, 0, 2, 3).contiguous()
|
| 811 |
+
else:
|
| 812 |
+
hdmap = None
|
| 813 |
+
return hdmap
|
| 814 |
+
|
| 815 |
+
def get_lidar_hdmap_bev(self, example, key="hdmap_bev"):
|
| 816 |
+
"""Multi-channel BEV hdmap raster -> (C_cls, N, Y, X) tensor.
|
| 817 |
+
|
| 818 |
+
Already a {0,1} top-down occupancy grid (one channel per semantic
|
| 819 |
+
class); NOT a range map, so it skips ``process_lidar`` (no depth
|
| 820 |
+
normalize / azimuth resize / repeat-crop) -- just tensor + permute to
|
| 821 |
+
the (C, N, H, W) convention the collation flattens."""
|
| 822 |
+
if key not in example["custom"]:
|
| 823 |
+
return None
|
| 824 |
+
bev = example["custom"][key] # (N, C_cls, Y, X) float32 in {0, 1}
|
| 825 |
+
if not isinstance(bev, torch.Tensor):
|
| 826 |
+
bev = torch.from_numpy(bev)
|
| 827 |
+
return bev.float().permute(1, 0, 2, 3).contiguous() # (C_cls, N, Y, X)
|
| 828 |
+
|
| 829 |
+
def get_rgb(self, example):
|
| 830 |
+
key = DataField.IMAGE_RGB
|
| 831 |
+
if key in example.keys():
|
| 832 |
+
rgb_images_dict = dict()
|
| 833 |
+
view_keys = example[key].keys()
|
| 834 |
+
for view_key in view_keys:
|
| 835 |
+
rgb_images = example[key][view_key]
|
| 836 |
+
rgb_images = self.process_rgb(rgb_images)
|
| 837 |
+
rgb_images = rgb_images.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W]
|
| 838 |
+
rgb_images_dict[key.value + "_" + str(view_key)] = rgb_images
|
| 839 |
+
else:
|
| 840 |
+
rgb_images_dict = None
|
| 841 |
+
return rgb_images_dict
|
| 842 |
+
|
| 843 |
+
def get_rgb_hdmap(self, example):
|
| 844 |
+
key = DataField.IMAGE_HDMAP
|
| 845 |
+
if key in example.keys():
|
| 846 |
+
rgb_hdmap_dict = dict()
|
| 847 |
+
view_keys = example[key].keys()
|
| 848 |
+
for view_key in view_keys:
|
| 849 |
+
rgb_hdmap = example[key][view_key]
|
| 850 |
+
rgb_hdmap = self.process_rgb(rgb_hdmap)
|
| 851 |
+
rgb_hdmap = rgb_hdmap.permute(1, 0, 2, 3).contiguous() # shape: [C, N, H, W]
|
| 852 |
+
rgb_hdmap_dict[key.value + "_" + str(view_key)] = rgb_hdmap
|
| 853 |
+
else:
|
| 854 |
+
rgb_hdmap_dict = None
|
| 855 |
+
return rgb_hdmap_dict
|
| 856 |
+
|
| 857 |
+
def get_camera_c2lidar_transform(self, example):
|
| 858 |
+
key = DataField.CAMERA_C2LIDAR_TRANSFORM
|
| 859 |
+
if key in example.keys():
|
| 860 |
+
camera_c2lidar_transform_dict = dict()
|
| 861 |
+
view_keys = example[key].keys()
|
| 862 |
+
for view_key in view_keys:
|
| 863 |
+
camera_c2lidar_transform = example[key][view_key]
|
| 864 |
+
camera_c2lidar_transform_dict[key.value + "_" + str(view_key)] = camera_c2lidar_transform
|
| 865 |
+
else:
|
| 866 |
+
camera_c2lidar_transform_dict = None
|
| 867 |
+
return camera_c2lidar_transform_dict
|
| 868 |
+
|
| 869 |
+
def get_camera_intrinsics(self, example):
|
| 870 |
+
key = DataField.CAMERA_INTRINSICS
|
| 871 |
+
if key in example.keys():
|
| 872 |
+
view_keys = example[key].keys()
|
| 873 |
+
camera_intrinsics_dict = dict()
|
| 874 |
+
for view_key in view_keys:
|
| 875 |
+
camera_intrinsics = example[key][view_key]
|
| 876 |
+
camera_intrinsics_dict[key.value + "_" + str(view_key)] = camera_intrinsics
|
| 877 |
+
else:
|
| 878 |
+
camera_intrinsics_dict = None
|
| 879 |
+
return camera_intrinsics_dict
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def __getitem__(self, idx):
|
| 884 |
+
if self.load_rgb_only:
|
| 885 |
+
raise NotImplementedError
|
| 886 |
+
if self.load_lidar_or_rgb:
|
| 887 |
+
raise NotImplementedError
|
| 888 |
+
|
| 889 |
+
# sample the video index
|
| 890 |
+
if self._explicit_windows is not None:
|
| 891 |
+
# Deterministic parity mode: caller-provided (clip_idx, native rows).
|
| 892 |
+
lidar_data_idx, lidar_frame_indices = self._explicit_windows[idx]
|
| 893 |
+
lidar_frame_indices = np.asarray(lidar_frame_indices, dtype=np.int64)
|
| 894 |
+
else:
|
| 895 |
+
lidar_data_idx = (idx % self.n_data_per_node) + self.data_start_idx # frame idx
|
| 896 |
+
lidar_frame_indices = self.sample_frame_indices(load_lidar=True)
|
| 897 |
+
|
| 898 |
+
# load the data
|
| 899 |
+
try:
|
| 900 |
+
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
|
| 901 |
+
# 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])
|
| 902 |
+
example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom", DataField.CAMERA_C2LIDAR_TRANSFORM, DataField.CAMERA_INTRINSICS, DataField.IMAGE_RGB])
|
| 903 |
+
else:
|
| 904 |
+
example = self.dataset._read_rgb_and_lidar(lidar_data_idx, lidar_frame_indices, ["custom"])
|
| 905 |
+
except Exception as e:
|
| 906 |
+
log.info(f"Error loading data for index {idx}: {e}", rank0_only=False)
|
| 907 |
+
return self.__getitem__(np.random.randint(0, self.__len__()))
|
| 908 |
+
|
| 909 |
+
lidar_rangemap = self.get_lidar(example)
|
| 910 |
+
lidar_hdmap = self.get_lidar_hdmap(example)
|
| 911 |
+
bev_hdmap = self.get_lidar_hdmap_bev(example)
|
| 912 |
+
rgb_images = self.get_rgb(example)
|
| 913 |
+
rgb_hdmap = self.get_rgb_hdmap(example)
|
| 914 |
+
try:
|
| 915 |
+
t5_embed = self.prepare_t5_embeddings(example, lidar_frame_indices)
|
| 916 |
+
except (FileNotFoundError, RuntimeError) as e:
|
| 917 |
+
log.warning(
|
| 918 |
+
f"T5 embedding load failed for index {idx} "
|
| 919 |
+
f"(key={example['__key__']}): {e}; retrying with new index",
|
| 920 |
+
rank0_only=False,
|
| 921 |
+
)
|
| 922 |
+
return self.__getitem__(np.random.randint(0, self.__len__()))
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
cam_intrinsics = self.get_camera_intrinsics(example)
|
| 926 |
+
cam_c2lidar_transform = self.get_camera_c2lidar_transform(example)
|
| 927 |
+
|
| 928 |
+
key = "video"
|
| 929 |
+
|
| 930 |
+
sample = {}
|
| 931 |
+
sample[key] = lidar_rangemap
|
| 932 |
+
sample["__key__"] = example["__key__"]
|
| 933 |
+
sample["clip_name"] = "%s-%s-%d" % (self.data_name, example["__key__"], idx)
|
| 934 |
+
sample["data_type"] = "lidar"
|
| 935 |
+
sample["num_frames"] = self.sample_n_frames + 1 if self.is_video_tokenizer else self.sample_n_frames
|
| 936 |
+
sample["is_preprocessed"] = True
|
| 937 |
+
sample["image_size"] = torch.tensor(self.lidar_size)
|
| 938 |
+
sample["padding_mask"] = torch.zeros(1, self.lidar_size[0], self.lidar_size[1])
|
| 939 |
+
sample["fps"] = 24 # unsure why this value
|
| 940 |
+
sample['num_views'] = self.num_views
|
| 941 |
+
sample["view_indices"] = torch.arange(self.num_views + self.plus) # +1 for the lidar view
|
| 942 |
+
sample["timestamp_list"] = example["timestamp_list"]
|
| 943 |
+
sample["pose_sensor_start_end"] = example["pose_sensor_start_end"]
|
| 944 |
+
# Sweep-start ego poses for the *actually sampled* frames (sequential
|
| 945 |
+
# sampling uses a random start_idx) -- forwarded so --save_poses dumps
|
| 946 |
+
# poses aligned to the dumped range maps rather than re-deriving from
|
| 947 |
+
# metadata assuming start frame 0.
|
| 948 |
+
sample["lidar_to_world"] = np.asarray(
|
| 949 |
+
example["lidar_to_world"], dtype=np.float32)
|
| 950 |
+
sample["rgb_frame_indices"]=example["rgb_frame_indices"]
|
| 951 |
+
sample.update(t5_embed)
|
| 952 |
+
|
| 953 |
+
if lidar_hdmap is not None:
|
| 954 |
+
sample["lidar_hdmap"] = lidar_hdmap
|
| 955 |
+
if bev_hdmap is not None:
|
| 956 |
+
sample["bev_hdmap"] = bev_hdmap
|
| 957 |
+
if rgb_images is not None:
|
| 958 |
+
sample.update(rgb_images)
|
| 959 |
+
if rgb_hdmap is not None:
|
| 960 |
+
sample.update(rgb_hdmap)
|
| 961 |
+
if self.load_lidar_and_rgb:
|
| 962 |
+
|
| 963 |
+
sample.update(cam_intrinsics)
|
| 964 |
+
sample.update(cam_c2lidar_transform)
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
del example
|
| 968 |
+
gc.collect()
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Exact track-ID join for legacy Waymo HDMap box dumps."""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_NCORE_CLASS_TO_BOX_TYPE = {
|
| 14 |
+
"vehicle": 0,
|
| 15 |
+
"pedestrian": 1,
|
| 16 |
+
"cyclist": 2,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def resolve_waymo_box_track_ids_from_ncore(
|
| 21 |
+
*,
|
| 22 |
+
hdmap_composer,
|
| 23 |
+
sequence_loader,
|
| 24 |
+
lidar_sensor,
|
| 25 |
+
) -> tuple[np.ndarray, dict[str, Any]]:
|
| 26 |
+
"""Attach exact NCore cuboid track IDs to legacy HDMap box rows."""
|
| 27 |
+
box_frame = np.asarray(hdmap_composer.box_frame, dtype=np.int64)
|
| 28 |
+
existing = np.asarray(hdmap_composer.box_track_id, dtype=np.int64)
|
| 29 |
+
if existing.shape != box_frame.shape:
|
| 30 |
+
raise ValueError(
|
| 31 |
+
"box_track_id must align with box_frame, got "
|
| 32 |
+
f"{existing.shape} and {box_frame.shape}"
|
| 33 |
+
)
|
| 34 |
+
if existing.size == 0 or np.all(existing >= 0):
|
| 35 |
+
return existing.copy(), {
|
| 36 |
+
"track_id_source": "hdmap_npz",
|
| 37 |
+
"matched_box_rows": int(existing.shape[0]),
|
| 38 |
+
"max_box_center_error_m": 0.0,
|
| 39 |
+
"max_box_size_error_m": 0.0,
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
from ncore.impl.data.v4.components import CuboidsComponent
|
| 43 |
+
|
| 44 |
+
component_reader = getattr(sequence_loader, "_reader", None)
|
| 45 |
+
if component_reader is None:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
"the NCore sequence loader does not expose its component reader"
|
| 48 |
+
)
|
| 49 |
+
cuboid_readers = component_reader.open_component_readers(
|
| 50 |
+
CuboidsComponent.Reader
|
| 51 |
+
)
|
| 52 |
+
if "default" not in cuboid_readers:
|
| 53 |
+
raise ValueError(
|
| 54 |
+
"the NCore sequence has no default cuboid component; exact dynamic "
|
| 55 |
+
"actor composition is unavailable"
|
| 56 |
+
)
|
| 57 |
+
observations = list(cuboid_readers["default"].get_observations())
|
| 58 |
+
|
| 59 |
+
frame_timestamps = np.asarray(
|
| 60 |
+
lidar_sensor.get_frames_timestamps_us(), dtype=np.int64
|
| 61 |
+
)
|
| 62 |
+
timestamp_to_frame = {
|
| 63 |
+
int(timestamp): frame_index
|
| 64 |
+
for frame_index, timestamp in enumerate(frame_timestamps)
|
| 65 |
+
}
|
| 66 |
+
frame_indices = np.arange(frame_timestamps.shape[0], dtype=np.int64)
|
| 67 |
+
lidar_to_world = np.asarray(
|
| 68 |
+
lidar_sensor.get_frames_T_sensor_target("world", frame_indices),
|
| 69 |
+
dtype=np.float64,
|
| 70 |
+
)
|
| 71 |
+
sensor_id = str(lidar_sensor.sensor_id)
|
| 72 |
+
|
| 73 |
+
candidates: dict[
|
| 74 |
+
tuple[int, int], list[tuple[str, np.ndarray, np.ndarray]]
|
| 75 |
+
] = {}
|
| 76 |
+
for observation in observations:
|
| 77 |
+
class_name = str(observation.class_id).split(".")[-1].lower()
|
| 78 |
+
box_type = _NCORE_CLASS_TO_BOX_TYPE.get(class_name)
|
| 79 |
+
if box_type is None:
|
| 80 |
+
continue
|
| 81 |
+
if str(observation.reference_frame_id) != sensor_id:
|
| 82 |
+
raise ValueError(
|
| 83 |
+
"expected NCore cuboids in the LiDAR frame, got "
|
| 84 |
+
f"{observation.reference_frame_id!r}"
|
| 85 |
+
)
|
| 86 |
+
frame_index = timestamp_to_frame.get(
|
| 87 |
+
int(observation.reference_frame_timestamp_us)
|
| 88 |
+
)
|
| 89 |
+
if frame_index is None:
|
| 90 |
+
continue
|
| 91 |
+
pose = lidar_to_world[frame_index]
|
| 92 |
+
center_sensor = np.asarray(
|
| 93 |
+
observation.bbox3.centroid, dtype=np.float64
|
| 94 |
+
)
|
| 95 |
+
center_world = center_sensor @ pose[:3, :3].T + pose[:3, 3]
|
| 96 |
+
candidates.setdefault((frame_index, box_type), []).append(
|
| 97 |
+
(
|
| 98 |
+
str(observation.track_id),
|
| 99 |
+
center_world,
|
| 100 |
+
np.asarray(observation.bbox3.dim, dtype=np.float64),
|
| 101 |
+
)
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
box_o2w = np.asarray(hdmap_composer.box_o2w, dtype=np.float64)
|
| 105 |
+
box_lwh = np.asarray(hdmap_composer.box_lwh, dtype=np.float64)
|
| 106 |
+
box_type = np.asarray(hdmap_composer.box_type, dtype=np.int64)
|
| 107 |
+
matched_track_names: list[str | None] = [None] * box_frame.shape[0]
|
| 108 |
+
center_errors: list[float] = []
|
| 109 |
+
size_errors: list[float] = []
|
| 110 |
+
|
| 111 |
+
for key in sorted(set(zip(box_frame.tolist(), box_type.tolist()))):
|
| 112 |
+
rows = np.nonzero(
|
| 113 |
+
(box_frame == key[0]) & (box_type == key[1])
|
| 114 |
+
)[0]
|
| 115 |
+
frame_candidates = candidates.get(key, [])
|
| 116 |
+
if len(frame_candidates) != int(rows.shape[0]):
|
| 117 |
+
raise ValueError(
|
| 118 |
+
"NCore cuboids do not align with HDMap boxes for "
|
| 119 |
+
f"frame/type={key}: boxes={rows.shape[0]}, "
|
| 120 |
+
f"cuboids={len(frame_candidates)}"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
candidate_centers = np.stack(
|
| 124 |
+
[candidate[1] for candidate in frame_candidates]
|
| 125 |
+
)
|
| 126 |
+
candidate_sizes = np.stack(
|
| 127 |
+
[candidate[2] for candidate in frame_candidates]
|
| 128 |
+
)
|
| 129 |
+
row_centers = box_o2w[rows, :3, 3]
|
| 130 |
+
row_sizes = box_lwh[rows]
|
| 131 |
+
center_distance = np.linalg.norm(
|
| 132 |
+
row_centers[:, None] - candidate_centers[None], axis=-1
|
| 133 |
+
)
|
| 134 |
+
size_distance = np.linalg.norm(
|
| 135 |
+
row_sizes[:, None] - candidate_sizes[None], axis=-1
|
| 136 |
+
)
|
| 137 |
+
cost = center_distance + size_distance
|
| 138 |
+
|
| 139 |
+
row_assignment = np.full(rows.shape[0], -1, dtype=np.int64)
|
| 140 |
+
used_candidates = np.zeros(len(frame_candidates), dtype=bool)
|
| 141 |
+
for flat_index in np.argsort(cost, axis=None):
|
| 142 |
+
local_row, candidate_index = np.unravel_index(
|
| 143 |
+
int(flat_index), cost.shape
|
| 144 |
+
)
|
| 145 |
+
if (
|
| 146 |
+
row_assignment[local_row] >= 0
|
| 147 |
+
or used_candidates[candidate_index]
|
| 148 |
+
):
|
| 149 |
+
continue
|
| 150 |
+
row_assignment[local_row] = candidate_index
|
| 151 |
+
used_candidates[candidate_index] = True
|
| 152 |
+
if (row_assignment < 0).any():
|
| 153 |
+
raise RuntimeError(
|
| 154 |
+
f"failed to join all HDMap boxes for frame/type={key}"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
for local_row, candidate_index in enumerate(row_assignment):
|
| 158 |
+
center_error = float(
|
| 159 |
+
center_distance[local_row, candidate_index]
|
| 160 |
+
)
|
| 161 |
+
size_error = float(size_distance[local_row, candidate_index])
|
| 162 |
+
if center_error > 0.05 or size_error > 0.01:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
"NCore cuboid does not exactly match its HDMap box: "
|
| 165 |
+
f"frame/type={key}, center_error={center_error:.6f}m, "
|
| 166 |
+
f"size_error={size_error:.6f}m"
|
| 167 |
+
)
|
| 168 |
+
matched_track_names[int(rows[local_row])] = frame_candidates[
|
| 169 |
+
int(candidate_index)
|
| 170 |
+
][0]
|
| 171 |
+
center_errors.append(center_error)
|
| 172 |
+
size_errors.append(size_error)
|
| 173 |
+
|
| 174 |
+
if any(track_name is None for track_name in matched_track_names):
|
| 175 |
+
raise RuntimeError("not every HDMap box received an NCore track ID")
|
| 176 |
+
unique_names = sorted(set(matched_track_names))
|
| 177 |
+
name_to_id = {
|
| 178 |
+
track_name: track_id
|
| 179 |
+
for track_id, track_name in enumerate(unique_names)
|
| 180 |
+
}
|
| 181 |
+
resolved = np.asarray(
|
| 182 |
+
[name_to_id[track_name] for track_name in matched_track_names],
|
| 183 |
+
dtype=np.int64,
|
| 184 |
+
)
|
| 185 |
+
return resolved, {
|
| 186 |
+
"track_id_source": "ncore_cuboids_exact_geometry_join",
|
| 187 |
+
"matched_box_rows": int(resolved.shape[0]),
|
| 188 |
+
"cuboid_tracks": int(len(unique_names)),
|
| 189 |
+
"max_box_center_error_m": max(center_errors, default=0.0),
|
| 190 |
+
"max_box_size_error_m": max(size_errors, default=0.0),
|
| 191 |
+
}
|
diffusion/training/functional/loss.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Tuple, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from diffusion.functional.batch_ops import batch_mul
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def create_per_sample_loss_mask(
|
| 24 |
+
loss_masking_cfg: dict,
|
| 25 |
+
data_batch: dict,
|
| 26 |
+
x_shape: Tuple[int],
|
| 27 |
+
dtype: torch.dtype,
|
| 28 |
+
device: Union[str, torch.device] = "cuda",
|
| 29 |
+
):
|
| 30 |
+
"""
|
| 31 |
+
Creates a per-sample loss mask based on the given configuration and input data batch.
|
| 32 |
+
|
| 33 |
+
This function generates a dictionary of loss masks for each specified key in the loss masking configuration.
|
| 34 |
+
For keys present in both the configuration and the data batch, the corresponding data batch value is used.
|
| 35 |
+
For keys present only in the configuration, a tensor of zeros with the specified shape is created.
|
| 36 |
+
Additionally, it computes loss mask weights for each key based on the configuration values and adjusts them
|
| 37 |
+
based on the presence of certain keys in the data batch, such as "skip_face" and "object_loss_map".
|
| 38 |
+
|
| 39 |
+
Note:
|
| 40 |
+
- The original `loss_masking_cfg` and `data_batch` are not modified by this function.
|
| 41 |
+
- For image data, it is assumed that the channel is always the first dimension.
|
| 42 |
+
- `skip_face` is for face regions that should be skipped during training, the key is provided so that we can generate
|
| 43 |
+
diverse human and avoid collapse to a single face given certain prompts. The issue happens for getty projects,
|
| 44 |
+
where face distribution in the dataset is high unbalanced that single man face can be shown in more than 100+ images.
|
| 45 |
+
|
| 46 |
+
Parameters:
|
| 47 |
+
loss_masking_cfg (dict): Configuration for loss masking, specifying which keys to include and their weights.
|
| 48 |
+
data_batch (dict): The batch of data containing actual data points and potential mask indicators like "skip_face".
|
| 49 |
+
x_shape (tuple): The shape of the input data, used to initialize zero masks for keys not in the data batch.
|
| 50 |
+
dtype (torch.dtype): The data type for the tensors in the loss masks.
|
| 51 |
+
device (str, optional): The device on which to create the tensors. Defaults to 'cuda'.
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
dict: A dictionary containing combined loss masks adjusted according to the `loss_masking_cfg` and `data_batch`.
|
| 55 |
+
|
| 56 |
+
Raises:
|
| 57 |
+
AssertionError: If "skip_face" is not present in `data_batch`.
|
| 58 |
+
|
| 59 |
+
Note: `create_combined_loss_mask` is assumed to be a separate function that combines individual loss masks into a
|
| 60 |
+
single mask or set of masks based on the given parameters. Its behavior should be documented separately.
|
| 61 |
+
"""
|
| 62 |
+
loss_mask_data: dict = {}
|
| 63 |
+
for key in loss_masking_cfg:
|
| 64 |
+
if key not in data_batch:
|
| 65 |
+
loss_mask_data[key] = torch.zeros((x_shape[0], 1, x_shape[2], x_shape[3]), device=device)
|
| 66 |
+
else:
|
| 67 |
+
loss_mask_data[key] = data_batch[key]
|
| 68 |
+
|
| 69 |
+
if "skip_face" not in data_batch:
|
| 70 |
+
# When skip_face is not there in data_dict, use 0 as default. This will not skip any sample.
|
| 71 |
+
data_batch["skip_face"] = torch.zeros((x_shape[0],), dtype=dtype, device=device)
|
| 72 |
+
|
| 73 |
+
loss_mask_weight: dict = {}
|
| 74 |
+
for k, v in loss_masking_cfg.items():
|
| 75 |
+
loss_mask_weight[k] = torch.tensor(v, device=device).expand(data_batch["skip_face"].size())
|
| 76 |
+
|
| 77 |
+
if "human_face_mask" in loss_mask_weight:
|
| 78 |
+
loss_mask_weight["human_face_mask"] = (1 - data_batch["skip_face"]) * loss_mask_weight["human_face_mask"]
|
| 79 |
+
|
| 80 |
+
if "object_loss_map" in data_batch:
|
| 81 |
+
loss_mask_weight["object_loss_map"] = torch.ones(data_batch["object_loss_map"].shape[0], device=device)
|
| 82 |
+
|
| 83 |
+
return create_combined_loss_mask(loss_mask_data, x_shape, dtype, device, loss_mask_weight)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def create_combined_loss_mask(data, x_shape, dtype, device="cuda", loss_masking=None):
|
| 87 |
+
"""
|
| 88 |
+
Creates a combined loss mask from multiple input masks.
|
| 89 |
+
|
| 90 |
+
This function combines several loss masks into a single mask. In regions where masks overlap,
|
| 91 |
+
the highest value is assigned. Non-overlapping regions are assigned a default value of 1.
|
| 92 |
+
Regions with a mask value of zero are explicitly zeroed out, which is essential for padded loss calculations.
|
| 93 |
+
|
| 94 |
+
Example:
|
| 95 |
+
Given the following masks and weights:
|
| 96 |
+
mask1: [0, 1, 1, 1, 0, 0], weight: 2
|
| 97 |
+
mask2: [1, 0, 1, 0, 0, 0], weight: 4
|
| 98 |
+
mask3: [0, 1, 0, 0, 0, 0], weight: 0
|
| 99 |
+
The resulting combined loss mask would be:
|
| 100 |
+
[4, 0, 4, 2, 1, 1]
|
| 101 |
+
|
| 102 |
+
Parameters:
|
| 103 |
+
data (dict): Contains the loss masks and their weights.
|
| 104 |
+
x_shape (tuple): The shape of the output mask.
|
| 105 |
+
dtype: The data type for the output mask.
|
| 106 |
+
device: The device on which the output mask will be allocated.
|
| 107 |
+
loss_masking: The loss masking weight configuration.
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
torch.Tensor: The combined loss mask.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
loss_mask = torch.ones(x_shape, dtype=dtype, device=device)
|
| 114 |
+
zero_mask = torch.ones(x_shape, dtype=dtype, device=device)
|
| 115 |
+
|
| 116 |
+
if loss_masking:
|
| 117 |
+
for key in loss_masking:
|
| 118 |
+
# Repeat mask along channel's dimension. ndim=4 for images.
|
| 119 |
+
repeat_dims = (1, x_shape[1]) + tuple([1] * (data[key].ndim - 2))
|
| 120 |
+
mask_key = torch.tile(data[key], dims=repeat_dims)
|
| 121 |
+
weight_key = loss_masking[key]
|
| 122 |
+
|
| 123 |
+
# handle zero weight case
|
| 124 |
+
is_zero_weight = (weight_key == 0).float()[:, None, None, None]
|
| 125 |
+
zero_mask = zero_mask * (
|
| 126 |
+
(1 - is_zero_weight) * torch.ones(x_shape, dtype=dtype, device=device)
|
| 127 |
+
+ is_zero_weight * (1 - mask_key.bool().float())
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# calculate weights
|
| 131 |
+
no_mask_region = (mask_key.bool() == 0).float()
|
| 132 |
+
loss_mask = batch_mul(mask_key, weight_key) + batch_mul(no_mask_region, loss_mask)
|
| 133 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from utils import distributed, log
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TeroPolyScheduler:
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
total_Mimg: int,
|
| 27 |
+
batch_size: int,
|
| 28 |
+
ref_Mimg: Optional[int] = None,
|
| 29 |
+
ref_batches: float = 70e3 / 1024,
|
| 30 |
+
max_lr_ratio: Optional[float] = 1.0,
|
| 31 |
+
min_lr_ratio: Optional[float] = None,
|
| 32 |
+
rampup_Mimg: float = 0,
|
| 33 |
+
rampdown_Mimg: int = 0,
|
| 34 |
+
verbosity_interval: int = 0,
|
| 35 |
+
formula: str = "poly",
|
| 36 |
+
poly_exp: float = 0.5,
|
| 37 |
+
):
|
| 38 |
+
self.total_Mimg = total_Mimg
|
| 39 |
+
self.batch_size = batch_size * distributed.get_world_size()
|
| 40 |
+
self.ref_Mimg = ref_Mimg or ref_batches * batch_size / 1e6
|
| 41 |
+
self.ref_batches = ref_batches
|
| 42 |
+
self.max_lr_ratio = max_lr_ratio
|
| 43 |
+
self.min_lr_ratio = min_lr_ratio
|
| 44 |
+
self.rampup_Mimg = rampup_Mimg
|
| 45 |
+
self.rampdown_Mimg = rampdown_Mimg
|
| 46 |
+
self.verbosity_interval = verbosity_interval
|
| 47 |
+
self.formula = formula
|
| 48 |
+
self.poly_exp = poly_exp
|
| 49 |
+
|
| 50 |
+
self._model = None
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def model(self):
|
| 54 |
+
return self._model
|
| 55 |
+
|
| 56 |
+
@model.setter
|
| 57 |
+
def model(self, model):
|
| 58 |
+
self._model = model
|
| 59 |
+
|
| 60 |
+
def schedule(self, n, **kwargs):
|
| 61 |
+
cur_Mimg = getattr(self.model, "sample_counter", 0) / 1e6
|
| 62 |
+
|
| 63 |
+
if self.formula == "constant":
|
| 64 |
+
lr = 1.0
|
| 65 |
+
elif self.formula == "poly":
|
| 66 |
+
lr = max(cur_Mimg / self.ref_Mimg, 1e-8) ** -self.poly_exp
|
| 67 |
+
else:
|
| 68 |
+
raise ValueError(f'Invalid learning rate formula "{self.formula}"')
|
| 69 |
+
|
| 70 |
+
if self.max_lr_ratio is not None:
|
| 71 |
+
lr = min(lr, self.max_lr_ratio)
|
| 72 |
+
if self.min_lr_ratio is not None:
|
| 73 |
+
lr = max(lr, self.min_lr_ratio)
|
| 74 |
+
|
| 75 |
+
if self.rampup_Mimg > 0 and cur_Mimg < self.rampup_Mimg:
|
| 76 |
+
lr *= cur_Mimg / self.rampup_Mimg
|
| 77 |
+
if self.rampdown_Mimg > 0 and cur_Mimg > self.total_Mimg - self.rampdown_Mimg:
|
| 78 |
+
lr *= (self.total_Mimg - cur_Mimg) / self.rampdown_Mimg
|
| 79 |
+
|
| 80 |
+
return lr
|
| 81 |
+
|
| 82 |
+
def __call__(self, n, **kwargs):
|
| 83 |
+
return self.schedule(n, **kwargs)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class LambdaWarmUpCosineScheduler:
|
| 87 |
+
"""
|
| 88 |
+
A learning rate scheduler that combines warm-up with a cosine decay schedule for multiple cycles.
|
| 89 |
+
It supports different configurations for each cycle, including the number of warm-up steps, minimum
|
| 90 |
+
and maximum scaling factors for the learning rate.
|
| 91 |
+
|
| 92 |
+
The scheduler is intended to be used with a base learning rate of 1.0, where the actual learning
|
| 93 |
+
rate at any step is the base learning rate multiplied by the scaling factor computed by the scheduler.
|
| 94 |
+
|
| 95 |
+
Parameters:
|
| 96 |
+
warm_up_steps (list[int]): List of integers where each element represents the number of warm-up
|
| 97 |
+
steps for the corresponding cycle.
|
| 98 |
+
f_min (list[float]): List of the minimum scaling factors for each cycle after warm-up.
|
| 99 |
+
f_max (list[float]): List of the maximum scaling factors at the start and end of each cosine cycle.
|
| 100 |
+
f_start (list[float]): List of starting scaling factors for each warm-up phase.
|
| 101 |
+
cycle_lengths (list[int]): List of the total lengths of each cycle, including warm-up steps.
|
| 102 |
+
verbosity_interval (int, optional): Interval of training steps at which to print current step and
|
| 103 |
+
scaling factor information. Set to 0 by default to disable verbosity.
|
| 104 |
+
|
| 105 |
+
Examples:
|
| 106 |
+
>>> scheduler = LambdaWarmUpCosineScheduler2(
|
| 107 |
+
warm_up_steps=[10, 10],
|
| 108 |
+
f_min=[0.1, 0.1],
|
| 109 |
+
f_max=[1.0, 1.0],
|
| 110 |
+
f_start=[0.01, 0.01],
|
| 111 |
+
cycle_lengths=[50, 50],
|
| 112 |
+
verbosity_interval=10)
|
| 113 |
+
>>> for step in range(100):
|
| 114 |
+
>>> lr_multiplier = scheduler(step)
|
| 115 |
+
>>> print(f"Step {step}: LR Multiplier = {lr_multiplier}")
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def __init__(self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0):
|
| 119 |
+
assert len(warm_up_steps) == len(f_min) == len(f_max) == len(f_start) == len(cycle_lengths)
|
| 120 |
+
self.lr_warm_up_steps = warm_up_steps
|
| 121 |
+
self.f_start = f_start
|
| 122 |
+
self.f_min = f_min
|
| 123 |
+
self.f_max = f_max
|
| 124 |
+
self.cycle_lengths = cycle_lengths
|
| 125 |
+
self.cum_cycles = np.cumsum([0] + list(self.cycle_lengths))
|
| 126 |
+
self.last_f = 0.0
|
| 127 |
+
self.verbosity_interval = verbosity_interval
|
| 128 |
+
|
| 129 |
+
def find_in_interval(self, n):
|
| 130 |
+
interval = 0
|
| 131 |
+
for cl in self.cum_cycles[1:]:
|
| 132 |
+
if n <= cl:
|
| 133 |
+
return interval
|
| 134 |
+
interval += 1
|
| 135 |
+
|
| 136 |
+
def schedule(self, n, **kwargs):
|
| 137 |
+
cycle = self.find_in_interval(n)
|
| 138 |
+
n = n - self.cum_cycles[cycle]
|
| 139 |
+
if self.verbosity_interval > 0:
|
| 140 |
+
if n % self.verbosity_interval == 0:
|
| 141 |
+
log.info(f"current step: {n}, recent lr-multiplier: {self.last_f}, " f"current cycle {cycle}")
|
| 142 |
+
if n < self.lr_warm_up_steps[cycle]:
|
| 143 |
+
f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
|
| 144 |
+
self.last_f = f
|
| 145 |
+
return f
|
| 146 |
+
else:
|
| 147 |
+
t = (n - self.lr_warm_up_steps[cycle]) / (self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle])
|
| 148 |
+
t = min(t, 1.0)
|
| 149 |
+
f = self.f_min[cycle] + 0.5 * (self.f_max[cycle] - self.f_min[cycle]) * (1 + np.cos(t * np.pi))
|
| 150 |
+
self.last_f = f
|
| 151 |
+
return f
|
| 152 |
+
|
| 153 |
+
def __call__(self, n, **kwargs):
|
| 154 |
+
return self.schedule(n, **kwargs)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class LambdaLinearScheduler(LambdaWarmUpCosineScheduler):
|
| 158 |
+
"""
|
| 159 |
+
Linear instead of cosine decay for the main part of the cycle.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def schedule(self, n, **kwargs):
|
| 163 |
+
cycle = self.find_in_interval(n)
|
| 164 |
+
n = n - self.cum_cycles[cycle]
|
| 165 |
+
if self.verbosity_interval > 0:
|
| 166 |
+
if n % self.verbosity_interval == 0:
|
| 167 |
+
log.info(f"current step: {n}, recent lr-multiplier: {self.last_f}, " f"current cycle {cycle}")
|
| 168 |
+
|
| 169 |
+
if n < self.lr_warm_up_steps[cycle]:
|
| 170 |
+
f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
|
| 171 |
+
self.last_f = f
|
| 172 |
+
return f
|
| 173 |
+
else:
|
| 174 |
+
f = self.f_min[cycle] + (self.f_max[cycle] - self.f_min[cycle]) * (self.cycle_lengths[cycle] - n) / (
|
| 175 |
+
self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle]
|
| 176 |
+
)
|
| 177 |
+
self.last_f = f
|
| 178 |
+
return f
|
diffusion/training/models/fm_solvers_dpm.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
# Copyright 2025 TSAIL Team and The HuggingFace Team. All rights reserved.
|
| 4 |
+
# NVIDIA modifications: LiDAR rectified-flow sampling integration.
|
| 5 |
+
|
| 6 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
|
| 7 |
+
# Specialized for FLOW MATCHING (rectified flow): prediction_type="flow_prediction",
|
| 8 |
+
# flow sigmas (alpha_t = 1 - sigma, sigma_t = sigma), and the SAME shift / LTX-stretch
|
| 9 |
+
# sigma ladder as ``FlowUniPCMultistepScheduler`` so it is a drop-in sibling of the
|
| 10 |
+
# UniPC scheduler already used by the RF models.
|
| 11 |
+
#
|
| 12 |
+
# Supports the "dpmsolver++" (deterministic, high-order ODE) and "sde-dpmsolver++"
|
| 13 |
+
# (stochastic) algorithm types -- i.e. "Flow-DPM-Solver++". Orders 1-3, midpoint /
|
| 14 |
+
# heun second-order variants.
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from typing import List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 22 |
+
from diffusers.schedulers.scheduling_utils import (
|
| 23 |
+
KarrasDiffusionSchedulers,
|
| 24 |
+
SchedulerMixin,
|
| 25 |
+
SchedulerOutput,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
from diffusion.training.schedulers.shift_schedule import stretch_shifts_to_terminal
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class FlowDPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
|
| 32 |
+
"""Flow-matching DPM-Solver++ (and SDE-DPM-Solver++) multistep scheduler.
|
| 33 |
+
|
| 34 |
+
Mirrors :class:`FlowUniPCMultistepScheduler` (same flow sigma ladder,
|
| 35 |
+
``set_timesteps`` shift/stretch interface, ``step`` signature) but the
|
| 36 |
+
update rule is DPM-Solver++ (data-prediction exponential integrator).
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
solver_order: 1, 2, or 3. Effective ODE order. 2 is a good default for
|
| 40 |
+
guided sampling; 3 for unconditional.
|
| 41 |
+
algorithm_type: ``"dpmsolver++"`` (deterministic) or
|
| 42 |
+
``"sde-dpmsolver++"`` (stochastic). The SDE variant injects fresh
|
| 43 |
+
noise each step (the marginal-preserving Langevin term) and tends to
|
| 44 |
+
beat the ODE for imperfect models at enough steps.
|
| 45 |
+
solver_type: ``"midpoint"`` or ``"heun"`` (2nd-order coefficient variant).
|
| 46 |
+
lower_order_final / euler_at_final: drop to lower order on the last
|
| 47 |
+
step(s) for stability at small step counts (recommended).
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
|
| 51 |
+
order = 1
|
| 52 |
+
|
| 53 |
+
@register_to_config
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
num_train_timesteps: int = 1000,
|
| 57 |
+
solver_order: int = 2,
|
| 58 |
+
prediction_type: str = "flow_prediction",
|
| 59 |
+
shift: Optional[float] = 1.0,
|
| 60 |
+
use_dynamic_shifting: bool = False,
|
| 61 |
+
thresholding: bool = False,
|
| 62 |
+
dynamic_thresholding_ratio: float = 0.995,
|
| 63 |
+
sample_max_value: float = 1.0,
|
| 64 |
+
algorithm_type: str = "dpmsolver++",
|
| 65 |
+
solver_type: str = "midpoint",
|
| 66 |
+
lower_order_final: bool = True,
|
| 67 |
+
euler_at_final: bool = False,
|
| 68 |
+
final_sigmas_type: str = "zero", # "zero" | "sigma_min"
|
| 69 |
+
):
|
| 70 |
+
if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"]:
|
| 71 |
+
raise NotImplementedError(
|
| 72 |
+
f"{algorithm_type} is not implemented for {self.__class__}. "
|
| 73 |
+
"Use 'dpmsolver++' or 'sde-dpmsolver++'."
|
| 74 |
+
)
|
| 75 |
+
if solver_type not in ["midpoint", "heun"]:
|
| 76 |
+
if solver_type in ["logrho", "bh1", "bh2"]:
|
| 77 |
+
self.register_to_config(solver_type="midpoint")
|
| 78 |
+
else:
|
| 79 |
+
raise NotImplementedError(
|
| 80 |
+
f"{solver_type} is not implemented for {self.__class__}"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Flow sigma ladder (sigma in [0,1]); mirrors FlowUniPCMultistepScheduler.
|
| 84 |
+
self.num_inference_steps = None
|
| 85 |
+
alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps)[::-1].copy()
|
| 86 |
+
sigmas = 1.0 - alphas
|
| 87 |
+
sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32)
|
| 88 |
+
if not use_dynamic_shifting:
|
| 89 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
|
| 90 |
+
|
| 91 |
+
self.sigmas = sigmas
|
| 92 |
+
self.timesteps = sigmas * num_train_timesteps
|
| 93 |
+
|
| 94 |
+
self.model_outputs = [None] * solver_order
|
| 95 |
+
self.lower_order_nums = 0
|
| 96 |
+
self._step_index = None
|
| 97 |
+
self._begin_index = None
|
| 98 |
+
|
| 99 |
+
self.sigmas = self.sigmas.to("cpu")
|
| 100 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 101 |
+
self.sigma_max = self.sigmas[0].item()
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def step_index(self):
|
| 105 |
+
return self._step_index
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def begin_index(self):
|
| 109 |
+
return self._begin_index
|
| 110 |
+
|
| 111 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 112 |
+
self._begin_index = begin_index
|
| 113 |
+
|
| 114 |
+
def _sigma_to_alpha_sigma_t(self, sigma):
|
| 115 |
+
# Flow matching: x_t = (1 - sigma) * x0 + sigma * eps.
|
| 116 |
+
return 1 - sigma, sigma
|
| 117 |
+
|
| 118 |
+
def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
|
| 119 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 120 |
+
|
| 121 |
+
def set_timesteps(
|
| 122 |
+
self,
|
| 123 |
+
num_inference_steps: Union[int, None] = None,
|
| 124 |
+
device: Union[str, torch.device] = None,
|
| 125 |
+
sigmas: Optional[List[float]] = None,
|
| 126 |
+
mu: Optional[float] = None,
|
| 127 |
+
shift: Optional[float] = None,
|
| 128 |
+
stretch_terminal: Optional[float] = None,
|
| 129 |
+
):
|
| 130 |
+
"""Build the flow sigma ladder (shift + optional LTX stretch), append the
|
| 131 |
+
terminal sigma, and reset the multistep buffers. Signature matches
|
| 132 |
+
``FlowUniPCMultistepScheduler.set_timesteps`` so it's a drop-in swap."""
|
| 133 |
+
if self.config.use_dynamic_shifting and mu is None:
|
| 134 |
+
raise ValueError("pass `mu` when `use_dynamic_shifting=True`")
|
| 135 |
+
|
| 136 |
+
if sigmas is None:
|
| 137 |
+
sigmas = np.linspace(self.sigma_max, self.sigma_min, num_inference_steps + 1).copy()[:-1]
|
| 138 |
+
|
| 139 |
+
if self.config.use_dynamic_shifting:
|
| 140 |
+
sigmas = self.time_shift(mu, 1.0, sigmas)
|
| 141 |
+
else:
|
| 142 |
+
if shift is None:
|
| 143 |
+
shift = self.config.shift
|
| 144 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
|
| 145 |
+
if stretch_terminal is not None:
|
| 146 |
+
sigmas = stretch_shifts_to_terminal(
|
| 147 |
+
np.asarray(sigmas, dtype=np.float64), float(stretch_terminal)
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
if self.config.final_sigmas_type == "sigma_min":
|
| 151 |
+
sigma_last = self.sigma_min
|
| 152 |
+
elif self.config.final_sigmas_type == "zero":
|
| 153 |
+
sigma_last = 0
|
| 154 |
+
else:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
f"`final_sigmas_type` must be 'zero' or 'sigma_min', got "
|
| 157 |
+
f"{self.config.final_sigmas_type}"
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
timesteps = sigmas * self.config.num_train_timesteps
|
| 161 |
+
sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32)
|
| 162 |
+
|
| 163 |
+
self.sigmas = torch.from_numpy(sigmas)
|
| 164 |
+
self.timesteps = torch.from_numpy(timesteps).to(device=device, dtype=torch.int64)
|
| 165 |
+
|
| 166 |
+
self.num_inference_steps = len(timesteps)
|
| 167 |
+
self.model_outputs = [None] * self.config.solver_order
|
| 168 |
+
self.lower_order_nums = 0
|
| 169 |
+
self._step_index = None
|
| 170 |
+
self._begin_index = None
|
| 171 |
+
self.sigmas = self.sigmas.to("cpu")
|
| 172 |
+
|
| 173 |
+
def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
|
| 174 |
+
dtype = sample.dtype
|
| 175 |
+
batch_size, channels, *remaining_dims = sample.shape
|
| 176 |
+
if dtype not in (torch.float32, torch.float64):
|
| 177 |
+
sample = sample.float()
|
| 178 |
+
sample = sample.reshape(batch_size, channels * int(np.prod(remaining_dims)))
|
| 179 |
+
abs_sample = sample.abs()
|
| 180 |
+
s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
|
| 181 |
+
s = torch.clamp(s, min=1, max=self.config.sample_max_value)
|
| 182 |
+
s = s.unsqueeze(1)
|
| 183 |
+
sample = torch.clamp(sample, -s, s) / s
|
| 184 |
+
sample = sample.reshape(batch_size, channels, *remaining_dims)
|
| 185 |
+
return sample.to(dtype)
|
| 186 |
+
|
| 187 |
+
def convert_model_output(
|
| 188 |
+
self, model_output: torch.Tensor, *args, sample: torch.Tensor = None, **kwargs
|
| 189 |
+
) -> torch.Tensor:
|
| 190 |
+
"""Flow velocity -> predicted clean latent x0 (DPM-Solver++ is a data-
|
| 191 |
+
prediction integrator). x_t = (1-sigma)x0 + sigma*eps, v = eps - x0
|
| 192 |
+
=> x0 = x_t - sigma * v."""
|
| 193 |
+
if sample is None:
|
| 194 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 195 |
+
if self.config.prediction_type != "flow_prediction":
|
| 196 |
+
raise ValueError(
|
| 197 |
+
f"prediction_type {self.config.prediction_type} must be "
|
| 198 |
+
"'flow_prediction' for FlowDPMSolverMultistepScheduler."
|
| 199 |
+
)
|
| 200 |
+
sigma_t = self.sigmas[self.step_index]
|
| 201 |
+
x0_pred = sample - sigma_t * model_output
|
| 202 |
+
if self.config.thresholding:
|
| 203 |
+
x0_pred = self._threshold_sample(x0_pred)
|
| 204 |
+
return x0_pred
|
| 205 |
+
|
| 206 |
+
def dpm_solver_first_order_update(
|
| 207 |
+
self, model_output: torch.Tensor, *args,
|
| 208 |
+
sample: torch.Tensor = None, noise: Optional[torch.Tensor] = None, **kwargs,
|
| 209 |
+
) -> torch.Tensor:
|
| 210 |
+
if sample is None:
|
| 211 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 212 |
+
sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
|
| 213 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 214 |
+
alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
|
| 215 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 216 |
+
lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
|
| 217 |
+
h = lambda_t - lambda_s
|
| 218 |
+
if self.config.algorithm_type == "dpmsolver++":
|
| 219 |
+
x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
|
| 220 |
+
elif self.config.algorithm_type == "sde-dpmsolver++":
|
| 221 |
+
assert noise is not None
|
| 222 |
+
x_t = (
|
| 223 |
+
(sigma_t / sigma_s * torch.exp(-h)) * sample
|
| 224 |
+
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
|
| 225 |
+
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
|
| 226 |
+
)
|
| 227 |
+
return x_t
|
| 228 |
+
|
| 229 |
+
def multistep_dpm_solver_second_order_update(
|
| 230 |
+
self, model_output_list: List[torch.Tensor], *args,
|
| 231 |
+
sample: torch.Tensor = None, noise: Optional[torch.Tensor] = None, **kwargs,
|
| 232 |
+
) -> torch.Tensor:
|
| 233 |
+
if sample is None:
|
| 234 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 235 |
+
sigma_t, sigma_s0, sigma_s1 = (
|
| 236 |
+
self.sigmas[self.step_index + 1],
|
| 237 |
+
self.sigmas[self.step_index],
|
| 238 |
+
self.sigmas[self.step_index - 1],
|
| 239 |
+
)
|
| 240 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 241 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 242 |
+
alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
|
| 243 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 244 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 245 |
+
lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
|
| 246 |
+
|
| 247 |
+
m0, m1 = model_output_list[-1], model_output_list[-2]
|
| 248 |
+
h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
|
| 249 |
+
r0 = h_0 / h
|
| 250 |
+
D0, D1 = m0, (1.0 / r0) * (m0 - m1)
|
| 251 |
+
if self.config.algorithm_type == "dpmsolver++":
|
| 252 |
+
if self.config.solver_type == "midpoint":
|
| 253 |
+
x_t = (
|
| 254 |
+
(sigma_t / sigma_s0) * sample
|
| 255 |
+
- (alpha_t * (torch.exp(-h) - 1.0)) * D0
|
| 256 |
+
- 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
|
| 257 |
+
)
|
| 258 |
+
else: # heun
|
| 259 |
+
x_t = (
|
| 260 |
+
(sigma_t / sigma_s0) * sample
|
| 261 |
+
- (alpha_t * (torch.exp(-h) - 1.0)) * D0
|
| 262 |
+
+ (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
|
| 263 |
+
)
|
| 264 |
+
elif self.config.algorithm_type == "sde-dpmsolver++":
|
| 265 |
+
assert noise is not None
|
| 266 |
+
if self.config.solver_type == "midpoint":
|
| 267 |
+
x_t = (
|
| 268 |
+
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
|
| 269 |
+
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
|
| 270 |
+
+ 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
|
| 271 |
+
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
|
| 272 |
+
)
|
| 273 |
+
else: # heun
|
| 274 |
+
x_t = (
|
| 275 |
+
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
|
| 276 |
+
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
|
| 277 |
+
+ (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
|
| 278 |
+
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
|
| 279 |
+
)
|
| 280 |
+
return x_t
|
| 281 |
+
|
| 282 |
+
def multistep_dpm_solver_third_order_update(
|
| 283 |
+
self, model_output_list: List[torch.Tensor], *args,
|
| 284 |
+
sample: torch.Tensor = None, noise: Optional[torch.Tensor] = None, **kwargs,
|
| 285 |
+
) -> torch.Tensor:
|
| 286 |
+
if sample is None:
|
| 287 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 288 |
+
sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
|
| 289 |
+
self.sigmas[self.step_index + 1],
|
| 290 |
+
self.sigmas[self.step_index],
|
| 291 |
+
self.sigmas[self.step_index - 1],
|
| 292 |
+
self.sigmas[self.step_index - 2],
|
| 293 |
+
)
|
| 294 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 295 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 296 |
+
alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
|
| 297 |
+
alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2)
|
| 298 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 299 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 300 |
+
lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
|
| 301 |
+
lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2)
|
| 302 |
+
|
| 303 |
+
m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
|
| 304 |
+
h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
|
| 305 |
+
r0, r1 = h_0 / h, h_1 / h
|
| 306 |
+
D0 = m0
|
| 307 |
+
D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
|
| 308 |
+
D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
|
| 309 |
+
D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
|
| 310 |
+
if self.config.algorithm_type == "dpmsolver++":
|
| 311 |
+
x_t = (
|
| 312 |
+
(sigma_t / sigma_s0) * sample
|
| 313 |
+
- (alpha_t * (torch.exp(-h) - 1.0)) * D0
|
| 314 |
+
+ (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
|
| 315 |
+
- (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
|
| 316 |
+
)
|
| 317 |
+
elif self.config.algorithm_type == "sde-dpmsolver++":
|
| 318 |
+
assert noise is not None
|
| 319 |
+
x_t = (
|
| 320 |
+
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
|
| 321 |
+
+ (alpha_t * (1.0 - torch.exp(-2.0 * h))) * D0
|
| 322 |
+
+ (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
|
| 323 |
+
+ (alpha_t * ((1.0 - torch.exp(-2.0 * h) - 2.0 * h) / (2.0 * h) ** 2 - 0.5)) * D2
|
| 324 |
+
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
|
| 325 |
+
)
|
| 326 |
+
return x_t
|
| 327 |
+
|
| 328 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 329 |
+
if schedule_timesteps is None:
|
| 330 |
+
schedule_timesteps = self.timesteps
|
| 331 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 332 |
+
pos = 1 if len(indices) > 1 else 0
|
| 333 |
+
return indices[pos].item()
|
| 334 |
+
|
| 335 |
+
def _init_step_index(self, timestep):
|
| 336 |
+
if self.begin_index is None:
|
| 337 |
+
if isinstance(timestep, torch.Tensor):
|
| 338 |
+
timestep = timestep.to(self.timesteps.device)
|
| 339 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 340 |
+
else:
|
| 341 |
+
self._step_index = self._begin_index
|
| 342 |
+
|
| 343 |
+
def step(
|
| 344 |
+
self,
|
| 345 |
+
model_output: torch.Tensor,
|
| 346 |
+
timestep: Union[int, torch.Tensor],
|
| 347 |
+
sample: torch.Tensor,
|
| 348 |
+
generator=None,
|
| 349 |
+
variance_noise: Optional[torch.Tensor] = None,
|
| 350 |
+
return_dict: bool = True,
|
| 351 |
+
) -> Union[SchedulerOutput, Tuple]:
|
| 352 |
+
"""One multistep DPM-Solver++ update. Signature matches
|
| 353 |
+
``FlowUniPCMultistepScheduler.step`` (extra ``variance_noise`` kwarg for
|
| 354 |
+
the SDE variant is optional)."""
|
| 355 |
+
if self.num_inference_steps is None:
|
| 356 |
+
raise ValueError(
|
| 357 |
+
"Number of inference steps is 'None', run 'set_timesteps' first."
|
| 358 |
+
)
|
| 359 |
+
if self.step_index is None:
|
| 360 |
+
self._init_step_index(timestep)
|
| 361 |
+
|
| 362 |
+
# Lower the order on the final step(s) for stability (and to land exactly
|
| 363 |
+
# on x0 when the terminal sigma is 0).
|
| 364 |
+
is_last = self.step_index == len(self.timesteps) - 1
|
| 365 |
+
lower_order_final = is_last and (
|
| 366 |
+
self.config.euler_at_final
|
| 367 |
+
or (self.config.lower_order_final and len(self.timesteps) < 15)
|
| 368 |
+
or self.config.final_sigmas_type == "zero"
|
| 369 |
+
)
|
| 370 |
+
lower_order_second = (
|
| 371 |
+
(self.step_index == len(self.timesteps) - 2)
|
| 372 |
+
and self.config.lower_order_final
|
| 373 |
+
and len(self.timesteps) < 15
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
model_output = self.convert_model_output(model_output, sample=sample)
|
| 377 |
+
for i in range(self.config.solver_order - 1):
|
| 378 |
+
self.model_outputs[i] = self.model_outputs[i + 1]
|
| 379 |
+
self.model_outputs[-1] = model_output
|
| 380 |
+
|
| 381 |
+
sample = sample.to(torch.float32)
|
| 382 |
+
if self.config.algorithm_type == "sde-dpmsolver++":
|
| 383 |
+
if variance_noise is None:
|
| 384 |
+
noise = torch.randn(
|
| 385 |
+
model_output.shape, generator=generator,
|
| 386 |
+
device=model_output.device, dtype=torch.float32,
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
noise = variance_noise.to(device=model_output.device, dtype=torch.float32)
|
| 390 |
+
else:
|
| 391 |
+
noise = None
|
| 392 |
+
|
| 393 |
+
if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
|
| 394 |
+
prev_sample = self.dpm_solver_first_order_update(
|
| 395 |
+
model_output, sample=sample, noise=noise
|
| 396 |
+
)
|
| 397 |
+
elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
|
| 398 |
+
prev_sample = self.multistep_dpm_solver_second_order_update(
|
| 399 |
+
self.model_outputs, sample=sample, noise=noise
|
| 400 |
+
)
|
| 401 |
+
else:
|
| 402 |
+
prev_sample = self.multistep_dpm_solver_third_order_update(
|
| 403 |
+
self.model_outputs, sample=sample, noise=noise
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
if self.lower_order_nums < self.config.solver_order:
|
| 407 |
+
self.lower_order_nums += 1
|
| 408 |
+
|
| 409 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 410 |
+
self._step_index += 1
|
| 411 |
+
|
| 412 |
+
if not return_dict:
|
| 413 |
+
return (prev_sample, model_output)
|
| 414 |
+
return SchedulerOutput(prev_sample=prev_sample)
|
| 415 |
+
|
| 416 |
+
def scale_model_input(self, sample: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
| 417 |
+
return sample
|
| 418 |
+
|
| 419 |
+
def __len__(self):
|
| 420 |
+
return self.config.num_train_timesteps
|
diffusion/training/models/fm_solvers_unipc.py
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
# Copyright 2024 TSAIL Team and The HuggingFace Team. All rights reserved.
|
| 4 |
+
# NVIDIA modifications: LiDAR rectified-flow sampling integration.
|
| 5 |
+
|
| 6 |
+
# Copied from https://github.com/huggingface/diffusers/blob/v0.31.0/src/diffusers/schedulers/scheduling_unipc_multistep.py
|
| 7 |
+
# Convert unipc for flow matching
|
| 8 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
from typing import List, Optional, Tuple, Union
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 16 |
+
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
|
| 17 |
+
from diffusers.utils import deprecate
|
| 18 |
+
|
| 19 |
+
from diffusion.training.schedulers.shift_schedule import stretch_shifts_to_terminal
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FlowUniPCMultistepScheduler(SchedulerMixin, ConfigMixin):
|
| 23 |
+
"""
|
| 24 |
+
`UniPCMultistepScheduler` is a training-free framework designed for the fast sampling of diffusion models.
|
| 25 |
+
|
| 26 |
+
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
|
| 27 |
+
methods the library implements for all schedulers such as loading and saving.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
num_train_timesteps (`int`, defaults to 1000):
|
| 31 |
+
The number of diffusion steps to train the model.
|
| 32 |
+
solver_order (`int`, default `2`):
|
| 33 |
+
The UniPC order which can be any positive integer. The effective order of accuracy is `solver_order + 1`
|
| 34 |
+
due to the UniC. It is recommended to use `solver_order=2` for guided sampling, and `solver_order=3` for
|
| 35 |
+
unconditional sampling.
|
| 36 |
+
prediction_type (`str`, defaults to "flow_prediction"):
|
| 37 |
+
Prediction type of the scheduler function; must be `flow_prediction` for this scheduler, which predicts
|
| 38 |
+
the flow of the diffusion process.
|
| 39 |
+
thresholding (`bool`, defaults to `False`):
|
| 40 |
+
Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
|
| 41 |
+
as Stable Diffusion.
|
| 42 |
+
dynamic_thresholding_ratio (`float`, defaults to 0.995):
|
| 43 |
+
The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
|
| 44 |
+
sample_max_value (`float`, defaults to 1.0):
|
| 45 |
+
The threshold value for dynamic thresholding. Valid only when `thresholding=True` and `predict_x0=True`.
|
| 46 |
+
predict_x0 (`bool`, defaults to `True`):
|
| 47 |
+
Whether to use the updating algorithm on the predicted x0.
|
| 48 |
+
solver_type (`str`, default `bh2`):
|
| 49 |
+
Solver type for UniPC. It is recommended to use `bh1` for unconditional sampling when steps < 10, and `bh2`
|
| 50 |
+
otherwise.
|
| 51 |
+
lower_order_final (`bool`, default `True`):
|
| 52 |
+
Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
|
| 53 |
+
stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
|
| 54 |
+
disable_corrector (`list`, default `[]`):
|
| 55 |
+
Decides which step to disable the corrector to mitigate the misalignment between `epsilon_theta(x_t, c)`
|
| 56 |
+
and `epsilon_theta(x_t^c, c)` which can influence convergence for a large guidance scale. Corrector is
|
| 57 |
+
usually disabled during the first few steps.
|
| 58 |
+
solver_p (`SchedulerMixin`, default `None`):
|
| 59 |
+
Any other scheduler that if specified, the algorithm becomes `solver_p + UniC`.
|
| 60 |
+
use_karras_sigmas (`bool`, *optional*, defaults to `False`):
|
| 61 |
+
Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
|
| 62 |
+
the sigmas are determined according to a sequence of noise levels {σi}.
|
| 63 |
+
use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
|
| 64 |
+
Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
|
| 65 |
+
timestep_spacing (`str`, defaults to `"linspace"`):
|
| 66 |
+
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
|
| 67 |
+
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
|
| 68 |
+
steps_offset (`int`, defaults to 0):
|
| 69 |
+
An offset added to the inference steps, as required by some model families.
|
| 70 |
+
final_sigmas_type (`str`, defaults to `"zero"`):
|
| 71 |
+
The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
|
| 72 |
+
sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
|
| 76 |
+
order = 1
|
| 77 |
+
|
| 78 |
+
@register_to_config
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
num_train_timesteps: int = 1000,
|
| 82 |
+
solver_order: int = 2,
|
| 83 |
+
prediction_type: str = "flow_prediction",
|
| 84 |
+
shift: Optional[float] = 1.0,
|
| 85 |
+
use_dynamic_shifting=False,
|
| 86 |
+
thresholding: bool = False,
|
| 87 |
+
dynamic_thresholding_ratio: float = 0.995,
|
| 88 |
+
sample_max_value: float = 1.0,
|
| 89 |
+
predict_x0: bool = True,
|
| 90 |
+
solver_type: str = "bh2",
|
| 91 |
+
lower_order_final: bool = True,
|
| 92 |
+
disable_corrector: List[int] = [],
|
| 93 |
+
solver_p: SchedulerMixin = None,
|
| 94 |
+
timestep_spacing: str = "linspace",
|
| 95 |
+
steps_offset: int = 0,
|
| 96 |
+
final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
|
| 97 |
+
):
|
| 98 |
+
if solver_type not in ["bh1", "bh2"]:
|
| 99 |
+
if solver_type in ["midpoint", "heun", "logrho"]:
|
| 100 |
+
self.register_to_config(solver_type="bh2")
|
| 101 |
+
else:
|
| 102 |
+
raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
|
| 103 |
+
|
| 104 |
+
self.predict_x0 = predict_x0
|
| 105 |
+
# setable values
|
| 106 |
+
self.num_inference_steps = None
|
| 107 |
+
alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps)[::-1].copy()
|
| 108 |
+
sigmas = 1.0 - alphas
|
| 109 |
+
sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32)
|
| 110 |
+
|
| 111 |
+
if not use_dynamic_shifting:
|
| 112 |
+
# when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution
|
| 113 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) # pyright: ignore
|
| 114 |
+
|
| 115 |
+
self.sigmas = sigmas
|
| 116 |
+
self.timesteps = sigmas * num_train_timesteps
|
| 117 |
+
|
| 118 |
+
self.model_outputs = [None] * solver_order
|
| 119 |
+
self.timestep_list = [None] * solver_order
|
| 120 |
+
self.lower_order_nums = 0
|
| 121 |
+
self.disable_corrector = disable_corrector
|
| 122 |
+
self.solver_p = solver_p
|
| 123 |
+
self.last_sample = None
|
| 124 |
+
self._step_index = None
|
| 125 |
+
self._begin_index = None
|
| 126 |
+
|
| 127 |
+
self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 128 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 129 |
+
self.sigma_max = self.sigmas[0].item()
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def step_index(self):
|
| 133 |
+
"""
|
| 134 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 135 |
+
"""
|
| 136 |
+
return self._step_index
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
def begin_index(self):
|
| 140 |
+
"""
|
| 141 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 142 |
+
"""
|
| 143 |
+
return self._begin_index
|
| 144 |
+
|
| 145 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
|
| 146 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 147 |
+
"""
|
| 148 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
begin_index (`int`):
|
| 152 |
+
The begin index for the scheduler.
|
| 153 |
+
"""
|
| 154 |
+
self._begin_index = begin_index
|
| 155 |
+
|
| 156 |
+
# Modified from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.set_timesteps
|
| 157 |
+
def set_timesteps(
|
| 158 |
+
self,
|
| 159 |
+
num_inference_steps: Union[int, None] = None,
|
| 160 |
+
device: Union[str, torch.device] = None,
|
| 161 |
+
sigmas: Optional[List[float]] = None,
|
| 162 |
+
mu: Optional[Union[float, None]] = None,
|
| 163 |
+
shift: Optional[Union[float, None]] = None,
|
| 164 |
+
stretch_terminal: Optional[float] = None,
|
| 165 |
+
use_kerras_sigma: bool = False,
|
| 166 |
+
):
|
| 167 |
+
"""
|
| 168 |
+
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
|
| 169 |
+
Args:
|
| 170 |
+
num_inference_steps (`int`):
|
| 171 |
+
Total number of the spacing of the time steps.
|
| 172 |
+
device (`str` or `torch.device`, *optional*):
|
| 173 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 174 |
+
"""
|
| 175 |
+
if self.config.use_dynamic_shifting and mu is None:
|
| 176 |
+
raise ValueError(" you have to pass a value for `mu` when `use_dynamic_shifting` is set to be `True`")
|
| 177 |
+
|
| 178 |
+
if use_kerras_sigma:
|
| 179 |
+
# force to use the exact sigma used in edm sampler
|
| 180 |
+
sigma_max = 200
|
| 181 |
+
sigma_min = 0.01
|
| 182 |
+
rho = 7
|
| 183 |
+
sigmas = np.arange(num_inference_steps + 1) / num_inference_steps
|
| 184 |
+
min_inv_rho = sigma_min ** (1 / rho)
|
| 185 |
+
max_inv_rho = sigma_max ** (1 / rho)
|
| 186 |
+
sigmas = (max_inv_rho + sigmas * (min_inv_rho - max_inv_rho)) ** rho
|
| 187 |
+
sigmas = sigmas / (1 + sigmas)
|
| 188 |
+
else:
|
| 189 |
+
if sigmas is None:
|
| 190 |
+
# RF sampling is defined on the continuous [1, 0] interval.
|
| 191 |
+
# Do not inherit the training table's discretized 0.999
|
| 192 |
+
# endpoint or few-step schedules drift from the distilled
|
| 193 |
+
# query ladder.
|
| 194 |
+
sigmas = np.linspace(
|
| 195 |
+
1.0,
|
| 196 |
+
0.0,
|
| 197 |
+
num_inference_steps + 1,
|
| 198 |
+
dtype=np.float64,
|
| 199 |
+
)[:-1]
|
| 200 |
+
|
| 201 |
+
if self.config.use_dynamic_shifting:
|
| 202 |
+
sigmas = self.time_shift(mu, 1.0, sigmas) # pyright: ignore
|
| 203 |
+
else:
|
| 204 |
+
if shift is None:
|
| 205 |
+
shift = self.config.shift
|
| 206 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas) # pyright: ignore
|
| 207 |
+
if stretch_terminal is not None:
|
| 208 |
+
sigmas = stretch_shifts_to_terminal(
|
| 209 |
+
np.asarray(sigmas, dtype=np.float64),
|
| 210 |
+
float(stretch_terminal),
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if self.config.final_sigmas_type == "sigma_min":
|
| 214 |
+
sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5
|
| 215 |
+
elif self.config.final_sigmas_type == "zero":
|
| 216 |
+
sigma_last = 0
|
| 217 |
+
else:
|
| 218 |
+
raise ValueError(
|
| 219 |
+
f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
timesteps = sigmas * self.config.num_train_timesteps
|
| 223 |
+
sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32) # pyright: ignore
|
| 224 |
+
|
| 225 |
+
self.sigmas = torch.from_numpy(sigmas)
|
| 226 |
+
self.timesteps = torch.from_numpy(timesteps).to(
|
| 227 |
+
device=device, dtype=torch.float32
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
self.num_inference_steps = len(timesteps)
|
| 231 |
+
|
| 232 |
+
self.model_outputs = [
|
| 233 |
+
None,
|
| 234 |
+
] * self.config.solver_order
|
| 235 |
+
self.lower_order_nums = 0
|
| 236 |
+
self.last_sample = None
|
| 237 |
+
if self.solver_p:
|
| 238 |
+
self.solver_p.set_timesteps(self.num_inference_steps, device=device)
|
| 239 |
+
|
| 240 |
+
# add an index counter for schedulers that allow duplicated timesteps
|
| 241 |
+
self._step_index = None
|
| 242 |
+
self._begin_index = None
|
| 243 |
+
self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 244 |
+
|
| 245 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
|
| 246 |
+
def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
|
| 247 |
+
"""
|
| 248 |
+
"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
|
| 249 |
+
prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
|
| 250 |
+
s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
|
| 251 |
+
pixels from saturation at each step. We find that dynamic thresholding results in significantly better
|
| 252 |
+
photorealism as well as better image-text alignment, especially when using very large guidance weights."
|
| 253 |
+
|
| 254 |
+
https://arxiv.org/abs/2205.11487
|
| 255 |
+
"""
|
| 256 |
+
dtype = sample.dtype
|
| 257 |
+
batch_size, channels, *remaining_dims = sample.shape
|
| 258 |
+
|
| 259 |
+
if dtype not in (torch.float32, torch.float64):
|
| 260 |
+
sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
|
| 261 |
+
|
| 262 |
+
# Flatten sample for doing quantile calculation along each image
|
| 263 |
+
sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
|
| 264 |
+
|
| 265 |
+
abs_sample = sample.abs() # "a certain percentile absolute pixel value"
|
| 266 |
+
|
| 267 |
+
s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
|
| 268 |
+
s = torch.clamp(
|
| 269 |
+
s, min=1, max=self.config.sample_max_value
|
| 270 |
+
) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
|
| 271 |
+
s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
|
| 272 |
+
sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
|
| 273 |
+
|
| 274 |
+
sample = sample.reshape(batch_size, channels, *remaining_dims)
|
| 275 |
+
sample = sample.to(dtype)
|
| 276 |
+
|
| 277 |
+
return sample
|
| 278 |
+
|
| 279 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._sigma_to_t
|
| 280 |
+
def _sigma_to_t(self, sigma):
|
| 281 |
+
return sigma * self.config.num_train_timesteps
|
| 282 |
+
|
| 283 |
+
def _sigma_to_alpha_sigma_t(self, sigma):
|
| 284 |
+
return 1 - sigma, sigma
|
| 285 |
+
|
| 286 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.set_timesteps
|
| 287 |
+
def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
|
| 288 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 289 |
+
|
| 290 |
+
def convert_model_output(
|
| 291 |
+
self,
|
| 292 |
+
model_output: torch.Tensor,
|
| 293 |
+
*args,
|
| 294 |
+
sample: torch.Tensor = None,
|
| 295 |
+
**kwargs,
|
| 296 |
+
) -> torch.Tensor:
|
| 297 |
+
r"""
|
| 298 |
+
Convert the model output to the corresponding type the UniPC algorithm needs.
|
| 299 |
+
|
| 300 |
+
Args:
|
| 301 |
+
model_output (`torch.Tensor`):
|
| 302 |
+
The direct output from the learned diffusion model.
|
| 303 |
+
timestep (`int`):
|
| 304 |
+
The current discrete timestep in the diffusion chain.
|
| 305 |
+
sample (`torch.Tensor`):
|
| 306 |
+
A current instance of a sample created by the diffusion process.
|
| 307 |
+
|
| 308 |
+
Returns:
|
| 309 |
+
`torch.Tensor`:
|
| 310 |
+
The converted model output.
|
| 311 |
+
"""
|
| 312 |
+
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
|
| 313 |
+
if sample is None:
|
| 314 |
+
if len(args) > 1:
|
| 315 |
+
sample = args[1]
|
| 316 |
+
else:
|
| 317 |
+
raise ValueError("missing `sample` as a required keyward argument")
|
| 318 |
+
if timestep is not None:
|
| 319 |
+
deprecate(
|
| 320 |
+
"timesteps",
|
| 321 |
+
"1.0.0",
|
| 322 |
+
"Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
sigma = self.sigmas[self.step_index]
|
| 326 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
|
| 327 |
+
|
| 328 |
+
# print("sigma_t ==>", self.step_index, sigma, sigma_t, alpha_t, sample.shape, model_output.shape)
|
| 329 |
+
if self.predict_x0:
|
| 330 |
+
if self.config.prediction_type == "flow_prediction":
|
| 331 |
+
sigma_t = self.sigmas[self.step_index]
|
| 332 |
+
x0_pred = sample - sigma_t * model_output
|
| 333 |
+
else:
|
| 334 |
+
raise ValueError(
|
| 335 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`,"
|
| 336 |
+
" `v_prediction` or `flow_prediction` for the UniPCMultistepScheduler."
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
if self.config.thresholding:
|
| 340 |
+
x0_pred = self._threshold_sample(x0_pred)
|
| 341 |
+
# print("self.config.thresholding", self.config.thresholding)
|
| 342 |
+
return x0_pred
|
| 343 |
+
else:
|
| 344 |
+
if self.config.prediction_type == "flow_prediction":
|
| 345 |
+
sigma_t = self.sigmas[self.step_index]
|
| 346 |
+
epsilon = sample - (1 - sigma_t) * model_output
|
| 347 |
+
else:
|
| 348 |
+
raise ValueError(
|
| 349 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`,"
|
| 350 |
+
" `v_prediction` or `flow_prediction` for the UniPCMultistepScheduler."
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
if self.config.thresholding:
|
| 354 |
+
sigma_t = self.sigmas[self.step_index]
|
| 355 |
+
x0_pred = sample - sigma_t * model_output
|
| 356 |
+
x0_pred = self._threshold_sample(x0_pred)
|
| 357 |
+
epsilon = model_output + x0_pred
|
| 358 |
+
|
| 359 |
+
return epsilon
|
| 360 |
+
|
| 361 |
+
def multistep_uni_p_bh_update(
|
| 362 |
+
self,
|
| 363 |
+
model_output: torch.Tensor,
|
| 364 |
+
*args,
|
| 365 |
+
sample: torch.Tensor = None,
|
| 366 |
+
order: int = None, # pyright: ignore
|
| 367 |
+
**kwargs,
|
| 368 |
+
) -> torch.Tensor:
|
| 369 |
+
"""
|
| 370 |
+
One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified.
|
| 371 |
+
|
| 372 |
+
Args:
|
| 373 |
+
model_output (`torch.Tensor`):
|
| 374 |
+
The direct output from the learned diffusion model at the current timestep.
|
| 375 |
+
prev_timestep (`int`):
|
| 376 |
+
The previous discrete timestep in the diffusion chain.
|
| 377 |
+
sample (`torch.Tensor`):
|
| 378 |
+
A current instance of a sample created by the diffusion process.
|
| 379 |
+
order (`int`):
|
| 380 |
+
The order of UniP at this timestep (corresponds to the *p* in UniPC-p).
|
| 381 |
+
|
| 382 |
+
Returns:
|
| 383 |
+
`torch.Tensor`:
|
| 384 |
+
The sample tensor at the previous timestep.
|
| 385 |
+
"""
|
| 386 |
+
prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None)
|
| 387 |
+
if sample is None:
|
| 388 |
+
if len(args) > 1:
|
| 389 |
+
sample = args[1]
|
| 390 |
+
else:
|
| 391 |
+
raise ValueError(" missing `sample` as a required keyward argument")
|
| 392 |
+
if order is None:
|
| 393 |
+
if len(args) > 2:
|
| 394 |
+
order = args[2]
|
| 395 |
+
else:
|
| 396 |
+
raise ValueError(" missing `order` as a required keyward argument")
|
| 397 |
+
if prev_timestep is not None:
|
| 398 |
+
deprecate(
|
| 399 |
+
"prev_timestep",
|
| 400 |
+
"1.0.0",
|
| 401 |
+
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 402 |
+
)
|
| 403 |
+
model_output_list = self.model_outputs
|
| 404 |
+
|
| 405 |
+
s0 = self.timestep_list[-1]
|
| 406 |
+
m0 = model_output_list[-1]
|
| 407 |
+
x = sample
|
| 408 |
+
|
| 409 |
+
if self.solver_p:
|
| 410 |
+
x_t = self.solver_p.step(model_output, s0, x).prev_sample
|
| 411 |
+
return x_t
|
| 412 |
+
|
| 413 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] # pyright: ignore
|
| 414 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 415 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 416 |
+
|
| 417 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 418 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 419 |
+
|
| 420 |
+
h = lambda_t - lambda_s0
|
| 421 |
+
device = sample.device
|
| 422 |
+
|
| 423 |
+
rks = []
|
| 424 |
+
D1s = []
|
| 425 |
+
for i in range(1, order):
|
| 426 |
+
si = self.step_index - i # pyright: ignore
|
| 427 |
+
mi = model_output_list[-(i + 1)]
|
| 428 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 429 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 430 |
+
rk = (lambda_si - lambda_s0) / h
|
| 431 |
+
rks.append(rk)
|
| 432 |
+
D1s.append((mi - m0) / rk) # pyright: ignore
|
| 433 |
+
|
| 434 |
+
rks.append(1.0)
|
| 435 |
+
rks = torch.tensor(rks, device=device)
|
| 436 |
+
|
| 437 |
+
R = []
|
| 438 |
+
b = []
|
| 439 |
+
|
| 440 |
+
hh = -h if self.predict_x0 else h
|
| 441 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 442 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 443 |
+
|
| 444 |
+
factorial_i = 1
|
| 445 |
+
|
| 446 |
+
if self.config.solver_type == "bh1":
|
| 447 |
+
B_h = hh
|
| 448 |
+
elif self.config.solver_type == "bh2":
|
| 449 |
+
B_h = torch.expm1(hh)
|
| 450 |
+
else:
|
| 451 |
+
raise NotImplementedError()
|
| 452 |
+
|
| 453 |
+
for i in range(1, order + 1):
|
| 454 |
+
R.append(torch.pow(rks, i - 1))
|
| 455 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 456 |
+
factorial_i *= i + 1
|
| 457 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 458 |
+
|
| 459 |
+
R = torch.stack(R)
|
| 460 |
+
b = torch.tensor(b, device=device)
|
| 461 |
+
|
| 462 |
+
if len(D1s) > 0:
|
| 463 |
+
D1s = torch.stack(D1s, dim=1) # (B, K)
|
| 464 |
+
# for order 2, we use a simplified version
|
| 465 |
+
if order == 2:
|
| 466 |
+
rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 467 |
+
else:
|
| 468 |
+
rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype)
|
| 469 |
+
else:
|
| 470 |
+
D1s = None
|
| 471 |
+
|
| 472 |
+
if self.predict_x0:
|
| 473 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 474 |
+
if D1s is not None:
|
| 475 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) # pyright: ignore
|
| 476 |
+
else:
|
| 477 |
+
pred_res = 0
|
| 478 |
+
x_t = x_t_ - alpha_t * B_h * pred_res
|
| 479 |
+
else:
|
| 480 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 481 |
+
if D1s is not None:
|
| 482 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) # pyright: ignore
|
| 483 |
+
else:
|
| 484 |
+
pred_res = 0
|
| 485 |
+
x_t = x_t_ - sigma_t * B_h * pred_res
|
| 486 |
+
|
| 487 |
+
x_t = x_t.to(x.dtype)
|
| 488 |
+
return x_t
|
| 489 |
+
|
| 490 |
+
def multistep_uni_c_bh_update(
|
| 491 |
+
self,
|
| 492 |
+
this_model_output: torch.Tensor,
|
| 493 |
+
*args,
|
| 494 |
+
last_sample: torch.Tensor = None,
|
| 495 |
+
this_sample: torch.Tensor = None,
|
| 496 |
+
order: int = None, # pyright: ignore
|
| 497 |
+
**kwargs,
|
| 498 |
+
) -> torch.Tensor:
|
| 499 |
+
"""
|
| 500 |
+
One step for the UniC (B(h) version).
|
| 501 |
+
|
| 502 |
+
Args:
|
| 503 |
+
this_model_output (`torch.Tensor`):
|
| 504 |
+
The model outputs at `x_t`.
|
| 505 |
+
this_timestep (`int`):
|
| 506 |
+
The current timestep `t`.
|
| 507 |
+
last_sample (`torch.Tensor`):
|
| 508 |
+
The generated sample before the last predictor `x_{t-1}`.
|
| 509 |
+
this_sample (`torch.Tensor`):
|
| 510 |
+
The generated sample after the last predictor `x_{t}`.
|
| 511 |
+
order (`int`):
|
| 512 |
+
The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`.
|
| 513 |
+
|
| 514 |
+
Returns:
|
| 515 |
+
`torch.Tensor`:
|
| 516 |
+
The corrected sample tensor at the current timestep.
|
| 517 |
+
"""
|
| 518 |
+
this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None)
|
| 519 |
+
if last_sample is None:
|
| 520 |
+
if len(args) > 1:
|
| 521 |
+
last_sample = args[1]
|
| 522 |
+
else:
|
| 523 |
+
raise ValueError(" missing`last_sample` as a required keyward argument")
|
| 524 |
+
if this_sample is None:
|
| 525 |
+
if len(args) > 2:
|
| 526 |
+
this_sample = args[2]
|
| 527 |
+
else:
|
| 528 |
+
raise ValueError(" missing`this_sample` as a required keyward argument")
|
| 529 |
+
if order is None:
|
| 530 |
+
if len(args) > 3:
|
| 531 |
+
order = args[3]
|
| 532 |
+
else:
|
| 533 |
+
raise ValueError(" missing`order` as a required keyward argument")
|
| 534 |
+
if this_timestep is not None:
|
| 535 |
+
deprecate(
|
| 536 |
+
"this_timestep",
|
| 537 |
+
"1.0.0",
|
| 538 |
+
"Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
model_output_list = self.model_outputs
|
| 542 |
+
|
| 543 |
+
m0 = model_output_list[-1]
|
| 544 |
+
x = last_sample
|
| 545 |
+
x_t = this_sample
|
| 546 |
+
model_t = this_model_output
|
| 547 |
+
|
| 548 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1] # pyright: ignore
|
| 549 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 550 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 551 |
+
|
| 552 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 553 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 554 |
+
|
| 555 |
+
h = lambda_t - lambda_s0
|
| 556 |
+
device = this_sample.device
|
| 557 |
+
|
| 558 |
+
rks = []
|
| 559 |
+
D1s = []
|
| 560 |
+
for i in range(1, order):
|
| 561 |
+
si = self.step_index - (i + 1) # pyright: ignore
|
| 562 |
+
mi = model_output_list[-(i + 1)]
|
| 563 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 564 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 565 |
+
rk = (lambda_si - lambda_s0) / h
|
| 566 |
+
rks.append(rk)
|
| 567 |
+
D1s.append((mi - m0) / rk) # pyright: ignore
|
| 568 |
+
|
| 569 |
+
rks.append(1.0)
|
| 570 |
+
rks = torch.tensor(rks, device=device)
|
| 571 |
+
|
| 572 |
+
R = []
|
| 573 |
+
b = []
|
| 574 |
+
|
| 575 |
+
hh = -h if self.predict_x0 else h
|
| 576 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 577 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 578 |
+
|
| 579 |
+
factorial_i = 1
|
| 580 |
+
|
| 581 |
+
if self.config.solver_type == "bh1":
|
| 582 |
+
B_h = hh
|
| 583 |
+
elif self.config.solver_type == "bh2":
|
| 584 |
+
B_h = torch.expm1(hh)
|
| 585 |
+
else:
|
| 586 |
+
raise NotImplementedError()
|
| 587 |
+
|
| 588 |
+
for i in range(1, order + 1):
|
| 589 |
+
R.append(torch.pow(rks, i - 1))
|
| 590 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 591 |
+
factorial_i *= i + 1
|
| 592 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 593 |
+
|
| 594 |
+
R = torch.stack(R)
|
| 595 |
+
b = torch.tensor(b, device=device)
|
| 596 |
+
|
| 597 |
+
if len(D1s) > 0:
|
| 598 |
+
D1s = torch.stack(D1s, dim=1)
|
| 599 |
+
else:
|
| 600 |
+
D1s = None
|
| 601 |
+
|
| 602 |
+
# for order 1, we use a simplified version
|
| 603 |
+
if order == 1:
|
| 604 |
+
rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 605 |
+
else:
|
| 606 |
+
rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype)
|
| 607 |
+
|
| 608 |
+
if self.predict_x0:
|
| 609 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 610 |
+
if D1s is not None:
|
| 611 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 612 |
+
else:
|
| 613 |
+
corr_res = 0
|
| 614 |
+
D1_t = model_t - m0
|
| 615 |
+
x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 616 |
+
else:
|
| 617 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 618 |
+
if D1s is not None:
|
| 619 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 620 |
+
else:
|
| 621 |
+
corr_res = 0
|
| 622 |
+
D1_t = model_t - m0
|
| 623 |
+
x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 624 |
+
x_t = x_t.to(x.dtype)
|
| 625 |
+
return x_t
|
| 626 |
+
|
| 627 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 628 |
+
if schedule_timesteps is None:
|
| 629 |
+
schedule_timesteps = self.timesteps
|
| 630 |
+
|
| 631 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 632 |
+
|
| 633 |
+
# The sigma index that is taken for the **very** first `step`
|
| 634 |
+
# is always the second index (or the last index if there is only 1)
|
| 635 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 636 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 637 |
+
pos = 1 if len(indices) > 1 else 0
|
| 638 |
+
|
| 639 |
+
return indices[pos].item()
|
| 640 |
+
|
| 641 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index
|
| 642 |
+
def _init_step_index(self, timestep):
|
| 643 |
+
"""
|
| 644 |
+
Initialize the step_index counter for the scheduler.
|
| 645 |
+
"""
|
| 646 |
+
|
| 647 |
+
if self.begin_index is None:
|
| 648 |
+
if isinstance(timestep, torch.Tensor):
|
| 649 |
+
timestep = timestep.to(self.timesteps.device)
|
| 650 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 651 |
+
else:
|
| 652 |
+
self._step_index = self._begin_index
|
| 653 |
+
|
| 654 |
+
def step(
|
| 655 |
+
self,
|
| 656 |
+
model_output: torch.Tensor,
|
| 657 |
+
timestep: Union[int, torch.Tensor],
|
| 658 |
+
sample: torch.Tensor,
|
| 659 |
+
return_dict: bool = True,
|
| 660 |
+
generator=None,
|
| 661 |
+
) -> Union[SchedulerOutput, Tuple]:
|
| 662 |
+
"""
|
| 663 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
|
| 664 |
+
the multistep UniPC.
|
| 665 |
+
|
| 666 |
+
Args:
|
| 667 |
+
model_output (`torch.Tensor`):
|
| 668 |
+
The direct output from learned diffusion model.
|
| 669 |
+
timestep (`int`):
|
| 670 |
+
The current discrete timestep in the diffusion chain.
|
| 671 |
+
sample (`torch.Tensor`):
|
| 672 |
+
A current instance of a sample created by the diffusion process.
|
| 673 |
+
return_dict (`bool`):
|
| 674 |
+
Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
|
| 675 |
+
|
| 676 |
+
Returns:
|
| 677 |
+
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
|
| 678 |
+
If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
|
| 679 |
+
tuple is returned where the first element is the sample tensor.
|
| 680 |
+
|
| 681 |
+
"""
|
| 682 |
+
if self.num_inference_steps is None:
|
| 683 |
+
raise ValueError(
|
| 684 |
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
if self.step_index is None:
|
| 688 |
+
self._init_step_index(timestep)
|
| 689 |
+
|
| 690 |
+
# print("self.step_index ==> ", self.step_index)
|
| 691 |
+
|
| 692 |
+
use_corrector = (
|
| 693 |
+
self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None # pyright: ignore
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
model_output_convert = self.convert_model_output(model_output, sample=sample)
|
| 697 |
+
|
| 698 |
+
if use_corrector:
|
| 699 |
+
sample = self.multistep_uni_c_bh_update(
|
| 700 |
+
this_model_output=model_output_convert,
|
| 701 |
+
last_sample=self.last_sample,
|
| 702 |
+
this_sample=sample,
|
| 703 |
+
order=self.this_order,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
for i in range(self.config.solver_order - 1):
|
| 707 |
+
self.model_outputs[i] = self.model_outputs[i + 1]
|
| 708 |
+
self.timestep_list[i] = self.timestep_list[i + 1]
|
| 709 |
+
|
| 710 |
+
self.model_outputs[-1] = model_output_convert
|
| 711 |
+
self.timestep_list[-1] = timestep # pyright: ignore
|
| 712 |
+
|
| 713 |
+
if self.config.lower_order_final:
|
| 714 |
+
this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index) # pyright: ignore
|
| 715 |
+
else:
|
| 716 |
+
this_order = self.config.solver_order
|
| 717 |
+
|
| 718 |
+
self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep
|
| 719 |
+
assert self.this_order > 0
|
| 720 |
+
|
| 721 |
+
self.last_sample = sample
|
| 722 |
+
prev_sample = self.multistep_uni_p_bh_update(
|
| 723 |
+
model_output=model_output, # pass the original non-converted model output, in case solver-p is used
|
| 724 |
+
sample=sample,
|
| 725 |
+
order=self.this_order,
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
if self.lower_order_nums < self.config.solver_order:
|
| 729 |
+
self.lower_order_nums += 1
|
| 730 |
+
|
| 731 |
+
# upon completion increase step index by one
|
| 732 |
+
self._step_index += 1 # pyright: ignore
|
| 733 |
+
|
| 734 |
+
if not return_dict:
|
| 735 |
+
return (prev_sample, model_output_convert)
|
| 736 |
+
|
| 737 |
+
return SchedulerOutput(prev_sample=prev_sample)
|
| 738 |
+
|
| 739 |
+
def scale_model_input(self, sample: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
| 740 |
+
"""
|
| 741 |
+
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
|
| 742 |
+
current timestep.
|
| 743 |
+
|
| 744 |
+
Args:
|
| 745 |
+
sample (`torch.Tensor`):
|
| 746 |
+
The input sample.
|
| 747 |
+
|
| 748 |
+
Returns:
|
| 749 |
+
`torch.Tensor`:
|
| 750 |
+
A scaled input sample.
|
| 751 |
+
"""
|
| 752 |
+
return sample
|
| 753 |
+
|
| 754 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.add_noise
|
| 755 |
+
def add_noise(
|
| 756 |
+
self,
|
| 757 |
+
original_samples: torch.Tensor,
|
| 758 |
+
noise: torch.Tensor,
|
| 759 |
+
timesteps: torch.IntTensor,
|
| 760 |
+
) -> torch.Tensor:
|
| 761 |
+
# Make sure sigmas and timesteps have the same device and dtype as original_samples
|
| 762 |
+
sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
|
| 763 |
+
if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
|
| 764 |
+
# mps does not support float64
|
| 765 |
+
schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
|
| 766 |
+
timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
|
| 767 |
+
else:
|
| 768 |
+
schedule_timesteps = self.timesteps.to(original_samples.device)
|
| 769 |
+
timesteps = timesteps.to(original_samples.device)
|
| 770 |
+
|
| 771 |
+
# begin_index is None when the scheduler is used for training or pipeline does not implement set_begin_index
|
| 772 |
+
if self.begin_index is None:
|
| 773 |
+
step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
|
| 774 |
+
elif self.step_index is not None:
|
| 775 |
+
# add_noise is called after first denoising step (for inpainting)
|
| 776 |
+
step_indices = [self.step_index] * timesteps.shape[0]
|
| 777 |
+
else:
|
| 778 |
+
# add noise is called before first denoising step to create initial latent(img2img)
|
| 779 |
+
step_indices = [self.begin_index] * timesteps.shape[0]
|
| 780 |
+
|
| 781 |
+
sigma = sigmas[step_indices].flatten()
|
| 782 |
+
while len(sigma.shape) < len(original_samples.shape):
|
| 783 |
+
sigma = sigma.unsqueeze(-1)
|
| 784 |
+
|
| 785 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
|
| 786 |
+
noisy_samples = alpha_t * original_samples + sigma_t * noise
|
| 787 |
+
return noisy_samples
|
| 788 |
+
|
| 789 |
+
def __len__(self):
|
| 790 |
+
return self.config.num_train_timesteps
|
diffusion/training/models/hdmaptolidar_model.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Hdmap-to-Lidar diffusion model.
|
| 5 |
+
|
| 6 |
+
Conditions on an HD-map via channel concatenation: the hdmap is resized to
|
| 7 |
+
the latent spatial resolution and concatenated with the noisy latent along
|
| 8 |
+
the channel dimension before the network.
|
| 9 |
+
|
| 10 |
+
Three hdmap-conditioning modes (mutually exclusive, evaluated in order):
|
| 11 |
+
|
| 12 |
+
* ``encode_hdmap_with_vae=True`` — run the hdmap through the same frozen VAE
|
| 13 |
+
encoder as the lidar. The encoded latent has the same shape as the noisy
|
| 14 |
+
lidar latent, so no resize / 1x1 conv is required; set
|
| 15 |
+
``additional_concat_ch`` to the VAE's ``latent_ch`` and
|
| 16 |
+
``net.in_channels = latent_ch * 2``.
|
| 17 |
+
* ``skip_hdmap_proj=True`` — bypass the projection and directly concat the
|
| 18 |
+
raw (spatially resized) hdmap; avoids randomly-initialised weights
|
| 19 |
+
corrupting the conditioning signal early in training.
|
| 20 |
+
* Default — a learnable 1x1 conv projects ``hdmap_channels`` →
|
| 21 |
+
``additional_concat_ch`` before concat.
|
| 22 |
+
|
| 23 |
+
Uses the standard ``GeneralDIT`` network (no multiview extensions).
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from typing import Tuple, Union
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
from einops import rearrange
|
| 31 |
+
from torch import Tensor, nn
|
| 32 |
+
|
| 33 |
+
from diffusion.functional.batch_ops import batch_mul
|
| 34 |
+
from diffusion.training.conditioner import BaseVideoCondition
|
| 35 |
+
from diffusion.training.models.model import DiffusionModel, _broadcast, broadcast_condition
|
| 36 |
+
from diffusion.training.models.model_image import (
|
| 37 |
+
CosmosCondition,
|
| 38 |
+
DenoisePrediction,
|
| 39 |
+
diffusion_fsdp_class_decorator,
|
| 40 |
+
)
|
| 41 |
+
from diffusion.conditioner import DataType
|
| 42 |
+
from utils import log, misc
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Fixed class -> RGB palette for the "colored" BEV hdmap render fed to the
|
| 46 |
+
# frozen Wan2.2 VAE (must match scripts/hdmap_bev_wan2p2_roundtrip.py so the
|
| 47 |
+
# training render == the render validated by the roundtrip test).
|
| 48 |
+
# Order = waymo_hdmap.CLASS_NAMES: lane, road_line, road_edge, crosswalk,
|
| 49 |
+
# vehicle, pedestrian, cyclist.
|
| 50 |
+
_BEV_CLASS_COLORS = (
|
| 51 |
+
(0.20, 0.20, 0.20), # lane - dark gray
|
| 52 |
+
(1.00, 1.00, 0.00), # road_line - yellow
|
| 53 |
+
(1.00, 1.00, 1.00), # road_edge - white
|
| 54 |
+
(0.00, 1.00, 1.00), # crosswalk - cyan
|
| 55 |
+
(1.00, 0.00, 0.00), # vehicle - red
|
| 56 |
+
(0.00, 1.00, 0.00), # pedestrian - green
|
| 57 |
+
(0.00, 0.00, 1.00), # cyclist - blue
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class HdmapToLidarModel(DiffusionModel):
|
| 62 |
+
"""Rectified-flow diffusion conditioned on HD-map via channel concat."""
|
| 63 |
+
|
| 64 |
+
def __init__(self, config):
|
| 65 |
+
super().__init__(config)
|
| 66 |
+
|
| 67 |
+
self.diffusion_dtype = torch.bfloat16
|
| 68 |
+
|
| 69 |
+
hdmap_ch = getattr(config, "hdmap_channels", 3)
|
| 70 |
+
additional_concat_ch = getattr(config, "additional_concat_ch", 3)
|
| 71 |
+
self.skip_hdmap_proj = getattr(config, "skip_hdmap_proj", False)
|
| 72 |
+
self.encode_hdmap_with_vae = bool(
|
| 73 |
+
getattr(config, "encode_hdmap_with_vae", False)
|
| 74 |
+
)
|
| 75 |
+
self.bev_hdmap_pool = None
|
| 76 |
+
self.bev_hdmap_wan = None
|
| 77 |
+
if getattr(config, "bev_hdmap_wan_encode", False) or getattr(
|
| 78 |
+
config, "bev_hdmap_pool", False
|
| 79 |
+
):
|
| 80 |
+
raise ValueError(
|
| 81 |
+
"The public LidarVerse release supports range-rendered HDMap "
|
| 82 |
+
"conditioning only"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
if self.encode_hdmap_with_vae:
|
| 86 |
+
# Hdmap is routed through the same frozen VAE as the lidar.
|
| 87 |
+
# The encoded latent already lives in (B, latent_ch, T_z, H_z, W_z)
|
| 88 |
+
# — no spatial/temporal resize and no learnable projection are
|
| 89 |
+
# required. ``additional_concat_ch`` is bookkeeping here and
|
| 90 |
+
# should equal the VAE's ``latent_ch`` so that the downstream
|
| 91 |
+
# ``net.in_channels = lidar_latent_ch + additional_concat_ch``
|
| 92 |
+
# matches reality. Mutually exclusive with ``skip_hdmap_proj``.
|
| 93 |
+
assert not self.skip_hdmap_proj, (
|
| 94 |
+
"encode_hdmap_with_vae and skip_hdmap_proj are mutually "
|
| 95 |
+
"exclusive."
|
| 96 |
+
)
|
| 97 |
+
self.hdmap_proj = None
|
| 98 |
+
self._hdmap_concat_ch = additional_concat_ch
|
| 99 |
+
log.info(
|
| 100 |
+
f"HdmapToLidarModel: encode_hdmap_with_vae=True, "
|
| 101 |
+
f"concat {additional_concat_ch} VAE-encoded hdmap channels"
|
| 102 |
+
)
|
| 103 |
+
elif self.skip_hdmap_proj:
|
| 104 |
+
self.hdmap_proj = None
|
| 105 |
+
self._hdmap_concat_ch = hdmap_ch
|
| 106 |
+
log.info(
|
| 107 |
+
f"HdmapToLidarModel: raw hdmap concat (no proj), {hdmap_ch} ch"
|
| 108 |
+
)
|
| 109 |
+
elif additional_concat_ch > 0:
|
| 110 |
+
self.hdmap_proj = nn.Conv2d(hdmap_ch, additional_concat_ch, kernel_size=1)
|
| 111 |
+
self._hdmap_concat_ch = additional_concat_ch
|
| 112 |
+
log.info(
|
| 113 |
+
f"HdmapToLidarModel: hdmap_proj {hdmap_ch} -> {additional_concat_ch}"
|
| 114 |
+
)
|
| 115 |
+
else:
|
| 116 |
+
self.hdmap_proj = None
|
| 117 |
+
self._hdmap_concat_ch = 0
|
| 118 |
+
|
| 119 |
+
# Per-sample dropout of the hdmap condition during training, enabling
|
| 120 |
+
# classifier-free guidance at inference. Defaults to 0.0 (no dropout)
|
| 121 |
+
# so existing configs remain unchanged.
|
| 122 |
+
self.hdmap_dropout_prob = float(getattr(config, "hdmap_dropout_prob", 0.0))
|
| 123 |
+
# Mixture of dropout regimes; see LidarModelConfig.hdmap_dropout_modes.
|
| 124 |
+
# When dropout fires for a sample we draw one of these uniformly.
|
| 125 |
+
# Legacy default is ("full",) which reproduces the original CFG-only
|
| 126 |
+
# behavior bit-for-bit.
|
| 127 |
+
raw_modes = list(getattr(config, "hdmap_dropout_modes", ["full"]))
|
| 128 |
+
_ALLOWED_MODES = ("full", "frame_bernoulli", "keep_first_k")
|
| 129 |
+
for m in raw_modes:
|
| 130 |
+
if m not in _ALLOWED_MODES:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"hdmap_dropout_modes contains unknown mode {m!r}; "
|
| 133 |
+
f"allowed: {_ALLOWED_MODES}"
|
| 134 |
+
)
|
| 135 |
+
if len(raw_modes) == 0:
|
| 136 |
+
raise ValueError("hdmap_dropout_modes must not be empty")
|
| 137 |
+
self.hdmap_dropout_modes = raw_modes
|
| 138 |
+
self.hdmap_frame_dropout_rate = float(
|
| 139 |
+
getattr(config, "hdmap_frame_dropout_rate", 0.5)
|
| 140 |
+
)
|
| 141 |
+
self.hdmap_keep_first_k = int(getattr(config, "hdmap_keep_first_k", 1))
|
| 142 |
+
self.hdmap_artifixer_dropout = bool(
|
| 143 |
+
getattr(config, "hdmap_artifixer_dropout", False)
|
| 144 |
+
)
|
| 145 |
+
if self.hdmap_dropout_prob > 0.0:
|
| 146 |
+
log.info(
|
| 147 |
+
f"HdmapToLidarModel: hdmap_dropout_prob={self.hdmap_dropout_prob}, "
|
| 148 |
+
f"hdmap_dropout_modes={self.hdmap_dropout_modes} "
|
| 149 |
+
f"(frame_rate={self.hdmap_frame_dropout_rate}, "
|
| 150 |
+
f"keep_first_k={self.hdmap_keep_first_k}, "
|
| 151 |
+
f"artifixer={self.hdmap_artifixer_dropout})"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
self._current_hdmap = None
|
| 155 |
+
self._num_dataset_embeddings = int(
|
| 156 |
+
getattr(config.net, "num_dataset_embeddings", 0)
|
| 157 |
+
)
|
| 158 |
+
self._current_sensor_dataset_ids: Tensor | None = None
|
| 159 |
+
# Transient flag used by `generate_samples_from_batch` to zero the
|
| 160 |
+
# hdmap for the unconditional CFG pass. Kept off outside inference.
|
| 161 |
+
self._hdmap_force_null = False
|
| 162 |
+
# Inference-only: when set to int K, zero all hdmap latent frames except
|
| 163 |
+
# the first K in get_data_and_condition (see usage there). None = off.
|
| 164 |
+
self._hdmap_keep_first_k_infer = None
|
| 165 |
+
# Inference-only: when set to a list of ints, keep exactly those hdmap
|
| 166 |
+
# latent-frame indices (negatives index from the end). Takes precedence
|
| 167 |
+
# over _hdmap_keep_first_k_infer. None = off.
|
| 168 |
+
self._hdmap_keep_frames_infer = None
|
| 169 |
+
|
| 170 |
+
# ------------------------------------------------------------------
|
| 171 |
+
# HD-map helpers
|
| 172 |
+
# ------------------------------------------------------------------
|
| 173 |
+
|
| 174 |
+
def _prepare_hdmap(
|
| 175 |
+
self, hdmap: torch.Tensor, latent: torch.Tensor
|
| 176 |
+
) -> torch.Tensor:
|
| 177 |
+
"""Resize hdmap to latent spatial dims and optionally project channels.
|
| 178 |
+
|
| 179 |
+
When ``skip_hdmap_proj`` is True the raw resized hdmap is returned
|
| 180 |
+
without any learnable transformation.
|
| 181 |
+
|
| 182 |
+
Works for both 4-D ``(B, C, H, W)`` and 5-D ``(B, C, T, H, W)`` inputs.
|
| 183 |
+
"""
|
| 184 |
+
is_5d = hdmap.ndim == 5
|
| 185 |
+
if is_5d:
|
| 186 |
+
B, C, T, H, W = hdmap.shape
|
| 187 |
+
lat_T, lat_H, lat_W = latent.shape[2], latent.shape[3], latent.shape[4]
|
| 188 |
+
hdmap = F.interpolate(
|
| 189 |
+
hdmap.reshape(B * T, C, H, W),
|
| 190 |
+
size=(lat_H, lat_W),
|
| 191 |
+
mode="nearest-exact",
|
| 192 |
+
)
|
| 193 |
+
if self.hdmap_proj is not None:
|
| 194 |
+
hdmap = self.hdmap_proj(hdmap)
|
| 195 |
+
_, C_out, _, _ = hdmap.shape
|
| 196 |
+
hdmap = hdmap.reshape(B, C_out, T, lat_H, lat_W)
|
| 197 |
+
if T != lat_T:
|
| 198 |
+
hdmap = F.interpolate(
|
| 199 |
+
hdmap,
|
| 200 |
+
size=(lat_T, lat_H, lat_W),
|
| 201 |
+
mode="nearest-exact",
|
| 202 |
+
)
|
| 203 |
+
else:
|
| 204 |
+
lat_H, lat_W = latent.shape[2], latent.shape[3]
|
| 205 |
+
hdmap = F.interpolate(
|
| 206 |
+
hdmap, size=(lat_H, lat_W), mode="nearest-exact"
|
| 207 |
+
)
|
| 208 |
+
if self.hdmap_proj is not None:
|
| 209 |
+
hdmap = self.hdmap_proj(hdmap)
|
| 210 |
+
return hdmap
|
| 211 |
+
|
| 212 |
+
# ------------------------------------------------------------------
|
| 213 |
+
# HD-map training-time dropout (3-mode mixture)
|
| 214 |
+
# ------------------------------------------------------------------
|
| 215 |
+
|
| 216 |
+
def _apply_hdmap_dropout(self, hdmap_z: torch.Tensor) -> torch.Tensor:
|
| 217 |
+
"""Per-sample dropout with a uniform mixture over enabled modes.
|
| 218 |
+
|
| 219 |
+
With probability ``self.hdmap_dropout_prob`` each sample is "fired"
|
| 220 |
+
for dropout. Conditional on firing, a mode is drawn uniformly from
|
| 221 |
+
``self.hdmap_dropout_modes``:
|
| 222 |
+
|
| 223 |
+
* ``"full"`` -- zero the entire hdmap latent
|
| 224 |
+
* ``"frame_bernoulli"`` -- zero each frame independently with rate
|
| 225 |
+
``self.hdmap_frame_dropout_rate``
|
| 226 |
+
* ``"keep_first_k"`` -- zero all frames except the first
|
| 227 |
+
``self.hdmap_keep_first_k`` frames
|
| 228 |
+
|
| 229 |
+
Frame-wise modes require a temporal axis at ``hdmap_z.shape[2]``;
|
| 230 |
+
image-mode inputs (4-D) silently collapse to the legacy "full" path
|
| 231 |
+
regardless of the configured mixture.
|
| 232 |
+
"""
|
| 233 |
+
B = hdmap_z.shape[0]
|
| 234 |
+
device = hdmap_z.device
|
| 235 |
+
if self.hdmap_artifixer_dropout:
|
| 236 |
+
# ArtiFixer samples one conditioning decision for the whole batch.
|
| 237 |
+
# Its RGB condition is masked before VAE encoding and accompanied by
|
| 238 |
+
# a separate opacity mask. LiDAR HDMap conditioning has no opacity
|
| 239 |
+
# channel, so the behaviorally equivalent safe representation is a
|
| 240 |
+
# zero latent suffix (the existing unconditional HDMap convention).
|
| 241 |
+
if bool(
|
| 242 |
+
torch.rand((), device=device) < self.hdmap_dropout_prob
|
| 243 |
+
):
|
| 244 |
+
return torch.zeros_like(hdmap_z)
|
| 245 |
+
if hdmap_z.ndim != 5 or hdmap_z.shape[2] == 1:
|
| 246 |
+
return hdmap_z
|
| 247 |
+
num_frames = hdmap_z.shape[2]
|
| 248 |
+
keep_frames = int(
|
| 249 |
+
torch.randint(
|
| 250 |
+
1, num_frames + 1, (1,), device=device
|
| 251 |
+
).item()
|
| 252 |
+
)
|
| 253 |
+
frame_keep = torch.zeros(
|
| 254 |
+
(1, 1, num_frames, 1, 1),
|
| 255 |
+
device=device,
|
| 256 |
+
dtype=hdmap_z.dtype,
|
| 257 |
+
)
|
| 258 |
+
frame_keep[:, :, :keep_frames] = 1.0
|
| 259 |
+
return hdmap_z * frame_keep
|
| 260 |
+
|
| 261 |
+
fire = torch.rand(B, device=device) < self.hdmap_dropout_prob # (B,)
|
| 262 |
+
if not fire.any():
|
| 263 |
+
return hdmap_z
|
| 264 |
+
|
| 265 |
+
is_video = hdmap_z.ndim == 5
|
| 266 |
+
T_lat = hdmap_z.shape[2] if is_video else 1
|
| 267 |
+
# Frame-wise modes are meaningless for 4-D / T=1 hdmaps; fall back
|
| 268 |
+
# to the legacy full-dropout path in that case.
|
| 269 |
+
if (not is_video) or T_lat == 1:
|
| 270 |
+
keep_sample = (~fire).to(hdmap_z.dtype)
|
| 271 |
+
keep_sample = keep_sample.view(B, *([1] * (hdmap_z.ndim - 1)))
|
| 272 |
+
return hdmap_z * keep_sample
|
| 273 |
+
|
| 274 |
+
n_modes = len(self.hdmap_dropout_modes)
|
| 275 |
+
mode_ix = torch.randint(0, n_modes, (B,), device=device) # (B,)
|
| 276 |
+
|
| 277 |
+
# frame_keep[b, t] == 1 means "keep frame t of sample b".
|
| 278 |
+
frame_keep = torch.ones(
|
| 279 |
+
(B, T_lat), device=device, dtype=hdmap_z.dtype
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
for ix, mode in enumerate(self.hdmap_dropout_modes):
|
| 283 |
+
sel = fire & (mode_ix == ix) # (B,)
|
| 284 |
+
if not sel.any():
|
| 285 |
+
continue
|
| 286 |
+
if mode == "full":
|
| 287 |
+
# Zero every frame for this sample.
|
| 288 |
+
drop_mask = torch.zeros(
|
| 289 |
+
(1, T_lat), device=device, dtype=hdmap_z.dtype
|
| 290 |
+
)
|
| 291 |
+
frame_keep = torch.where(sel.view(B, 1), drop_mask, frame_keep)
|
| 292 |
+
elif mode == "frame_bernoulli":
|
| 293 |
+
per_frame = (
|
| 294 |
+
torch.rand((B, T_lat), device=device)
|
| 295 |
+
>= self.hdmap_frame_dropout_rate
|
| 296 |
+
).to(hdmap_z.dtype)
|
| 297 |
+
frame_keep = torch.where(sel.view(B, 1), per_frame, frame_keep)
|
| 298 |
+
elif mode == "keep_first_k":
|
| 299 |
+
K = max(0, min(int(self.hdmap_keep_first_k), T_lat))
|
| 300 |
+
keep_first = torch.zeros(
|
| 301 |
+
(1, T_lat), device=device, dtype=hdmap_z.dtype
|
| 302 |
+
)
|
| 303 |
+
if K > 0:
|
| 304 |
+
keep_first[:, :K] = 1.0
|
| 305 |
+
frame_keep = torch.where(sel.view(B, 1), keep_first, frame_keep)
|
| 306 |
+
else:
|
| 307 |
+
# Caught at __init__; defensive.
|
| 308 |
+
raise ValueError(f"Unknown hdmap dropout mode: {mode!r}")
|
| 309 |
+
|
| 310 |
+
# Broadcast to (B, 1, T, 1, 1) and apply.
|
| 311 |
+
frame_keep = frame_keep.view(B, 1, T_lat, 1, 1)
|
| 312 |
+
return hdmap_z * frame_keep
|
| 313 |
+
|
| 314 |
+
# ------------------------------------------------------------------
|
| 315 |
+
# Override: encode/decode for video support
|
| 316 |
+
# ------------------------------------------------------------------
|
| 317 |
+
|
| 318 |
+
def _encode_with_vae(
|
| 319 |
+
self, vae, state: torch.Tensor
|
| 320 |
+
) -> torch.Tensor:
|
| 321 |
+
if getattr(vae, "is_image", True):
|
| 322 |
+
return vae.encode(state.squeeze(2)).unsqueeze(2) * self.sigma_data
|
| 323 |
+
return vae.encode(state) * self.sigma_data
|
| 324 |
+
|
| 325 |
+
def _decode_with_vae(
|
| 326 |
+
self,
|
| 327 |
+
vae,
|
| 328 |
+
latent: torch.Tensor,
|
| 329 |
+
t: float | torch.Tensor | None = None,
|
| 330 |
+
) -> torch.Tensor:
|
| 331 |
+
is_ltx = getattr(vae, "is_ltx", False)
|
| 332 |
+
if t is not None and not is_ltx:
|
| 333 |
+
raise ValueError(
|
| 334 |
+
f"Got t={t!r} but {type(vae).__name__} is not LTX-style"
|
| 335 |
+
)
|
| 336 |
+
if getattr(vae, "is_image", True):
|
| 337 |
+
return vae.decode(latent.squeeze(2) / self.sigma_data).unsqueeze(2)
|
| 338 |
+
if is_ltx:
|
| 339 |
+
return vae.decode(latent / self.sigma_data, t=t)
|
| 340 |
+
return vae.decode(latent / self.sigma_data)
|
| 341 |
+
|
| 342 |
+
@torch.no_grad()
|
| 343 |
+
def encode(self, state: torch.Tensor) -> torch.Tensor:
|
| 344 |
+
# Disable any outer autocast so the VAE wrapper exclusively controls
|
| 345 |
+
# encoder precision. Existing configs remain FP32; selected configs
|
| 346 |
+
# may opt into a measured BF16 encoder.
|
| 347 |
+
state = state.float()
|
| 348 |
+
with torch.autocast("cuda", enabled=False):
|
| 349 |
+
if self.intensity_vae is None:
|
| 350 |
+
return self._encode_with_vae(self.vae, state)
|
| 351 |
+
if state.shape[1] == 1:
|
| 352 |
+
return self._encode_with_vae(self.vae, state)
|
| 353 |
+
if state.shape[1] != 2:
|
| 354 |
+
raise ValueError(
|
| 355 |
+
"paired range/intensity encoding expects C=1 or C=2, "
|
| 356 |
+
f"got {tuple(state.shape)}"
|
| 357 |
+
)
|
| 358 |
+
range_z = self._encode_with_vae(self.vae, state[:, :1])
|
| 359 |
+
intensity_z = self._encode_with_vae(
|
| 360 |
+
self.intensity_vae, state[:, 1:2]
|
| 361 |
+
)
|
| 362 |
+
if range_z.shape[2:] != intensity_z.shape[2:]:
|
| 363 |
+
raise ValueError(
|
| 364 |
+
"range and intensity tokenizer grids do not align: "
|
| 365 |
+
f"{tuple(range_z.shape)} vs {tuple(intensity_z.shape)}"
|
| 366 |
+
)
|
| 367 |
+
return torch.cat([range_z, intensity_z], dim=1)
|
| 368 |
+
|
| 369 |
+
@torch.no_grad()
|
| 370 |
+
def _encode_stream_with_vae(
|
| 371 |
+
self,
|
| 372 |
+
vae,
|
| 373 |
+
state_new: torch.Tensor,
|
| 374 |
+
temporal_kv_cache=None,
|
| 375 |
+
max_cache_frames: int | None = None,
|
| 376 |
+
):
|
| 377 |
+
if getattr(vae, "is_image", True):
|
| 378 |
+
raise NotImplementedError(
|
| 379 |
+
"streaming encode requires a causal video VAE"
|
| 380 |
+
)
|
| 381 |
+
if not hasattr(vae, "encode_stream"):
|
| 382 |
+
raise NotImplementedError(
|
| 383 |
+
f"{type(vae).__name__} does not implement encode_stream"
|
| 384 |
+
)
|
| 385 |
+
latent, new_cache = vae.encode_stream(
|
| 386 |
+
state_new,
|
| 387 |
+
temporal_kv_cache=temporal_kv_cache,
|
| 388 |
+
max_cache_frames=max_cache_frames,
|
| 389 |
+
)
|
| 390 |
+
return latent * self.sigma_data, new_cache
|
| 391 |
+
|
| 392 |
+
@torch.no_grad()
|
| 393 |
+
def encode_stream(
|
| 394 |
+
self,
|
| 395 |
+
state_new: torch.Tensor,
|
| 396 |
+
temporal_kv_cache=None,
|
| 397 |
+
max_cache_frames: int | None = None,
|
| 398 |
+
):
|
| 399 |
+
"""Encode newly appended frames at the VAE's configured precision."""
|
| 400 |
+
state_new = state_new.float()
|
| 401 |
+
with torch.autocast("cuda", enabled=False):
|
| 402 |
+
if self.intensity_vae is None or state_new.shape[1] == 1:
|
| 403 |
+
return self._encode_stream_with_vae(
|
| 404 |
+
self.vae,
|
| 405 |
+
state_new,
|
| 406 |
+
temporal_kv_cache=temporal_kv_cache,
|
| 407 |
+
max_cache_frames=max_cache_frames,
|
| 408 |
+
)
|
| 409 |
+
if state_new.shape[1] != 2:
|
| 410 |
+
raise ValueError(
|
| 411 |
+
"paired range/intensity streaming encode expects C=1 "
|
| 412 |
+
f"or C=2, got {tuple(state_new.shape)}"
|
| 413 |
+
)
|
| 414 |
+
if temporal_kv_cache is None:
|
| 415 |
+
range_cache = None
|
| 416 |
+
intensity_cache = None
|
| 417 |
+
elif isinstance(temporal_kv_cache, dict) and set(
|
| 418 |
+
temporal_kv_cache
|
| 419 |
+
) == {"range", "intensity"}:
|
| 420 |
+
range_cache = temporal_kv_cache["range"]
|
| 421 |
+
intensity_cache = temporal_kv_cache["intensity"]
|
| 422 |
+
else:
|
| 423 |
+
raise ValueError(
|
| 424 |
+
"paired range/intensity streaming cache must contain "
|
| 425 |
+
"exactly 'range' and 'intensity'"
|
| 426 |
+
)
|
| 427 |
+
range_z, range_cache = self._encode_stream_with_vae(
|
| 428 |
+
self.vae,
|
| 429 |
+
state_new[:, :1],
|
| 430 |
+
temporal_kv_cache=range_cache,
|
| 431 |
+
max_cache_frames=max_cache_frames,
|
| 432 |
+
)
|
| 433 |
+
intensity_z, intensity_cache = self._encode_stream_with_vae(
|
| 434 |
+
self.intensity_vae,
|
| 435 |
+
state_new[:, 1:2],
|
| 436 |
+
temporal_kv_cache=intensity_cache,
|
| 437 |
+
max_cache_frames=max_cache_frames,
|
| 438 |
+
)
|
| 439 |
+
if range_z.shape[2:] != intensity_z.shape[2:]:
|
| 440 |
+
raise ValueError(
|
| 441 |
+
"range and intensity streaming latent grids do not align: "
|
| 442 |
+
f"{tuple(range_z.shape)} vs {tuple(intensity_z.shape)}"
|
| 443 |
+
)
|
| 444 |
+
return torch.cat([range_z, intensity_z], dim=1), {
|
| 445 |
+
"range": range_cache,
|
| 446 |
+
"intensity": intensity_cache,
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
@torch.no_grad()
|
| 450 |
+
def decode(
|
| 451 |
+
self,
|
| 452 |
+
latent: torch.Tensor,
|
| 453 |
+
t: float | torch.Tensor | None = None,
|
| 454 |
+
) -> torch.Tensor:
|
| 455 |
+
"""Decode a diffusion-space latent back to pixels.
|
| 456 |
+
|
| 457 |
+
``t`` (rectified-flow timestep in [0, 1]) is forwarded to the VAE
|
| 458 |
+
wrapper only when ``self.vae.is_ltx`` is True (i.e. the wrapped
|
| 459 |
+
VAE net supports LTX-style timestep-conditioned decoding via
|
| 460 |
+
``decode(z, t=t)``). For non-LTX wrappers -- which is every
|
| 461 |
+
wrapper today other than ``ConfigBasedVideoVAE`` around a
|
| 462 |
+
``TransformerVAELTX`` with ``denoising_t_max > 0`` -- passing
|
| 463 |
+
``t`` raises so we don't silently drop it. Note: T=1 single-
|
| 464 |
+
frame inputs go through the video path unchanged; ``is_ltx`` is
|
| 465 |
+
about the wrapper's decode signature, not the input tensor's
|
| 466 |
+
temporal length.
|
| 467 |
+
"""
|
| 468 |
+
if self.intensity_vae is not None:
|
| 469 |
+
latent = latent.float()
|
| 470 |
+
range_channels = int(self.vae.latent_ch)
|
| 471 |
+
intensity_channels = int(self.intensity_vae.latent_ch)
|
| 472 |
+
with torch.autocast("cuda", enabled=False):
|
| 473 |
+
if latent.shape[1] == range_channels:
|
| 474 |
+
return self._decode_with_vae(self.vae, latent, t=t)
|
| 475 |
+
if latent.shape[1] != range_channels + intensity_channels:
|
| 476 |
+
raise ValueError(
|
| 477 |
+
"paired range/intensity decoding expects "
|
| 478 |
+
f"{range_channels} or "
|
| 479 |
+
f"{range_channels + intensity_channels} channels, "
|
| 480 |
+
f"got {tuple(latent.shape)}"
|
| 481 |
+
)
|
| 482 |
+
if t is not None:
|
| 483 |
+
raise ValueError(
|
| 484 |
+
"paired range/intensity decoding does not support "
|
| 485 |
+
"timestep-conditioned VAE decoding"
|
| 486 |
+
)
|
| 487 |
+
range_recon = self._decode_with_vae(
|
| 488 |
+
self.vae, latent[:, :range_channels]
|
| 489 |
+
)
|
| 490 |
+
intensity_recon = self._decode_with_vae(
|
| 491 |
+
self.intensity_vae, latent[:, range_channels:]
|
| 492 |
+
)
|
| 493 |
+
if range_recon.shape[2:] != intensity_recon.shape[2:]:
|
| 494 |
+
raise ValueError(
|
| 495 |
+
"range and intensity decoder grids do not align: "
|
| 496 |
+
f"{tuple(range_recon.shape)} vs "
|
| 497 |
+
f"{tuple(intensity_recon.shape)}"
|
| 498 |
+
)
|
| 499 |
+
return torch.cat([range_recon, intensity_recon], dim=1)
|
| 500 |
+
is_ltx = getattr(self.vae, "is_ltx", False)
|
| 501 |
+
if t is not None and not is_ltx:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"Got t={t!r} but the wrapped VAE "
|
| 504 |
+
f"({type(self.vae).__name__}) is not LTX-style "
|
| 505 |
+
f"(is_ltx=False). Either drop --decoder_t1 or swap in a "
|
| 506 |
+
f"TransformerVAELTX checkpoint with denoising_t_max > 0."
|
| 507 |
+
)
|
| 508 |
+
latent = latent.float()
|
| 509 |
+
with torch.autocast("cuda", enabled=False):
|
| 510 |
+
if getattr(self.vae, "is_image", True):
|
| 511 |
+
# 4D image-tokenizer wrapper path (no T dim). LTX-style
|
| 512 |
+
# decoders are never image VAEs in this codebase, so we
|
| 513 |
+
# ignore ``t`` here (the gate above already rejected
|
| 514 |
+
# non-None t for any non-LTX wrapper).
|
| 515 |
+
return super().decode(latent)
|
| 516 |
+
if is_ltx:
|
| 517 |
+
return self.vae.decode(latent / self.sigma_data, t=t)
|
| 518 |
+
return self.vae.decode(latent / self.sigma_data)
|
| 519 |
+
|
| 520 |
+
@torch.no_grad()
|
| 521 |
+
def decode_stream(
|
| 522 |
+
self,
|
| 523 |
+
latent_new: torch.Tensor,
|
| 524 |
+
temporal_kv_cache=None,
|
| 525 |
+
max_cache_frames: int | None = None,
|
| 526 |
+
):
|
| 527 |
+
"""Decode only newly appended diffusion-space latent frames."""
|
| 528 |
+
if getattr(self.vae, "is_image", True):
|
| 529 |
+
raise NotImplementedError(
|
| 530 |
+
"streaming decode requires a causal video VAE"
|
| 531 |
+
)
|
| 532 |
+
if not hasattr(self.vae, "decode_stream"):
|
| 533 |
+
raise NotImplementedError(
|
| 534 |
+
f"{type(self.vae).__name__} does not implement decode_stream"
|
| 535 |
+
)
|
| 536 |
+
latent_new = latent_new.float()
|
| 537 |
+
with torch.autocast("cuda", enabled=False):
|
| 538 |
+
decode_kwargs = {"temporal_kv_cache": temporal_kv_cache}
|
| 539 |
+
if max_cache_frames is not None:
|
| 540 |
+
decode_kwargs["max_cache_frames"] = max_cache_frames
|
| 541 |
+
return self.vae.decode_stream(
|
| 542 |
+
latent_new / self.sigma_data,
|
| 543 |
+
**decode_kwargs,
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
# ------------------------------------------------------------------
|
| 547 |
+
# BEV hdmap -> Wan2.2 latent
|
| 548 |
+
# ------------------------------------------------------------------
|
| 549 |
+
|
| 550 |
+
@torch.no_grad()
|
| 551 |
+
def _bev_hdmap_to_wan_latent(self, bev: torch.Tensor) -> torch.Tensor:
|
| 552 |
+
"""``(B, C_cls, T, Y, X)`` {0,1} BEV raster -> ``(B, 48, T, Y/16, X/16)``.
|
| 553 |
+
|
| 554 |
+
Renders the per-class occupancy grid into a 3-channel image (colored
|
| 555 |
+
palette or grayscale occupancy), maps to [-1, 1], and encodes with the
|
| 556 |
+
frozen Wan2.2 RGB VAE. Matches the render used in the roundtrip test.
|
| 557 |
+
"""
|
| 558 |
+
assert bev.ndim == 5, f"bev_hdmap must be 5-D (B,C,T,Y,X), got {bev.shape}"
|
| 559 |
+
B, C, T, Y, X = bev.shape
|
| 560 |
+
bev = (bev.reshape(B * T, C, Y, X) > 0.5).float()
|
| 561 |
+
if self.bev_hdmap_render_mode == "occupancy":
|
| 562 |
+
occ = bev.amax(dim=1, keepdim=True) # (BT, 1, Y, X)
|
| 563 |
+
img01 = occ.repeat(1, 3, 1, 1)
|
| 564 |
+
else: # colored (later classes paint over earlier ones)
|
| 565 |
+
pal = self._bev_palette.to(device=bev.device, dtype=bev.dtype) # (C, 3)
|
| 566 |
+
img01 = bev.new_zeros(B * T, 3, Y, X)
|
| 567 |
+
n = min(C, pal.shape[0])
|
| 568 |
+
for ci in range(n):
|
| 569 |
+
m = bev[:, ci : ci + 1] > 0.5 # (BT, 1, Y, X)
|
| 570 |
+
img01 = torch.where(m, pal[ci].view(1, 3, 1, 1), img01)
|
| 571 |
+
img = (img01 * 2.0 - 1.0).reshape(B, 3, T, Y, X) # Wan wants (B,3,T,H,W)
|
| 572 |
+
return self.bev_hdmap_wan.encode(img)
|
| 573 |
+
|
| 574 |
+
# ------------------------------------------------------------------
|
| 575 |
+
# Override: data preparation
|
| 576 |
+
# ------------------------------------------------------------------
|
| 577 |
+
|
| 578 |
+
def _store_hdmap_latent(self, hdmap_z: Tensor | None) -> None:
|
| 579 |
+
"""Apply configured HDMap masking and store the current latent."""
|
| 580 |
+
if hdmap_z is None:
|
| 581 |
+
self._current_hdmap = None
|
| 582 |
+
return
|
| 583 |
+
|
| 584 |
+
if self.training and self.hdmap_dropout_prob > 0.0:
|
| 585 |
+
hdmap_z = self._apply_hdmap_dropout(hdmap_z)
|
| 586 |
+
|
| 587 |
+
frames_inf = getattr(self, "_hdmap_keep_frames_infer", None)
|
| 588 |
+
k_inf = getattr(self, "_hdmap_keep_first_k_infer", None)
|
| 589 |
+
if (frames_inf is not None or k_inf is not None) and hdmap_z.ndim == 5:
|
| 590 |
+
T_lat = hdmap_z.shape[2]
|
| 591 |
+
frame_keep = torch.zeros(
|
| 592 |
+
(1, 1, T_lat, 1, 1),
|
| 593 |
+
device=hdmap_z.device,
|
| 594 |
+
dtype=hdmap_z.dtype,
|
| 595 |
+
)
|
| 596 |
+
if frames_inf is not None:
|
| 597 |
+
kept = sorted({int(i) % T_lat for i in frames_inf})
|
| 598 |
+
for i in kept:
|
| 599 |
+
frame_keep[:, :, i] = 1.0
|
| 600 |
+
log.info(
|
| 601 |
+
f"[infer] hdmap keep_frames={kept}/{T_lat}: zeroed "
|
| 602 |
+
f"{T_lat - len(kept)} other hdmap latent frames"
|
| 603 |
+
)
|
| 604 |
+
else:
|
| 605 |
+
K = max(0, min(int(k_inf), T_lat))
|
| 606 |
+
if K > 0:
|
| 607 |
+
frame_keep[:, :, :K] = 1.0
|
| 608 |
+
log.info(
|
| 609 |
+
f"[infer] hdmap keep_first_k={K}/{T_lat}: zeroed "
|
| 610 |
+
f"{T_lat - K} trailing hdmap latent frames"
|
| 611 |
+
)
|
| 612 |
+
hdmap_z = hdmap_z * frame_keep
|
| 613 |
+
if getattr(self, "_hdmap_force_zero_latent", False):
|
| 614 |
+
hdmap_z = torch.zeros_like(hdmap_z)
|
| 615 |
+
self._current_hdmap = hdmap_z
|
| 616 |
+
|
| 617 |
+
def get_data_and_condition(
|
| 618 |
+
self, data_batch: dict[str, Tensor]
|
| 619 |
+
) -> Tuple[Tensor, Tensor, BaseVideoCondition]:
|
| 620 |
+
self._normalize_video_databatch_inplace(data_batch)
|
| 621 |
+
self._augment_image_dim_inplace(data_batch)
|
| 622 |
+
input_key = self.input_data_key
|
| 623 |
+
is_image_batch = self.is_image_batch(data_batch)
|
| 624 |
+
is_video_batch = not is_image_batch
|
| 625 |
+
|
| 626 |
+
for key in sorted(data_batch.keys()):
|
| 627 |
+
data_batch[key] = _broadcast(
|
| 628 |
+
data_batch[key], to_tp=True, to_cp=is_video_batch
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
if is_image_batch:
|
| 632 |
+
input_key = self.input_image_key
|
| 633 |
+
|
| 634 |
+
# Encode lidar
|
| 635 |
+
raw_state = data_batch[input_key]
|
| 636 |
+
self._current_sensor_dataset_ids = None
|
| 637 |
+
if self._num_dataset_embeddings > 0:
|
| 638 |
+
dataset_ids = data_batch.get("sensor_dataset_id")
|
| 639 |
+
if dataset_ids is None:
|
| 640 |
+
raise KeyError(
|
| 641 |
+
"dataset-conditioned DiT requires sensor_dataset_id"
|
| 642 |
+
)
|
| 643 |
+
dataset_ids = torch.as_tensor(
|
| 644 |
+
dataset_ids, device=raw_state.device, dtype=torch.long
|
| 645 |
+
).reshape(-1)
|
| 646 |
+
if dataset_ids.shape != (raw_state.shape[0],):
|
| 647 |
+
raise ValueError(
|
| 648 |
+
"sensor_dataset_id must have one value per sample, got "
|
| 649 |
+
f"{tuple(dataset_ids.shape)} for B={raw_state.shape[0]}"
|
| 650 |
+
)
|
| 651 |
+
if bool(
|
| 652 |
+
((dataset_ids < 0) | (
|
| 653 |
+
dataset_ids >= self._num_dataset_embeddings
|
| 654 |
+
)).any()
|
| 655 |
+
):
|
| 656 |
+
raise ValueError(
|
| 657 |
+
"sensor_dataset_id contains a value outside [0, "
|
| 658 |
+
f"{self._num_dataset_embeddings})"
|
| 659 |
+
)
|
| 660 |
+
self._current_sensor_dataset_ids = dataset_ids
|
| 661 |
+
latent_state = self.encode(raw_state).contiguous()
|
| 662 |
+
latent_state = latent_state.to(self.diffusion_dtype)
|
| 663 |
+
|
| 664 |
+
# Prepare HD-map conditioning
|
| 665 |
+
hdmap_z = None
|
| 666 |
+
if self._hdmap_concat_ch > 0:
|
| 667 |
+
if self.bev_hdmap_wan is not None:
|
| 668 |
+
# BEV-native path: render the multi-channel BEV hdmap raster
|
| 669 |
+
# (B, C_cls, T, Y, X) to a 3-ch image and encode it with the
|
| 670 |
+
# frozen Wan2.2 VAE -> (B, 48, T, Y/16, X/16).
|
| 671 |
+
bev = data_batch.get("bev_hdmap")
|
| 672 |
+
if bev is not None:
|
| 673 |
+
hdmap_z = self._bev_hdmap_to_wan_latent(bev.float()).to(
|
| 674 |
+
self.diffusion_dtype
|
| 675 |
+
)
|
| 676 |
+
elif self.bev_hdmap_pool is not None:
|
| 677 |
+
# BEV-native path: pool the multi-channel BEV hdmap raster
|
| 678 |
+
# (B, C_cls, T, Y, X) down to the latent grid (B, out, T, Hz, Wz).
|
| 679 |
+
bev = data_batch.get("bev_hdmap")
|
| 680 |
+
if bev is not None:
|
| 681 |
+
hdmap_z = self.bev_hdmap_pool(bev.float()).to(self.diffusion_dtype)
|
| 682 |
+
else:
|
| 683 |
+
hdmap = data_batch.get("lidar_hdmap")
|
| 684 |
+
if hdmap is not None:
|
| 685 |
+
if self.encode_hdmap_with_vae:
|
| 686 |
+
if getattr(self, "_hdmap_force_zero_latent", False):
|
| 687 |
+
hdmap_z = latent_state.new_zeros(
|
| 688 |
+
latent_state.shape[0],
|
| 689 |
+
self._hdmap_concat_ch,
|
| 690 |
+
*latent_state.shape[2:],
|
| 691 |
+
)
|
| 692 |
+
else:
|
| 693 |
+
# Hdmap shares the lidar's pixel format (C, T, H, W);
|
| 694 |
+
# reuse the lidar VAE so the conditioning is already in
|
| 695 |
+
# the same latent space as the noisy target.
|
| 696 |
+
# ``self.encode`` already applies the ``sigma_data``
|
| 697 |
+
# scaling, matching ``latent_state``. For a mono
|
| 698 |
+
# ``mask_as_input`` VAE the wrapper auto-derives +
|
| 699 |
+
# appends the (threshold) validity-mask channel from the
|
| 700 |
+
# 1-channel depth -- the SAME encode path as the lidar.
|
| 701 |
+
hdmap_z = self.encode(hdmap.float()).contiguous()
|
| 702 |
+
else:
|
| 703 |
+
hdmap_z = self._prepare_hdmap(hdmap.float(), latent_state)
|
| 704 |
+
hdmap_z = hdmap_z.to(self.diffusion_dtype)
|
| 705 |
+
self._store_hdmap_latent(hdmap_z)
|
| 706 |
+
|
| 707 |
+
# Condition
|
| 708 |
+
condition = self.conditioner(data_batch)
|
| 709 |
+
if is_image_batch:
|
| 710 |
+
condition.data_type = DataType.IMAGE
|
| 711 |
+
else:
|
| 712 |
+
condition.data_type = DataType.VIDEO
|
| 713 |
+
|
| 714 |
+
latent_state = _broadcast(latent_state, to_tp=True, to_cp=is_video_batch)
|
| 715 |
+
condition = broadcast_condition(condition, to_tp=True, to_cp=is_video_batch)
|
| 716 |
+
|
| 717 |
+
return raw_state, latent_state, condition
|
| 718 |
+
|
| 719 |
+
# ------------------------------------------------------------------
|
| 720 |
+
# Override: denoise — concat hdmap with network input
|
| 721 |
+
# ------------------------------------------------------------------
|
| 722 |
+
|
| 723 |
+
def denoise(
|
| 724 |
+
self, xt: torch.Tensor, sigma: torch.Tensor, condition: CosmosCondition
|
| 725 |
+
) -> DenoisePrediction:
|
| 726 |
+
if getattr(self.config, "use_dummy_temporal_dim", False):
|
| 727 |
+
xt = xt.unsqueeze(2)
|
| 728 |
+
|
| 729 |
+
xt = xt.to(**self.tensor_kwargs)
|
| 730 |
+
sigma = sigma.to(**self.tensor_kwargs)
|
| 731 |
+
|
| 732 |
+
c_skip, c_out, c_in, c_noise = self.scaling(sigma=sigma)
|
| 733 |
+
|
| 734 |
+
net_input = batch_mul(c_in, xt)
|
| 735 |
+
|
| 736 |
+
# Channel-concat HD-map
|
| 737 |
+
if self._current_hdmap is not None:
|
| 738 |
+
hdmap = self._current_hdmap.to(net_input.dtype)
|
| 739 |
+
# Handle CFG batch doubling
|
| 740 |
+
if net_input.shape[0] != hdmap.shape[0]:
|
| 741 |
+
repeats = net_input.shape[0] // hdmap.shape[0]
|
| 742 |
+
hdmap = hdmap.repeat(repeats, *([1] * (hdmap.ndim - 1)))
|
| 743 |
+
# Unconditional CFG pass: replace hdmap with zeros (the "null"
|
| 744 |
+
# condition the model saw during training with hdmap dropout).
|
| 745 |
+
if self._hdmap_force_null:
|
| 746 |
+
hdmap = torch.zeros_like(hdmap)
|
| 747 |
+
net_input = torch.cat([net_input, hdmap], dim=1)
|
| 748 |
+
|
| 749 |
+
net_output = self.net(
|
| 750 |
+
x=net_input,
|
| 751 |
+
timesteps=c_noise,
|
| 752 |
+
**condition.to_dict(),
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
logvar = self.model.logvar(c_noise)
|
| 756 |
+
x0_pred = batch_mul(c_skip, xt) + batch_mul(c_out, net_output)
|
| 757 |
+
eps_pred = batch_mul(xt - x0_pred, 1.0 / sigma)
|
| 758 |
+
|
| 759 |
+
if getattr(self.config, "use_dummy_temporal_dim", False):
|
| 760 |
+
x0_pred = x0_pred.squeeze(2)
|
| 761 |
+
eps_pred = eps_pred.squeeze(2)
|
| 762 |
+
|
| 763 |
+
return DenoisePrediction(x0_pred, eps_pred, logvar)
|
| 764 |
+
|
| 765 |
+
# ------------------------------------------------------------------
|
| 766 |
+
# Override: validation — provide defaults for missing keys
|
| 767 |
+
# ------------------------------------------------------------------
|
| 768 |
+
|
| 769 |
+
@torch.no_grad()
|
| 770 |
+
def validation_step(
|
| 771 |
+
self, data: dict[str, Tensor], iteration: int
|
| 772 |
+
) -> tuple[dict[str, Tensor], Tensor]:
|
| 773 |
+
raw_data, x0, condition = self.get_data_and_condition(data)
|
| 774 |
+
|
| 775 |
+
guidance = data.get("guidance", 1.5)
|
| 776 |
+
data = misc.to(data, **self.tensor_kwargs)
|
| 777 |
+
|
| 778 |
+
sample = self.generate_samples_from_batch(
|
| 779 |
+
data,
|
| 780 |
+
guidance=guidance,
|
| 781 |
+
state_shape=x0.shape[1:],
|
| 782 |
+
n_sample=x0.shape[0],
|
| 783 |
+
)
|
| 784 |
+
sample = self.decode(sample)
|
| 785 |
+
reconstruction = self.decode(x0)
|
| 786 |
+
|
| 787 |
+
hdmap = data.get("lidar_hdmap")
|
| 788 |
+
if hdmap is not None:
|
| 789 |
+
hdmap = hdmap.float().cpu()
|
| 790 |
+
|
| 791 |
+
return {
|
| 792 |
+
"gt": raw_data,
|
| 793 |
+
"result": sample,
|
| 794 |
+
"reconstruction": reconstruction,
|
| 795 |
+
"lidar_hdmap": hdmap,
|
| 796 |
+
}, torch.tensor([0]).to(**self.tensor_kwargs)
|
| 797 |
+
|
| 798 |
+
# ------------------------------------------------------------------
|
| 799 |
+
# Lifecycle
|
| 800 |
+
# ------------------------------------------------------------------
|
| 801 |
+
|
| 802 |
+
def on_train_start(
|
| 803 |
+
self, memory_format: torch.memory_format = torch.preserve_format
|
| 804 |
+
) -> None:
|
| 805 |
+
super().on_train_start(memory_format)
|
| 806 |
+
if self.hdmap_proj is not None:
|
| 807 |
+
self.hdmap_proj = self.hdmap_proj.to(
|
| 808 |
+
device="cuda", dtype=torch.float32
|
| 809 |
+
)
|
| 810 |
+
# The frozen Wan2.2 hdmap encoder lives on ``self`` (not in
|
| 811 |
+
# ``self.model``), so the trainer's ``self.model.to(cuda)`` does not
|
| 812 |
+
# move it. Place it on CUDA explicitly, mirroring ``hdmap_proj`` (kept
|
| 813 |
+
# fp32 -- it was built with is_bf16=False and encodes in fp32).
|
| 814 |
+
if self.bev_hdmap_wan is not None:
|
| 815 |
+
self.bev_hdmap_wan = self.bev_hdmap_wan.to(device="cuda")
|
| 816 |
+
self._bev_palette = self._bev_palette.to(device="cuda")
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
@diffusion_fsdp_class_decorator
|
| 820 |
+
class FSDPHdmapToLidarDiffusionModel(HdmapToLidarModel):
|
| 821 |
+
pass
|
diffusion/training/models/hdmaptolidar_model_rf.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffusion/training/models/hdmaptolidar_model_sf_dmd.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffusion/training/models/model.py
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import amp_C
|
| 20 |
+
import torch
|
| 21 |
+
from apex.multi_tensor_apply import multi_tensor_applier
|
| 22 |
+
from einops import rearrange
|
| 23 |
+
from megatron.core import parallel_state
|
| 24 |
+
from torch import Tensor
|
| 25 |
+
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
|
| 26 |
+
from torch.distributed import broadcast_object_list, get_process_group_ranks
|
| 27 |
+
from torch.distributed.utils import _verify_param_shape_across_processes
|
| 28 |
+
|
| 29 |
+
from diffusion.conditioner import DataType
|
| 30 |
+
from diffusion.modules.res_sampler import COMMON_SOLVER_OPTIONS
|
| 31 |
+
from diffusion.training.conditioner import BaseVideoCondition
|
| 32 |
+
from diffusion.training.context_parallel import cat_outputs_cp, split_inputs_cp
|
| 33 |
+
from diffusion.training.models.model_image import CosmosCondition
|
| 34 |
+
from diffusion.training.models.model_image import DiffusionModel as ImageModel
|
| 35 |
+
from diffusion.training.models.model_image import diffusion_fsdp_class_decorator
|
| 36 |
+
from utils import distributed, log, misc
|
| 37 |
+
|
| 38 |
+
l2_norm_impl = amp_C.multi_tensor_l2norm
|
| 39 |
+
multi_tensor_scale_impl = amp_C.multi_tensor_scale
|
| 40 |
+
|
| 41 |
+
# key to check if the video data is normalized or image data is converted to video data
|
| 42 |
+
# to avoid apply normalization or augment image dimension multiple times
|
| 43 |
+
# It is due to we do not have normalization and augment image dimension in the dataloader and move it to the model
|
| 44 |
+
IS_PREPROCESSED_KEY = "is_preprocessed"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def robust_broadcast(tensor: torch.Tensor, src: int, pg, is_check_shape: bool = False) -> torch.Tensor:
|
| 48 |
+
"""
|
| 49 |
+
Perform a robust broadcast operation that works regardless of tensor shapes on different ranks.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
tensor (torch.Tensor): The tensor to broadcast (on src rank) or receive (on other ranks).
|
| 53 |
+
src (int): The source rank for the broadcast. Defaults to 0.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
torch.Tensor: The broadcasted tensor on all ranks.
|
| 57 |
+
"""
|
| 58 |
+
# First, broadcast the shape of the tensor
|
| 59 |
+
if distributed.get_rank() == src:
|
| 60 |
+
shape = torch.tensor(tensor.shape).cuda()
|
| 61 |
+
else:
|
| 62 |
+
shape = torch.empty(tensor.dim(), dtype=torch.long).cuda()
|
| 63 |
+
if is_check_shape:
|
| 64 |
+
_verify_param_shape_across_processes(pg, [shape])
|
| 65 |
+
torch.distributed.broadcast(shape, src, group=pg)
|
| 66 |
+
|
| 67 |
+
# Resize the tensor on non-src ranks if necessary
|
| 68 |
+
if distributed.get_rank() != src:
|
| 69 |
+
tensor = tensor.new_empty(shape.tolist()).type_as(tensor)
|
| 70 |
+
|
| 71 |
+
# Now broadcast the tensor data
|
| 72 |
+
torch.distributed.broadcast(tensor, src, group=pg)
|
| 73 |
+
|
| 74 |
+
return tensor
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _broadcast(item: torch.Tensor | str | None, to_tp: bool = True, to_cp: bool = True) -> torch.Tensor | str | None:
|
| 78 |
+
"""
|
| 79 |
+
Broadcast the item from the minimum rank in the specified group(s).
|
| 80 |
+
Since global rank = tp_rank + cp_rank * tp_size + ...
|
| 81 |
+
First broadcast in the tp_group and then in the cp_group will
|
| 82 |
+
ensure that the item is broadcasted across ranks in cp_group and tp_group.
|
| 83 |
+
|
| 84 |
+
Parameters:
|
| 85 |
+
- item: The item to broadcast (can be a torch.Tensor, str, or None).
|
| 86 |
+
- to_tp: Whether to broadcast to the tensor model parallel group.
|
| 87 |
+
- to_cp: Whether to broadcast to the context parallel group.
|
| 88 |
+
"""
|
| 89 |
+
if not parallel_state.is_initialized():
|
| 90 |
+
return item
|
| 91 |
+
tp_group = parallel_state.get_tensor_model_parallel_group()
|
| 92 |
+
cp_group = parallel_state.get_context_parallel_group()
|
| 93 |
+
|
| 94 |
+
to_tp = to_tp and parallel_state.get_tensor_model_parallel_world_size() > 1
|
| 95 |
+
to_cp = to_cp and parallel_state.get_context_parallel_world_size() > 1
|
| 96 |
+
|
| 97 |
+
if to_tp:
|
| 98 |
+
min_tp_rank = min(get_process_group_ranks(tp_group))
|
| 99 |
+
|
| 100 |
+
if to_cp:
|
| 101 |
+
min_cp_rank = min(get_process_group_ranks(cp_group))
|
| 102 |
+
|
| 103 |
+
if isinstance(item, torch.Tensor): # assume the device is cuda
|
| 104 |
+
# log.info(f"{item.shape}", rank0_only=False)
|
| 105 |
+
if to_tp:
|
| 106 |
+
# torch.distributed.broadcast(item, min_tp_rank, group=tp_group)
|
| 107 |
+
item = robust_broadcast(item, min_tp_rank, tp_group)
|
| 108 |
+
if to_cp:
|
| 109 |
+
# torch.distributed.broadcast(item, min_cp_rank, group=cp_group)
|
| 110 |
+
item = robust_broadcast(item, min_cp_rank, cp_group)
|
| 111 |
+
elif item is not None:
|
| 112 |
+
broadcastable_list = [item]
|
| 113 |
+
if to_tp:
|
| 114 |
+
# log.info(f"{broadcastable_list}", rank0_only=False)
|
| 115 |
+
broadcast_object_list(broadcastable_list, min_tp_rank, group=tp_group)
|
| 116 |
+
if to_cp:
|
| 117 |
+
broadcast_object_list(broadcastable_list, min_cp_rank, group=cp_group)
|
| 118 |
+
|
| 119 |
+
item = broadcastable_list[0]
|
| 120 |
+
return item
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def broadcast_condition(condition: BaseVideoCondition, to_tp: bool = True, to_cp: bool = True) -> BaseVideoCondition:
|
| 124 |
+
condition_kwargs = {}
|
| 125 |
+
for k, v in condition.to_dict().items():
|
| 126 |
+
if isinstance(v, torch.Tensor):
|
| 127 |
+
assert not v.requires_grad, f"{k} requires gradient. the current impl does not support it"
|
| 128 |
+
condition_kwargs[k] = _broadcast(v, to_tp=to_tp, to_cp=to_cp)
|
| 129 |
+
condition = type(condition)(**condition_kwargs)
|
| 130 |
+
return condition
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class DiffusionModel(ImageModel):
|
| 134 |
+
def __init__(self, config):
|
| 135 |
+
super().__init__(config)
|
| 136 |
+
# Initialize trained_data_record with defaultdict, key: image, video, iteration
|
| 137 |
+
self.trained_data_record = {
|
| 138 |
+
"image": 0,
|
| 139 |
+
"video": 0,
|
| 140 |
+
"iteration": 0,
|
| 141 |
+
}
|
| 142 |
+
if parallel_state.is_initialized():
|
| 143 |
+
self.data_parallel_size = parallel_state.get_data_parallel_world_size()
|
| 144 |
+
else:
|
| 145 |
+
self.data_parallel_size = 1
|
| 146 |
+
|
| 147 |
+
if self.config.adjust_video_noise:
|
| 148 |
+
self.video_noise_multiplier = math.sqrt(self.state_shape[1])
|
| 149 |
+
else:
|
| 150 |
+
self.video_noise_multiplier = 1.0
|
| 151 |
+
|
| 152 |
+
def setup_data_key(self) -> None:
|
| 153 |
+
self.input_data_key = self.config.input_data_key # by default it is video key for Video diffusion model
|
| 154 |
+
self.input_image_key = self.config.input_image_key
|
| 155 |
+
|
| 156 |
+
def is_image_batch(self, data_batch: dict[str, Tensor]) -> bool:
|
| 157 |
+
"""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.
|
| 158 |
+
Another comes from a dataloader which we by default assumes as video_data for video model training.
|
| 159 |
+
"""
|
| 160 |
+
is_image = self.input_image_key in data_batch
|
| 161 |
+
is_video = self.input_data_key in data_batch
|
| 162 |
+
assert (
|
| 163 |
+
is_image != is_video
|
| 164 |
+
), "Only one of the input_image_key or input_data_key should be present in the data_batch."
|
| 165 |
+
return is_image
|
| 166 |
+
|
| 167 |
+
def draw_training_sigma_and_epsilon(self, size: int, condition: BaseVideoCondition) -> Tensor:
|
| 168 |
+
sigma_B, epsilon = super().draw_training_sigma_and_epsilon(size, condition)
|
| 169 |
+
is_video_batch = condition.data_type == DataType.VIDEO
|
| 170 |
+
multiplier = self.video_noise_multiplier if is_video_batch else 1
|
| 171 |
+
sigma_B = _broadcast(sigma_B * multiplier, to_tp=True, to_cp=is_video_batch)
|
| 172 |
+
epsilon = _broadcast(epsilon, to_tp=True, to_cp=is_video_batch)
|
| 173 |
+
return sigma_B, epsilon
|
| 174 |
+
|
| 175 |
+
@torch.no_grad()
|
| 176 |
+
def validation_step(
|
| 177 |
+
self, data: dict[str, torch.Tensor], iteration: int
|
| 178 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor]:
|
| 179 |
+
"""
|
| 180 |
+
save generated videos
|
| 181 |
+
"""
|
| 182 |
+
raw_data, x0, condition = self.get_data_and_condition(data)
|
| 183 |
+
guidance = data["guidance"]
|
| 184 |
+
data = misc.to(data, **self.tensor_kwargs)
|
| 185 |
+
sample = self.generate_samples_from_batch(
|
| 186 |
+
data,
|
| 187 |
+
guidance=guidance,
|
| 188 |
+
# make sure no mismatch and also works for cp
|
| 189 |
+
state_shape=x0.shape[1:],
|
| 190 |
+
n_sample=x0.shape[0],
|
| 191 |
+
)
|
| 192 |
+
sample = self.decode(sample)
|
| 193 |
+
gt = raw_data
|
| 194 |
+
caption = data["ai_caption"]
|
| 195 |
+
return {"gt": gt, "result": sample, "caption": caption}, torch.tensor([0]).to(**self.tensor_kwargs)
|
| 196 |
+
|
| 197 |
+
def training_step(self, data_batch: Dict[str, Tensor], iteration: int) -> Tuple[Dict[str, Tensor] | Tensor]:
|
| 198 |
+
input_key = self.input_data_key # by default it is video key
|
| 199 |
+
if self.is_image_batch(data_batch):
|
| 200 |
+
input_key = self.input_image_key
|
| 201 |
+
batch_size = data_batch[input_key].shape[0]
|
| 202 |
+
self.trained_data_record["image" if self.is_image_batch(data_batch) else "video"] += (
|
| 203 |
+
batch_size * self.data_parallel_size
|
| 204 |
+
)
|
| 205 |
+
self.trained_data_record["iteration"] += 1
|
| 206 |
+
return super().training_step(data_batch, iteration)
|
| 207 |
+
|
| 208 |
+
def state_dict(self) -> Dict[str, Any]:
|
| 209 |
+
state_dict = super().state_dict()
|
| 210 |
+
state_dict["trained_data_record"] = self.trained_data_record
|
| 211 |
+
return state_dict
|
| 212 |
+
|
| 213 |
+
def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False):
|
| 214 |
+
if "trained_data_record" in state_dict and hasattr(self, "trained_data_record"):
|
| 215 |
+
trained_data_record = state_dict.pop("trained_data_record")
|
| 216 |
+
if trained_data_record:
|
| 217 |
+
assert set(trained_data_record.keys()) == set(self.trained_data_record.keys())
|
| 218 |
+
for k, v in trained_data_record.items():
|
| 219 |
+
self.trained_data_record[k] = v
|
| 220 |
+
else:
|
| 221 |
+
log.warning("trained_data_record not found in the state_dict.")
|
| 222 |
+
return super().load_state_dict(state_dict, strict, assign)
|
| 223 |
+
|
| 224 |
+
def _normalize_video_databatch_inplace(self, data_batch: dict[str, Tensor], input_key: str = None) -> None:
|
| 225 |
+
"""
|
| 226 |
+
Normalizes video data in-place on a CUDA device to reduce data loading overhead.
|
| 227 |
+
|
| 228 |
+
This function modifies the video data tensor within the provided data_batch dictionary
|
| 229 |
+
in-place, scaling the uint8 data from the range [0, 255] to the normalized range [-1, 1].
|
| 230 |
+
|
| 231 |
+
Warning:
|
| 232 |
+
A warning is issued if the data has not been previously normalized.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
data_batch (dict[str, Tensor]): A dictionary containing the video data under a specific key.
|
| 236 |
+
This tensor is expected to be on a CUDA device and have dtype of torch.uint8.
|
| 237 |
+
|
| 238 |
+
Side Effects:
|
| 239 |
+
Modifies the 'input_data_key' tensor within the 'data_batch' dictionary in-place.
|
| 240 |
+
|
| 241 |
+
Note:
|
| 242 |
+
This operation is performed directly on the CUDA device to avoid the overhead associated
|
| 243 |
+
with moving data to/from the GPU. Ensure that the tensor is already on the appropriate device
|
| 244 |
+
and has the correct dtype (torch.uint8) to avoid unexpected behaviors.
|
| 245 |
+
"""
|
| 246 |
+
input_key = self.input_data_key if input_key is None else input_key
|
| 247 |
+
# only handle video batch
|
| 248 |
+
if input_key in data_batch:
|
| 249 |
+
# Check if the data has already been normalized and avoid re-normalizing
|
| 250 |
+
if IS_PREPROCESSED_KEY in data_batch and data_batch[IS_PREPROCESSED_KEY] is True:
|
| 251 |
+
assert torch.is_floating_point(data_batch[input_key]), "Video data is not in float format."
|
| 252 |
+
assert torch.all(
|
| 253 |
+
(data_batch[input_key] >= -1.0001) & (data_batch[input_key] <= 1.0001)
|
| 254 |
+
), f"Video data is not in the range [-1, 1]. get data range [{data_batch[input_key].min()}, {data_batch[input_key].max()}]"
|
| 255 |
+
else:
|
| 256 |
+
assert data_batch[input_key].dtype == torch.uint8, "Video data is not in uint8 format."
|
| 257 |
+
data_batch[input_key] = data_batch[input_key].to(**self.tensor_kwargs) / 127.5 - 1.0
|
| 258 |
+
data_batch[IS_PREPROCESSED_KEY] = True
|
| 259 |
+
|
| 260 |
+
def _augment_image_dim_inplace(self, data_batch: dict[str, Tensor], input_key: str = None) -> None:
|
| 261 |
+
input_key = self.input_image_key if input_key is None else input_key
|
| 262 |
+
if input_key in data_batch:
|
| 263 |
+
# Check if the data has already been augmented and avoid re-augmenting
|
| 264 |
+
if IS_PREPROCESSED_KEY in data_batch and data_batch[IS_PREPROCESSED_KEY] is True:
|
| 265 |
+
assert (
|
| 266 |
+
data_batch[input_key].shape[2] == 1
|
| 267 |
+
), f"Image data is claimed be augmented while its shape is {data_batch[input_key].shape}"
|
| 268 |
+
return
|
| 269 |
+
else:
|
| 270 |
+
data_batch[input_key] = rearrange(data_batch[input_key], "b c h w -> b c 1 h w").contiguous()
|
| 271 |
+
data_batch[IS_PREPROCESSED_KEY] = True
|
| 272 |
+
|
| 273 |
+
def get_data_and_condition(self, data_batch: dict[str, Tensor]) -> Tuple[Tensor, BaseVideoCondition]:
|
| 274 |
+
self._normalize_video_databatch_inplace(data_batch)
|
| 275 |
+
self._augment_image_dim_inplace(data_batch)
|
| 276 |
+
input_key = self.input_data_key # by default it is video key
|
| 277 |
+
is_image_batch = self.is_image_batch(data_batch)
|
| 278 |
+
is_video_batch = not is_image_batch
|
| 279 |
+
|
| 280 |
+
# Broadcast data and condition across TP and CP groups.
|
| 281 |
+
# sort keys to make sure the order is same, IMPORTANT! otherwise, nccl will hang!
|
| 282 |
+
local_keys = sorted(list(data_batch.keys()))
|
| 283 |
+
# log.critical(f"all keys {local_keys}", rank0_only=False)
|
| 284 |
+
for key in local_keys:
|
| 285 |
+
data_batch[key] = _broadcast(data_batch[key], to_tp=True, to_cp=is_video_batch)
|
| 286 |
+
|
| 287 |
+
if is_image_batch:
|
| 288 |
+
input_key = self.input_image_key
|
| 289 |
+
|
| 290 |
+
# Latent state
|
| 291 |
+
raw_state = data_batch[input_key]
|
| 292 |
+
latent_state = self.encode(raw_state).contiguous()
|
| 293 |
+
|
| 294 |
+
# Condition
|
| 295 |
+
condition = self.conditioner(data_batch)
|
| 296 |
+
if is_image_batch:
|
| 297 |
+
condition.data_type = DataType.IMAGE
|
| 298 |
+
else:
|
| 299 |
+
condition.data_type = DataType.VIDEO
|
| 300 |
+
|
| 301 |
+
# VAE has randomness. CP/TP group should have the same encoded output.
|
| 302 |
+
|
| 303 |
+
latent_state = _broadcast(latent_state, to_tp=True, to_cp=is_video_batch)
|
| 304 |
+
condition = broadcast_condition(condition, to_tp=True, to_cp=is_video_batch)
|
| 305 |
+
|
| 306 |
+
return raw_state, latent_state, condition
|
| 307 |
+
|
| 308 |
+
def on_train_start(self, memory_format: torch.memory_format = torch.preserve_format) -> None:
|
| 309 |
+
super().on_train_start(memory_format)
|
| 310 |
+
if parallel_state.is_initialized() and parallel_state.get_tensor_model_parallel_world_size() > 1:
|
| 311 |
+
sequence_parallel = getattr(parallel_state, "sequence_parallel", False)
|
| 312 |
+
if sequence_parallel:
|
| 313 |
+
self.net.enable_sequence_parallel()
|
| 314 |
+
|
| 315 |
+
def compute_loss_with_epsilon_and_sigma(
|
| 316 |
+
self,
|
| 317 |
+
data_batch: dict[str, torch.Tensor],
|
| 318 |
+
x0_from_data_batch: torch.Tensor,
|
| 319 |
+
x0: torch.Tensor,
|
| 320 |
+
condition: CosmosCondition,
|
| 321 |
+
epsilon: torch.Tensor,
|
| 322 |
+
sigma: torch.Tensor,
|
| 323 |
+
):
|
| 324 |
+
if self.is_image_batch(data_batch):
|
| 325 |
+
# Turn off CP
|
| 326 |
+
self.net.disable_context_parallel()
|
| 327 |
+
else:
|
| 328 |
+
if parallel_state.is_initialized():
|
| 329 |
+
if parallel_state.get_context_parallel_world_size() > 1:
|
| 330 |
+
# Turn on CP
|
| 331 |
+
cp_group = parallel_state.get_context_parallel_group()
|
| 332 |
+
self.net.enable_context_parallel(cp_group)
|
| 333 |
+
log.debug("[CP] Split x0 and epsilon")
|
| 334 |
+
x0 = split_inputs_cp(x=x0, seq_dim=2, cp_group=self.net.cp_group)
|
| 335 |
+
epsilon = split_inputs_cp(x=epsilon, seq_dim=2, cp_group=self.net.cp_group)
|
| 336 |
+
|
| 337 |
+
output_batch, kendall_loss, pred_mse, edm_loss = super().compute_loss_with_epsilon_and_sigma(
|
| 338 |
+
data_batch, x0_from_data_batch, x0, condition, epsilon, sigma
|
| 339 |
+
)
|
| 340 |
+
if not self.is_image_batch(data_batch):
|
| 341 |
+
if self.loss_reduce == "sum" and parallel_state.get_context_parallel_world_size() > 1:
|
| 342 |
+
kendall_loss *= parallel_state.get_context_parallel_world_size()
|
| 343 |
+
|
| 344 |
+
return output_batch, kendall_loss, pred_mse, edm_loss
|
| 345 |
+
|
| 346 |
+
def get_x0_fn_from_batch(
|
| 347 |
+
self,
|
| 348 |
+
data_batch: Dict,
|
| 349 |
+
guidance: float = 1.5,
|
| 350 |
+
is_negative_prompt: bool = False,
|
| 351 |
+
) -> Callable:
|
| 352 |
+
"""
|
| 353 |
+
Generates a callable function `x0_fn` based on the provided data batch and guidance factor.
|
| 354 |
+
|
| 355 |
+
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.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
- 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`
|
| 359 |
+
- 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.
|
| 360 |
+
- is_negative_prompt (bool): use negative prompt t5 in uncondition if true
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
- Callable: A function `x0_fn(noise_x, sigma)` that takes two arguments, `noise_x` and `sigma`, and return x0 predictoin
|
| 364 |
+
|
| 365 |
+
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.
|
| 366 |
+
"""
|
| 367 |
+
if is_negative_prompt:
|
| 368 |
+
condition, uncondition = self.conditioner.get_condition_with_negative_prompt(data_batch)
|
| 369 |
+
else:
|
| 370 |
+
condition, uncondition = self.conditioner.get_condition_uncondition(data_batch)
|
| 371 |
+
|
| 372 |
+
to_cp = self.net.is_context_parallel_enabled
|
| 373 |
+
# For inference, check if parallel_state is initialized
|
| 374 |
+
if parallel_state.is_initialized():
|
| 375 |
+
condition = broadcast_condition(condition, to_tp=True, to_cp=to_cp)
|
| 376 |
+
uncondition = broadcast_condition(uncondition, to_tp=True, to_cp=to_cp)
|
| 377 |
+
else:
|
| 378 |
+
assert not to_cp, "parallel_state is not initialized, context parallel should be turned off."
|
| 379 |
+
|
| 380 |
+
def x0_fn(noise_x: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
|
| 381 |
+
cond_x0 = self.denoise(noise_x, sigma, condition).x0
|
| 382 |
+
uncond_x0 = self.denoise(noise_x, sigma, uncondition).x0
|
| 383 |
+
raw_x0 = cond_x0 + guidance * (cond_x0 - uncond_x0)
|
| 384 |
+
if "guided_image" in data_batch:
|
| 385 |
+
# replacement trick that enables inpainting with base model
|
| 386 |
+
assert "guided_mask" in data_batch, "guided_mask should be in data_batch if guided_image is present"
|
| 387 |
+
guide_image = data_batch["guided_image"]
|
| 388 |
+
guide_mask = data_batch["guided_mask"]
|
| 389 |
+
raw_x0 = guide_mask * guide_image + (1 - guide_mask) * raw_x0
|
| 390 |
+
return raw_x0
|
| 391 |
+
|
| 392 |
+
return x0_fn
|
| 393 |
+
|
| 394 |
+
def get_x_from_clean(
|
| 395 |
+
self,
|
| 396 |
+
in_clean_img: torch.Tensor,
|
| 397 |
+
sigma_max: float | None,
|
| 398 |
+
seed: int = 1,
|
| 399 |
+
) -> Tensor:
|
| 400 |
+
"""
|
| 401 |
+
in_clean_img (torch.Tensor): input clean image for image-to-image/video-to-video by adding noise then denoising
|
| 402 |
+
sigma_max (float): maximum sigma applied to in_clean_image for image-to-image/video-to-video
|
| 403 |
+
"""
|
| 404 |
+
if in_clean_img is None:
|
| 405 |
+
return None
|
| 406 |
+
generator = torch.Generator(device=self.tensor_kwargs["device"])
|
| 407 |
+
generator.manual_seed(seed)
|
| 408 |
+
noise = torch.randn(*in_clean_img.shape, **self.tensor_kwargs, generator=generator)
|
| 409 |
+
if sigma_max is None:
|
| 410 |
+
sigma_max = self.sde.sigma_max
|
| 411 |
+
x_sigma_max = in_clean_img + noise * sigma_max
|
| 412 |
+
return x_sigma_max
|
| 413 |
+
|
| 414 |
+
def generate_samples_from_batch(
|
| 415 |
+
self,
|
| 416 |
+
data_batch: Dict,
|
| 417 |
+
guidance: float = 1.5,
|
| 418 |
+
seed: int = 1,
|
| 419 |
+
state_shape: Tuple | None = None,
|
| 420 |
+
n_sample: int | None = None,
|
| 421 |
+
is_negative_prompt: bool = False,
|
| 422 |
+
num_steps: int = 35,
|
| 423 |
+
solver_option: COMMON_SOLVER_OPTIONS = "2ab",
|
| 424 |
+
x_sigma_max: Optional[torch.Tensor] = None,
|
| 425 |
+
sigma_max: float | None = None,
|
| 426 |
+
return_noise: bool = False,
|
| 427 |
+
) -> Tensor | Tuple[Tensor, Tensor]:
|
| 428 |
+
"""
|
| 429 |
+
Generate samples from the batch. Based on given batch, it will automatically determine whether to generate image or video samples.
|
| 430 |
+
Args:
|
| 431 |
+
data_batch (dict): raw data batch draw from the training data loader.
|
| 432 |
+
iteration (int): Current iteration number.
|
| 433 |
+
guidance (float): guidance weights
|
| 434 |
+
seed (int): random seed
|
| 435 |
+
state_shape (tuple): shape of the state, default to self.state_shape if not provided
|
| 436 |
+
n_sample (int): number of samples to generate
|
| 437 |
+
is_negative_prompt (bool): use negative prompt t5 in uncondition if true
|
| 438 |
+
num_steps (int): number of steps for the diffusion process
|
| 439 |
+
solver_option (str): differential equation solver option, default to "2ab"~(mulitstep solver)
|
| 440 |
+
return_noise (bool): return the initial noise or not, used for ODE pairs generation
|
| 441 |
+
"""
|
| 442 |
+
self._normalize_video_databatch_inplace(data_batch)
|
| 443 |
+
self._augment_image_dim_inplace(data_batch)
|
| 444 |
+
is_image_batch = self.is_image_batch(data_batch)
|
| 445 |
+
if n_sample is None:
|
| 446 |
+
input_key = self.input_image_key if is_image_batch else self.input_data_key
|
| 447 |
+
n_sample = data_batch[input_key].shape[0]
|
| 448 |
+
if state_shape is None:
|
| 449 |
+
if is_image_batch:
|
| 450 |
+
state_shape = (self.state_shape[0], 1, *self.state_shape[2:]) # C,T,H,W
|
| 451 |
+
|
| 452 |
+
x0_fn = self.get_x0_fn_from_batch(data_batch, guidance, is_negative_prompt=is_negative_prompt)
|
| 453 |
+
|
| 454 |
+
x_sigma_max = (
|
| 455 |
+
misc.arch_invariant_rand(
|
| 456 |
+
(n_sample,) + tuple(state_shape),
|
| 457 |
+
torch.float32,
|
| 458 |
+
self.tensor_kwargs["device"],
|
| 459 |
+
seed,
|
| 460 |
+
)
|
| 461 |
+
* self.sde.sigma_max
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
if self.net.is_context_parallel_enabled:
|
| 465 |
+
x_sigma_max = split_inputs_cp(x=x_sigma_max, seq_dim=2, cp_group=self.net.cp_group)
|
| 466 |
+
|
| 467 |
+
samples = self.sampler(
|
| 468 |
+
x0_fn, x_sigma_max, num_steps=num_steps, sigma_max=self.sde.sigma_max, solver_option=solver_option
|
| 469 |
+
)
|
| 470 |
+
if self.net.is_context_parallel_enabled:
|
| 471 |
+
samples = cat_outputs_cp(samples, seq_dim=2, cp_group=self.net.cp_group)
|
| 472 |
+
|
| 473 |
+
if return_noise:
|
| 474 |
+
if self.net.is_context_parallel_enabled:
|
| 475 |
+
x_sigma_max = cat_outputs_cp(x_sigma_max, seq_dim=2, cp_group=self.net.cp_group)
|
| 476 |
+
return samples, x_sigma_max / self.sde.sigma_max
|
| 477 |
+
|
| 478 |
+
return samples
|
| 479 |
+
|
| 480 |
+
def on_after_backward(self, iteration: int = 0):
|
| 481 |
+
finalize_model_grads([self])
|
| 482 |
+
|
| 483 |
+
def get_grad_norm(
|
| 484 |
+
self,
|
| 485 |
+
norm_type: Union[int, float] = 2,
|
| 486 |
+
filter_fn: Callable[[str, torch.nn.Parameter], bool] | None = None,
|
| 487 |
+
) -> float:
|
| 488 |
+
"""Calculate the norm of gradients, handling model parallel parameters.
|
| 489 |
+
|
| 490 |
+
This function is adapted from torch.nn.utils.clip_grad.clip_grad_norm_
|
| 491 |
+
with added functionality to handle model parallel parameters.
|
| 492 |
+
|
| 493 |
+
Args:
|
| 494 |
+
norm_type (float or int): Type of norm to use. Can be 2 for L2 norm.
|
| 495 |
+
'inf' for infinity norm is not supported.
|
| 496 |
+
filter_fn (callable, optional): Function to filter parameters for norm calculation.
|
| 497 |
+
Takes parameter name and parameter as input, returns True if this parameter is sharded else False.
|
| 498 |
+
|
| 499 |
+
Returns:
|
| 500 |
+
float: Total norm of the parameters (viewed as a single vector).
|
| 501 |
+
|
| 502 |
+
Note:
|
| 503 |
+
- Uses NVIDIA's multi-tensor applier for efficient norm calculation.
|
| 504 |
+
- Handles both model parallel and non-model parallel parameters separately.
|
| 505 |
+
- Currently only supports L2 norm (norm_type = 2).
|
| 506 |
+
"""
|
| 507 |
+
# Get model parallel group if parallel state is initialized
|
| 508 |
+
if parallel_state.is_initialized():
|
| 509 |
+
model_parallel_group = parallel_state.get_model_parallel_group()
|
| 510 |
+
else:
|
| 511 |
+
model_parallel_group = None
|
| 512 |
+
|
| 513 |
+
# Default filter function to identify tensor parallel parameters
|
| 514 |
+
if filter_fn is None:
|
| 515 |
+
|
| 516 |
+
def is_tp(name, param):
|
| 517 |
+
return (
|
| 518 |
+
any(key in name for key in ["to_q.0", "to_k.0", "to_v.0", "to_out.0", "layer1", "layer2"])
|
| 519 |
+
and "_extra_state" not in name
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
filter_fn = is_tp
|
| 523 |
+
|
| 524 |
+
# Separate gradients into model parallel and non-model parallel
|
| 525 |
+
without_mp_grads_for_norm = []
|
| 526 |
+
with_mp_grads_for_norm = []
|
| 527 |
+
for name, param in self.named_parameters():
|
| 528 |
+
if param.grad is not None:
|
| 529 |
+
if filter_fn(name, param):
|
| 530 |
+
with_mp_grads_for_norm.append(param.grad.detach())
|
| 531 |
+
else:
|
| 532 |
+
without_mp_grads_for_norm.append(param.grad.detach())
|
| 533 |
+
|
| 534 |
+
# Only L2 norm is currently supported
|
| 535 |
+
if norm_type != 2.0:
|
| 536 |
+
raise NotImplementedError(f"Norm type {norm_type} is not supported. Only L2 norm (2.0) is implemented.")
|
| 537 |
+
|
| 538 |
+
# Calculate L2 norm using NVIDIA's multi-tensor applier
|
| 539 |
+
dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device="cuda")
|
| 540 |
+
|
| 541 |
+
# Calculate norm for non-model parallel gradients
|
| 542 |
+
without_mp_grad_norm = torch.tensor([0], dtype=torch.float, device="cuda")
|
| 543 |
+
if without_mp_grads_for_norm:
|
| 544 |
+
without_mp_grad_norm, _ = multi_tensor_applier(
|
| 545 |
+
l2_norm_impl,
|
| 546 |
+
dummy_overflow_buf,
|
| 547 |
+
[without_mp_grads_for_norm],
|
| 548 |
+
False, # no per-parameter norm
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
# Calculate norm for model parallel gradients
|
| 552 |
+
with_mp_grad_norm = torch.tensor([0], dtype=torch.float, device="cuda")
|
| 553 |
+
if with_mp_grads_for_norm:
|
| 554 |
+
with_mp_grad_norm, _ = multi_tensor_applier(
|
| 555 |
+
l2_norm_impl,
|
| 556 |
+
dummy_overflow_buf,
|
| 557 |
+
[with_mp_grads_for_norm],
|
| 558 |
+
False, # no per-parameter norm
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
# Square the norms as we'll be summing across model parallel GPUs
|
| 562 |
+
total_without_mp_norm = without_mp_grad_norm**2
|
| 563 |
+
total_with_mp_norm = with_mp_grad_norm**2
|
| 564 |
+
|
| 565 |
+
# Sum across all model-parallel GPUs
|
| 566 |
+
torch.distributed.all_reduce(total_with_mp_norm, op=torch.distributed.ReduceOp.SUM, group=model_parallel_group)
|
| 567 |
+
|
| 568 |
+
# Combine norms from model parallel and non-model parallel gradients
|
| 569 |
+
total_norm = (total_with_mp_norm.item() + total_without_mp_norm.item()) ** 0.5
|
| 570 |
+
|
| 571 |
+
return total_norm
|
| 572 |
+
|
| 573 |
+
def clip_grad_norm_(self, max_norm: float):
|
| 574 |
+
"""
|
| 575 |
+
This function performs gradient clipping to prevent exploding gradients.
|
| 576 |
+
It calculates the total norm of the gradients, and if it exceeds the
|
| 577 |
+
specified max_norm, scales the gradients down proportionally.
|
| 578 |
+
|
| 579 |
+
Args:
|
| 580 |
+
max_norm (float): The maximum allowed norm for the gradients.
|
| 581 |
+
|
| 582 |
+
Returns:
|
| 583 |
+
torch.Tensor: The total norm of the gradients before clipping.
|
| 584 |
+
|
| 585 |
+
Note:
|
| 586 |
+
This implementation uses NVIDIA's multi-tensor applier for efficiency.
|
| 587 |
+
"""
|
| 588 |
+
# Collect gradients from all parameters that require gradients
|
| 589 |
+
grads = []
|
| 590 |
+
for param in self.parameters():
|
| 591 |
+
if param.grad is not None:
|
| 592 |
+
grads.append(param.grad.detach())
|
| 593 |
+
|
| 594 |
+
# Calculate the total norm of the gradients
|
| 595 |
+
total_norm = self.get_grad_norm()
|
| 596 |
+
|
| 597 |
+
# Compute the clipping coefficient
|
| 598 |
+
clip_coeff = max_norm / (total_norm + 1.0e-6)
|
| 599 |
+
|
| 600 |
+
# Apply gradient clipping if the total norm exceeds max_norm
|
| 601 |
+
if clip_coeff < 1.0:
|
| 602 |
+
dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device="cuda")
|
| 603 |
+
# Apply the scaling to the gradients using multi_tensor_applier for efficiency
|
| 604 |
+
multi_tensor_applier(multi_tensor_scale_impl, dummy_overflow_buf, [grads, grads], clip_coeff)
|
| 605 |
+
|
| 606 |
+
return torch.tensor([total_norm])
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def _allreduce_layernorm_grads(model: List[torch.nn.Module]):
|
| 610 |
+
"""
|
| 611 |
+
All-reduce the following layernorm grads:
|
| 612 |
+
- When tensor parallel is enabled, all-reduce grads of QK-layernorm
|
| 613 |
+
- When sequence parallel, all-reduce grads of AdaLN, t_embedder, additional_timestamp_embedder,
|
| 614 |
+
and affline_norm.
|
| 615 |
+
"""
|
| 616 |
+
sequence_parallel = getattr(parallel_state, "sequence_parallel", False)
|
| 617 |
+
|
| 618 |
+
if parallel_state.get_tensor_model_parallel_world_size() > 1:
|
| 619 |
+
grads = []
|
| 620 |
+
for model_chunk in model:
|
| 621 |
+
for name, param in model_chunk.named_parameters():
|
| 622 |
+
if not param.requires_grad:
|
| 623 |
+
continue
|
| 624 |
+
|
| 625 |
+
if "to_q.1" in name or "to_k.1" in name: # TP # Q-layernorm # K-layernorm
|
| 626 |
+
# grad = param.main_grad
|
| 627 |
+
grad = param.grad
|
| 628 |
+
if grad is not None:
|
| 629 |
+
grads.append(grad.data)
|
| 630 |
+
|
| 631 |
+
if sequence_parallel: # TP + SP
|
| 632 |
+
if (
|
| 633 |
+
"t_embedder" in name
|
| 634 |
+
or "adaLN_modulation" in name
|
| 635 |
+
or "additional_timestamp_embedder" in name
|
| 636 |
+
or "affline_norm" in name
|
| 637 |
+
or "input_hint_block" in name
|
| 638 |
+
or "zero_blocks" in name
|
| 639 |
+
):
|
| 640 |
+
# grad = param.main_grad
|
| 641 |
+
grad = param.grad
|
| 642 |
+
if grad is not None:
|
| 643 |
+
grads.append(grad.data)
|
| 644 |
+
|
| 645 |
+
if grads:
|
| 646 |
+
coalesced = _flatten_dense_tensors(grads)
|
| 647 |
+
torch.distributed.all_reduce(coalesced, group=parallel_state.get_tensor_model_parallel_group())
|
| 648 |
+
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
|
| 649 |
+
buf.copy_(synced)
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def finalize_model_grads(model: List[torch.nn.Module]):
|
| 653 |
+
"""
|
| 654 |
+
All-reduce layernorm grads for tensor/sequence parallelism.
|
| 655 |
+
Reference implementation: https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/distributed/finalize_model_grads.py#L99
|
| 656 |
+
"""
|
| 657 |
+
|
| 658 |
+
_allreduce_layernorm_grads(model)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
@diffusion_fsdp_class_decorator
|
| 662 |
+
class FSDPDiffusionModel(DiffusionModel):
|
| 663 |
+
pass
|
diffusion/training/models/model_image.py
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import functools
|
| 17 |
+
from contextlib import contextmanager
|
| 18 |
+
from dataclasses import dataclass, fields
|
| 19 |
+
from typing import Any, Callable, Dict, Mapping, Optional, Tuple, Type, TypeVar
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from megatron.core import parallel_state
|
| 25 |
+
from torch.distributed.fsdp import FullStateDictConfig
|
| 26 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 27 |
+
from torch.distributed.fsdp import ShardingStrategy, StateDictType
|
| 28 |
+
from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy
|
| 29 |
+
from torch.nn.modules.module import _IncompatibleKeys
|
| 30 |
+
|
| 31 |
+
from diffusion.functional.batch_ops import batch_mul
|
| 32 |
+
from diffusion.module.blocks import FourierFeatures
|
| 33 |
+
from diffusion.training.module.pretrained_vae_base import BaseVAE
|
| 34 |
+
from diffusion.modules.denoiser_scaling import EDMScaling
|
| 35 |
+
from diffusion.modules.res_sampler import COMMON_SOLVER_OPTIONS, Sampler
|
| 36 |
+
from diffusion.training.functional.loss import create_per_sample_loss_mask
|
| 37 |
+
from diffusion.training.utils.fsdp_helper import apply_fsdp_checkpointing, hsdp_device_mesh
|
| 38 |
+
from diffusion.training.utils.optim_instantiate import get_base_scheduler
|
| 39 |
+
from diffusion.types import DenoisePrediction
|
| 40 |
+
from utils import distributed, log, misc
|
| 41 |
+
from utils.ema import FastEmaModelUpdater
|
| 42 |
+
from utils.lazy_config import LazyDict
|
| 43 |
+
from utils.lazy_config import instantiate as lazy_instantiate
|
| 44 |
+
from utils.model import Model
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class CosmosCondition:
|
| 49 |
+
crossattn_emb: torch.Tensor
|
| 50 |
+
crossattn_mask: torch.Tensor
|
| 51 |
+
padding_mask: Optional[torch.Tensor] = None
|
| 52 |
+
scalar_feature: Optional[torch.Tensor] = None
|
| 53 |
+
|
| 54 |
+
def to_dict(self) -> Dict[str, Optional[torch.Tensor]]:
|
| 55 |
+
return {f.name: getattr(self, f.name) for f in fields(self)}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class DiffusionModel(Model):
|
| 59 |
+
def __init__(self, config):
|
| 60 |
+
super().__init__()
|
| 61 |
+
|
| 62 |
+
self.config = config
|
| 63 |
+
|
| 64 |
+
# how many sample have been processed
|
| 65 |
+
self.sample_counter = 0
|
| 66 |
+
self.precision = {
|
| 67 |
+
"float32": torch.float32,
|
| 68 |
+
"float16": torch.float16,
|
| 69 |
+
"bfloat16": torch.bfloat16,
|
| 70 |
+
}[config.precision]
|
| 71 |
+
self.tensor_kwargs = {"device": "cuda", "dtype": self.precision}
|
| 72 |
+
log.warning(f"DiffusionModel: precision {self.precision}")
|
| 73 |
+
# Timer passed to network to detect slow ranks.
|
| 74 |
+
# 1. set data keys and data information
|
| 75 |
+
self.sigma_data = config.sigma_data
|
| 76 |
+
self.state_shape = list(config.latent_shape)
|
| 77 |
+
self.setup_data_key()
|
| 78 |
+
|
| 79 |
+
# 2. setup up diffusion processing and scaling~(pre-condition), sampler
|
| 80 |
+
self.sde = lazy_instantiate(config.sde)
|
| 81 |
+
self.sampler = Sampler()
|
| 82 |
+
self.scaling = EDMScaling(self.sigma_data)
|
| 83 |
+
|
| 84 |
+
# 3. vae
|
| 85 |
+
with misc.timer("DiffusionModel: set_up_vae"):
|
| 86 |
+
self.vae: BaseVAE = lazy_instantiate(config.vae)
|
| 87 |
+
self.intensity_vae: BaseVAE | None = None
|
| 88 |
+
intensity_vae_config = getattr(config, "intensity_vae", None)
|
| 89 |
+
if intensity_vae_config is not None:
|
| 90 |
+
self.intensity_vae = lazy_instantiate(intensity_vae_config)
|
| 91 |
+
expected_latent_ch = self.vae.latent_ch + (
|
| 92 |
+
0
|
| 93 |
+
if self.intensity_vae is None
|
| 94 |
+
else self.intensity_vae.latent_ch
|
| 95 |
+
)
|
| 96 |
+
assert (
|
| 97 |
+
expected_latent_ch == self.state_shape[0]
|
| 98 |
+
), (
|
| 99 |
+
f"combined latent_ch {expected_latent_ch} != state_shape "
|
| 100 |
+
f"{self.state_shape[0]}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# 4. Set up loss options, including loss masking, loss reduce and loss scaling
|
| 104 |
+
self.loss_masking: Optional[Dict] = config.loss_masking
|
| 105 |
+
self.loss_reduce = getattr(config, "loss_reduce", "mean")
|
| 106 |
+
assert self.loss_reduce in ["mean", "sum"]
|
| 107 |
+
self.loss_scale = getattr(config, "loss_scale", 1.0)
|
| 108 |
+
log.critical(f"Using {self.loss_reduce} loss reduce with loss scale {self.loss_scale}")
|
| 109 |
+
log.critical(f"Enable loss masking: {config.loss_mask_enabled}")
|
| 110 |
+
|
| 111 |
+
# 5. diffusion neural networks part
|
| 112 |
+
self.set_up_model()
|
| 113 |
+
|
| 114 |
+
def setup_data_key(self) -> None:
|
| 115 |
+
self.input_data_key = self.config.input_data_key
|
| 116 |
+
|
| 117 |
+
def build_model(self) -> torch.nn.ModuleDict:
|
| 118 |
+
config = self.config
|
| 119 |
+
net = lazy_instantiate(config.net)
|
| 120 |
+
conditioner = lazy_instantiate(config.conditioner)
|
| 121 |
+
logvar = torch.nn.Sequential(
|
| 122 |
+
FourierFeatures(num_channels=128, normalize=True), torch.nn.Linear(128, 1, bias=False)
|
| 123 |
+
)
|
| 124 |
+
if bool(getattr(config, "optimizer_net_only", False)):
|
| 125 |
+
conditioner.requires_grad_(False)
|
| 126 |
+
logvar.requires_grad_(False)
|
| 127 |
+
|
| 128 |
+
return torch.nn.ModuleDict(
|
| 129 |
+
{
|
| 130 |
+
"net": net,
|
| 131 |
+
"conditioner": conditioner,
|
| 132 |
+
"logvar": logvar,
|
| 133 |
+
}
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
@misc.timer("DiffusionModel: set_up_model")
|
| 137 |
+
def set_up_model(self):
|
| 138 |
+
config = self.config
|
| 139 |
+
self.model = self.build_model()
|
| 140 |
+
if config.ema.enabled:
|
| 141 |
+
with misc.timer("DiffusionModel: instantiate ema"):
|
| 142 |
+
config.ema.model = self.model
|
| 143 |
+
self.model_ema = lazy_instantiate(config.ema)
|
| 144 |
+
config.ema.model = None
|
| 145 |
+
else:
|
| 146 |
+
self.model_ema = None
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def net(self):
|
| 150 |
+
return self.model.net
|
| 151 |
+
|
| 152 |
+
@property
|
| 153 |
+
def conditioner(self):
|
| 154 |
+
return self.model.conditioner
|
| 155 |
+
|
| 156 |
+
def on_before_zero_grad(
|
| 157 |
+
self, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler.LRScheduler, iteration: int
|
| 158 |
+
) -> None:
|
| 159 |
+
"""
|
| 160 |
+
update the model_ema
|
| 161 |
+
"""
|
| 162 |
+
if self.config.ema.enabled:
|
| 163 |
+
self.model_ema.update_average(self.model, iteration)
|
| 164 |
+
|
| 165 |
+
def on_train_start(self, memory_format: torch.memory_format = torch.preserve_format) -> None:
|
| 166 |
+
if self.config.ema.enabled:
|
| 167 |
+
self.model_ema.to(dtype=torch.float32)
|
| 168 |
+
if hasattr(self.vae, "reset_dtype"):
|
| 169 |
+
self.vae.reset_dtype()
|
| 170 |
+
if self.intensity_vae is not None and hasattr(
|
| 171 |
+
self.intensity_vae, "reset_dtype"
|
| 172 |
+
):
|
| 173 |
+
self.intensity_vae.reset_dtype()
|
| 174 |
+
self.model = self.model.to(memory_format=memory_format, **self.tensor_kwargs)
|
| 175 |
+
|
| 176 |
+
if hasattr(self.config, "use_torch_compile") and self.config.use_torch_compile: # compatible with old config
|
| 177 |
+
if torch.__version__ < "2.3":
|
| 178 |
+
log.warning(
|
| 179 |
+
"torch.compile in Pytorch version older than 2.3 doesn't work well with activation checkpointing.\n"
|
| 180 |
+
"It's very likely there will be no significant speedup from torch.compile.\n"
|
| 181 |
+
"Please use at least 24.04 Pytorch container."
|
| 182 |
+
)
|
| 183 |
+
# Increasing cache size. It's required because of the model size and dynamic input shapes resulting in
|
| 184 |
+
# multiple different triton kernels. For 28 TransformerBlocks, the cache limit of 256 should be enough for
|
| 185 |
+
# up to 9 different input shapes, as 28*9 < 256. If you have more Blocks or input shapes, and you observe
|
| 186 |
+
# graph breaks at each Block (detectable with torch._dynamo.explain) or warnings about
|
| 187 |
+
# exceeding cache limit, you may want to increase this size.
|
| 188 |
+
# Starting with 24.05 Pytorch container, the default value is 256 anyway.
|
| 189 |
+
# You can read more about it in the comments in Pytorch source code under path torch/_dynamo/cache_size.py.
|
| 190 |
+
torch._dynamo.config.accumulated_cache_size_limit = 256
|
| 191 |
+
# dynamic=False means that a separate kernel is created for each shape. It incurs higher compilation costs
|
| 192 |
+
# at initial iterations, but can result in more specialized and efficient kernels.
|
| 193 |
+
# dynamic=True currently throws errors in pytorch 2.3.
|
| 194 |
+
self.model.net = torch.compile(self.model.net, dynamic=False, disable=not self.config.use_torch_compile)
|
| 195 |
+
|
| 196 |
+
def compute_loss_with_epsilon_and_sigma(
|
| 197 |
+
self,
|
| 198 |
+
data_batch: dict[str, torch.Tensor],
|
| 199 |
+
x0_from_data_batch: torch.Tensor,
|
| 200 |
+
x0: torch.Tensor,
|
| 201 |
+
condition: CosmosCondition,
|
| 202 |
+
epsilon: torch.Tensor,
|
| 203 |
+
sigma: torch.Tensor,
|
| 204 |
+
):
|
| 205 |
+
"""
|
| 206 |
+
Compute loss givee epsilon and sigma
|
| 207 |
+
|
| 208 |
+
This method is responsible for computing loss give epsilon and sigma. It involves:
|
| 209 |
+
1. Adding noise to the input data using the SDE process.
|
| 210 |
+
2. Passing the noisy data through the network to generate predictions.
|
| 211 |
+
3. Computing the loss based on the difference between the predictions and the original data, \
|
| 212 |
+
considering any configured loss weighting.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
data_batch (dict): raw data batch draw from the training data loader.
|
| 216 |
+
x0_from_data_batch: raw image/video
|
| 217 |
+
x0: image/video latent
|
| 218 |
+
condition: text condition
|
| 219 |
+
epsilon: noise
|
| 220 |
+
sigma: noise level
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
tuple: A tuple containing four elements:
|
| 224 |
+
- dict: additional data that used to debug / logging / callbacks
|
| 225 |
+
- Tensor 1: kendall loss,
|
| 226 |
+
- Tensor 2: MSE loss,
|
| 227 |
+
- Tensor 3: EDM loss
|
| 228 |
+
|
| 229 |
+
Raises:
|
| 230 |
+
AssertionError: If the class is conditional, \
|
| 231 |
+
but no number of classes is specified in the network configuration.
|
| 232 |
+
|
| 233 |
+
Notes:
|
| 234 |
+
- The method handles different types of conditioning
|
| 235 |
+
- The method also supports Kendall's loss
|
| 236 |
+
"""
|
| 237 |
+
# Get the mean and stand deviation of the marginal probability distribution.
|
| 238 |
+
mean, std = self.sde.marginal_prob(x0, sigma)
|
| 239 |
+
# Generate noisy observations
|
| 240 |
+
xt = mean + batch_mul(std, epsilon) # corrupted data
|
| 241 |
+
# make prediction
|
| 242 |
+
model_pred = self.denoise(xt, sigma, condition)
|
| 243 |
+
# loss weights for different noise levels
|
| 244 |
+
weights_per_sigma = self.get_per_sigma_loss_weights(sigma=sigma)
|
| 245 |
+
# extra weight for each sample, for example, aesthetic weight, camera weight
|
| 246 |
+
weights_per_sample = self.get_per_sample_weight(data_batch, x0_from_data_batch.shape[0])
|
| 247 |
+
# extra loss mask for each sample, for example, human faces, hands
|
| 248 |
+
loss_mask_per_sample = self.get_per_sample_loss_mask(data_batch, x0_from_data_batch.shape, x0.shape)
|
| 249 |
+
pred_mse = (x0 - model_pred.x0) ** 2 * loss_mask_per_sample
|
| 250 |
+
edm_loss = batch_mul(pred_mse, weights_per_sigma * weights_per_sample)
|
| 251 |
+
if self.config.loss_add_logvar:
|
| 252 |
+
kendall_loss = batch_mul(edm_loss, torch.exp(-model_pred.logvar).view(-1)).flatten(
|
| 253 |
+
start_dim=1
|
| 254 |
+
) + model_pred.logvar.view(-1, 1)
|
| 255 |
+
else:
|
| 256 |
+
kendall_loss = edm_loss.flatten(start_dim=1)
|
| 257 |
+
output_batch = {
|
| 258 |
+
"x0": x0,
|
| 259 |
+
"xt": xt,
|
| 260 |
+
"sigma": sigma,
|
| 261 |
+
"weights_per_sigma": weights_per_sigma,
|
| 262 |
+
"weights_per_sample": weights_per_sample,
|
| 263 |
+
"loss_mask_per_sample": loss_mask_per_sample,
|
| 264 |
+
"condition": condition,
|
| 265 |
+
"model_pred": model_pred,
|
| 266 |
+
"mse_loss": pred_mse.mean(),
|
| 267 |
+
"edm_loss": edm_loss.mean(),
|
| 268 |
+
}
|
| 269 |
+
return output_batch, kendall_loss, pred_mse, edm_loss
|
| 270 |
+
|
| 271 |
+
def training_step(
|
| 272 |
+
self, data_batch: dict[str, torch.Tensor], iteration: int
|
| 273 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor]:
|
| 274 |
+
"""
|
| 275 |
+
Performs a single training step for the diffusion model.
|
| 276 |
+
|
| 277 |
+
This method is responsible for executing one iteration of the model's training. It involves:
|
| 278 |
+
1. Adding noise to the input data using the SDE process.
|
| 279 |
+
2. Passing the noisy data through the network to generate predictions.
|
| 280 |
+
3. Computing the loss based on the difference between the predictions and the original data, \
|
| 281 |
+
considering any configured loss weighting.
|
| 282 |
+
|
| 283 |
+
Args:
|
| 284 |
+
data_batch (dict): raw data batch draw from the training data loader.
|
| 285 |
+
iteration (int): Current iteration number.
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
tuple: A tuple containing two elements:
|
| 289 |
+
- dict: additional data that used to debug / logging / callbacks
|
| 290 |
+
- Tensor: The computed loss for the training step as a PyTorch Tensor.
|
| 291 |
+
|
| 292 |
+
Raises:
|
| 293 |
+
AssertionError: If the class is conditional, \
|
| 294 |
+
but no number of classes is specified in the network configuration.
|
| 295 |
+
|
| 296 |
+
Notes:
|
| 297 |
+
- The method handles different types of conditioning
|
| 298 |
+
- The method also supports Kendall's loss
|
| 299 |
+
"""
|
| 300 |
+
# Get the input data to noise and denoise~(image, video) and the corresponding conditioner.
|
| 301 |
+
x0_from_data_batch, x0, condition = self.get_data_and_condition(data_batch)
|
| 302 |
+
|
| 303 |
+
# Sample pertubation noise levels and N(0, 1) noises
|
| 304 |
+
sigma, epsilon = self.draw_training_sigma_and_epsilon(x0.size(), condition)
|
| 305 |
+
|
| 306 |
+
output_batch, kendall_loss, pred_mse, edm_loss = self.compute_loss_with_epsilon_and_sigma(
|
| 307 |
+
data_batch, x0_from_data_batch, x0, condition, epsilon, sigma
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
if self.loss_reduce == "mean":
|
| 311 |
+
kendall_loss = kendall_loss.mean() * self.loss_scale
|
| 312 |
+
elif self.loss_reduce == "sum":
|
| 313 |
+
kendall_loss = kendall_loss.sum(dim=1).mean() * self.loss_scale
|
| 314 |
+
else:
|
| 315 |
+
raise ValueError(f"Invalid loss_reduce: {self.loss_reduce}")
|
| 316 |
+
|
| 317 |
+
return output_batch, kendall_loss
|
| 318 |
+
|
| 319 |
+
def denoise(self, xt: torch.Tensor, sigma: torch.Tensor, condition: CosmosCondition) -> DenoisePrediction:
|
| 320 |
+
"""
|
| 321 |
+
Performs denoising on the input noise data, noise level, and condition
|
| 322 |
+
|
| 323 |
+
Args:
|
| 324 |
+
xt (torch.Tensor): The input noise data.
|
| 325 |
+
sigma (torch.Tensor): The noise level.
|
| 326 |
+
condition (CosmosCondition): conditional information, generated from self.conditioner
|
| 327 |
+
|
| 328 |
+
Returns:
|
| 329 |
+
DenoisePrediction: The denoised prediction, it includes clean data predicton (x0), \
|
| 330 |
+
noise prediction (eps_pred) and optional confidence (logvar).
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
if getattr(self.config, "use_dummy_temporal_dim", False):
|
| 334 |
+
# When using video DiT model for image, we need to use a dummy temporal dimension.
|
| 335 |
+
xt = xt.unsqueeze(2)
|
| 336 |
+
|
| 337 |
+
xt = xt.to(**self.tensor_kwargs)
|
| 338 |
+
sigma = sigma.to(**self.tensor_kwargs)
|
| 339 |
+
# get precondition for the network
|
| 340 |
+
c_skip, c_out, c_in, c_noise = self.scaling(sigma=sigma)
|
| 341 |
+
|
| 342 |
+
# forward pass through the network
|
| 343 |
+
net_output = self.net(
|
| 344 |
+
x=batch_mul(c_in, xt), # Eq. 7 of https://arxiv.org/pdf/2206.00364.pdf
|
| 345 |
+
timesteps=c_noise, # Eq. 7 of https://arxiv.org/pdf/2206.00364.pdf
|
| 346 |
+
**condition.to_dict(),
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
logvar = self.model.logvar(c_noise)
|
| 350 |
+
x0_pred = batch_mul(c_skip, xt) + batch_mul(c_out, net_output)
|
| 351 |
+
|
| 352 |
+
# get noise prediction based on sde
|
| 353 |
+
eps_pred = batch_mul(xt - x0_pred, 1.0 / sigma)
|
| 354 |
+
|
| 355 |
+
if getattr(self.config, "use_dummy_temporal_dim", False):
|
| 356 |
+
x0_pred = x0_pred.squeeze(2)
|
| 357 |
+
eps_pred = eps_pred.squeeze(2)
|
| 358 |
+
|
| 359 |
+
return DenoisePrediction(x0_pred, eps_pred, logvar)
|
| 360 |
+
|
| 361 |
+
@torch.no_grad()
|
| 362 |
+
def encode(self, state: torch.Tensor) -> torch.Tensor:
|
| 363 |
+
assert state.shape[2] == 1, "Lidar should have 1 frame"
|
| 364 |
+
return self.vae.encode(state.squeeze(2)).unsqueeze(2) * self.sigma_data
|
| 365 |
+
|
| 366 |
+
@torch.no_grad()
|
| 367 |
+
def decode(self, latent: torch.Tensor) -> torch.Tensor:
|
| 368 |
+
assert latent.shape[2] == 1, "Lidar should have 1 frame"
|
| 369 |
+
return self.vae.decode(latent.squeeze(2) / self.sigma_data).unsqueeze(2)
|
| 370 |
+
|
| 371 |
+
def draw_training_sigma_and_epsilon(self, x0_size: int, condition: Any) -> torch.Tensor:
|
| 372 |
+
del condition
|
| 373 |
+
batch_size = x0_size[0]
|
| 374 |
+
epsilon = torch.randn(x0_size, **self.tensor_kwargs)
|
| 375 |
+
return self.sde.sample_t(batch_size).to(**self.tensor_kwargs), epsilon
|
| 376 |
+
|
| 377 |
+
def get_data_and_condition(self, data_batch: dict[str, torch.Tensor]) -> Tuple[torch.Tensor, CosmosCondition]:
|
| 378 |
+
"""
|
| 379 |
+
processing data batch draw from data loader and return data and condition that used for denoising task
|
| 380 |
+
|
| 381 |
+
Returns:
|
| 382 |
+
raw_state (tensor): the image / video data that feed to vae
|
| 383 |
+
latent_state (tensor): nosie-free state, the vae latent state
|
| 384 |
+
condition (CosmosCondition): condition information for conditional generation. Generated from conditioner
|
| 385 |
+
"""
|
| 386 |
+
raw_state = data_batch[self.input_data_key]
|
| 387 |
+
latent_state = self.encode(raw_state)
|
| 388 |
+
condition = self.conditioner(data_batch)
|
| 389 |
+
return raw_state, latent_state, condition
|
| 390 |
+
|
| 391 |
+
def get_per_sample_weight(self, data_batch: dict[str, torch.Tensor], batch_size: int):
|
| 392 |
+
r"""
|
| 393 |
+
extra weight for each sample, for example, aesthetic weight
|
| 394 |
+
Args:
|
| 395 |
+
data_batch: raw data batch draw from the training data loader.
|
| 396 |
+
batch_size: int, the batch size of the input data
|
| 397 |
+
"""
|
| 398 |
+
aesthetic_cfg = getattr(self.config, "aesthetic_finetuning", None)
|
| 399 |
+
if (aesthetic_cfg is not None) and getattr(aesthetic_cfg, "enabled", False):
|
| 400 |
+
sample_weight = data_batch["aesthetic_weight"]
|
| 401 |
+
else:
|
| 402 |
+
sample_weight = torch.ones(batch_size, **self.tensor_kwargs)
|
| 403 |
+
|
| 404 |
+
camera_cfg = getattr(self.config, "camera_sample_weight", None)
|
| 405 |
+
if (camera_cfg is not None) and getattr(camera_cfg, "enabled", False):
|
| 406 |
+
sample_weight *= 1 + (data_batch["camera_attributes"][:, 1:].sum(dim=1) != 0) * (camera_cfg.weight - 1)
|
| 407 |
+
return sample_weight
|
| 408 |
+
|
| 409 |
+
def get_per_sample_loss_mask(self, data_batch, raw_x_shape, latent_x_shape):
|
| 410 |
+
"""
|
| 411 |
+
extra loss mask for each sample, for example, human faces, hands.
|
| 412 |
+
|
| 413 |
+
Args:
|
| 414 |
+
data_batch (dict): raw data batch draw from the training data loader.
|
| 415 |
+
raw_x_shape (tuple): shape of the input data. We need the raw_x_shape for necessary resize operation.
|
| 416 |
+
latent_x_shape (tuple): shape of the latent data
|
| 417 |
+
"""
|
| 418 |
+
if self.config.loss_mask_enabled:
|
| 419 |
+
raw_x_shape = [raw_x_shape[0], 1, *raw_x_shape[2:]]
|
| 420 |
+
weights = create_per_sample_loss_mask(
|
| 421 |
+
self.loss_masking, data_batch, raw_x_shape, torch.get_default_dtype(), "cuda"
|
| 422 |
+
)
|
| 423 |
+
return F.interpolate(weights, size=latent_x_shape[2:], mode="bilinear")
|
| 424 |
+
|
| 425 |
+
return 1.0
|
| 426 |
+
|
| 427 |
+
def get_per_sigma_loss_weights(self, sigma: torch.Tensor):
|
| 428 |
+
"""
|
| 429 |
+
Args:
|
| 430 |
+
sigma (tensor): noise level
|
| 431 |
+
|
| 432 |
+
Returns:
|
| 433 |
+
loss weights per sigma noise level
|
| 434 |
+
"""
|
| 435 |
+
return (sigma**2 + self.sigma_data**2) / (sigma * self.sigma_data) ** 2
|
| 436 |
+
|
| 437 |
+
def generate_samples(self, batch_size: int, condition: CosmosCondition) -> torch.Tensor:
|
| 438 |
+
"""
|
| 439 |
+
Generate samples with given condition. It is WITHOUT classifier-free-guidance.
|
| 440 |
+
|
| 441 |
+
Args:
|
| 442 |
+
batch_size (int):
|
| 443 |
+
condition (CosmosCondition): condition information generated from self.conditioner
|
| 444 |
+
"""
|
| 445 |
+
x_sigma_max = torch.randn(batch_size, *self.state_shape, **self.tensor_kwargs) * self.sde.sigma_max
|
| 446 |
+
|
| 447 |
+
def x0_fn(x, t):
|
| 448 |
+
return self.denoise(x, t, condition).x0 # ODE function
|
| 449 |
+
|
| 450 |
+
return self.sampler(x0_fn, x_sigma_max, sigma_max=self.sde.sigma_max)
|
| 451 |
+
|
| 452 |
+
def generate_cfg_samples(
|
| 453 |
+
self, batch_size: int, condition: CosmosCondition, uncondition: CosmosCondition, guidance=1.5
|
| 454 |
+
) -> torch.Tensor:
|
| 455 |
+
"""
|
| 456 |
+
Generate samples with with classifier-free-guidance.
|
| 457 |
+
|
| 458 |
+
Args:
|
| 459 |
+
batch_size (int):
|
| 460 |
+
condition (CosmosCondition): condition information generated from self.conditioner
|
| 461 |
+
uncondition (CosmosCondition): uncondition information, possibily generated from self.conditioner
|
| 462 |
+
"""
|
| 463 |
+
x_sigma_max = torch.randn(batch_size, *self.state_shape, **self.tensor_kwargs) * self.sde.sigma_max
|
| 464 |
+
|
| 465 |
+
def x0_fn(x, t):
|
| 466 |
+
cond_x0 = self.denoise(x, t, condition).x0
|
| 467 |
+
uncond_x0 = self.denoise(x, t, uncondition).x0
|
| 468 |
+
return cond_x0 + guidance * (cond_x0 - uncond_x0)
|
| 469 |
+
|
| 470 |
+
return self.sampler(x0_fn, x_sigma_max, sigma_max=self.sde.sigma_max)
|
| 471 |
+
|
| 472 |
+
def get_x0_fn_from_batch(
|
| 473 |
+
self,
|
| 474 |
+
data_batch: Dict,
|
| 475 |
+
guidance: float = 1.5,
|
| 476 |
+
is_negative_prompt: bool = False,
|
| 477 |
+
) -> Callable:
|
| 478 |
+
"""
|
| 479 |
+
Generates a callable function `x0_fn` based on the provided data batch and guidance factor.
|
| 480 |
+
|
| 481 |
+
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.
|
| 482 |
+
|
| 483 |
+
Args:
|
| 484 |
+
- 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`
|
| 485 |
+
- 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.
|
| 486 |
+
- is_negative_prompt (bool): use negative prompt t5 in uncondition if true
|
| 487 |
+
|
| 488 |
+
Returns:
|
| 489 |
+
- Callable: A function `x0_fn(noise_x, sigma)` that takes two arguments, `noise_x` and `sigma`, and return x0 predictoin
|
| 490 |
+
|
| 491 |
+
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.
|
| 492 |
+
"""
|
| 493 |
+
if is_negative_prompt:
|
| 494 |
+
condition, uncondition = self.conditioner.get_condition_with_negative_prompt(data_batch)
|
| 495 |
+
else:
|
| 496 |
+
condition, uncondition = self.conditioner.get_condition_uncondition(data_batch)
|
| 497 |
+
|
| 498 |
+
def x0_fn(noise_x: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
|
| 499 |
+
cond_x0 = self.denoise(noise_x, sigma, condition).x0
|
| 500 |
+
uncond_x0 = self.denoise(noise_x, sigma, uncondition).x0
|
| 501 |
+
return cond_x0 + guidance * (cond_x0 - uncond_x0)
|
| 502 |
+
|
| 503 |
+
return x0_fn
|
| 504 |
+
|
| 505 |
+
def generate_samples_from_batch(
|
| 506 |
+
self,
|
| 507 |
+
data_batch: Dict,
|
| 508 |
+
guidance: float = 1.5,
|
| 509 |
+
seed: int = 1,
|
| 510 |
+
state_shape: Optional[Tuple] = None,
|
| 511 |
+
n_sample: Optional[int] = None,
|
| 512 |
+
is_negative_prompt: bool = False,
|
| 513 |
+
num_steps: int = 35,
|
| 514 |
+
solver_option: COMMON_SOLVER_OPTIONS = "2ab",
|
| 515 |
+
) -> torch.Tensor:
|
| 516 |
+
"""
|
| 517 |
+
Args:
|
| 518 |
+
data_batch (dict): raw data batch draw from the training data loader.
|
| 519 |
+
iteration (int): Current iteration number.
|
| 520 |
+
guidance (float): guidance weights
|
| 521 |
+
seed (int): random seed
|
| 522 |
+
state_shape (tuple): shape of the state, default to self.state_shape if not provided
|
| 523 |
+
n_sample (int): number of samples to generate
|
| 524 |
+
is_negative_prompt (bool): use negative prompt t5 in uncondition if true
|
| 525 |
+
num_steps (int): number of steps for the diffusion process
|
| 526 |
+
solver_option (str): differential equation solver option, default to "2ab"~(mulitstep solver)
|
| 527 |
+
"""
|
| 528 |
+
x0_fn = self.get_x0_fn_from_batch(data_batch, guidance, is_negative_prompt=is_negative_prompt)
|
| 529 |
+
batch_size = n_sample or data_batch[self.input_data_key].shape[0]
|
| 530 |
+
state_shape = state_shape or self.state_shape
|
| 531 |
+
x_sigma_max = (
|
| 532 |
+
misc.arch_invariant_rand(
|
| 533 |
+
(batch_size,) + tuple(state_shape),
|
| 534 |
+
torch.float32,
|
| 535 |
+
self.tensor_kwargs["device"],
|
| 536 |
+
seed,
|
| 537 |
+
)
|
| 538 |
+
* self.sde.sigma_max
|
| 539 |
+
)
|
| 540 |
+
return self.sampler(
|
| 541 |
+
x0_fn, x_sigma_max, sigma_max=self.sde.sigma_max, num_steps=num_steps, solver_option=solver_option
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
@torch.no_grad()
|
| 545 |
+
def validation_step(
|
| 546 |
+
self, data: dict[str, torch.Tensor], iteration: int
|
| 547 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor]:
|
| 548 |
+
"""
|
| 549 |
+
Current code does nothing.
|
| 550 |
+
"""
|
| 551 |
+
return {}, torch.tensor(0).to(**self.tensor_kwargs)
|
| 552 |
+
|
| 553 |
+
@torch.no_grad()
|
| 554 |
+
def forward(self, xt, t, condition: CosmosCondition):
|
| 555 |
+
"""
|
| 556 |
+
Performs denoising on the input noise data, noise level, and condition
|
| 557 |
+
|
| 558 |
+
Args:
|
| 559 |
+
xt (torch.Tensor): The input noise data.
|
| 560 |
+
sigma (torch.Tensor): The noise level.
|
| 561 |
+
condition (CosmosCondition): conditional information, generated from self.conditioner
|
| 562 |
+
|
| 563 |
+
Returns:
|
| 564 |
+
DenoisePrediction: The denoised prediction, it includes clean data predicton (x0), \
|
| 565 |
+
noise prediction (eps_pred) and optional confidence (logvar).
|
| 566 |
+
"""
|
| 567 |
+
return self.denoise(xt, t, condition)
|
| 568 |
+
|
| 569 |
+
def init_optimizer_scheduler(
|
| 570 |
+
self, optimizer_config: LazyDict, scheduler_config: LazyDict
|
| 571 |
+
) -> tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler]:
|
| 572 |
+
"""Creates the optimizer and scheduler for the model.
|
| 573 |
+
|
| 574 |
+
Args:
|
| 575 |
+
config_model (ModelConfig): The config object for the model.
|
| 576 |
+
|
| 577 |
+
Returns:
|
| 578 |
+
optimizer (torch.optim.Optimizer): The model optimizer.
|
| 579 |
+
scheduler (torch.optim.lr_scheduler.LRScheduler): The optimization scheduler.
|
| 580 |
+
"""
|
| 581 |
+
optimizer = lazy_instantiate(optimizer_config, model=self.model)
|
| 582 |
+
scheduler = get_base_scheduler(optimizer, self, scheduler_config)
|
| 583 |
+
return optimizer, scheduler
|
| 584 |
+
|
| 585 |
+
def state_dict(self) -> Dict[str, Any]:
|
| 586 |
+
"""
|
| 587 |
+
Returns the current state of the model as a dictionary.
|
| 588 |
+
|
| 589 |
+
Returns:
|
| 590 |
+
Dict: The current state of the model as a dictionary.
|
| 591 |
+
"""
|
| 592 |
+
return {
|
| 593 |
+
"model": self.model.state_dict(),
|
| 594 |
+
"ema": self.model_ema.state_dict() if self.config.ema.enabled else None,
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False):
|
| 598 |
+
"""
|
| 599 |
+
Loads a state dictionary into the model and optionally its EMA counterpart.
|
| 600 |
+
Different from torch strict=False mode, the method will not raise error for unmatched state shape while raise warning.
|
| 601 |
+
|
| 602 |
+
Parameters:
|
| 603 |
+
state_dict (Mapping[str, Any]): A dictionary containing separate state dictionaries for the model and
|
| 604 |
+
potentially for an EMA version of the model under the keys 'model' and 'ema', respectively.
|
| 605 |
+
strict (bool, optional): If True, the method will enforce that the keys in the state dict match exactly
|
| 606 |
+
those in the model and EMA model (if applicable). Defaults to True.
|
| 607 |
+
assign (bool, optional): If True and in strict mode, will assign the state dictionary directly rather than
|
| 608 |
+
matching keys one-by-one. This is typically used when loading parts of state dicts
|
| 609 |
+
or using customized loading procedures. Defaults to False.
|
| 610 |
+
"""
|
| 611 |
+
if strict:
|
| 612 |
+
# the converted tpsp checkpoint has "ema" and it is None
|
| 613 |
+
if self.config.ema.enabled and state_dict["ema"] is not None:
|
| 614 |
+
ema_results: _IncompatibleKeys = self.model_ema.load_state_dict(
|
| 615 |
+
state_dict["ema"], strict=strict, assign=assign
|
| 616 |
+
)
|
| 617 |
+
reg_results: _IncompatibleKeys = self.model.load_state_dict(
|
| 618 |
+
state_dict["model"], strict=strict, assign=assign
|
| 619 |
+
)
|
| 620 |
+
if self.config.ema.enabled and state_dict["ema"] is not None:
|
| 621 |
+
return _IncompatibleKeys(
|
| 622 |
+
ema_results.missing_keys + reg_results.missing_keys,
|
| 623 |
+
ema_results.unexpected_keys + reg_results.unexpected_keys,
|
| 624 |
+
)
|
| 625 |
+
return reg_results
|
| 626 |
+
else:
|
| 627 |
+
from diffusion.training.utils.checkpointer import non_strict_load_model
|
| 628 |
+
|
| 629 |
+
log.critical("load model in non-strict mode")
|
| 630 |
+
if "model" in state_dict:
|
| 631 |
+
log.critical(non_strict_load_model(self.model, state_dict["model"]), rank0_only=False)
|
| 632 |
+
else:
|
| 633 |
+
log.critical(non_strict_load_model(self.model, state_dict), rank0_only=False)
|
| 634 |
+
if self.config.ema.enabled and "ema" in state_dict and state_dict["ema"] is not None:
|
| 635 |
+
log.critical("load ema model in non-strict mode")
|
| 636 |
+
log.critical(non_strict_load_model(self.model_ema, state_dict["ema"]), rank0_only=False)
|
| 637 |
+
|
| 638 |
+
def get_ckpt_postfix(self) -> Tuple[str, int, int]:
|
| 639 |
+
"""Get the checkpoint file postfix.
|
| 640 |
+
|
| 641 |
+
Args:
|
| 642 |
+
iteration (int): The current iteration number.
|
| 643 |
+
|
| 644 |
+
Returns:
|
| 645 |
+
postfix (str): The postfix of the checkpoint file.
|
| 646 |
+
rank_to_save ema (int), we will not save each ema model in each rank, \
|
| 647 |
+
ema model with same rate will be saved once
|
| 648 |
+
total_ema_num (int)
|
| 649 |
+
"""
|
| 650 |
+
total_ema_num = min(self.config.ema.num, distributed.get_world_size())
|
| 651 |
+
rank = distributed.get_rank()
|
| 652 |
+
if rank == 0:
|
| 653 |
+
return "", 0, total_ema_num
|
| 654 |
+
if self.config.ema.enabled:
|
| 655 |
+
if rank < self.config.ema.num:
|
| 656 |
+
return f"_RANK{rank}", rank, total_ema_num
|
| 657 |
+
return "", 0, total_ema_num # use rank 0 to save the checkpoint
|
| 658 |
+
|
| 659 |
+
@contextmanager
|
| 660 |
+
def ema_scope(self, context=None, is_cpu=False):
|
| 661 |
+
if self.config.ema.enabled:
|
| 662 |
+
self.model_ema.cache(self.model.parameters(), is_cpu=is_cpu)
|
| 663 |
+
self.model_ema.copy_to(self.model)
|
| 664 |
+
if context is not None:
|
| 665 |
+
log.info(f"{context}: Switched to EMA weights")
|
| 666 |
+
try:
|
| 667 |
+
yield None
|
| 668 |
+
finally:
|
| 669 |
+
if self.config.ema.enabled:
|
| 670 |
+
self.model_ema.restore(self.model.parameters())
|
| 671 |
+
if context is not None:
|
| 672 |
+
log.info(f"{context}: Restored training weights")
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
T = TypeVar("T", bound=DiffusionModel)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def diffusion_fsdp_class_decorator(base_class: Type[T]) -> Type[T]:
|
| 679 |
+
"""
|
| 680 |
+
Decorator for the FSDP class for the diffusion model, which handles the FSDP specific logic for the diffusion model.
|
| 681 |
+
"""
|
| 682 |
+
|
| 683 |
+
class FSDPClass(base_class):
|
| 684 |
+
"""
|
| 685 |
+
Handle FSDP specific logic for the diffusion model. Including:
|
| 686 |
+
- FSDP model initialization
|
| 687 |
+
- FSDP model / optimizer save and loading
|
| 688 |
+
- Different from the original DiffusionModel, the impl of multi-rank EMA is a bit hacky. \
|
| 689 |
+
We need to make sure sharded model weights for EMA and regular model are the same.
|
| 690 |
+
"""
|
| 691 |
+
|
| 692 |
+
def __init__(self, config, fsdp_checkpointer: Any):
|
| 693 |
+
self.fsdp_checkpointer = fsdp_checkpointer
|
| 694 |
+
super().__init__(config)
|
| 695 |
+
|
| 696 |
+
def set_up_model(self):
|
| 697 |
+
config = self.config
|
| 698 |
+
|
| 699 |
+
# 1. build FSDP sharding strategy and device_mesh
|
| 700 |
+
strategy = {
|
| 701 |
+
"full": ShardingStrategy.FULL_SHARD,
|
| 702 |
+
"hybrid": ShardingStrategy.HYBRID_SHARD,
|
| 703 |
+
}[config.fsdp.sharding_strategy]
|
| 704 |
+
log.critical(f"Using {strategy} sharding strategy for FSDP")
|
| 705 |
+
|
| 706 |
+
if config.fsdp.sharding_strategy == "hybrid":
|
| 707 |
+
sharding_group_size = getattr(config.fsdp, "sharding_group_size", 8)
|
| 708 |
+
device_mesh = hsdp_device_mesh(
|
| 709 |
+
sharding_group_size=sharding_group_size,
|
| 710 |
+
)
|
| 711 |
+
shard_group = device_mesh.get_group(mesh_dim="shard")
|
| 712 |
+
replicate_group = device_mesh.get_group(mesh_dim="replicate")
|
| 713 |
+
fsdp_process_group = (shard_group, replicate_group)
|
| 714 |
+
else:
|
| 715 |
+
device_mesh = hsdp_device_mesh(
|
| 716 |
+
sharding_group_size=distributed.get_world_size(),
|
| 717 |
+
)
|
| 718 |
+
shard_group = device_mesh.get_group(mesh_dim="shard")
|
| 719 |
+
fsdp_process_group = shard_group
|
| 720 |
+
|
| 721 |
+
# We piggyback the `device_mesh` to megatron-core's `parallel_state` for global access.
|
| 722 |
+
# This is not megatron-core's original API.
|
| 723 |
+
parallel_state.fsdp_device_mesh = device_mesh
|
| 724 |
+
|
| 725 |
+
def get_wrap_policy(_model):
|
| 726 |
+
if not hasattr(_model.net, "fsdp_wrap_block_cls"):
|
| 727 |
+
raise ValueError(
|
| 728 |
+
"Networks does not have fsdp_wrap_block_cls attribute, please check the net definition"
|
| 729 |
+
)
|
| 730 |
+
fsdp_blocks_cls = _model.net.fsdp_wrap_block_cls
|
| 731 |
+
fsdp_blocks_cls = (
|
| 732 |
+
list(fsdp_blocks_cls) if isinstance(fsdp_blocks_cls, (list, tuple, set)) else [fsdp_blocks_cls]
|
| 733 |
+
)
|
| 734 |
+
log.critical(f"Using FSDP blocks {fsdp_blocks_cls}")
|
| 735 |
+
|
| 736 |
+
log.critical(f"Using wrap policy {config.fsdp.policy}")
|
| 737 |
+
if config.fsdp.policy == "size":
|
| 738 |
+
min_num_params = getattr(config.fsdp, "min_num_params", 100)
|
| 739 |
+
log.critical(f"Using {min_num_params} as the minimum number of parameters for auto-wrap policy")
|
| 740 |
+
wrap_policy = functools.partial(size_based_auto_wrap_policy, min_num_params=min_num_params)
|
| 741 |
+
else:
|
| 742 |
+
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
|
| 743 |
+
|
| 744 |
+
wrap_policy = functools.partial(
|
| 745 |
+
transformer_auto_wrap_policy,
|
| 746 |
+
transformer_layer_cls=set(fsdp_blocks_cls),
|
| 747 |
+
)
|
| 748 |
+
return wrap_policy
|
| 749 |
+
|
| 750 |
+
# 2. build naive pytorch model and load weights if exists
|
| 751 |
+
replica_idx, shard_idx = device_mesh.get_coordinate()
|
| 752 |
+
# 2.1 handle ema case first, since float32 is more expensive
|
| 753 |
+
if config.ema.enabled:
|
| 754 |
+
with misc.timer("Creating PyTorch model and loading weights for ema"):
|
| 755 |
+
model_ema = self.build_model().float()
|
| 756 |
+
model_ema.cuda().eval().requires_grad_(False)
|
| 757 |
+
load_error = None
|
| 758 |
+
if distributed.get_rank() == 0:
|
| 759 |
+
# only load model in rank0 to reduce network traffic
|
| 760 |
+
try:
|
| 761 |
+
self.fsdp_checkpointer.load_model_during_init(
|
| 762 |
+
model_ema, is_ema=True
|
| 763 |
+
)
|
| 764 |
+
except Exception as exc: # noqa: BLE001
|
| 765 |
+
load_error = repr(exc)
|
| 766 |
+
load_errors = [load_error]
|
| 767 |
+
torch.distributed.broadcast_object_list(
|
| 768 |
+
load_errors, src=0
|
| 769 |
+
)
|
| 770 |
+
if load_errors[0] is not None:
|
| 771 |
+
raise RuntimeError(
|
| 772 |
+
"EMA model initialization failed on rank 0: "
|
| 773 |
+
f"{load_errors[0]}"
|
| 774 |
+
)
|
| 775 |
+
# sync ema model weights from rank0
|
| 776 |
+
with misc.timer("Sync model states for EMA model"):
|
| 777 |
+
#! this is IMPORTANT, see the following comment about regular model for details
|
| 778 |
+
#! we broadcast the ema model first, since it is fp32 and costs more memory
|
| 779 |
+
distributed.sync_model_states(model_ema, device_mesh.get_group(mesh_dim="shard"))
|
| 780 |
+
torch.cuda.empty_cache()
|
| 781 |
+
distributed.sync_model_states(model_ema, device_mesh.get_group(mesh_dim="replicate"))
|
| 782 |
+
torch.cuda.empty_cache()
|
| 783 |
+
# for ema model with dfiferent rate, we download the model when necessary
|
| 784 |
+
replica_load_error = None
|
| 785 |
+
if shard_idx == 0 and replica_idx > 0 and replica_idx < config.ema.num:
|
| 786 |
+
print("loading ema model in rank", replica_idx)
|
| 787 |
+
try:
|
| 788 |
+
self.fsdp_checkpointer.load_model_during_init(
|
| 789 |
+
model_ema,
|
| 790 |
+
is_ema=True,
|
| 791 |
+
ema_id=replica_idx,
|
| 792 |
+
)
|
| 793 |
+
print(
|
| 794 |
+
"finish loading ema model in rank",
|
| 795 |
+
replica_idx,
|
| 796 |
+
)
|
| 797 |
+
except Exception as exc: # noqa: BLE001
|
| 798 |
+
replica_load_error = repr(exc)
|
| 799 |
+
replica_errors = [None] * distributed.get_world_size()
|
| 800 |
+
torch.distributed.all_gather_object(
|
| 801 |
+
replica_errors, replica_load_error
|
| 802 |
+
)
|
| 803 |
+
replica_failures = [
|
| 804 |
+
item for item in replica_errors if item is not None
|
| 805 |
+
]
|
| 806 |
+
if replica_failures:
|
| 807 |
+
raise RuntimeError(
|
| 808 |
+
"replica EMA initialization failed: "
|
| 809 |
+
f"{replica_failures}"
|
| 810 |
+
)
|
| 811 |
+
# 2.1.2 create FSDP model for ema model
|
| 812 |
+
with misc.timer("Creating FSDP model for EMA model"):
|
| 813 |
+
self.model_ema = FSDP(
|
| 814 |
+
model_ema,
|
| 815 |
+
sync_module_states=True, # it can reduce network traffic by only loading model in rank0 and sync
|
| 816 |
+
process_group=device_mesh.get_group(mesh_dim=1),
|
| 817 |
+
sharding_strategy=ShardingStrategy.FULL_SHARD,
|
| 818 |
+
auto_wrap_policy=get_wrap_policy(model_ema),
|
| 819 |
+
device_id=torch.cuda.current_device(),
|
| 820 |
+
limit_all_gathers=True,
|
| 821 |
+
use_orig_params=bool(
|
| 822 |
+
getattr(config.fsdp, "use_orig_params", False)
|
| 823 |
+
),
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
# extra ema model upate logic to the model
|
| 827 |
+
self.model_ema_worker = FastEmaModelUpdater()
|
| 828 |
+
s = 0.1
|
| 829 |
+
replica_idx, shard_idx = device_mesh.get_coordinate()
|
| 830 |
+
divider = 2**replica_idx if replica_idx < config.ema.num else 1
|
| 831 |
+
if replica_idx < config.ema.num:
|
| 832 |
+
if shard_idx == 0:
|
| 833 |
+
print(f"EMA: rank {replica_idx}, rate {config.ema.rate / divider}")
|
| 834 |
+
s = config.ema.rate / divider
|
| 835 |
+
self.ema_exp_coefficient = np.roots([1, 7, 16 - s**-2, 12 - s**-2]).real.max()
|
| 836 |
+
|
| 837 |
+
torch.cuda.empty_cache()
|
| 838 |
+
|
| 839 |
+
# 2.2 handle regular model
|
| 840 |
+
with misc.timer("Creating PyTorch model and loading weights for regular model"):
|
| 841 |
+
model = self.build_model().cuda().to(**self.tensor_kwargs)
|
| 842 |
+
|
| 843 |
+
load_error = None
|
| 844 |
+
if distributed.get_rank() == 0:
|
| 845 |
+
# only load model in rank0 to reduce network traffic and sync later
|
| 846 |
+
try:
|
| 847 |
+
self.fsdp_checkpointer.load_model_during_init(
|
| 848 |
+
model, is_ema=False
|
| 849 |
+
)
|
| 850 |
+
except Exception as exc: # noqa: BLE001
|
| 851 |
+
load_error = repr(exc)
|
| 852 |
+
load_errors = [load_error]
|
| 853 |
+
torch.distributed.broadcast_object_list(
|
| 854 |
+
load_errors, src=0
|
| 855 |
+
)
|
| 856 |
+
if load_errors[0] is not None:
|
| 857 |
+
raise RuntimeError(
|
| 858 |
+
"regular model initialization failed on rank 0: "
|
| 859 |
+
f"{load_errors[0]}"
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
#! overwrite the forward method so that it will invoke the FSDP-specific pre- and post-forward sharding logic
|
| 863 |
+
model.forward = super().training_step
|
| 864 |
+
#! this is IMPORTANT, though following two lines are identical to sync_module_states=True in FSDP
|
| 865 |
+
#! we do it twice so that following line can warm up and avoid OOM in aws 128+ nodes settings
|
| 866 |
+
#! qsh hypothesize that it is due to overhead of initialization of nccl network communication;
|
| 867 |
+
#! without it, peak mem : reg_model + ema_model + FSDP overhead + nccl communication initialization overhead
|
| 868 |
+
#! with it, peak men: reg_model + ema_model + FSDP overhead
|
| 869 |
+
#! it is tricky, but it works!
|
| 870 |
+
with misc.timer("Sync model states for regular model"):
|
| 871 |
+
distributed.sync_model_states(model, device_mesh.get_group(mesh_dim="shard"))
|
| 872 |
+
torch.cuda.empty_cache()
|
| 873 |
+
distributed.sync_model_states(model, device_mesh.get_group(mesh_dim="replicate"))
|
| 874 |
+
torch.cuda.empty_cache()
|
| 875 |
+
|
| 876 |
+
with misc.timer("Creating FSDP model"):
|
| 877 |
+
self.model = FSDP(
|
| 878 |
+
model.to(**self.tensor_kwargs),
|
| 879 |
+
sync_module_states=True, # it can reduce network traffic by only loading model in rank0 and sync
|
| 880 |
+
sharding_strategy=strategy,
|
| 881 |
+
auto_wrap_policy=get_wrap_policy(model),
|
| 882 |
+
process_group=fsdp_process_group,
|
| 883 |
+
limit_all_gathers=True,
|
| 884 |
+
use_orig_params=bool(
|
| 885 |
+
getattr(config.fsdp, "use_orig_params", False)
|
| 886 |
+
),
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
if self.config.fsdp.checkpoint:
|
| 890 |
+
fsdp_blocks_cls = model.net.fsdp_wrap_block_cls
|
| 891 |
+
fsdp_blocks_cls = (
|
| 892 |
+
list(fsdp_blocks_cls)
|
| 893 |
+
if isinstance(fsdp_blocks_cls, (list, tuple, set))
|
| 894 |
+
else [fsdp_blocks_cls]
|
| 895 |
+
)
|
| 896 |
+
log.critical(f"Applying FSDP checkpointing with FSDP blocks: {fsdp_blocks_cls}")
|
| 897 |
+
apply_fsdp_checkpointing(self.model, list_block_cls=fsdp_blocks_cls)
|
| 898 |
+
|
| 899 |
+
torch.cuda.empty_cache()
|
| 900 |
+
|
| 901 |
+
def on_before_zero_grad(
|
| 902 |
+
self, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler.LRScheduler, iteration: int
|
| 903 |
+
) -> None:
|
| 904 |
+
del scheduler, optimizer
|
| 905 |
+
|
| 906 |
+
if self.config.ema.enabled:
|
| 907 |
+
# calculate beta for EMA update
|
| 908 |
+
if iteration == 0:
|
| 909 |
+
beta = 0.0
|
| 910 |
+
else:
|
| 911 |
+
i = iteration + 1
|
| 912 |
+
beta = (1 - 1 / i) ** (self.ema_exp_coefficient + 1)
|
| 913 |
+
self.model_ema_worker.update_average(self.model, self.model_ema, beta=beta)
|
| 914 |
+
|
| 915 |
+
def training_step(
|
| 916 |
+
self, data_batch: Dict[str, torch.Tensor], iteration: int
|
| 917 |
+
) -> Tuple[Dict[str, torch.Tensor] | torch.Tensor]:
|
| 918 |
+
# ! Important!!!
|
| 919 |
+
# ! make sure the training step is the same as the forward method~(training_step in the super class)
|
| 920 |
+
# ! this is necessary to trigger the FSDP-specific pre- and post-forward sharding logic
|
| 921 |
+
return self.model(data_batch, iteration)
|
| 922 |
+
|
| 923 |
+
def state_dict(self) -> Dict:
|
| 924 |
+
raise NotImplementedError(
|
| 925 |
+
"FSDPDiffModle does not support state_dict, use state_dict_model and FSDPCheckpointer"
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
@misc.timer("FSDP state_dict_model")
|
| 929 |
+
def state_dict_model(self) -> Dict:
|
| 930 |
+
with FSDP.summon_full_params(self.model):
|
| 931 |
+
pass
|
| 932 |
+
with FSDP.state_dict_type(
|
| 933 |
+
self.model, StateDictType.FULL_STATE_DICT, FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
|
| 934 |
+
):
|
| 935 |
+
model_state = self.model.state_dict()
|
| 936 |
+
if self.config.ema.enabled:
|
| 937 |
+
with FSDP.summon_full_params(self.model_ema):
|
| 938 |
+
pass
|
| 939 |
+
with FSDP.state_dict_type(
|
| 940 |
+
self.model_ema,
|
| 941 |
+
StateDictType.FULL_STATE_DICT,
|
| 942 |
+
FullStateDictConfig(offload_to_cpu=True, rank0_only=True),
|
| 943 |
+
):
|
| 944 |
+
ema_model_state = self.model_ema.state_dict()
|
| 945 |
+
else:
|
| 946 |
+
ema_model_state = None
|
| 947 |
+
return {
|
| 948 |
+
"model": model_state,
|
| 949 |
+
"ema": ema_model_state,
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
def load_state_dict(self, state_dict: Dict, strict: bool = True, assign: bool = False) -> None:
|
| 953 |
+
raise NotImplementedError("FSDPDiffModle does not support load_state_dict, using FSDPCheckpointer")
|
| 954 |
+
|
| 955 |
+
def init_optimizer_scheduler(
|
| 956 |
+
self, optimizer_config: LazyDict, scheduler_config: LazyDict
|
| 957 |
+
) -> tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LRScheduler]:
|
| 958 |
+
optimizer, scheduler = super().init_optimizer_scheduler(optimizer_config, scheduler_config)
|
| 959 |
+
self.fsdp_checkpointer.load_optim_scheduler_during_init(
|
| 960 |
+
self.model,
|
| 961 |
+
optimizer,
|
| 962 |
+
scheduler,
|
| 963 |
+
)
|
| 964 |
+
return optimizer, scheduler
|
| 965 |
+
|
| 966 |
+
@contextmanager
|
| 967 |
+
def ema_scope(self, context=None, is_cpu=False):
|
| 968 |
+
if self.config.ema.enabled:
|
| 969 |
+
self.model_ema_worker.cache(self.model.parameters(), is_cpu=is_cpu)
|
| 970 |
+
self.model_ema_worker.copy_to(src_model=self.model_ema, tgt_model=self.model)
|
| 971 |
+
if context is not None:
|
| 972 |
+
log.info(f"{context}: Switched to EMA weights")
|
| 973 |
+
try:
|
| 974 |
+
yield None
|
| 975 |
+
finally:
|
| 976 |
+
if self.config.ema.enabled:
|
| 977 |
+
self.model_ema_worker.restore(self.model.parameters())
|
| 978 |
+
if context is not None:
|
| 979 |
+
log.info(f"{context}: Restored training weights")
|
| 980 |
+
|
| 981 |
+
def get_ckpt_postfix(self) -> Tuple[str, int]:
|
| 982 |
+
"""Get the checkpoint file postfix. check FSDPCheckpointer for more details
|
| 983 |
+
|
| 984 |
+
Args:
|
| 985 |
+
iteration (int): The current iteration number.
|
| 986 |
+
|
| 987 |
+
Returns:
|
| 988 |
+
postfix (str): The postfix of the checkpoint file.
|
| 989 |
+
replicate_idx, shard_idx (int), current gpu replicate_idx, shard_idx in FSDP \
|
| 990 |
+
we will not save each ema model in each GPU, \
|
| 991 |
+
ema model with same rate will be saved once
|
| 992 |
+
total_ema_num (int)
|
| 993 |
+
"""
|
| 994 |
+
mesh_shape = parallel_state.fsdp_device_mesh.shape
|
| 995 |
+
total_ema_num = min(self.config.ema.num, mesh_shape[0])
|
| 996 |
+
replicate_idx, shard_idx = parallel_state.fsdp_device_mesh.get_coordinate()
|
| 997 |
+
if replicate_idx == 0:
|
| 998 |
+
return "", 0, shard_idx, total_ema_num
|
| 999 |
+
if self.config.ema.enabled:
|
| 1000 |
+
if replicate_idx < self.config.ema.num:
|
| 1001 |
+
return f"_RANK{replicate_idx}", replicate_idx, shard_idx, total_ema_num
|
| 1002 |
+
return "", replicate_idx, shard_idx, total_ema_num
|
| 1003 |
+
|
| 1004 |
+
return FSDPClass
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
@diffusion_fsdp_class_decorator
|
| 1008 |
+
class FSDPDiffusionModel(DiffusionModel):
|
| 1009 |
+
pass
|
diffusion/training/module/pretrained_vae_base.py
ADDED
|
@@ -0,0 +1,844 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
from abc import ABC, abstractmethod
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
|
| 22 |
+
from utils.distributed import rank0_first
|
| 23 |
+
from utils.misc import load_from_s3_with_cache
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class BaseVAE(torch.nn.Module, ABC):
|
| 27 |
+
"""
|
| 28 |
+
Abstract base class for a Variational Autoencoder (VAE).
|
| 29 |
+
|
| 30 |
+
All subclasses should implement the methods to define the behavior for encoding
|
| 31 |
+
and decoding, along with specifying the latent channel size.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(self, channel: int = 3, name: str = "vae"):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.channel = channel
|
| 37 |
+
self.name = name
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def latent_ch(self) -> int:
|
| 41 |
+
"""
|
| 42 |
+
Returns the number of latent channels in the VAE.
|
| 43 |
+
"""
|
| 44 |
+
return self.channel
|
| 45 |
+
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def encode(self, state: torch.Tensor) -> torch.Tensor:
|
| 48 |
+
"""
|
| 49 |
+
Encodes the input tensor into a latent representation.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
- state (torch.Tensor): The input tensor to encode.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
- torch.Tensor: The encoded latent tensor.
|
| 56 |
+
"""
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
@abstractmethod
|
| 60 |
+
def decode(self, latent: torch.Tensor) -> torch.Tensor:
|
| 61 |
+
"""
|
| 62 |
+
Decodes the latent representation back to the original space.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
- latent (torch.Tensor): The latent tensor to decode.
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
- torch.Tensor: The decoded tensor.
|
| 69 |
+
"""
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def spatial_compression_factor(self) -> int:
|
| 74 |
+
"""
|
| 75 |
+
Returns the spatial reduction factor for the VAE.
|
| 76 |
+
"""
|
| 77 |
+
raise NotImplementedError("The spatial_compression_factor property must be implemented in the derived class.")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class BasePretrainedImageVAE(BaseVAE):
|
| 81 |
+
"""
|
| 82 |
+
A base class for pretrained Variational Autoencoder (VAE) that loads mean and standard deviation values
|
| 83 |
+
from a remote store, handles data type conversions, and normalization
|
| 84 |
+
using provided mean and standard deviation values for latent space representation.
|
| 85 |
+
Derived classes should load pre-trained encoder and decoder components from a remote store
|
| 86 |
+
|
| 87 |
+
Attributes:
|
| 88 |
+
latent_mean (Tensor): The mean used for normalizing the latent representation.
|
| 89 |
+
latent_std (Tensor): The standard deviation used for normalizing the latent representation.
|
| 90 |
+
dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
mean_std_fp (str): File path to the pickle file containing mean and std of the latent space.
|
| 94 |
+
latent_ch (int, optional): Number of latent channels (default is 16).
|
| 95 |
+
is_image (bool, optional): Flag to indicate whether the output is an image (default is True).
|
| 96 |
+
is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True).
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
name: str,
|
| 102 |
+
mean_std_fp: str,
|
| 103 |
+
latent_ch: int = 16,
|
| 104 |
+
is_image: bool = True,
|
| 105 |
+
is_bf16: bool = True,
|
| 106 |
+
) -> None:
|
| 107 |
+
super().__init__(latent_ch, name)
|
| 108 |
+
dtype = torch.bfloat16 if is_bf16 else torch.float32
|
| 109 |
+
self.dtype = dtype
|
| 110 |
+
self.is_image = is_image
|
| 111 |
+
self.mean_std_fp = mean_std_fp
|
| 112 |
+
self.name = name
|
| 113 |
+
|
| 114 |
+
self.backend_args = None
|
| 115 |
+
|
| 116 |
+
self.register_mean_std(mean_std_fp)
|
| 117 |
+
|
| 118 |
+
def register_mean_std(self, mean_std_fp: str) -> None:
|
| 119 |
+
latent_mean, latent_std = torch.load(mean_std_fp, map_location="cuda", weights_only=True)
|
| 120 |
+
target_shape = [1, self.latent_ch, 1, 1] if self.is_image else [1, self.latent_ch, 1, 1, 1]
|
| 121 |
+
self.register_buffer(
|
| 122 |
+
"latent_mean",
|
| 123 |
+
latent_mean.to(self.dtype).reshape(*target_shape),
|
| 124 |
+
persistent=False,
|
| 125 |
+
)
|
| 126 |
+
self.register_buffer(
|
| 127 |
+
"latent_std",
|
| 128 |
+
latent_std.to(self.dtype).reshape(*target_shape),
|
| 129 |
+
persistent=False,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
@torch.no_grad()
|
| 133 |
+
def encode(self, state: torch.Tensor) -> torch.Tensor:
|
| 134 |
+
"""
|
| 135 |
+
Encode the input state to latent space; also handle the dtype conversion, mean and std scaling
|
| 136 |
+
"""
|
| 137 |
+
in_dtype = state.dtype
|
| 138 |
+
latent_mean = self.latent_mean.to(in_dtype)
|
| 139 |
+
latent_std = self.latent_std.to(in_dtype)
|
| 140 |
+
encoded_state = self.encoder(state.to(self.dtype))
|
| 141 |
+
if isinstance(encoded_state, torch.Tensor):
|
| 142 |
+
pass
|
| 143 |
+
elif isinstance(encoded_state, tuple):
|
| 144 |
+
assert isinstance(encoded_state[0], torch.Tensor)
|
| 145 |
+
encoded_state = encoded_state[0]
|
| 146 |
+
else:
|
| 147 |
+
raise ValueError("Invalid type of encoded state")
|
| 148 |
+
return (encoded_state.to(in_dtype) - latent_mean) / latent_std
|
| 149 |
+
|
| 150 |
+
@torch.no_grad()
|
| 151 |
+
def decode(self, latent: torch.Tensor) -> torch.Tensor:
|
| 152 |
+
"""
|
| 153 |
+
Decode the input latent to state; also handle the dtype conversion, mean and std scaling
|
| 154 |
+
"""
|
| 155 |
+
in_dtype = latent.dtype
|
| 156 |
+
latent = latent * self.latent_std.to(in_dtype) + self.latent_mean.to(in_dtype)
|
| 157 |
+
return self.decoder(latent.to(self.dtype)).to(in_dtype)
|
| 158 |
+
|
| 159 |
+
def reset_dtype(self, *args, **kwargs):
|
| 160 |
+
"""
|
| 161 |
+
Resets the data type of the encoder and decoder to the model's default data type.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
*args, **kwargs: Unused, present to allow flexibility in method calls.
|
| 165 |
+
"""
|
| 166 |
+
del args, kwargs
|
| 167 |
+
self.decoder.to(self.dtype)
|
| 168 |
+
self.encoder.to(self.dtype)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class JITVAE(BasePretrainedImageVAE):
|
| 172 |
+
"""
|
| 173 |
+
A JIT compiled Variational Autoencoder (VAE) that loads pre-trained encoder
|
| 174 |
+
and decoder components from a remote store, handles data type conversions, and normalization
|
| 175 |
+
using provided mean and standard deviation values for latent space representation.
|
| 176 |
+
|
| 177 |
+
Attributes:
|
| 178 |
+
encoder (Module): The JIT compiled encoder loaded from storage.
|
| 179 |
+
decoder (Module): The JIT compiled decoder loaded from storage.
|
| 180 |
+
latent_mean (Tensor): The mean used for normalizing the latent representation.
|
| 181 |
+
latent_std (Tensor): The standard deviation used for normalizing the latent representation.
|
| 182 |
+
dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
enc_fp (str): File path to the encoder's JIT file on the remote store.
|
| 186 |
+
dec_fp (str): File path to the decoder's JIT file on the remote store.
|
| 187 |
+
name (str): Name of the model, used for differentiating cache file paths.
|
| 188 |
+
mean_std_fp (str): File path to the pickle file containing mean and std of the latent space.
|
| 189 |
+
latent_ch (int, optional): Number of latent channels (default is 16).
|
| 190 |
+
is_image (bool, optional): Flag to indicate whether the output is an image (default is True).
|
| 191 |
+
is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True).
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
enc_fp: str,
|
| 197 |
+
dec_fp: str,
|
| 198 |
+
name: str,
|
| 199 |
+
mean_std_fp: str,
|
| 200 |
+
latent_ch: int = 16,
|
| 201 |
+
is_image: bool = True,
|
| 202 |
+
is_bf16: bool = True,
|
| 203 |
+
):
|
| 204 |
+
super().__init__(name, mean_std_fp, latent_ch, is_image, is_bf16)
|
| 205 |
+
self.load_encoder(enc_fp)
|
| 206 |
+
self.load_decoder(dec_fp)
|
| 207 |
+
|
| 208 |
+
def load_encoder(self, enc_fp: str) -> None:
|
| 209 |
+
"""
|
| 210 |
+
Load the encoder from the remote store.
|
| 211 |
+
|
| 212 |
+
Args:
|
| 213 |
+
- enc_fp (str): File path to the encoder's JIT file on the remote store.
|
| 214 |
+
"""
|
| 215 |
+
self.encoder = torch.jit.load(enc_fp, map_location="cuda")
|
| 216 |
+
self.encoder.eval()
|
| 217 |
+
for param in self.encoder.parameters():
|
| 218 |
+
param.requires_grad = False
|
| 219 |
+
self.encoder.to(self.dtype)
|
| 220 |
+
|
| 221 |
+
def load_decoder(self, dec_fp: str) -> None:
|
| 222 |
+
"""
|
| 223 |
+
Load the decoder from the remote store.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
- dec_fp (str): File path to the decoder's JIT file on the remote store.
|
| 227 |
+
"""
|
| 228 |
+
self.decoder = torch.jit.load(dec_fp, map_location="cuda")
|
| 229 |
+
self.decoder.eval()
|
| 230 |
+
for param in self.decoder.parameters():
|
| 231 |
+
param.requires_grad = False
|
| 232 |
+
self.decoder.to(self.dtype)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class StateDictVAE(BasePretrainedImageVAE):
|
| 236 |
+
"""
|
| 237 |
+
A Variational Autoencoder (VAE) that loads pre-trained weights into
|
| 238 |
+
provided encoder and decoder components from a remote store, handles data type conversions,
|
| 239 |
+
and normalization using provided mean and standard deviation values for latent space representation.
|
| 240 |
+
|
| 241 |
+
Attributes:
|
| 242 |
+
encoder (Module): The encoder with weights loaded from storage.
|
| 243 |
+
decoder (Module): The decoder with weights loaded from storage.
|
| 244 |
+
latent_mean (Tensor): The mean used for normalizing the latent representation.
|
| 245 |
+
latent_std (Tensor): The standard deviation used for normalizing the latent representation.
|
| 246 |
+
dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
enc_fp (str): File path to the encoder's JIT file on the remote store.
|
| 250 |
+
dec_fp (str): File path to the decoder's JIT file on the remote store.
|
| 251 |
+
vae (Module): Instance of VAE with not loaded weights
|
| 252 |
+
name (str): Name of the model, used for differentiating cache file paths.
|
| 253 |
+
mean_std_fp (str): File path to the pickle file containing mean and std of the latent space.
|
| 254 |
+
latent_ch (int, optional): Number of latent channels (default is 16).
|
| 255 |
+
is_image (bool, optional): Flag to indicate whether the output is an image (default is True).
|
| 256 |
+
is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True).
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
def __init__(
|
| 260 |
+
self,
|
| 261 |
+
enc_fp: str,
|
| 262 |
+
dec_fp: str,
|
| 263 |
+
vae: torch.nn.Module,
|
| 264 |
+
name: str,
|
| 265 |
+
mean_std_fp: str,
|
| 266 |
+
latent_ch: int = 16,
|
| 267 |
+
is_image: bool = True,
|
| 268 |
+
is_bf16: bool = True,
|
| 269 |
+
):
|
| 270 |
+
super().__init__(name, mean_std_fp, latent_ch, is_image, is_bf16)
|
| 271 |
+
|
| 272 |
+
self.load_encoder_and_decoder(enc_fp, dec_fp, vae)
|
| 273 |
+
|
| 274 |
+
def load_encoder_and_decoder(self, enc_fp: str, dec_fp: str, vae: torch.nn.Module) -> None:
|
| 275 |
+
"""
|
| 276 |
+
Load the encoder from the remote store.
|
| 277 |
+
|
| 278 |
+
Args:
|
| 279 |
+
- vae_fp (str): File path to the vae's state dict file on the remote store.
|
| 280 |
+
- vae (str): VAE module into which weights will be loaded.
|
| 281 |
+
"""
|
| 282 |
+
state_dict_enc = load_from_s3_with_cache(
|
| 283 |
+
enc_fp,
|
| 284 |
+
f"vae/{self.name}_enc.jit",
|
| 285 |
+
easy_io_kwargs={"map_location": torch.device(torch.cuda.current_device())},
|
| 286 |
+
backend_args=self.backend_args,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
state_dict_dec = load_from_s3_with_cache(
|
| 290 |
+
dec_fp,
|
| 291 |
+
f"vae/{self.name}_dec.jit",
|
| 292 |
+
easy_io_kwargs={"map_location": torch.device(torch.cuda.current_device())},
|
| 293 |
+
backend_args=self.backend_args,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
jit_weights_state_dict = state_dict_enc.state_dict() | state_dict_dec.state_dict()
|
| 297 |
+
jit_weights_state_dict = {
|
| 298 |
+
k: v
|
| 299 |
+
for k, v in jit_weights_state_dict.items()
|
| 300 |
+
# Global variables captured by JIT
|
| 301 |
+
if k
|
| 302 |
+
not in (
|
| 303 |
+
"encoder.patcher.wavelets",
|
| 304 |
+
"encoder.patcher._arange",
|
| 305 |
+
"decoder.unpatcher.wavelets",
|
| 306 |
+
"decoder.unpatcher._arange",
|
| 307 |
+
)
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
vae.load_state_dict(jit_weights_state_dict)
|
| 311 |
+
vae.eval()
|
| 312 |
+
for param in vae.parameters():
|
| 313 |
+
param.requires_grad = False
|
| 314 |
+
vae.to(self.dtype)
|
| 315 |
+
|
| 316 |
+
self.vae = vae
|
| 317 |
+
self.encoder = self.vae.encode
|
| 318 |
+
self.decoder = self.vae.decode
|
| 319 |
+
|
| 320 |
+
def reset_dtype(self, *args, **kwargs):
|
| 321 |
+
"""
|
| 322 |
+
Resets the data type of the encoder and decoder to the model's default data type.
|
| 323 |
+
|
| 324 |
+
Args:
|
| 325 |
+
*args, **kwargs: Unused, present to allow flexibility in method calls.
|
| 326 |
+
"""
|
| 327 |
+
del args, kwargs
|
| 328 |
+
self.vae.to(self.dtype)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class ConfigBasedVideoVAE(BaseVAE):
|
| 332 |
+
"""VAE loaded from a tokenizer experiment config + training checkpoint.
|
| 333 |
+
|
| 334 |
+
Works with any tokenizer that exposes `encode(x) -> (sample, (mu, logvar))`
|
| 335 |
+
and `decode(z) -> x`, including WanVAE2P1 and TransformerVAE.
|
| 336 |
+
|
| 337 |
+
Latent statistics can be supplied either via ``mean_std_fp`` (a saved
|
| 338 |
+
``(mean, std)`` tuple / ``{"mean", "std"}`` dict) or via inline
|
| 339 |
+
``latent_mean`` / ``latent_std`` lists. Inline values take precedence
|
| 340 |
+
so callers that don't have a ``latent_stats.pt`` next to their
|
| 341 |
+
checkpoint (e.g. the public ``Wan2.1_VAE.pth`` release) can pass the
|
| 342 |
+
per-channel statistics directly from a constant.
|
| 343 |
+
"""
|
| 344 |
+
|
| 345 |
+
def __init__(
|
| 346 |
+
self,
|
| 347 |
+
experiment_name: str,
|
| 348 |
+
checkpoint_path: str,
|
| 349 |
+
mean_std_fp: str | None = None,
|
| 350 |
+
latent_ch: int = 64,
|
| 351 |
+
is_bf16: bool = False,
|
| 352 |
+
spatial_compression: int = 8,
|
| 353 |
+
latent_mean: list[float] | tuple[float, ...] | None = None,
|
| 354 |
+
latent_std: list[float] | tuple[float, ...] | None = None,
|
| 355 |
+
apply_validity_mask: bool = False,
|
| 356 |
+
intensity_pad_value: float = 0.0,
|
| 357 |
+
network_overrides: dict | None = None,
|
| 358 |
+
use_ema: bool = False,
|
| 359 |
+
per_frame: bool = False,
|
| 360 |
+
encoder_is_bf16: bool | None = None,
|
| 361 |
+
decoder_is_bf16: bool | None = None,
|
| 362 |
+
strict_checkpoint: bool = False,
|
| 363 |
+
):
|
| 364 |
+
super().__init__(channel=latent_ch, name=f"config_vae_{experiment_name}")
|
| 365 |
+
from diffusion.training.module.vae_utils import (
|
| 366 |
+
build_vae_from_tokenizer_experiment,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
self.is_image = False
|
| 370 |
+
self._spatial_compression = spatial_compression
|
| 371 |
+
# per_frame: the wrapped net is a 2D (single-frame) tokenizer (cosmos CI,
|
| 372 |
+
# LiDM) whose encode/decode take (B, C, H, W). encode/decode fold the clip's
|
| 373 |
+
# T axis into the batch, run the net per frame, and reshape the latent back
|
| 374 |
+
# to (B, Cz, T, Hz, Wz) so the rest of the video pipeline (5D latent-stat
|
| 375 |
+
# buffers, DiT) is unchanged. The first-frame prepend still happens in the
|
| 376 |
+
# dataset (is_video_tokenizer=True) -> T frames each encoded independently.
|
| 377 |
+
self.per_frame = bool(per_frame)
|
| 378 |
+
encoder_is_bf16 = (
|
| 379 |
+
is_bf16 if encoder_is_bf16 is None else encoder_is_bf16
|
| 380 |
+
)
|
| 381 |
+
decoder_is_bf16 = (
|
| 382 |
+
is_bf16 if decoder_is_bf16 is None else decoder_is_bf16
|
| 383 |
+
)
|
| 384 |
+
self.encoder_dtype = (
|
| 385 |
+
torch.bfloat16 if encoder_is_bf16 else torch.float32
|
| 386 |
+
)
|
| 387 |
+
self.decoder_dtype = (
|
| 388 |
+
torch.bfloat16 if decoder_is_bf16 else torch.float32
|
| 389 |
+
)
|
| 390 |
+
# Keep the legacy public dtype tied to decode. Encode paths use the
|
| 391 |
+
# explicit encoder dtype below.
|
| 392 |
+
self.dtype = self.decoder_dtype
|
| 393 |
+
|
| 394 |
+
# ``network_overrides`` are applied AFTER the experiment's own network
|
| 395 |
+
# overrides (e.g. ``utonia_align=False`` to skip building the training-only
|
| 396 |
+
# VF/PTv3 teacher -- encode/decode is bit-identical and the leftover
|
| 397 |
+
# ``utonia.*`` ckpt keys drop harmlessly under the strict=False load below).
|
| 398 |
+
self.vae_net = build_vae_from_tokenizer_experiment(
|
| 399 |
+
experiment_name, **(network_overrides or {})
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
# Validity-head support: predict_validity VAEs return a per-pixel raydrop
|
| 403 |
+
# logit from decode(); when ``apply_validity_mask`` is set we fill the
|
| 404 |
+
# predicted-invalid pixels with the depth sentinel so the decoded range
|
| 405 |
+
# map carries raydrop directly (matches the trained 2-channel output).
|
| 406 |
+
self.predict_validity = bool(getattr(self.vae_net, "predict_validity", False))
|
| 407 |
+
# decoder_validity_head: a SEPARATE additive head taps the decoder recon
|
| 408 |
+
# and emits a raydrop logit via decode(z, return_validity=True) (does NOT
|
| 409 |
+
# widen the main conv). Mutually exclusive with predict_validity. Handled
|
| 410 |
+
# on the same masking path below.
|
| 411 |
+
self.decoder_validity_head = bool(getattr(self.vae_net, "decoder_validity_head", False))
|
| 412 |
+
self.apply_validity_mask = bool(apply_validity_mask)
|
| 413 |
+
self.invalid_fill = float(getattr(self.vae_net, "mask_input_min_value", -1.0))
|
| 414 |
+
# Fill value for DATA channels missing from the input (e.g. the intensity
|
| 415 |
+
# channel when encoding a mono-depth hdmap through a [depth, intensity]
|
| 416 |
+
# VAE). Intensity is normalized to [-1, 1]; a flat plane is OOD, so this
|
| 417 |
+
# is exposed for A/B tuning. Default 0.0 preserves prior behavior.
|
| 418 |
+
self.intensity_pad_value = float(intensity_pad_value)
|
| 419 |
+
|
| 420 |
+
# ``is_ltx`` flags whether the wrapped VAE supports LTX-style
|
| 421 |
+
# timestep-conditioned decoding (``decode(z, t=...)`` with a
|
| 422 |
+
# rectified-flow t threading through AdaLN). Detected from the
|
| 423 |
+
# underlying net's ``denoising_t_max`` attr -- the LTX
|
| 424 |
+
# TransformerVAELTX sets it to > 0 when AdaLN is built.
|
| 425 |
+
# Callers should gate any ``t`` they want to pass to
|
| 426 |
+
# ``decode`` on this flag rather than guessing from the model
|
| 427 |
+
# class or ``is_image``.
|
| 428 |
+
self.is_ltx = bool(getattr(self.vae_net, "denoising_t_max", 0.0) > 0)
|
| 429 |
+
|
| 430 |
+
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 431 |
+
state = ckpt.get("model", ckpt)
|
| 432 |
+
vae_state = {}
|
| 433 |
+
for k, v in state.items():
|
| 434 |
+
for prefix in ("network.", "vae.", "model.network.", "model.vae."):
|
| 435 |
+
if k.startswith(prefix):
|
| 436 |
+
k = k[len(prefix):]
|
| 437 |
+
break
|
| 438 |
+
vae_state[k] = v
|
| 439 |
+
from tokenizer.networks.transformers.transformer_vae_cross_dataset import (
|
| 440 |
+
CrossDatasetTransformerVAE,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
if isinstance(self.vae_net, CrossDatasetTransformerVAE):
|
| 444 |
+
# Cross-dataset encode/decode regenerate this nonlearned grid at
|
| 445 |
+
# the input resolution; its saved shape is not a model constraint.
|
| 446 |
+
saved_coords = vae_state.pop("coords", None)
|
| 447 |
+
if saved_coords is not None:
|
| 448 |
+
print(
|
| 449 |
+
"[ConfigBasedVideoVAE] ignoring derived cross-dataset "
|
| 450 |
+
f"coords buffer {tuple(saved_coords.shape)}; "
|
| 451 |
+
"coordinates are regenerated for each input grid"
|
| 452 |
+
)
|
| 453 |
+
incompatible = self.vae_net.load_state_dict(vae_state, strict=False)
|
| 454 |
+
if strict_checkpoint:
|
| 455 |
+
allowed_missing = (
|
| 456 |
+
{"coords"}
|
| 457 |
+
if isinstance(self.vae_net, CrossDatasetTransformerVAE)
|
| 458 |
+
else set()
|
| 459 |
+
)
|
| 460 |
+
missing = sorted(set(incompatible.missing_keys) - allowed_missing)
|
| 461 |
+
unexpected = incompatible.unexpected_keys
|
| 462 |
+
if missing or unexpected:
|
| 463 |
+
raise RuntimeError(
|
| 464 |
+
"Tokenizer checkpoint/config mismatch: "
|
| 465 |
+
f"missing={missing[:12]}, unexpected={unexpected[:12]}. "
|
| 466 |
+
"Refusing inference with partially loaded weights."
|
| 467 |
+
)
|
| 468 |
+
print("[ConfigBasedVideoVAE] checkpoint/config match: all weights loaded")
|
| 469 |
+
|
| 470 |
+
# Optional: overlay the EMA shadow weights bundled in the same tokenizer
|
| 471 |
+
# ckpt (``ema.network-<name>`` where <name> is the param name with "."
|
| 472 |
+
# replaced by "-"; see utils/ema.py). Only trainable params are EMA'd, so
|
| 473 |
+
# buffers stay at their reg values -- hence overlay onto the reg-loaded net
|
| 474 |
+
# with strict=False rather than a from-scratch load. NOTE: the diffusion
|
| 475 |
+
# model was trained on reg-encoded latents, so this only swaps the DECODER
|
| 476 |
+
# weights at inference -- an EMA-vs-reg decode A/B, not a latent-space change.
|
| 477 |
+
if use_ema:
|
| 478 |
+
ema_state = {
|
| 479 |
+
k[len("ema.network-"):].replace("-", "."): v
|
| 480 |
+
for k, v in state.items()
|
| 481 |
+
if k.startswith("ema.network-")
|
| 482 |
+
}
|
| 483 |
+
if not ema_state:
|
| 484 |
+
raise RuntimeError(
|
| 485 |
+
f"use_ema=True but no 'ema.network-*' keys in {checkpoint_path} "
|
| 486 |
+
"(EMA was not enabled for this tokenizer run)."
|
| 487 |
+
)
|
| 488 |
+
_, unexpected = self.vae_net.load_state_dict(ema_state, strict=False)
|
| 489 |
+
if unexpected:
|
| 490 |
+
raise RuntimeError(
|
| 491 |
+
f"EMA overlay had {len(unexpected)} unexpected keys, e.g. "
|
| 492 |
+
f"{unexpected[:5]} -- ema->net name remap is wrong for this arch."
|
| 493 |
+
)
|
| 494 |
+
print(f"[ConfigBasedVideoVAE] use_ema=True: overlaid {len(ema_state)} "
|
| 495 |
+
"EMA params onto the decoder/vae_net")
|
| 496 |
+
|
| 497 |
+
self.vae_net.eval()
|
| 498 |
+
for p in self.vae_net.parameters():
|
| 499 |
+
p.requires_grad = False
|
| 500 |
+
self._reset_module_dtypes()
|
| 501 |
+
|
| 502 |
+
if latent_mean is not None and latent_std is not None:
|
| 503 |
+
assert len(latent_mean) == latent_ch and len(latent_std) == latent_ch, (
|
| 504 |
+
f"Inline latent_mean/latent_std must have length latent_ch={latent_ch}, "
|
| 505 |
+
f"got {len(latent_mean)}/{len(latent_std)}"
|
| 506 |
+
)
|
| 507 |
+
latent_mean_t = torch.tensor(list(latent_mean), dtype=torch.float32)
|
| 508 |
+
latent_std_t = torch.tensor(list(latent_std), dtype=torch.float32)
|
| 509 |
+
else:
|
| 510 |
+
assert mean_std_fp is not None, (
|
| 511 |
+
"ConfigBasedVideoVAE requires either mean_std_fp or "
|
| 512 |
+
"(latent_mean, latent_std)."
|
| 513 |
+
)
|
| 514 |
+
stats = torch.load(mean_std_fp, map_location="cpu", weights_only=False)
|
| 515 |
+
if isinstance(stats, (tuple, list)):
|
| 516 |
+
latent_mean_t, latent_std_t = stats
|
| 517 |
+
else:
|
| 518 |
+
latent_mean_t = stats["mean"]
|
| 519 |
+
latent_std_t = stats["std"]
|
| 520 |
+
shape = [1, latent_ch, 1, 1, 1]
|
| 521 |
+
self.register_buffer(
|
| 522 |
+
"latent_mean",
|
| 523 |
+
latent_mean_t.to(self.dtype).reshape(*shape),
|
| 524 |
+
persistent=False,
|
| 525 |
+
)
|
| 526 |
+
self.register_buffer(
|
| 527 |
+
"latent_std",
|
| 528 |
+
latent_std_t.to(self.dtype).reshape(*shape),
|
| 529 |
+
persistent=False,
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
def _reset_module_dtypes(self) -> None:
|
| 533 |
+
self.vae_net.to(self.decoder_dtype)
|
| 534 |
+
if self.encoder_dtype == self.decoder_dtype:
|
| 535 |
+
return
|
| 536 |
+
if not all(
|
| 537 |
+
hasattr(self.vae_net, name) for name in ("encoder", "quant_conv")
|
| 538 |
+
):
|
| 539 |
+
raise ValueError(
|
| 540 |
+
"mixed VAE precision requires separate encoder and "
|
| 541 |
+
"quant_conv modules"
|
| 542 |
+
)
|
| 543 |
+
self.vae_net.encoder.to(self.encoder_dtype)
|
| 544 |
+
self.vae_net.quant_conv.to(self.encoder_dtype)
|
| 545 |
+
|
| 546 |
+
def _prepare_encoder_input(self, state: torch.Tensor) -> torch.Tensor:
|
| 547 |
+
x = state.to(self.encoder_dtype)
|
| 548 |
+
# mask_as_input VAEs expect a [data..., mask] encoder input, but
|
| 549 |
+
# vae_net.encode() does NOT build the mask (forward() does). The net
|
| 550 |
+
# reconstructs ``out_channels`` DATA channels (1 = [depth] mono, 2 =
|
| 551 |
+
# [depth, intensity]); build the full encoder input to match training:
|
| 552 |
+
# * pad missing data channels with zeros (e.g. hdmap is mono depth even
|
| 553 |
+
# for an intensity VAE -> [depth, 0(intensity)] before the mask),
|
| 554 |
+
# * derive the validity mask from depth (ch0, same threshold as the
|
| 555 |
+
# loss/forward) and concat it.
|
| 556 |
+
# No-op for non-mask VAEs and for inputs that already carry the mask
|
| 557 |
+
# channel (x.shape[1] == data_ch + 1). Bit-identical to the old 1ch path
|
| 558 |
+
# for mono mask VAEs (out_channels == 1).
|
| 559 |
+
if getattr(self.vae_net, "mask_as_input", False):
|
| 560 |
+
data_ch = int(getattr(self.vae_net, "out_channels", 1))
|
| 561 |
+
if x.shape[1] <= data_ch:
|
| 562 |
+
if x.shape[1] < data_ch: # pad missing data channels (intensity)
|
| 563 |
+
pad = x.new_full(
|
| 564 |
+
(x.shape[0], data_ch - x.shape[1]) + tuple(x.shape[2:]),
|
| 565 |
+
self.intensity_pad_value)
|
| 566 |
+
x = torch.cat([x, pad], dim=1)
|
| 567 |
+
thr = self.vae_net.mask_input_min_value + self.vae_net.mask_input_eps
|
| 568 |
+
valid = (x[:, :1] > thr).to(x.dtype)
|
| 569 |
+
x = torch.cat([x, valid], dim=1)
|
| 570 |
+
return x
|
| 571 |
+
|
| 572 |
+
@torch.no_grad()
|
| 573 |
+
def encode(
|
| 574 |
+
self,
|
| 575 |
+
state: torch.Tensor,
|
| 576 |
+
sensor_dataset_id: torch.Tensor | int | None = None,
|
| 577 |
+
) -> torch.Tensor:
|
| 578 |
+
if sensor_dataset_id is not None:
|
| 579 |
+
setter = getattr(self.vae_net, "set_dataset_id", None)
|
| 580 |
+
if setter is not None:
|
| 581 |
+
setter(sensor_dataset_id)
|
| 582 |
+
elif getattr(self.vae_net, "uses_dataset_id", False):
|
| 583 |
+
raise TypeError(
|
| 584 |
+
f"{type(self.vae_net).__name__} requires a dataset ID but "
|
| 585 |
+
"does not expose set_dataset_id()"
|
| 586 |
+
)
|
| 587 |
+
x = self._prepare_encoder_input(state)
|
| 588 |
+
if self.per_frame:
|
| 589 |
+
# 2D net: (B, C, T, H, W) -> encode each frame as (B*T, C, H, W).
|
| 590 |
+
B, C, T, H, W = x.shape
|
| 591 |
+
frames = x.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W)
|
| 592 |
+
enc = self.vae_net.encode(frames)
|
| 593 |
+
z = enc[0] if isinstance(enc, tuple) else enc
|
| 594 |
+
Cz, Hz, Wz = z.shape[1], z.shape[2], z.shape[3]
|
| 595 |
+
latent = z.reshape(B, T, Cz, Hz, Wz).permute(0, 2, 1, 3, 4)
|
| 596 |
+
else:
|
| 597 |
+
encoded = self.vae_net.encode(x)
|
| 598 |
+
latent = encoded[0] if isinstance(encoded, tuple) else encoded
|
| 599 |
+
latent = latent.to(self.encoder_dtype)
|
| 600 |
+
latent_mean = self.latent_mean.to(self.encoder_dtype)
|
| 601 |
+
latent_std = self.latent_std.to(self.encoder_dtype)
|
| 602 |
+
return (latent - latent_mean) / latent_std
|
| 603 |
+
|
| 604 |
+
@torch.no_grad()
|
| 605 |
+
def encode_stream(
|
| 606 |
+
self,
|
| 607 |
+
state_new: torch.Tensor,
|
| 608 |
+
temporal_kv_cache=None,
|
| 609 |
+
max_cache_frames: int | None = None,
|
| 610 |
+
):
|
| 611 |
+
"""Encode newly appended frames with the wrapped causal VAE cache."""
|
| 612 |
+
if self.per_frame or not getattr(
|
| 613 |
+
self.vae_net, "supports_encoder_temporal_kv_cache", False
|
| 614 |
+
):
|
| 615 |
+
raise NotImplementedError(
|
| 616 |
+
f"{type(self.vae_net).__name__} does not support temporal "
|
| 617 |
+
"KV-cache encoding"
|
| 618 |
+
)
|
| 619 |
+
x_new = self._prepare_encoder_input(state_new)
|
| 620 |
+
encoded, new_cache = self.vae_net.encode_stream(
|
| 621 |
+
x_new,
|
| 622 |
+
temporal_kv_cache=temporal_kv_cache,
|
| 623 |
+
max_cache_frames=max_cache_frames,
|
| 624 |
+
)
|
| 625 |
+
latent = encoded[0] if isinstance(encoded, tuple) else encoded
|
| 626 |
+
latent = latent.to(self.encoder_dtype)
|
| 627 |
+
latent_mean = self.latent_mean.to(self.encoder_dtype)
|
| 628 |
+
latent_std = self.latent_std.to(self.encoder_dtype)
|
| 629 |
+
latent = (latent - latent_mean) / latent_std
|
| 630 |
+
return latent, new_cache
|
| 631 |
+
|
| 632 |
+
@torch.no_grad()
|
| 633 |
+
def decode(
|
| 634 |
+
self,
|
| 635 |
+
latent: torch.Tensor,
|
| 636 |
+
t: float | torch.Tensor | None = None,
|
| 637 |
+
return_validity: bool = False,
|
| 638 |
+
sensor_dataset_id: torch.Tensor | int | None = None,
|
| 639 |
+
) -> torch.Tensor:
|
| 640 |
+
"""Decode a normalized latent back to pixels.
|
| 641 |
+
|
| 642 |
+
Args:
|
| 643 |
+
latent: ``(B, latent_ch, T, H, W)`` in normalized-latent space
|
| 644 |
+
(i.e. already divided by ``self.sigma_data`` upstream).
|
| 645 |
+
t: optional rectified-flow timestep in ``[0, 1]``. Only
|
| 646 |
+
accepted when ``self.is_ltx`` is True (the wrapped VAE
|
| 647 |
+
net supports ``decode(z, t=t)``). For non-LTX wrappers
|
| 648 |
+
the standard ``decode(z)`` signature is used and
|
| 649 |
+
passing ``t`` raises -- prevents silently dropping the
|
| 650 |
+
timestep on an unrelated VAE.
|
| 651 |
+
return_validity: when True (and the wrapped net has a validity
|
| 652 |
+
head), also return the per-pixel validity probability
|
| 653 |
+
``(B, 1, T, H, W)`` in ``[0, 1]``; ``None`` otherwise.
|
| 654 |
+
|
| 655 |
+
When the wrapped net has ``predict_validity`` and this wrapper was
|
| 656 |
+
built with ``apply_validity_mask=True``, predicted-invalid pixels
|
| 657 |
+
(prob < 0.5) are filled with the depth sentinel so the returned range
|
| 658 |
+
map carries raydrop directly.
|
| 659 |
+
"""
|
| 660 |
+
if sensor_dataset_id is not None:
|
| 661 |
+
setter = getattr(self.vae_net, "set_dataset_id", None)
|
| 662 |
+
if setter is not None:
|
| 663 |
+
setter(sensor_dataset_id)
|
| 664 |
+
elif getattr(self.vae_net, "uses_dataset_id", False):
|
| 665 |
+
raise TypeError(
|
| 666 |
+
f"{type(self.vae_net).__name__} requires a dataset ID but "
|
| 667 |
+
"does not expose set_dataset_id()"
|
| 668 |
+
)
|
| 669 |
+
if t is not None and not self.is_ltx:
|
| 670 |
+
raise ValueError(
|
| 671 |
+
f"Got t={t!r} but the wrapped VAE net "
|
| 672 |
+
f"({type(self.vae_net).__name__}) is not LTX-style "
|
| 673 |
+
f"(is_ltx=False). Use a TransformerVAELTX checkpoint "
|
| 674 |
+
f"with denoising_t_max > 0 to enable timestep-"
|
| 675 |
+
f"conditioned decoding."
|
| 676 |
+
)
|
| 677 |
+
latent = latent.to(self.decoder_dtype)
|
| 678 |
+
latent_std = self.latent_std.to(self.decoder_dtype)
|
| 679 |
+
latent_mean = self.latent_mean.to(self.decoder_dtype)
|
| 680 |
+
latent = latent * latent_std + latent_mean
|
| 681 |
+
|
| 682 |
+
if self.per_frame:
|
| 683 |
+
# 2D net: (B, Cz, T, Hz, Wz) -> decode each frame as (B*T, Cz, Hz, Wz).
|
| 684 |
+
# These nets have no validity head, so return_validity yields None.
|
| 685 |
+
B, Cz, T, Hz, Wz = latent.shape
|
| 686 |
+
z = latent.permute(0, 2, 1, 3, 4).reshape(B * T, Cz, Hz, Wz)
|
| 687 |
+
rec = self.vae_net.decode(z)
|
| 688 |
+
if isinstance(rec, tuple):
|
| 689 |
+
rec = rec[0]
|
| 690 |
+
if rec.ndim == 5: # some nets return (B, C, 1, H, W)
|
| 691 |
+
rec = rec[:, :, 0]
|
| 692 |
+
C, H, W = rec.shape[1], rec.shape[2], rec.shape[3]
|
| 693 |
+
out = rec.reshape(B, T, C, H, W).permute(0, 2, 1, 3, 4)
|
| 694 |
+
if return_validity:
|
| 695 |
+
return out, None
|
| 696 |
+
return out
|
| 697 |
+
|
| 698 |
+
validity = None
|
| 699 |
+
if self.is_ltx:
|
| 700 |
+
out = self.vae_net.decode(latent, t=t)
|
| 701 |
+
elif self.predict_validity or self.decoder_validity_head:
|
| 702 |
+
out, logits = self.vae_net.decode(latent, return_validity=True)
|
| 703 |
+
if logits is not None:
|
| 704 |
+
validity = torch.sigmoid(logits.to(out.dtype))
|
| 705 |
+
if self.apply_validity_mask:
|
| 706 |
+
out = out.masked_fill(validity < 0.5, self.invalid_fill)
|
| 707 |
+
else:
|
| 708 |
+
out = self.vae_net.decode(latent)
|
| 709 |
+
|
| 710 |
+
if return_validity:
|
| 711 |
+
return out, validity
|
| 712 |
+
return out
|
| 713 |
+
|
| 714 |
+
@torch.no_grad()
|
| 715 |
+
def decode_stream(
|
| 716 |
+
self,
|
| 717 |
+
latent_new: torch.Tensor,
|
| 718 |
+
temporal_kv_cache=None,
|
| 719 |
+
return_validity: bool = False,
|
| 720 |
+
max_cache_frames: int | None = None,
|
| 721 |
+
):
|
| 722 |
+
"""Decode newly appended frames with the wrapped causal VAE cache."""
|
| 723 |
+
if self.per_frame or self.is_ltx or self.decoder_validity_head:
|
| 724 |
+
raise NotImplementedError(
|
| 725 |
+
"streaming decode currently supports the attention-based "
|
| 726 |
+
"TransformerVAE video decoder with its integrated validity head"
|
| 727 |
+
)
|
| 728 |
+
if not getattr(
|
| 729 |
+
self.vae_net, "supports_temporal_kv_cache", False
|
| 730 |
+
):
|
| 731 |
+
raise NotImplementedError(
|
| 732 |
+
f"{type(self.vae_net).__name__} does not support temporal "
|
| 733 |
+
"KV-cache decoding"
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
latent_new = latent_new.to(self.decoder_dtype)
|
| 737 |
+
latent_std = self.latent_std.to(self.decoder_dtype)
|
| 738 |
+
latent_mean = self.latent_mean.to(self.decoder_dtype)
|
| 739 |
+
latent_new = latent_new * latent_std + latent_mean
|
| 740 |
+
decode_kwargs = {
|
| 741 |
+
"temporal_kv_cache": temporal_kv_cache,
|
| 742 |
+
"return_validity": self.predict_validity,
|
| 743 |
+
}
|
| 744 |
+
if max_cache_frames is not None:
|
| 745 |
+
decode_kwargs["max_cache_frames"] = max_cache_frames
|
| 746 |
+
decoded, new_cache = self.vae_net.decode_stream(
|
| 747 |
+
latent_new, **decode_kwargs
|
| 748 |
+
)
|
| 749 |
+
validity = None
|
| 750 |
+
if self.predict_validity:
|
| 751 |
+
out, logits = decoded
|
| 752 |
+
validity = torch.sigmoid(logits.to(out.dtype))
|
| 753 |
+
if self.apply_validity_mask:
|
| 754 |
+
out = out.masked_fill(validity < 0.5, self.invalid_fill)
|
| 755 |
+
else:
|
| 756 |
+
out = decoded
|
| 757 |
+
|
| 758 |
+
if return_validity:
|
| 759 |
+
return out, validity, new_cache
|
| 760 |
+
return out, new_cache
|
| 761 |
+
|
| 762 |
+
def reset_dtype(self, *args, **kwargs):
|
| 763 |
+
del args, kwargs
|
| 764 |
+
self._reset_module_dtypes()
|
| 765 |
+
|
| 766 |
+
@property
|
| 767 |
+
def spatial_compression_factor(self) -> int:
|
| 768 |
+
return self._spatial_compression
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
class SDVAE(BaseVAE):
|
| 772 |
+
def __init__(self, batch_size=16, count_std: bool = False, is_downsample: bool = True) -> None:
|
| 773 |
+
super().__init__(channel=4, name="sd_vae")
|
| 774 |
+
self.dtype = torch.bfloat16
|
| 775 |
+
self.register_buffer(
|
| 776 |
+
"scale",
|
| 777 |
+
torch.tensor([4.17, 4.62, 3.71, 3.28], dtype=self.dtype).reciprocal().reshape(1, -1, 1, 1),
|
| 778 |
+
persistent=False,
|
| 779 |
+
)
|
| 780 |
+
self.register_buffer(
|
| 781 |
+
"bias",
|
| 782 |
+
-1.0 * torch.tensor([5.81, 3.25, 0.12, -2.15], dtype=self.dtype).reshape(1, -1, 1, 1) * self.scale,
|
| 783 |
+
persistent=False,
|
| 784 |
+
)
|
| 785 |
+
self.batch_size = batch_size
|
| 786 |
+
self.count_std = count_std
|
| 787 |
+
self.is_downsample = is_downsample
|
| 788 |
+
self.load_vae()
|
| 789 |
+
self.reset_dtype()
|
| 790 |
+
|
| 791 |
+
def reset_dtype(self, *args, **kwargs):
|
| 792 |
+
del args, kwargs
|
| 793 |
+
self.vae.to(self.dtype)
|
| 794 |
+
|
| 795 |
+
@rank0_first
|
| 796 |
+
def load_vae(self) -> None:
|
| 797 |
+
os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
|
| 798 |
+
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
|
| 799 |
+
import diffusers
|
| 800 |
+
|
| 801 |
+
vae_name = "stabilityai/sd-vae-ft-mse"
|
| 802 |
+
try:
|
| 803 |
+
vae = diffusers.models.AutoencoderKL.from_pretrained(vae_name, local_files_only=True)
|
| 804 |
+
except: # noqa: E722
|
| 805 |
+
# Could not load the model from cache; try without local_files_only.
|
| 806 |
+
vae = diffusers.models.AutoencoderKL.from_pretrained(vae_name)
|
| 807 |
+
self.vae = vae.eval().requires_grad_(False)
|
| 808 |
+
|
| 809 |
+
@torch.no_grad()
|
| 810 |
+
def encode(self, state: torch.Tensor) -> torch.Tensor:
|
| 811 |
+
"""
|
| 812 |
+
state : pixel range [-1, 1]
|
| 813 |
+
"""
|
| 814 |
+
if self.is_downsample:
|
| 815 |
+
_h, _w = state.shape[-2:]
|
| 816 |
+
state = F.interpolate(state, size=(_h // 2, _w // 2), mode="bilinear", align_corners=False)
|
| 817 |
+
in_dtype = state.dtype
|
| 818 |
+
state = state.to(self.dtype)
|
| 819 |
+
state = (state + 1.0) / 2.0
|
| 820 |
+
latent_dist = self.vae.encode(state)["latent_dist"]
|
| 821 |
+
mean, std = latent_dist.mean, latent_dist.std
|
| 822 |
+
if self.count_std:
|
| 823 |
+
latent = mean + torch.randn_like(mean) * std
|
| 824 |
+
else:
|
| 825 |
+
latent = mean
|
| 826 |
+
latent = latent * self.scale
|
| 827 |
+
latent = latent + self.bias
|
| 828 |
+
return latent.to(in_dtype)
|
| 829 |
+
|
| 830 |
+
@torch.no_grad()
|
| 831 |
+
def decode(self, latent: torch.Tensor) -> torch.Tensor:
|
| 832 |
+
in_dtype = latent.dtype
|
| 833 |
+
latent = latent.to(self.dtype)
|
| 834 |
+
latent = latent - self.bias
|
| 835 |
+
latent = latent / self.scale
|
| 836 |
+
latent = torch.cat([self.vae.decode(batch)["sample"] for batch in latent.split(self.batch_size)])
|
| 837 |
+
if self.is_downsample:
|
| 838 |
+
_h, _w = latent.shape[-2:]
|
| 839 |
+
latent = F.interpolate(latent, size=(_h * 2, _w * 2), mode="bilinear", align_corners=False)
|
| 840 |
+
return latent.to(in_dtype) * 2 - 1.0
|
| 841 |
+
|
| 842 |
+
@property
|
| 843 |
+
def spatial_compression_factor(self) -> int:
|
| 844 |
+
return 8
|
diffusion/training/module/vae_utils.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Build the public tokenizer architecture from its experiment config."""
|
| 5 |
+
|
| 6 |
+
import importlib
|
| 7 |
+
from copy import deepcopy
|
| 8 |
+
|
| 9 |
+
from omegaconf import DictConfig
|
| 10 |
+
|
| 11 |
+
from tokenizer.training.configs.base.nets.lidarverse import (
|
| 12 |
+
LIDARVERSE_TOKENIZER_CONFIG,
|
| 13 |
+
PAI_TOKENIZER_NAME,
|
| 14 |
+
)
|
| 15 |
+
from utils.lazy_config import instantiate
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def build_vae_from_tokenizer_experiment(experiment_name: str, **overrides):
|
| 19 |
+
"""Instantiate a tokenizer network without loading checkpoint weights."""
|
| 20 |
+
if experiment_name == PAI_TOKENIZER_NAME:
|
| 21 |
+
# The PAI expert has the same GridRoPE architecture, different weights.
|
| 22 |
+
network = deepcopy(LIDARVERSE_TOKENIZER_CONFIG)
|
| 23 |
+
network.activation_checkpointing = False
|
| 24 |
+
network.update(overrides)
|
| 25 |
+
return instantiate(network)
|
| 26 |
+
|
| 27 |
+
module = importlib.import_module(
|
| 28 |
+
f"tokenizer.training.configs.experiments.{experiment_name}"
|
| 29 |
+
)
|
| 30 |
+
experiment = getattr(module, "config", None)
|
| 31 |
+
if not isinstance(experiment, DictConfig):
|
| 32 |
+
experiment = next(
|
| 33 |
+
(
|
| 34 |
+
value
|
| 35 |
+
for value in vars(module).values()
|
| 36 |
+
if isinstance(value, DictConfig) and "defaults" in value
|
| 37 |
+
),
|
| 38 |
+
None,
|
| 39 |
+
)
|
| 40 |
+
if experiment is None:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
f"Tokenizer experiment {experiment_name!r} has no config"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
network_name = None
|
| 46 |
+
for entry in experiment["defaults"]:
|
| 47 |
+
try:
|
| 48 |
+
network_name = entry["override /network"]
|
| 49 |
+
except (KeyError, TypeError):
|
| 50 |
+
continue
|
| 51 |
+
break
|
| 52 |
+
if network_name != "lidarverse_tokenizer":
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Unsupported public tokenizer network: {network_name!r}"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
network = deepcopy(LIDARVERSE_TOKENIZER_CONFIG)
|
| 58 |
+
try:
|
| 59 |
+
experiment_overrides = experiment["model"]["config"]["network"]
|
| 60 |
+
except (KeyError, TypeError):
|
| 61 |
+
experiment_overrides = None
|
| 62 |
+
if isinstance(experiment_overrides, DictConfig):
|
| 63 |
+
for key in experiment_overrides:
|
| 64 |
+
network[key] = experiment_overrides[key]
|
| 65 |
+
for key, value in overrides.items():
|
| 66 |
+
network[key] = value
|
| 67 |
+
return instantiate(network)
|