Depth Estimation
Transformers
Safetensors
camera_depth_model
feature-extraction
camera-depth-model
rgbd
robotics
custom_code
Instructions to use bigshanedogg/Camera-Depth-Model-D405 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use bigshanedogg/Camera-Depth-Model-D405 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("depth-estimation", model="bigshanedogg/Camera-Depth-Model-D405", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("bigshanedogg/Camera-Depth-Model-D405", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload Camera-Depth-Model-D405 (transformers port, original code)
Browse files- LICENSE +408 -0
- LICENSE.code +175 -0
- NOTICE +24 -0
- README.md +83 -0
- cdm_dinov2.py +1130 -0
- cdm_dpt.py +730 -0
- config.json +25 -0
- configuration_camera_depth_model.py +26 -0
- image_processing_camera_depth_model.py +93 -0
- model.safetensors +3 -0
- modeling_camera_depth_model.py +88 -0
- processing_camera_depth_model.py +19 -0
- processor_config.json +16 -0
LICENSE
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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0 International
|
| 2 |
+
|
| 3 |
+
=======================================================================
|
| 4 |
+
|
| 5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 6 |
+
does not provide legal services or legal advice. Distribution of
|
| 7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 8 |
+
other relationship. Creative Commons makes its licenses and related
|
| 9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 10 |
+
warranties regarding its licenses, any material licensed under their
|
| 11 |
+
terms and conditions, or any related information. Creative Commons
|
| 12 |
+
disclaims all liability for damages resulting from their use to the
|
| 13 |
+
fullest extent possible.
|
| 14 |
+
|
| 15 |
+
Using Creative Commons Public Licenses
|
| 16 |
+
|
| 17 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 18 |
+
conditions that creators and other rights holders may use to share
|
| 19 |
+
original works of authorship and other material subject to copyright
|
| 20 |
+
and certain other rights specified in the public license below. The
|
| 21 |
+
following considerations are for informational purposes only, are not
|
| 22 |
+
exhaustive, and do not form part of our licenses.
|
| 23 |
+
|
| 24 |
+
Considerations for licensors: Our public licenses are
|
| 25 |
+
intended for use by those authorized to give the public
|
| 26 |
+
permission to use material in ways otherwise restricted by
|
| 27 |
+
copyright and certain other rights. Our licenses are
|
| 28 |
+
irrevocable. Licensors should read and understand the terms
|
| 29 |
+
and conditions of the license they choose before applying it.
|
| 30 |
+
Licensors should also secure all rights necessary before
|
| 31 |
+
applying our licenses so that the public can reuse the
|
| 32 |
+
material as expected. Licensors should clearly mark any
|
| 33 |
+
material not subject to the license. This includes other CC-
|
| 34 |
+
licensed material, or material used under an exception or
|
| 35 |
+
limitation to copyright. More considerations for licensors:
|
| 36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
| 37 |
+
|
| 38 |
+
Considerations for the public: By using one of our public
|
| 39 |
+
licenses, a licensor grants the public permission to use the
|
| 40 |
+
licensed material under specified terms and conditions. If
|
| 41 |
+
the licensor's permission is not necessary for any reason--for
|
| 42 |
+
example, because of any applicable exception or limitation to
|
| 43 |
+
copyright--then that use is not regulated by the license. Our
|
| 44 |
+
licenses grant only permissions under copyright and certain
|
| 45 |
+
other rights that a licensor has authority to grant. Use of
|
| 46 |
+
the licensed material may still be restricted for other
|
| 47 |
+
reasons, including because others have copyright or other
|
| 48 |
+
rights in the material. A licensor may make special requests,
|
| 49 |
+
such as asking that all changes be marked or described.
|
| 50 |
+
Although not required by our licenses, you are encouraged to
|
| 51 |
+
respect those requests where reasonable. More considerations
|
| 52 |
+
for the public:
|
| 53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
| 54 |
+
|
| 55 |
+
=======================================================================
|
| 56 |
+
|
| 57 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
| 58 |
+
License
|
| 59 |
+
|
| 60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 61 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 62 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
| 63 |
+
License"). To the extent this Public License may be interpreted as a
|
| 64 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
| 65 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
| 66 |
+
such rights in consideration of benefits the Licensor receives from
|
| 67 |
+
making the Licensed Material available under these terms and
|
| 68 |
+
conditions.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
Section 1 -- Definitions.
|
| 72 |
+
|
| 73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
| 74 |
+
Rights that is derived from or based upon the Licensed Material
|
| 75 |
+
and in which the Licensed Material is translated, altered,
|
| 76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
| 77 |
+
permission under the Copyright and Similar Rights held by the
|
| 78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
| 79 |
+
Material is a musical work, performance, or sound recording,
|
| 80 |
+
Adapted Material is always produced where the Licensed Material is
|
| 81 |
+
synched in timed relation with a moving image.
|
| 82 |
+
|
| 83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
| 84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
| 85 |
+
accordance with the terms and conditions of this Public License.
|
| 86 |
+
|
| 87 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
| 88 |
+
closely related to copyright including, without limitation,
|
| 89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 90 |
+
Rights, without regard to how the rights are labeled or
|
| 91 |
+
categorized. For purposes of this Public License, the rights
|
| 92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
| 93 |
+
Rights.
|
| 94 |
+
d. Effective Technological Measures means those measures that, in the
|
| 95 |
+
absence of proper authority, may not be circumvented under laws
|
| 96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
| 97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
| 98 |
+
agreements.
|
| 99 |
+
|
| 100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 101 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 102 |
+
that applies to Your use of the Licensed Material.
|
| 103 |
+
|
| 104 |
+
f. Licensed Material means the artistic or literary work, database,
|
| 105 |
+
or other material to which the Licensor applied this Public
|
| 106 |
+
License.
|
| 107 |
+
|
| 108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
| 109 |
+
terms and conditions of this Public License, which are limited to
|
| 110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 111 |
+
Licensed Material and that the Licensor has authority to license.
|
| 112 |
+
|
| 113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
| 114 |
+
under this Public License.
|
| 115 |
+
|
| 116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
| 117 |
+
commercial advantage or monetary compensation. For purposes of
|
| 118 |
+
this Public License, the exchange of the Licensed Material for
|
| 119 |
+
other material subject to Copyright and Similar Rights by digital
|
| 120 |
+
file-sharing or similar means is NonCommercial provided there is
|
| 121 |
+
no payment of monetary compensation in connection with the
|
| 122 |
+
exchange.
|
| 123 |
+
|
| 124 |
+
j. Share means to provide material to the public by any means or
|
| 125 |
+
process that requires permission under the Licensed Rights, such
|
| 126 |
+
as reproduction, public display, public performance, distribution,
|
| 127 |
+
dissemination, communication, or importation, and to make material
|
| 128 |
+
available to the public including in ways that members of the
|
| 129 |
+
public may access the material from a place and at a time
|
| 130 |
+
individually chosen by them.
|
| 131 |
+
|
| 132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
| 133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 135 |
+
as amended and/or succeeded, as well as other essentially
|
| 136 |
+
equivalent rights anywhere in the world.
|
| 137 |
+
|
| 138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
| 139 |
+
under this Public License. Your has a corresponding meaning.
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
Section 2 -- Scope.
|
| 143 |
+
|
| 144 |
+
a. License grant.
|
| 145 |
+
|
| 146 |
+
1. Subject to the terms and conditions of this Public License,
|
| 147 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 148 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 149 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 150 |
+
|
| 151 |
+
a. reproduce and Share the Licensed Material, in whole or
|
| 152 |
+
in part, for NonCommercial purposes only; and
|
| 153 |
+
|
| 154 |
+
b. produce, reproduce, and Share Adapted Material for
|
| 155 |
+
NonCommercial purposes only.
|
| 156 |
+
|
| 157 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 158 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 159 |
+
License does not apply, and You do not need to comply with
|
| 160 |
+
its terms and conditions.
|
| 161 |
+
|
| 162 |
+
3. Term. The term of this Public License is specified in Section
|
| 163 |
+
6(a).
|
| 164 |
+
|
| 165 |
+
4. Media and formats; technical modifications allowed. The
|
| 166 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
| 167 |
+
all media and formats whether now known or hereafter created,
|
| 168 |
+
and to make technical modifications necessary to do so. The
|
| 169 |
+
Licensor waives and/or agrees not to assert any right or
|
| 170 |
+
authority to forbid You from making technical modifications
|
| 171 |
+
necessary to exercise the Licensed Rights, including
|
| 172 |
+
technical modifications necessary to circumvent Effective
|
| 173 |
+
Technological Measures. For purposes of this Public License,
|
| 174 |
+
simply making modifications authorized by this Section 2(a)
|
| 175 |
+
(4) never produces Adapted Material.
|
| 176 |
+
|
| 177 |
+
5. Downstream recipients.
|
| 178 |
+
|
| 179 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
| 180 |
+
recipient of the Licensed Material automatically
|
| 181 |
+
receives an offer from the Licensor to exercise the
|
| 182 |
+
Licensed Rights under the terms and conditions of this
|
| 183 |
+
Public License.
|
| 184 |
+
|
| 185 |
+
b. No downstream restrictions. You may not offer or impose
|
| 186 |
+
any additional or different terms or conditions on, or
|
| 187 |
+
apply any Effective Technological Measures to, the
|
| 188 |
+
Licensed Material if doing so restricts exercise of the
|
| 189 |
+
Licensed Rights by any recipient of the Licensed
|
| 190 |
+
Material.
|
| 191 |
+
|
| 192 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
| 193 |
+
may be construed as permission to assert or imply that You
|
| 194 |
+
are, or that Your use of the Licensed Material is, connected
|
| 195 |
+
with, or sponsored, endorsed, or granted official status by,
|
| 196 |
+
the Licensor or others designated to receive attribution as
|
| 197 |
+
provided in Section 3(a)(1)(A)(i).
|
| 198 |
+
|
| 199 |
+
b. Other rights.
|
| 200 |
+
|
| 201 |
+
1. Moral rights, such as the right of integrity, are not
|
| 202 |
+
licensed under this Public License, nor are publicity,
|
| 203 |
+
privacy, and/or other similar personality rights; however, to
|
| 204 |
+
the extent possible, the Licensor waives and/or agrees not to
|
| 205 |
+
assert any such rights held by the Licensor to the limited
|
| 206 |
+
extent necessary to allow You to exercise the Licensed
|
| 207 |
+
Rights, but not otherwise.
|
| 208 |
+
|
| 209 |
+
2. Patent and trademark rights are not licensed under this
|
| 210 |
+
Public License.
|
| 211 |
+
|
| 212 |
+
3. To the extent possible, the Licensor waives any right to
|
| 213 |
+
collect royalties from You for the exercise of the Licensed
|
| 214 |
+
Rights, whether directly or through a collecting society
|
| 215 |
+
under any voluntary or waivable statutory or compulsory
|
| 216 |
+
licensing scheme. In all other cases the Licensor expressly
|
| 217 |
+
reserves any right to collect such royalties, including when
|
| 218 |
+
the Licensed Material is used other than for NonCommercial
|
| 219 |
+
purposes.
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
Section 3 -- License Conditions.
|
| 223 |
+
|
| 224 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 225 |
+
following conditions.
|
| 226 |
+
|
| 227 |
+
a. Attribution.
|
| 228 |
+
|
| 229 |
+
1. If You Share the Licensed Material (including in modified
|
| 230 |
+
form), You must:
|
| 231 |
+
|
| 232 |
+
a. retain the following if it is supplied by the Licensor
|
| 233 |
+
with the Licensed Material:
|
| 234 |
+
|
| 235 |
+
i. identification of the creator(s) of the Licensed
|
| 236 |
+
Material and any others designated to receive
|
| 237 |
+
attribution, in any reasonable manner requested by
|
| 238 |
+
the Licensor (including by pseudonym if
|
| 239 |
+
designated);
|
| 240 |
+
|
| 241 |
+
ii. a copyright notice;
|
| 242 |
+
|
| 243 |
+
iii. a notice that refers to this Public License;
|
| 244 |
+
|
| 245 |
+
iv. a notice that refers to the disclaimer of
|
| 246 |
+
warranties;
|
| 247 |
+
|
| 248 |
+
v. a URI or hyperlink to the Licensed Material to the
|
| 249 |
+
extent reasonably practicable;
|
| 250 |
+
|
| 251 |
+
b. indicate if You modified the Licensed Material and
|
| 252 |
+
retain an indication of any previous modifications; and
|
| 253 |
+
|
| 254 |
+
c. indicate the Licensed Material is licensed under this
|
| 255 |
+
Public License, and include the text of, or the URI or
|
| 256 |
+
hyperlink to, this Public License.
|
| 257 |
+
|
| 258 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 259 |
+
reasonable manner based on the medium, means, and context in
|
| 260 |
+
which You Share the Licensed Material. For example, it may be
|
| 261 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 262 |
+
hyperlink to a resource that includes the required
|
| 263 |
+
information.
|
| 264 |
+
|
| 265 |
+
3. If requested by the Licensor, You must remove any of the
|
| 266 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 267 |
+
reasonably practicable.
|
| 268 |
+
|
| 269 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
| 270 |
+
License You apply must not prevent recipients of the Adapted
|
| 271 |
+
Material from complying with this Public License.
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
Section 4 -- Sui Generis Database Rights.
|
| 275 |
+
|
| 276 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
| 277 |
+
apply to Your use of the Licensed Material:
|
| 278 |
+
|
| 279 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 280 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
| 281 |
+
portion of the contents of the database for NonCommercial purposes
|
| 282 |
+
only;
|
| 283 |
+
|
| 284 |
+
b. if You include all or a substantial portion of the database
|
| 285 |
+
contents in a database in which You have Sui Generis Database
|
| 286 |
+
Rights, then the database in which You have Sui Generis Database
|
| 287 |
+
Rights (but not its individual contents) is Adapted Material; and
|
| 288 |
+
|
| 289 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
| 290 |
+
all or a substantial portion of the contents of the database.
|
| 291 |
+
|
| 292 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 293 |
+
replace Your obligations under this Public License where the Licensed
|
| 294 |
+
Rights include other Copyright and Similar Rights.
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
| 298 |
+
|
| 299 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
| 300 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
| 301 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
| 302 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
| 303 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
| 304 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
| 305 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
| 306 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
| 307 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
| 308 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
| 309 |
+
|
| 310 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
| 311 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
| 312 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
| 313 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
| 314 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
| 315 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
| 316 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
| 317 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
| 318 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
| 319 |
+
|
| 320 |
+
c. The disclaimer of warranties and limitation of liability provided
|
| 321 |
+
above shall be interpreted in a manner that, to the extent
|
| 322 |
+
possible, most closely approximates an absolute disclaimer and
|
| 323 |
+
waiver of all liability.
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
Section 6 -- Term and Termination.
|
| 327 |
+
|
| 328 |
+
a. This Public License applies for the term of the Copyright and
|
| 329 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 330 |
+
this Public License, then Your rights under this Public License
|
| 331 |
+
terminate automatically.
|
| 332 |
+
|
| 333 |
+
b. Where Your right to use the Licensed Material has terminated under
|
| 334 |
+
Section 6(a), it reinstates:
|
| 335 |
+
|
| 336 |
+
1. automatically as of the date the violation is cured, provided
|
| 337 |
+
it is cured within 30 days of Your discovery of the
|
| 338 |
+
violation; or
|
| 339 |
+
|
| 340 |
+
2. upon express reinstatement by the Licensor.
|
| 341 |
+
|
| 342 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 343 |
+
right the Licensor may have to seek remedies for Your violations
|
| 344 |
+
of this Public License.
|
| 345 |
+
|
| 346 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
| 347 |
+
Licensed Material under separate terms or conditions or stop
|
| 348 |
+
distributing the Licensed Material at any time; however, doing so
|
| 349 |
+
will not terminate this Public License.
|
| 350 |
+
|
| 351 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 352 |
+
License.
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
Section 7 -- Other Terms and Conditions.
|
| 356 |
+
|
| 357 |
+
a. The Licensor shall not be bound by any additional or different
|
| 358 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 359 |
+
|
| 360 |
+
b. Any arrangements, understandings, or agreements regarding the
|
| 361 |
+
Licensed Material not stated herein are separate from and
|
| 362 |
+
independent of the terms and conditions of this Public License.
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
Section 8 -- Interpretation.
|
| 366 |
+
|
| 367 |
+
a. For the avoidance of doubt, this Public License does not, and
|
| 368 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 369 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 370 |
+
be made without permission under this Public License.
|
| 371 |
+
|
| 372 |
+
b. To the extent possible, if any provision of this Public License is
|
| 373 |
+
deemed unenforceable, it shall be automatically reformed to the
|
| 374 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 375 |
+
cannot be reformed, it shall be severed from this Public License
|
| 376 |
+
without affecting the enforceability of the remaining terms and
|
| 377 |
+
conditions.
|
| 378 |
+
|
| 379 |
+
c. No term or condition of this Public License will be waived and no
|
| 380 |
+
failure to comply consented to unless expressly agreed to by the
|
| 381 |
+
Licensor.
|
| 382 |
+
|
| 383 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
| 384 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 385 |
+
that apply to the Licensor or You, including from the legal
|
| 386 |
+
processes of any jurisdiction or authority.
|
| 387 |
+
|
| 388 |
+
=======================================================================
|
| 389 |
+
|
| 390 |
+
Creative Commons is not a party to its public
|
| 391 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
| 392 |
+
its public licenses to material it publishes and in those instances
|
| 393 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
| 394 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
| 395 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
| 396 |
+
material is shared under a Creative Commons public license or as
|
| 397 |
+
otherwise permitted by the Creative Commons policies published at
|
| 398 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
| 399 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
| 400 |
+
of Creative Commons without its prior written consent including,
|
| 401 |
+
without limitation, in connection with any unauthorized modifications
|
| 402 |
+
to any of its public licenses or any other arrangements,
|
| 403 |
+
understandings, or agreements concerning use of licensed material. For
|
| 404 |
+
the avoidance of doubt, this paragraph does not form part of the
|
| 405 |
+
public licenses.
|
| 406 |
+
|
| 407 |
+
Creative Commons may be contacted at creativecommons.org.
|
| 408 |
+
|
LICENSE.code
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
NOTICE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Camera-Depth-Model-D405 -- unofficial transformers-format package (trust_remote_code)
|
| 2 |
+
Packaged by bigshanedogg, 2026. NOT an official release of the original authors.
|
| 3 |
+
|
| 4 |
+
Components
|
| 5 |
+
----------
|
| 6 |
+
1. Camera Depth Model weights (cdm_d405.ckpt)
|
| 7 |
+
Source: https://huggingface.co/depth-anything/camera-depth-model-d405
|
| 8 |
+
Copyright: Minghuan Liu, Zhengbang Zhu, Xiaoshen Han, Peng Hu, Haotong Lin, Xinyao Li, Jingxiao Chen, Jiafeng Xu, Yichu Yang, Yunfeng Lin, Xinghang Li, Yong Yu, Weinan Zhang, Tao Kong, Bingyi Kang (ByteDance Seed)
|
| 9 |
+
License: CC-BY-NC-4.0 (non-commercial) -- LICENSE
|
| 10 |
+
2. Camera Depth Model code (cdm/rgbddepth/ incl. its DINOv2 copy, vendored into cdm_*.py; cdm/infer.py load_images / load_model steps in the image processor and build)
|
| 11 |
+
Source: https://github.com/ByteDance-Seed/manip-as-in-sim-suite @ 757b2ea26bcf7992c92ac80485d82b905e961850
|
| 12 |
+
Copyright: Copyright (c) 2025 Bytedance Ltd. and/or its affiliates; DINOv2 layers Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 13 |
+
License: Apache-2.0 -- LICENSE.code
|
| 14 |
+
|
| 15 |
+
Changes made in this package
|
| 16 |
+
----------------------------
|
| 17 |
+
- cdm_*.py: the official files concatenated into flat files; package-internal imports replaced by relative imports; NestedTensorBlock spelled out where dinov2.py imported it as Block. No computation changed.
|
| 18 |
+
- configuration_ / modeling_ / image_processing_ / processing_camera_depth_model.py: new transformers wrappers; the model runs RGBDDepth.forward / image2tensor; the image processor is infer.py load_images + image2tensor.
|
| 19 |
+
- model.safetensors: the checkpoint's model state dict (prefix removed as infer.py load_model), converted by save_pretrained, every tensor checked equal. The Lightning checkpoint's training state and its unused _mean / _std (ImageNet statistics; the original strict=False load ignores them) dropped.
|
| 20 |
+
|
| 21 |
+
License files
|
| 22 |
+
-------------
|
| 23 |
+
- LICENSE: Creative Commons Attribution-NonCommercial 4.0 International (weights)
|
| 24 |
+
- LICENSE.code: Apache License 2.0, copy from ByteDance-Seed/manip-as-in-sim-suite (code)
|
README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
library_name: transformers
|
| 4 |
+
base_model: depth-anything/camera-depth-model-d405
|
| 5 |
+
tags:
|
| 6 |
+
- camera-depth-model
|
| 7 |
+
- depth-estimation
|
| 8 |
+
- rgbd
|
| 9 |
+
- robotics
|
| 10 |
+
pipeline_tag: depth-estimation
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# Camera-Depth-Model-D405 — transformers format (original code)
|
| 14 |
+
|
| 15 |
+
Unofficial transformers port of the **Camera Depth Model** (CDM) `depth-anything/camera-depth-model-d405` (`cdm_d405.ckpt`) that runs
|
| 16 |
+
the **original** code. Loads with `trust_remote_code`. `model.safetensors` holds the checkpoint's model tensors under
|
| 17 |
+
their original names (every tensor checked equal). Trained for the **Intel RealSense D405** (camera-specific noise model).
|
| 18 |
+
|
| 19 |
+
> **Not an official release.** Camera Depth Models were created by Minghuan Liu, Zhengbang Zhu, Xiaoshen Han, Peng Hu,
|
| 20 |
+
> Haotong Lin, Xinyao Li, Jingxiao Chen, Jiafeng Xu, Yichu Yang, Yunfeng Lin, Xinghang Li, Yong Yu, Weinan Zhang, Tao
|
| 21 |
+
> Kong and Bingyi Kang (ByteDance Seed) — https://github.com/ByteDance-Seed/manip-as-in-sim-suite, paper *"Manipulation
|
| 22 |
+
> as in Simulation: Enabling Accurate Geometry Perception in Robots"* (arXiv 2509.02530).
|
| 23 |
+
|
| 24 |
+
## What it is
|
| 25 |
+
|
| 26 |
+
Denoised metric depth from an RGB image plus the raw depth of a depth camera. `CameraDepthModelForDepthEstimation`
|
| 27 |
+
holds the official `RGBDDepth`'s submodules (`pretrained` / `depth_pretrained`: two DINOv2 ViT-L/14, `crossAtts`,
|
| 28 |
+
`depth_head_rgbd`) and computes depth with that class's own `forward`, returning the standard `DepthEstimatorOutput`
|
| 29 |
+
(`predicted_depth`: **inverse depth**; meters = `1 / predicted_depth`, as the original `infer.py`); the official
|
| 30 |
+
`infer_image` and `image2tensor` are kept. Code vendored from ByteDance-Seed/manip-as-in-sim-suite @ 757b2ea2 (`cdm/rgbddepth/`)
|
| 31 |
+
into `cdm_dinov2.py` / `cdm_dpt.py`; edits: imports, and `Block` → `NestedTensorBlock` where the original imported
|
| 32 |
+
`NestedTensorBlock as Block`. `CameraDepthModelProcessor` (`processing_camera_depth_model.py`, `processor_config.json`)
|
| 33 |
+
wraps `CameraDepthModelImageProcessor`: `infer.py`'s `load_images` (raw depth / 1000, values above 25 m set to 0,
|
| 34 |
+
inverse depth) and `image2tensor`.
|
| 35 |
+
|
| 36 |
+
As in the original `infer.py` and README API, the image is given as RGB and `image2tensor` applies
|
| 37 |
+
`cv2.COLOR_BGR2RGB` to it, so the network sees the channels swapped. This port keeps that behaviour unchanged.
|
| 38 |
+
|
| 39 |
+
Verified against the official code (same process, V100): preprocessing (image and depth), `predicted_depth` (also as
|
| 40 |
+
a tuple), the hidden states, `infer_image`, the post-processing and fp16 autocast outputs are **bit-identical**.
|
| 41 |
+
|
| 42 |
+
## Usage
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
import torch
|
| 46 |
+
from transformers import AutoModelForDepthEstimation, AutoProcessor
|
| 47 |
+
|
| 48 |
+
model = AutoModelForDepthEstimation.from_pretrained("Camera-Depth-Model-D405", trust_remote_code=True).eval().cuda()
|
| 49 |
+
processor = AutoProcessor.from_pretrained("Camera-Depth-Model-D405", trust_remote_code=True)
|
| 50 |
+
# image: path / PIL / RGB uint8 array; depth: the camera's raw depth png (millimeters, depth_scale=1000) or meters
|
| 51 |
+
inputs = processor(images="rgb.png", depth="depth.png", return_tensors="pt").to("cuda")
|
| 52 |
+
with torch.no_grad():
|
| 53 |
+
outputs = model(**inputs) # outputs.predicted_depth: (1, H', W') inverse depth
|
| 54 |
+
inverse = processor.post_process_depth_estimation(outputs, target_sizes=[(height, width)])[0]["predicted_depth"]
|
| 55 |
+
depth_m = 1 / inverse
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
- `AutoModel` loads the same class. `output_hidden_states=True` adds the DINOv2 features of the RGB and depth branches; `return_dict=False` returns a tuple.
|
| 59 |
+
- `post_process_depth_estimation` resizes as the original `infer_image` (nearest).
|
| 60 |
+
- `depth_scale` / `max_depth` of the processor: the original's `--depth-scale` (1000) and the 25 m cut-off `infer.py` uses.
|
| 61 |
+
|
| 62 |
+
Runtime packages beyond torch / transformers: `opencv-python`, `torchvision` (as the original).
|
| 63 |
+
|
| 64 |
+
## Licensing
|
| 65 |
+
|
| 66 |
+
- Weights (`depth-anything/camera-depth-model-d405`): **CC-BY-NC-4.0** (non-commercial) — [`LICENSE`](LICENSE).
|
| 67 |
+
- Code (vendored files and the port): **Apache-2.0** — [`LICENSE.code`](LICENSE.code).
|
| 68 |
+
- Attribution, sources and the changes made here: [`NOTICE`](NOTICE).
|
| 69 |
+
|
| 70 |
+
## Citation
|
| 71 |
+
|
| 72 |
+
If you use this model, please cite the original work, as its authors ask:
|
| 73 |
+
|
| 74 |
+
```bibtex
|
| 75 |
+
@article{liu2025manipulation,
|
| 76 |
+
title={Manipulation as in Simulation: Enabling Accurate Geometry Perception in Robots},
|
| 77 |
+
author={Liu, Minghuan and Zhu, Zhengbang and Han, Xiaoshen and Hu, Peng and Lin, Haotong and
|
| 78 |
+
Li, Xinyao and Chen, Jingxiao and Xu, Jiafeng and Yang, Yichu and Lin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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ruff: noqa
|
| 2 |
+
# fmt: off
|
| 3 |
+
"""Camera Depth Model (CDM), vendored verbatim from ByteDance-Seed/manip-as-in-sim-suite @ 757b2ea26bcf7992c92ac80485d82b905e961850 (cdm/rgbddepth/): the
|
| 4 |
+
files below concatenated, package-internal imports replaced by relative imports of the other vendored files
|
| 5 |
+
(generated by scripts/model_ports/common/vendor_flat.py; do not edit by hand). Code license: Apache-2.0."""
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# ==============================================================================================================
|
| 9 |
+
# rgbddepth/dinov2_layers/mlp.py
|
| 10 |
+
# ==============================================================================================================
|
| 11 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 12 |
+
# All rights reserved.
|
| 13 |
+
#
|
| 14 |
+
# This source code is licensed under the license found in the
|
| 15 |
+
# LICENSE file in the root directory of this source tree.
|
| 16 |
+
|
| 17 |
+
# References:
|
| 18 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 19 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
from typing import Callable, Optional
|
| 23 |
+
|
| 24 |
+
from torch import Tensor, nn
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Mlp(nn.Module):
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
in_features: int,
|
| 31 |
+
hidden_features: Optional[int] = None,
|
| 32 |
+
out_features: Optional[int] = None,
|
| 33 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 34 |
+
drop: float = 0.0,
|
| 35 |
+
bias: bool = True,
|
| 36 |
+
) -> None:
|
| 37 |
+
super().__init__()
|
| 38 |
+
out_features = out_features or in_features
|
| 39 |
+
hidden_features = hidden_features or in_features
|
| 40 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
|
| 41 |
+
self.act = act_layer()
|
| 42 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 43 |
+
self.drop = nn.Dropout(drop)
|
| 44 |
+
|
| 45 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 46 |
+
x = self.fc1(x)
|
| 47 |
+
x = self.act(x)
|
| 48 |
+
x = self.drop(x)
|
| 49 |
+
x = self.fc2(x)
|
| 50 |
+
x = self.drop(x)
|
| 51 |
+
return x
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ==============================================================================================================
|
| 55 |
+
# rgbddepth/dinov2_layers/patch_embed.py
|
| 56 |
+
# ==============================================================================================================
|
| 57 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 58 |
+
# All rights reserved.
|
| 59 |
+
#
|
| 60 |
+
# This source code is licensed under the license found in the
|
| 61 |
+
# LICENSE file in the root directory of this source tree.
|
| 62 |
+
|
| 63 |
+
# References:
|
| 64 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 65 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
|
| 66 |
+
|
| 67 |
+
from typing import Callable, Optional, Tuple, Union
|
| 68 |
+
|
| 69 |
+
import torch.nn as nn
|
| 70 |
+
from torch import Tensor
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def make_2tuple(x):
|
| 74 |
+
if isinstance(x, tuple):
|
| 75 |
+
assert len(x) == 2
|
| 76 |
+
return x
|
| 77 |
+
|
| 78 |
+
assert isinstance(x, int)
|
| 79 |
+
return (x, x)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class PatchEmbed(nn.Module):
|
| 83 |
+
"""
|
| 84 |
+
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
img_size: Image size.
|
| 88 |
+
patch_size: Patch token size.
|
| 89 |
+
in_chans: Number of input image channels.
|
| 90 |
+
embed_dim: Number of linear projection output channels.
|
| 91 |
+
norm_layer: Normalization layer.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
| 97 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
| 98 |
+
in_chans: int = 3,
|
| 99 |
+
embed_dim: int = 768,
|
| 100 |
+
norm_layer: Optional[Callable] = None,
|
| 101 |
+
flatten_embedding: bool = True,
|
| 102 |
+
) -> None:
|
| 103 |
+
super().__init__()
|
| 104 |
+
|
| 105 |
+
image_HW = make_2tuple(img_size)
|
| 106 |
+
patch_HW = make_2tuple(patch_size)
|
| 107 |
+
patch_grid_size = (
|
| 108 |
+
image_HW[0] // patch_HW[0],
|
| 109 |
+
image_HW[1] // patch_HW[1],
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.img_size = image_HW
|
| 113 |
+
self.patch_size = patch_HW
|
| 114 |
+
self.patches_resolution = patch_grid_size
|
| 115 |
+
self.num_patches = patch_grid_size[0] * patch_grid_size[1]
|
| 116 |
+
|
| 117 |
+
self.in_chans = in_chans
|
| 118 |
+
self.embed_dim = embed_dim
|
| 119 |
+
|
| 120 |
+
self.flatten_embedding = flatten_embedding
|
| 121 |
+
|
| 122 |
+
self.proj = nn.Conv2d(
|
| 123 |
+
in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW
|
| 124 |
+
)
|
| 125 |
+
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
|
| 126 |
+
|
| 127 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 128 |
+
_, _, H, W = x.shape
|
| 129 |
+
patch_H, patch_W = self.patch_size
|
| 130 |
+
|
| 131 |
+
assert (
|
| 132 |
+
H % patch_H == 0
|
| 133 |
+
), f"Input image height {H} is not a multiple of patch height {patch_H}"
|
| 134 |
+
assert (
|
| 135 |
+
W % patch_W == 0
|
| 136 |
+
), f"Input image width {W} is not a multiple of patch width: {patch_W}"
|
| 137 |
+
|
| 138 |
+
x = self.proj(x) # B C H W
|
| 139 |
+
H, W = x.size(2), x.size(3)
|
| 140 |
+
x = x.flatten(2).transpose(1, 2) # B HW C
|
| 141 |
+
x = self.norm(x)
|
| 142 |
+
if not self.flatten_embedding:
|
| 143 |
+
x = x.reshape(-1, H, W, self.embed_dim) # B H W C
|
| 144 |
+
return x
|
| 145 |
+
|
| 146 |
+
def flops(self) -> float:
|
| 147 |
+
Ho, Wo = self.patches_resolution
|
| 148 |
+
flops = (
|
| 149 |
+
Ho
|
| 150 |
+
* Wo
|
| 151 |
+
* self.embed_dim
|
| 152 |
+
* self.in_chans
|
| 153 |
+
* (self.patch_size[0] * self.patch_size[1])
|
| 154 |
+
)
|
| 155 |
+
if self.norm is not None:
|
| 156 |
+
flops += Ho * Wo * self.embed_dim
|
| 157 |
+
return flops
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# ==============================================================================================================
|
| 161 |
+
# rgbddepth/dinov2_layers/swiglu_ffn.py
|
| 162 |
+
# ==============================================================================================================
|
| 163 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 164 |
+
# All rights reserved.
|
| 165 |
+
#
|
| 166 |
+
# This source code is licensed under the license found in the
|
| 167 |
+
# LICENSE file in the root directory of this source tree.
|
| 168 |
+
|
| 169 |
+
from typing import Callable, Optional
|
| 170 |
+
|
| 171 |
+
import torch.nn.functional as F
|
| 172 |
+
from torch import Tensor, nn
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class SwiGLUFFN(nn.Module):
|
| 176 |
+
def __init__(
|
| 177 |
+
self,
|
| 178 |
+
in_features: int,
|
| 179 |
+
hidden_features: Optional[int] = None,
|
| 180 |
+
out_features: Optional[int] = None,
|
| 181 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 182 |
+
drop: float = 0.0,
|
| 183 |
+
bias: bool = True,
|
| 184 |
+
) -> None:
|
| 185 |
+
super().__init__()
|
| 186 |
+
out_features = out_features or in_features
|
| 187 |
+
hidden_features = hidden_features or in_features
|
| 188 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
| 189 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 190 |
+
|
| 191 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 192 |
+
x12 = self.w12(x)
|
| 193 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 194 |
+
hidden = F.silu(x1) * x2
|
| 195 |
+
return self.w3(hidden)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
from xformers.ops import SwiGLU
|
| 200 |
+
|
| 201 |
+
XFORMERS_AVAILABLE = True
|
| 202 |
+
except ImportError:
|
| 203 |
+
SwiGLU = SwiGLUFFN
|
| 204 |
+
XFORMERS_AVAILABLE = False
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class SwiGLUFFNFused(SwiGLU):
|
| 208 |
+
def __init__(
|
| 209 |
+
self,
|
| 210 |
+
in_features: int,
|
| 211 |
+
hidden_features: Optional[int] = None,
|
| 212 |
+
out_features: Optional[int] = None,
|
| 213 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 214 |
+
drop: float = 0.0,
|
| 215 |
+
bias: bool = True,
|
| 216 |
+
) -> None:
|
| 217 |
+
out_features = out_features or in_features
|
| 218 |
+
hidden_features = hidden_features or in_features
|
| 219 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 220 |
+
super().__init__(
|
| 221 |
+
in_features=in_features,
|
| 222 |
+
hidden_features=hidden_features,
|
| 223 |
+
out_features=out_features,
|
| 224 |
+
bias=bias,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# ==============================================================================================================
|
| 229 |
+
# rgbddepth/dinov2_layers/drop_path.py
|
| 230 |
+
# ==============================================================================================================
|
| 231 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 232 |
+
# All rights reserved.
|
| 233 |
+
#
|
| 234 |
+
# This source code is licensed under the license found in the
|
| 235 |
+
# LICENSE file in the root directory of this source tree.
|
| 236 |
+
|
| 237 |
+
# References:
|
| 238 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 239 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
from torch import nn
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def drop_path(x, drop_prob: float = 0.0, training: bool = False):
|
| 246 |
+
if drop_prob == 0.0 or not training:
|
| 247 |
+
return x
|
| 248 |
+
keep_prob = 1 - drop_prob
|
| 249 |
+
shape = (x.shape[0],) + (1,) * (
|
| 250 |
+
x.ndim - 1
|
| 251 |
+
) # work with diff dim tensors, not just 2D ConvNets
|
| 252 |
+
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
| 253 |
+
if keep_prob > 0.0:
|
| 254 |
+
random_tensor.div_(keep_prob)
|
| 255 |
+
output = x * random_tensor
|
| 256 |
+
return output
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class DropPath(nn.Module):
|
| 260 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 261 |
+
|
| 262 |
+
def __init__(self, drop_prob=None):
|
| 263 |
+
super(DropPath, self).__init__()
|
| 264 |
+
self.drop_prob = drop_prob
|
| 265 |
+
|
| 266 |
+
def forward(self, x):
|
| 267 |
+
return drop_path(x, self.drop_prob, self.training)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# ==============================================================================================================
|
| 271 |
+
# rgbddepth/dinov2_layers/layer_scale.py
|
| 272 |
+
# ==============================================================================================================
|
| 273 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 274 |
+
# All rights reserved.
|
| 275 |
+
#
|
| 276 |
+
# This source code is licensed under the license found in the
|
| 277 |
+
# LICENSE file in the root directory of this source tree.
|
| 278 |
+
|
| 279 |
+
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
|
| 280 |
+
|
| 281 |
+
from typing import Union
|
| 282 |
+
|
| 283 |
+
import torch
|
| 284 |
+
from torch import Tensor, nn
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class LayerScale(nn.Module):
|
| 288 |
+
def __init__(
|
| 289 |
+
self,
|
| 290 |
+
dim: int,
|
| 291 |
+
init_values: Union[float, Tensor] = 1e-5,
|
| 292 |
+
inplace: bool = False,
|
| 293 |
+
) -> None:
|
| 294 |
+
super().__init__()
|
| 295 |
+
self.inplace = inplace
|
| 296 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
| 297 |
+
|
| 298 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 299 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# ==============================================================================================================
|
| 303 |
+
# rgbddepth/dinov2_layers/attention.py
|
| 304 |
+
# ==============================================================================================================
|
| 305 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 306 |
+
# All rights reserved.
|
| 307 |
+
#
|
| 308 |
+
# This source code is licensed under the license found in the
|
| 309 |
+
# LICENSE file in the root directory of this source tree.
|
| 310 |
+
|
| 311 |
+
# References:
|
| 312 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 313 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
|
| 314 |
+
|
| 315 |
+
import logging
|
| 316 |
+
|
| 317 |
+
from torch import Tensor, nn
|
| 318 |
+
|
| 319 |
+
logger = logging.getLogger("dinov2")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
try:
|
| 323 |
+
from xformers.ops import fmha, memory_efficient_attention, unbind
|
| 324 |
+
|
| 325 |
+
XFORMERS_AVAILABLE = True
|
| 326 |
+
except ImportError:
|
| 327 |
+
logger.warning("xFormers not available")
|
| 328 |
+
XFORMERS_AVAILABLE = False
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class Attention(nn.Module):
|
| 332 |
+
def __init__(
|
| 333 |
+
self,
|
| 334 |
+
dim: int,
|
| 335 |
+
num_heads: int = 8,
|
| 336 |
+
qkv_bias: bool = False,
|
| 337 |
+
proj_bias: bool = True,
|
| 338 |
+
attn_drop: float = 0.0,
|
| 339 |
+
proj_drop: float = 0.0,
|
| 340 |
+
) -> None:
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.num_heads = num_heads
|
| 343 |
+
head_dim = dim // num_heads
|
| 344 |
+
self.scale = head_dim**-0.5
|
| 345 |
+
|
| 346 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 347 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 348 |
+
self.proj = nn.Linear(dim, dim, bias=proj_bias)
|
| 349 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 350 |
+
|
| 351 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 352 |
+
B, N, C = x.shape
|
| 353 |
+
qkv = (
|
| 354 |
+
self.qkv(x)
|
| 355 |
+
.reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 356 |
+
.permute(2, 0, 3, 1, 4)
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
|
| 360 |
+
attn = q @ k.transpose(-2, -1)
|
| 361 |
+
|
| 362 |
+
attn = attn.softmax(dim=-1)
|
| 363 |
+
attn = self.attn_drop(attn)
|
| 364 |
+
|
| 365 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 366 |
+
x = self.proj(x)
|
| 367 |
+
x = self.proj_drop(x)
|
| 368 |
+
return x
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class MemEffAttention(Attention):
|
| 372 |
+
def forward(self, x: Tensor, attn_bias=None) -> Tensor:
|
| 373 |
+
if not XFORMERS_AVAILABLE:
|
| 374 |
+
assert attn_bias is None, "xFormers is required for nested tensors usage"
|
| 375 |
+
return super().forward(x)
|
| 376 |
+
|
| 377 |
+
B, N, C = x.shape
|
| 378 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 379 |
+
|
| 380 |
+
q, k, v = unbind(qkv, 2)
|
| 381 |
+
|
| 382 |
+
x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
|
| 383 |
+
x = x.reshape([B, N, C])
|
| 384 |
+
|
| 385 |
+
x = self.proj(x)
|
| 386 |
+
x = self.proj_drop(x)
|
| 387 |
+
return x
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
# ==============================================================================================================
|
| 391 |
+
# rgbddepth/dinov2_layers/block.py
|
| 392 |
+
# ==============================================================================================================
|
| 393 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 394 |
+
# All rights reserved.
|
| 395 |
+
#
|
| 396 |
+
# This source code is licensed under the license found in the
|
| 397 |
+
# LICENSE file in the root directory of this source tree.
|
| 398 |
+
|
| 399 |
+
# References:
|
| 400 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 401 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
|
| 402 |
+
|
| 403 |
+
import logging
|
| 404 |
+
from typing import Any, Callable, Dict, List, Tuple
|
| 405 |
+
|
| 406 |
+
import torch
|
| 407 |
+
from torch import Tensor, nn
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
logger = logging.getLogger("dinov2")
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
try:
|
| 414 |
+
from xformers.ops import fmha, index_select_cat, scaled_index_add
|
| 415 |
+
|
| 416 |
+
XFORMERS_AVAILABLE = True
|
| 417 |
+
except ImportError:
|
| 418 |
+
logger.warning("xFormers not available")
|
| 419 |
+
XFORMERS_AVAILABLE = False
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class Block(nn.Module):
|
| 423 |
+
def __init__(
|
| 424 |
+
self,
|
| 425 |
+
dim: int,
|
| 426 |
+
num_heads: int,
|
| 427 |
+
mlp_ratio: float = 4.0,
|
| 428 |
+
qkv_bias: bool = False,
|
| 429 |
+
proj_bias: bool = True,
|
| 430 |
+
ffn_bias: bool = True,
|
| 431 |
+
drop: float = 0.0,
|
| 432 |
+
attn_drop: float = 0.0,
|
| 433 |
+
init_values=None,
|
| 434 |
+
drop_path: float = 0.0,
|
| 435 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 436 |
+
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
|
| 437 |
+
attn_class: Callable[..., nn.Module] = Attention,
|
| 438 |
+
ffn_layer: Callable[..., nn.Module] = Mlp,
|
| 439 |
+
) -> None:
|
| 440 |
+
super().__init__()
|
| 441 |
+
# print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
|
| 442 |
+
self.norm1 = norm_layer(dim)
|
| 443 |
+
self.attn = attn_class(
|
| 444 |
+
dim,
|
| 445 |
+
num_heads=num_heads,
|
| 446 |
+
qkv_bias=qkv_bias,
|
| 447 |
+
proj_bias=proj_bias,
|
| 448 |
+
attn_drop=attn_drop,
|
| 449 |
+
proj_drop=drop,
|
| 450 |
+
)
|
| 451 |
+
self.ls1 = (
|
| 452 |
+
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
| 453 |
+
)
|
| 454 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 455 |
+
|
| 456 |
+
self.norm2 = norm_layer(dim)
|
| 457 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 458 |
+
self.mlp = ffn_layer(
|
| 459 |
+
in_features=dim,
|
| 460 |
+
hidden_features=mlp_hidden_dim,
|
| 461 |
+
act_layer=act_layer,
|
| 462 |
+
drop=drop,
|
| 463 |
+
bias=ffn_bias,
|
| 464 |
+
)
|
| 465 |
+
self.ls2 = (
|
| 466 |
+
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
| 467 |
+
)
|
| 468 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 469 |
+
|
| 470 |
+
self.sample_drop_ratio = drop_path
|
| 471 |
+
|
| 472 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 473 |
+
def attn_residual_func(x: Tensor) -> Tensor:
|
| 474 |
+
return self.ls1(self.attn(self.norm1(x)))
|
| 475 |
+
|
| 476 |
+
def ffn_residual_func(x: Tensor) -> Tensor:
|
| 477 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
| 478 |
+
|
| 479 |
+
if self.training and self.sample_drop_ratio > 0.1:
|
| 480 |
+
# the overhead is compensated only for a drop path rate larger than 0.1
|
| 481 |
+
x = drop_add_residual_stochastic_depth(
|
| 482 |
+
x,
|
| 483 |
+
residual_func=attn_residual_func,
|
| 484 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 485 |
+
)
|
| 486 |
+
x = drop_add_residual_stochastic_depth(
|
| 487 |
+
x,
|
| 488 |
+
residual_func=ffn_residual_func,
|
| 489 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 490 |
+
)
|
| 491 |
+
elif self.training and self.sample_drop_ratio > 0.0:
|
| 492 |
+
x = x + self.drop_path1(attn_residual_func(x))
|
| 493 |
+
x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
|
| 494 |
+
else:
|
| 495 |
+
x = x + attn_residual_func(x)
|
| 496 |
+
x = x + ffn_residual_func(x)
|
| 497 |
+
return x
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def drop_add_residual_stochastic_depth(
|
| 501 |
+
x: Tensor,
|
| 502 |
+
residual_func: Callable[[Tensor], Tensor],
|
| 503 |
+
sample_drop_ratio: float = 0.0,
|
| 504 |
+
) -> Tensor:
|
| 505 |
+
# 1) extract subset using permutation
|
| 506 |
+
b, n, d = x.shape
|
| 507 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
| 508 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 509 |
+
x_subset = x[brange]
|
| 510 |
+
|
| 511 |
+
# 2) apply residual_func to get residual
|
| 512 |
+
residual = residual_func(x_subset)
|
| 513 |
+
|
| 514 |
+
x_flat = x.flatten(1)
|
| 515 |
+
residual = residual.flatten(1)
|
| 516 |
+
|
| 517 |
+
residual_scale_factor = b / sample_subset_size
|
| 518 |
+
|
| 519 |
+
# 3) add the residual
|
| 520 |
+
x_plus_residual = torch.index_add(
|
| 521 |
+
x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor
|
| 522 |
+
)
|
| 523 |
+
return x_plus_residual.view_as(x)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def get_branges_scales(x, sample_drop_ratio=0.0):
|
| 527 |
+
b, n, d = x.shape
|
| 528 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
| 529 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 530 |
+
residual_scale_factor = b / sample_subset_size
|
| 531 |
+
return brange, residual_scale_factor
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
|
| 535 |
+
if scaling_vector is None:
|
| 536 |
+
x_flat = x.flatten(1)
|
| 537 |
+
residual = residual.flatten(1)
|
| 538 |
+
x_plus_residual = torch.index_add(
|
| 539 |
+
x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor
|
| 540 |
+
)
|
| 541 |
+
else:
|
| 542 |
+
x_plus_residual = scaled_index_add(
|
| 543 |
+
x,
|
| 544 |
+
brange,
|
| 545 |
+
residual.to(dtype=x.dtype),
|
| 546 |
+
scaling=scaling_vector,
|
| 547 |
+
alpha=residual_scale_factor,
|
| 548 |
+
)
|
| 549 |
+
return x_plus_residual
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
attn_bias_cache: Dict[Tuple, Any] = {}
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def get_attn_bias_and_cat(x_list, branges=None):
|
| 556 |
+
"""
|
| 557 |
+
this will perform the index select, cat the tensors, and provide the attn_bias from cache
|
| 558 |
+
"""
|
| 559 |
+
batch_sizes = (
|
| 560 |
+
[b.shape[0] for b in branges]
|
| 561 |
+
if branges is not None
|
| 562 |
+
else [x.shape[0] for x in x_list]
|
| 563 |
+
)
|
| 564 |
+
all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
|
| 565 |
+
if all_shapes not in attn_bias_cache.keys():
|
| 566 |
+
seqlens = []
|
| 567 |
+
for b, x in zip(batch_sizes, x_list):
|
| 568 |
+
for _ in range(b):
|
| 569 |
+
seqlens.append(x.shape[1])
|
| 570 |
+
attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
|
| 571 |
+
attn_bias._batch_sizes = batch_sizes
|
| 572 |
+
attn_bias_cache[all_shapes] = attn_bias
|
| 573 |
+
|
| 574 |
+
if branges is not None:
|
| 575 |
+
cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(
|
| 576 |
+
1, -1, x_list[0].shape[-1]
|
| 577 |
+
)
|
| 578 |
+
else:
|
| 579 |
+
tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
|
| 580 |
+
cat_tensors = torch.cat(tensors_bs1, dim=1)
|
| 581 |
+
|
| 582 |
+
return attn_bias_cache[all_shapes], cat_tensors
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def drop_add_residual_stochastic_depth_list(
|
| 586 |
+
x_list: List[Tensor],
|
| 587 |
+
residual_func: Callable[[Tensor, Any], Tensor],
|
| 588 |
+
sample_drop_ratio: float = 0.0,
|
| 589 |
+
scaling_vector=None,
|
| 590 |
+
) -> Tensor:
|
| 591 |
+
# 1) generate random set of indices for dropping samples in the batch
|
| 592 |
+
branges_scales = [
|
| 593 |
+
get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list
|
| 594 |
+
]
|
| 595 |
+
branges = [s[0] for s in branges_scales]
|
| 596 |
+
residual_scale_factors = [s[1] for s in branges_scales]
|
| 597 |
+
|
| 598 |
+
# 2) get attention bias and index+concat the tensors
|
| 599 |
+
attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
|
| 600 |
+
|
| 601 |
+
# 3) apply residual_func to get residual, and split the result
|
| 602 |
+
residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
|
| 603 |
+
|
| 604 |
+
outputs = []
|
| 605 |
+
for x, brange, residual, residual_scale_factor in zip(
|
| 606 |
+
x_list, branges, residual_list, residual_scale_factors
|
| 607 |
+
):
|
| 608 |
+
outputs.append(
|
| 609 |
+
add_residual(
|
| 610 |
+
x, brange, residual, residual_scale_factor, scaling_vector
|
| 611 |
+
).view_as(x)
|
| 612 |
+
)
|
| 613 |
+
return outputs
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class NestedTensorBlock(Block):
|
| 617 |
+
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
|
| 618 |
+
"""
|
| 619 |
+
x_list contains a list of tensors to nest together and run
|
| 620 |
+
"""
|
| 621 |
+
assert isinstance(self.attn, MemEffAttention)
|
| 622 |
+
|
| 623 |
+
if self.training and self.sample_drop_ratio > 0.0:
|
| 624 |
+
|
| 625 |
+
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 626 |
+
return self.attn(self.norm1(x), attn_bias=attn_bias)
|
| 627 |
+
|
| 628 |
+
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 629 |
+
return self.mlp(self.norm2(x))
|
| 630 |
+
|
| 631 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
| 632 |
+
x_list,
|
| 633 |
+
residual_func=attn_residual_func,
|
| 634 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 635 |
+
scaling_vector=(
|
| 636 |
+
self.ls1.gamma if isinstance(self.ls1, LayerScale) else None
|
| 637 |
+
),
|
| 638 |
+
)
|
| 639 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
| 640 |
+
x_list,
|
| 641 |
+
residual_func=ffn_residual_func,
|
| 642 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 643 |
+
scaling_vector=(
|
| 644 |
+
self.ls2.gamma if isinstance(self.ls1, LayerScale) else None
|
| 645 |
+
),
|
| 646 |
+
)
|
| 647 |
+
return x_list
|
| 648 |
+
else:
|
| 649 |
+
|
| 650 |
+
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 651 |
+
return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
|
| 652 |
+
|
| 653 |
+
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 654 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
| 655 |
+
|
| 656 |
+
attn_bias, x = get_attn_bias_and_cat(x_list)
|
| 657 |
+
x = x + attn_residual_func(x, attn_bias=attn_bias)
|
| 658 |
+
x = x + ffn_residual_func(x)
|
| 659 |
+
return attn_bias.split(x)
|
| 660 |
+
|
| 661 |
+
def forward(self, x_or_x_list):
|
| 662 |
+
if isinstance(x_or_x_list, Tensor):
|
| 663 |
+
return super().forward(x_or_x_list)
|
| 664 |
+
elif isinstance(x_or_x_list, list):
|
| 665 |
+
assert (
|
| 666 |
+
XFORMERS_AVAILABLE
|
| 667 |
+
), "Please install xFormers for nested tensors usage"
|
| 668 |
+
return self.forward_nested(x_or_x_list)
|
| 669 |
+
else:
|
| 670 |
+
raise AssertionError
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
# ==============================================================================================================
|
| 674 |
+
# rgbddepth/dinov2.py
|
| 675 |
+
# ==============================================================================================================
|
| 676 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 677 |
+
#
|
| 678 |
+
# This source code is licensed under the Apache License, Version 2.0
|
| 679 |
+
# found in the LICENSE file in the root directory of this source tree.
|
| 680 |
+
|
| 681 |
+
# References:
|
| 682 |
+
# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
|
| 683 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
|
| 684 |
+
|
| 685 |
+
import logging
|
| 686 |
+
import math
|
| 687 |
+
from functools import partial
|
| 688 |
+
from typing import Callable, Sequence, Tuple, Union
|
| 689 |
+
|
| 690 |
+
import torch
|
| 691 |
+
import torch.nn as nn
|
| 692 |
+
import torch.utils.checkpoint
|
| 693 |
+
from torch.nn.init import trunc_normal_
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
logger = logging.getLogger("dinov2")
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def named_apply(
|
| 700 |
+
fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False
|
| 701 |
+
) -> nn.Module:
|
| 702 |
+
if not depth_first and include_root:
|
| 703 |
+
fn(module=module, name=name)
|
| 704 |
+
for child_name, child_module in module.named_children():
|
| 705 |
+
child_name = ".".join((name, child_name)) if name else child_name
|
| 706 |
+
named_apply(
|
| 707 |
+
fn=fn,
|
| 708 |
+
module=child_module,
|
| 709 |
+
name=child_name,
|
| 710 |
+
depth_first=depth_first,
|
| 711 |
+
include_root=True,
|
| 712 |
+
)
|
| 713 |
+
if depth_first and include_root:
|
| 714 |
+
fn(module=module, name=name)
|
| 715 |
+
return module
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
class BlockChunk(nn.ModuleList):
|
| 719 |
+
def forward(self, x):
|
| 720 |
+
for b in self:
|
| 721 |
+
x = b(x)
|
| 722 |
+
return x
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
class DinoVisionTransformer(nn.Module):
|
| 726 |
+
def __init__(
|
| 727 |
+
self,
|
| 728 |
+
img_size=224,
|
| 729 |
+
patch_size=16,
|
| 730 |
+
in_chans=3,
|
| 731 |
+
embed_dim=768,
|
| 732 |
+
depth=12,
|
| 733 |
+
num_heads=12,
|
| 734 |
+
mlp_ratio=4.0,
|
| 735 |
+
qkv_bias=True,
|
| 736 |
+
ffn_bias=True,
|
| 737 |
+
proj_bias=True,
|
| 738 |
+
drop_path_rate=0.0,
|
| 739 |
+
drop_path_uniform=False,
|
| 740 |
+
init_values=None, # for layerscale: None or 0 => no layerscale
|
| 741 |
+
embed_layer=PatchEmbed,
|
| 742 |
+
act_layer=nn.GELU,
|
| 743 |
+
block_fn=NestedTensorBlock,
|
| 744 |
+
ffn_layer="mlp",
|
| 745 |
+
block_chunks=1,
|
| 746 |
+
num_register_tokens=0,
|
| 747 |
+
interpolate_antialias=False,
|
| 748 |
+
interpolate_offset=0.1,
|
| 749 |
+
):
|
| 750 |
+
"""
|
| 751 |
+
Args:
|
| 752 |
+
img_size (int, tuple): input image size
|
| 753 |
+
patch_size (int, tuple): patch size
|
| 754 |
+
in_chans (int): number of input channels
|
| 755 |
+
embed_dim (int): embedding dimension
|
| 756 |
+
depth (int): depth of transformer
|
| 757 |
+
num_heads (int): number of attention heads
|
| 758 |
+
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
|
| 759 |
+
qkv_bias (bool): enable bias for qkv if True
|
| 760 |
+
proj_bias (bool): enable bias for proj in attn if True
|
| 761 |
+
ffn_bias (bool): enable bias for ffn if True
|
| 762 |
+
drop_path_rate (float): stochastic depth rate
|
| 763 |
+
drop_path_uniform (bool): apply uniform drop rate across blocks
|
| 764 |
+
weight_init (str): weight init scheme
|
| 765 |
+
init_values (float): layer-scale init values
|
| 766 |
+
embed_layer (nn.Module): patch embedding layer
|
| 767 |
+
act_layer (nn.Module): MLP activation layer
|
| 768 |
+
block_fn (nn.Module): transformer block class
|
| 769 |
+
ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
|
| 770 |
+
block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
|
| 771 |
+
num_register_tokens: (int) number of extra cls tokens (so-called "registers")
|
| 772 |
+
interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
|
| 773 |
+
interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
|
| 774 |
+
"""
|
| 775 |
+
super().__init__()
|
| 776 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
| 777 |
+
|
| 778 |
+
self.num_features = self.embed_dim = (
|
| 779 |
+
embed_dim # num_features for consistency with other models
|
| 780 |
+
)
|
| 781 |
+
self.num_tokens = 1
|
| 782 |
+
self.n_blocks = depth
|
| 783 |
+
self.num_heads = num_heads
|
| 784 |
+
self.patch_size = patch_size
|
| 785 |
+
self.num_register_tokens = num_register_tokens
|
| 786 |
+
self.interpolate_antialias = interpolate_antialias
|
| 787 |
+
self.interpolate_offset = interpolate_offset
|
| 788 |
+
|
| 789 |
+
self.patch_embed = embed_layer(
|
| 790 |
+
img_size=img_size,
|
| 791 |
+
patch_size=patch_size,
|
| 792 |
+
in_chans=in_chans,
|
| 793 |
+
embed_dim=embed_dim,
|
| 794 |
+
)
|
| 795 |
+
num_patches = self.patch_embed.num_patches
|
| 796 |
+
|
| 797 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 798 |
+
self.pos_embed = nn.Parameter(
|
| 799 |
+
torch.zeros(1, num_patches + self.num_tokens, embed_dim)
|
| 800 |
+
)
|
| 801 |
+
assert num_register_tokens >= 0
|
| 802 |
+
self.register_tokens = (
|
| 803 |
+
nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim))
|
| 804 |
+
if num_register_tokens
|
| 805 |
+
else None
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
if drop_path_uniform is True:
|
| 809 |
+
dpr = [drop_path_rate] * depth
|
| 810 |
+
else:
|
| 811 |
+
dpr = [
|
| 812 |
+
x.item() for x in torch.linspace(0, drop_path_rate, depth)
|
| 813 |
+
] # stochastic depth decay rule
|
| 814 |
+
|
| 815 |
+
if ffn_layer == "mlp":
|
| 816 |
+
logger.info("using MLP layer as FFN")
|
| 817 |
+
ffn_layer = Mlp
|
| 818 |
+
elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
|
| 819 |
+
logger.info("using SwiGLU layer as FFN")
|
| 820 |
+
ffn_layer = SwiGLUFFNFused
|
| 821 |
+
elif ffn_layer == "identity":
|
| 822 |
+
logger.info("using Identity layer as FFN")
|
| 823 |
+
|
| 824 |
+
def f(*args, **kwargs):
|
| 825 |
+
return nn.Identity()
|
| 826 |
+
|
| 827 |
+
ffn_layer = f
|
| 828 |
+
else:
|
| 829 |
+
raise NotImplementedError
|
| 830 |
+
|
| 831 |
+
blocks_list = [
|
| 832 |
+
block_fn(
|
| 833 |
+
dim=embed_dim,
|
| 834 |
+
num_heads=num_heads,
|
| 835 |
+
mlp_ratio=mlp_ratio,
|
| 836 |
+
qkv_bias=qkv_bias,
|
| 837 |
+
proj_bias=proj_bias,
|
| 838 |
+
ffn_bias=ffn_bias,
|
| 839 |
+
drop_path=dpr[i],
|
| 840 |
+
norm_layer=norm_layer,
|
| 841 |
+
act_layer=act_layer,
|
| 842 |
+
ffn_layer=ffn_layer,
|
| 843 |
+
init_values=init_values,
|
| 844 |
+
)
|
| 845 |
+
for i in range(depth)
|
| 846 |
+
]
|
| 847 |
+
if block_chunks > 0:
|
| 848 |
+
self.chunked_blocks = True
|
| 849 |
+
chunked_blocks = []
|
| 850 |
+
chunksize = depth // block_chunks
|
| 851 |
+
for i in range(0, depth, chunksize):
|
| 852 |
+
# this is to keep the block index consistent if we chunk the block list
|
| 853 |
+
chunked_blocks.append(
|
| 854 |
+
[nn.Identity()] * i + blocks_list[i : i + chunksize]
|
| 855 |
+
)
|
| 856 |
+
self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
|
| 857 |
+
else:
|
| 858 |
+
self.chunked_blocks = False
|
| 859 |
+
self.blocks = nn.ModuleList(blocks_list)
|
| 860 |
+
|
| 861 |
+
self.norm = norm_layer(embed_dim)
|
| 862 |
+
self.head = nn.Identity()
|
| 863 |
+
|
| 864 |
+
self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
|
| 865 |
+
|
| 866 |
+
self.init_weights()
|
| 867 |
+
|
| 868 |
+
def init_weights(self):
|
| 869 |
+
trunc_normal_(self.pos_embed, std=0.02)
|
| 870 |
+
nn.init.normal_(self.cls_token, std=1e-6)
|
| 871 |
+
if self.register_tokens is not None:
|
| 872 |
+
nn.init.normal_(self.register_tokens, std=1e-6)
|
| 873 |
+
named_apply(init_weights_vit_timm, self)
|
| 874 |
+
|
| 875 |
+
def interpolate_pos_encoding(self, x, w, h):
|
| 876 |
+
previous_dtype = x.dtype
|
| 877 |
+
npatch = x.shape[1] - 1
|
| 878 |
+
N = self.pos_embed.shape[1] - 1
|
| 879 |
+
if npatch == N and w == h:
|
| 880 |
+
return self.pos_embed
|
| 881 |
+
pos_embed = self.pos_embed.float()
|
| 882 |
+
class_pos_embed = pos_embed[:, 0]
|
| 883 |
+
patch_pos_embed = pos_embed[:, 1:]
|
| 884 |
+
dim = x.shape[-1]
|
| 885 |
+
w0 = w // self.patch_size
|
| 886 |
+
h0 = h // self.patch_size
|
| 887 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 888 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 889 |
+
# DINOv2 with register modify the interpolate_offset from 0.1 to 0.0
|
| 890 |
+
w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset
|
| 891 |
+
# w0, h0 = w0 + 0.1, h0 + 0.1
|
| 892 |
+
|
| 893 |
+
sqrt_N = math.sqrt(N)
|
| 894 |
+
sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N
|
| 895 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 896 |
+
patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(
|
| 897 |
+
0, 3, 1, 2
|
| 898 |
+
),
|
| 899 |
+
scale_factor=(sx, sy),
|
| 900 |
+
# (int(w0), int(h0)), # to solve the upsampling shape issue
|
| 901 |
+
mode="bicubic",
|
| 902 |
+
antialias=self.interpolate_antialias,
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
assert int(w0) == patch_pos_embed.shape[-2]
|
| 906 |
+
assert int(h0) == patch_pos_embed.shape[-1]
|
| 907 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 908 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(
|
| 909 |
+
previous_dtype
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
def prepare_tokens_with_masks(self, x, masks=None):
|
| 913 |
+
B, nc, w, h = x.shape
|
| 914 |
+
x = self.patch_embed(x)
|
| 915 |
+
if masks is not None:
|
| 916 |
+
x = torch.where(
|
| 917 |
+
masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x
|
| 918 |
+
)
|
| 919 |
+
|
| 920 |
+
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
|
| 921 |
+
x = x + self.interpolate_pos_encoding(x, w, h)
|
| 922 |
+
|
| 923 |
+
if self.register_tokens is not None:
|
| 924 |
+
x = torch.cat(
|
| 925 |
+
(
|
| 926 |
+
x[:, :1],
|
| 927 |
+
self.register_tokens.expand(x.shape[0], -1, -1),
|
| 928 |
+
x[:, 1:],
|
| 929 |
+
),
|
| 930 |
+
dim=1,
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
return x
|
| 934 |
+
|
| 935 |
+
def forward_features_list(self, x_list, masks_list):
|
| 936 |
+
x = [
|
| 937 |
+
self.prepare_tokens_with_masks(x, masks)
|
| 938 |
+
for x, masks in zip(x_list, masks_list)
|
| 939 |
+
]
|
| 940 |
+
for blk in self.blocks:
|
| 941 |
+
x = blk(x)
|
| 942 |
+
|
| 943 |
+
all_x = x
|
| 944 |
+
output = []
|
| 945 |
+
for x, masks in zip(all_x, masks_list):
|
| 946 |
+
x_norm = self.norm(x)
|
| 947 |
+
output.append(
|
| 948 |
+
{
|
| 949 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 950 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
| 951 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
| 952 |
+
"x_prenorm": x,
|
| 953 |
+
"masks": masks,
|
| 954 |
+
}
|
| 955 |
+
)
|
| 956 |
+
return output
|
| 957 |
+
|
| 958 |
+
def forward_features(self, x, masks=None):
|
| 959 |
+
if isinstance(x, list):
|
| 960 |
+
return self.forward_features_list(x, masks)
|
| 961 |
+
|
| 962 |
+
x = self.prepare_tokens_with_masks(x, masks)
|
| 963 |
+
|
| 964 |
+
for blk in self.blocks:
|
| 965 |
+
x = blk(x)
|
| 966 |
+
|
| 967 |
+
x_norm = self.norm(x)
|
| 968 |
+
return {
|
| 969 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 970 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
| 971 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
| 972 |
+
"x_prenorm": x,
|
| 973 |
+
"masks": masks,
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
def _get_intermediate_layers_not_chunked(self, x, n=1):
|
| 977 |
+
x = self.prepare_tokens_with_masks(x)
|
| 978 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 979 |
+
output, total_block_len = [], len(self.blocks)
|
| 980 |
+
blocks_to_take = (
|
| 981 |
+
range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 982 |
+
)
|
| 983 |
+
for i, blk in enumerate(self.blocks):
|
| 984 |
+
x = blk(x)
|
| 985 |
+
if i in blocks_to_take:
|
| 986 |
+
output.append(x)
|
| 987 |
+
assert len(output) == len(
|
| 988 |
+
blocks_to_take
|
| 989 |
+
), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 990 |
+
return output
|
| 991 |
+
|
| 992 |
+
def _get_intermediate_layers_chunked(self, x, n=1):
|
| 993 |
+
x = self.prepare_tokens_with_masks(x)
|
| 994 |
+
output, i, total_block_len = [], 0, len(self.blocks[-1])
|
| 995 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 996 |
+
blocks_to_take = (
|
| 997 |
+
range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 998 |
+
)
|
| 999 |
+
for block_chunk in self.blocks:
|
| 1000 |
+
for blk in block_chunk[i:]: # Passing the nn.Identity()
|
| 1001 |
+
x = blk(x)
|
| 1002 |
+
if i in blocks_to_take:
|
| 1003 |
+
output.append(x)
|
| 1004 |
+
i += 1
|
| 1005 |
+
assert len(output) == len(
|
| 1006 |
+
blocks_to_take
|
| 1007 |
+
), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 1008 |
+
return output
|
| 1009 |
+
|
| 1010 |
+
def get_intermediate_layers(
|
| 1011 |
+
self,
|
| 1012 |
+
x: torch.Tensor,
|
| 1013 |
+
n: Union[int, Sequence] = 1, # Layers or n last layers to take
|
| 1014 |
+
reshape: bool = False,
|
| 1015 |
+
return_class_token: bool = False,
|
| 1016 |
+
norm=True,
|
| 1017 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
|
| 1018 |
+
if self.chunked_blocks:
|
| 1019 |
+
outputs = self._get_intermediate_layers_chunked(x, n)
|
| 1020 |
+
else:
|
| 1021 |
+
outputs = self._get_intermediate_layers_not_chunked(x, n)
|
| 1022 |
+
if norm:
|
| 1023 |
+
outputs = [self.norm(out) for out in outputs]
|
| 1024 |
+
class_tokens = [out[:, 0] for out in outputs]
|
| 1025 |
+
outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs]
|
| 1026 |
+
if reshape:
|
| 1027 |
+
B, _, w, h = x.shape
|
| 1028 |
+
outputs = [
|
| 1029 |
+
out.reshape(B, w // self.patch_size, h // self.patch_size, -1)
|
| 1030 |
+
.permute(0, 3, 1, 2)
|
| 1031 |
+
.contiguous()
|
| 1032 |
+
for out in outputs
|
| 1033 |
+
]
|
| 1034 |
+
if return_class_token:
|
| 1035 |
+
return tuple(zip(outputs, class_tokens))
|
| 1036 |
+
return tuple(outputs)
|
| 1037 |
+
|
| 1038 |
+
def forward(self, *args, is_training=False, **kwargs):
|
| 1039 |
+
ret = self.forward_features(*args, **kwargs)
|
| 1040 |
+
if is_training:
|
| 1041 |
+
return ret
|
| 1042 |
+
else:
|
| 1043 |
+
return self.head(ret["x_norm_clstoken"])
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
def init_weights_vit_timm(module: nn.Module, name: str = ""):
|
| 1047 |
+
"""ViT weight initialization, original timm impl (for reproducibility)"""
|
| 1048 |
+
if isinstance(module, nn.Linear):
|
| 1049 |
+
trunc_normal_(module.weight, std=0.02)
|
| 1050 |
+
if module.bias is not None:
|
| 1051 |
+
nn.init.zeros_(module.bias)
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
|
| 1055 |
+
model = DinoVisionTransformer(
|
| 1056 |
+
patch_size=patch_size,
|
| 1057 |
+
embed_dim=384,
|
| 1058 |
+
depth=12,
|
| 1059 |
+
num_heads=6,
|
| 1060 |
+
mlp_ratio=4,
|
| 1061 |
+
block_fn=partial(NestedTensorBlock, attn_class=MemEffAttention),
|
| 1062 |
+
num_register_tokens=num_register_tokens,
|
| 1063 |
+
**kwargs,
|
| 1064 |
+
)
|
| 1065 |
+
return model
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
|
| 1069 |
+
model = DinoVisionTransformer(
|
| 1070 |
+
patch_size=patch_size,
|
| 1071 |
+
embed_dim=768,
|
| 1072 |
+
depth=12,
|
| 1073 |
+
num_heads=12,
|
| 1074 |
+
mlp_ratio=4,
|
| 1075 |
+
block_fn=partial(NestedTensorBlock, attn_class=MemEffAttention),
|
| 1076 |
+
num_register_tokens=num_register_tokens,
|
| 1077 |
+
**kwargs,
|
| 1078 |
+
)
|
| 1079 |
+
return model
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
|
| 1083 |
+
model = DinoVisionTransformer(
|
| 1084 |
+
patch_size=patch_size,
|
| 1085 |
+
embed_dim=1024,
|
| 1086 |
+
depth=24,
|
| 1087 |
+
num_heads=16,
|
| 1088 |
+
mlp_ratio=4,
|
| 1089 |
+
block_fn=partial(NestedTensorBlock, attn_class=MemEffAttention),
|
| 1090 |
+
num_register_tokens=num_register_tokens,
|
| 1091 |
+
**kwargs,
|
| 1092 |
+
)
|
| 1093 |
+
return model
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
|
| 1097 |
+
"""
|
| 1098 |
+
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
|
| 1099 |
+
"""
|
| 1100 |
+
model = DinoVisionTransformer(
|
| 1101 |
+
patch_size=patch_size,
|
| 1102 |
+
embed_dim=1536,
|
| 1103 |
+
depth=40,
|
| 1104 |
+
num_heads=24,
|
| 1105 |
+
mlp_ratio=4,
|
| 1106 |
+
block_fn=partial(NestedTensorBlock, attn_class=MemEffAttention),
|
| 1107 |
+
num_register_tokens=num_register_tokens,
|
| 1108 |
+
**kwargs,
|
| 1109 |
+
)
|
| 1110 |
+
return model
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
def DINOv2(model_name):
|
| 1114 |
+
model_zoo = {
|
| 1115 |
+
"vits": vit_small,
|
| 1116 |
+
"vitb": vit_base,
|
| 1117 |
+
"vitl": vit_large,
|
| 1118 |
+
"vitg": vit_giant2,
|
| 1119 |
+
}
|
| 1120 |
+
|
| 1121 |
+
return model_zoo[model_name](
|
| 1122 |
+
img_size=518,
|
| 1123 |
+
patch_size=14,
|
| 1124 |
+
init_values=1.0,
|
| 1125 |
+
ffn_layer="mlp" if model_name != "vitg" else "swiglufused",
|
| 1126 |
+
block_chunks=0,
|
| 1127 |
+
num_register_tokens=0,
|
| 1128 |
+
interpolate_antialias=False,
|
| 1129 |
+
interpolate_offset=0.1,
|
| 1130 |
+
)
|
cdm_dpt.py
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# fmt: off
|
| 3 |
+
"""Camera Depth Model (CDM), vendored verbatim from ByteDance-Seed/manip-as-in-sim-suite @ 757b2ea26bcf7992c92ac80485d82b905e961850 (cdm/rgbddepth/): the
|
| 4 |
+
files below concatenated, package-internal imports replaced by relative imports of the other vendored files
|
| 5 |
+
(generated by scripts/model_ports/common/vendor_flat.py; do not edit by hand). Code license: Apache-2.0."""
|
| 6 |
+
from .cdm_dinov2 import DINOv2
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ==============================================================================================================
|
| 10 |
+
# rgbddepth/util/blocks.py
|
| 11 |
+
# ==============================================================================================================
|
| 12 |
+
#!/usr/bin/env python3
|
| 13 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
|
| 14 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 15 |
+
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
|
| 20 |
+
scratch = nn.Module()
|
| 21 |
+
|
| 22 |
+
out_shape1 = out_shape
|
| 23 |
+
out_shape2 = out_shape
|
| 24 |
+
out_shape3 = out_shape
|
| 25 |
+
if len(in_shape) >= 4:
|
| 26 |
+
out_shape4 = out_shape
|
| 27 |
+
|
| 28 |
+
if expand:
|
| 29 |
+
out_shape1 = out_shape
|
| 30 |
+
out_shape2 = out_shape * 2
|
| 31 |
+
out_shape3 = out_shape * 4
|
| 32 |
+
if len(in_shape) >= 4:
|
| 33 |
+
out_shape4 = out_shape * 8
|
| 34 |
+
|
| 35 |
+
scratch.layer1_rn = nn.Conv2d(
|
| 36 |
+
in_shape[0],
|
| 37 |
+
out_shape1,
|
| 38 |
+
kernel_size=3,
|
| 39 |
+
stride=1,
|
| 40 |
+
padding=1,
|
| 41 |
+
bias=False,
|
| 42 |
+
groups=groups,
|
| 43 |
+
)
|
| 44 |
+
scratch.layer2_rn = nn.Conv2d(
|
| 45 |
+
in_shape[1],
|
| 46 |
+
out_shape2,
|
| 47 |
+
kernel_size=3,
|
| 48 |
+
stride=1,
|
| 49 |
+
padding=1,
|
| 50 |
+
bias=False,
|
| 51 |
+
groups=groups,
|
| 52 |
+
)
|
| 53 |
+
scratch.layer3_rn = nn.Conv2d(
|
| 54 |
+
in_shape[2],
|
| 55 |
+
out_shape3,
|
| 56 |
+
kernel_size=3,
|
| 57 |
+
stride=1,
|
| 58 |
+
padding=1,
|
| 59 |
+
bias=False,
|
| 60 |
+
groups=groups,
|
| 61 |
+
)
|
| 62 |
+
if len(in_shape) >= 4:
|
| 63 |
+
scratch.layer4_rn = nn.Conv2d(
|
| 64 |
+
in_shape[3],
|
| 65 |
+
out_shape4,
|
| 66 |
+
kernel_size=3,
|
| 67 |
+
stride=1,
|
| 68 |
+
padding=1,
|
| 69 |
+
bias=False,
|
| 70 |
+
groups=groups,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
return scratch
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class ResidualConvUnit(nn.Module):
|
| 77 |
+
"""Residual convolution module."""
|
| 78 |
+
|
| 79 |
+
def __init__(self, features, activation, bn):
|
| 80 |
+
"""Init.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
features (int): number of features
|
| 84 |
+
"""
|
| 85 |
+
super().__init__()
|
| 86 |
+
|
| 87 |
+
self.bn = bn
|
| 88 |
+
|
| 89 |
+
self.groups = 1
|
| 90 |
+
|
| 91 |
+
self.conv1 = nn.Conv2d(
|
| 92 |
+
features,
|
| 93 |
+
features,
|
| 94 |
+
kernel_size=3,
|
| 95 |
+
stride=1,
|
| 96 |
+
padding=1,
|
| 97 |
+
bias=True,
|
| 98 |
+
groups=self.groups,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
self.conv2 = nn.Conv2d(
|
| 102 |
+
features,
|
| 103 |
+
features,
|
| 104 |
+
kernel_size=3,
|
| 105 |
+
stride=1,
|
| 106 |
+
padding=1,
|
| 107 |
+
bias=True,
|
| 108 |
+
groups=self.groups,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if self.bn == True:
|
| 112 |
+
self.bn1 = nn.BatchNorm2d(features)
|
| 113 |
+
self.bn2 = nn.BatchNorm2d(features)
|
| 114 |
+
|
| 115 |
+
self.activation = activation
|
| 116 |
+
|
| 117 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 118 |
+
|
| 119 |
+
def forward(self, x):
|
| 120 |
+
"""Forward pass.
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
x (tensor): input
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
tensor: output
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
out = self.activation(x)
|
| 130 |
+
out = self.conv1(out)
|
| 131 |
+
if self.bn == True:
|
| 132 |
+
out = self.bn1(out)
|
| 133 |
+
|
| 134 |
+
out = self.activation(out)
|
| 135 |
+
out = self.conv2(out)
|
| 136 |
+
if self.bn == True:
|
| 137 |
+
out = self.bn2(out)
|
| 138 |
+
|
| 139 |
+
if self.groups > 1:
|
| 140 |
+
out = self.conv_merge(out)
|
| 141 |
+
|
| 142 |
+
return self.skip_add.add(out, x)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class FeatureFusionBlock(nn.Module):
|
| 146 |
+
"""Feature fusion block."""
|
| 147 |
+
|
| 148 |
+
def __init__(
|
| 149 |
+
self,
|
| 150 |
+
features,
|
| 151 |
+
activation,
|
| 152 |
+
deconv=False,
|
| 153 |
+
bn=False,
|
| 154 |
+
expand=False,
|
| 155 |
+
align_corners=True,
|
| 156 |
+
size=None,
|
| 157 |
+
):
|
| 158 |
+
"""Init.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
features (int): number of features
|
| 162 |
+
"""
|
| 163 |
+
super(FeatureFusionBlock, self).__init__()
|
| 164 |
+
|
| 165 |
+
self.deconv = deconv
|
| 166 |
+
self.align_corners = align_corners
|
| 167 |
+
|
| 168 |
+
self.groups = 1
|
| 169 |
+
|
| 170 |
+
self.expand = expand
|
| 171 |
+
out_features = features
|
| 172 |
+
if self.expand == True:
|
| 173 |
+
out_features = features // 2
|
| 174 |
+
|
| 175 |
+
self.out_conv = nn.Conv2d(
|
| 176 |
+
features,
|
| 177 |
+
out_features,
|
| 178 |
+
kernel_size=1,
|
| 179 |
+
stride=1,
|
| 180 |
+
padding=0,
|
| 181 |
+
bias=True,
|
| 182 |
+
groups=1,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
|
| 186 |
+
self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
|
| 187 |
+
|
| 188 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 189 |
+
|
| 190 |
+
self.size = size
|
| 191 |
+
|
| 192 |
+
def forward(self, *xs, size=None):
|
| 193 |
+
"""Forward pass.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
tensor: output
|
| 197 |
+
"""
|
| 198 |
+
output = xs[0]
|
| 199 |
+
|
| 200 |
+
if len(xs) == 2:
|
| 201 |
+
res = self.resConfUnit1(xs[1])
|
| 202 |
+
output = self.skip_add.add(output, res)
|
| 203 |
+
|
| 204 |
+
output = self.resConfUnit2(output)
|
| 205 |
+
|
| 206 |
+
if (size is None) and (self.size is None):
|
| 207 |
+
modifier = {"scale_factor": 2}
|
| 208 |
+
elif size is None:
|
| 209 |
+
modifier = {"size": self.size}
|
| 210 |
+
else:
|
| 211 |
+
modifier = {"size": size}
|
| 212 |
+
|
| 213 |
+
output = nn.functional.interpolate(
|
| 214 |
+
output, **modifier, mode="bilinear", align_corners=self.align_corners
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
output = self.out_conv(output)
|
| 218 |
+
|
| 219 |
+
return output
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ==============================================================================================================
|
| 223 |
+
# rgbddepth/util/transform.py
|
| 224 |
+
# ==============================================================================================================
|
| 225 |
+
#!/usr/bin/env python3
|
| 226 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
|
| 227 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 228 |
+
|
| 229 |
+
import cv2
|
| 230 |
+
import numpy as np
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class Resize(object):
|
| 234 |
+
"""Resize sample to given size (width, height)."""
|
| 235 |
+
|
| 236 |
+
def __init__(
|
| 237 |
+
self,
|
| 238 |
+
width,
|
| 239 |
+
height,
|
| 240 |
+
resize_target=True,
|
| 241 |
+
keep_aspect_ratio=False,
|
| 242 |
+
ensure_multiple_of=1,
|
| 243 |
+
resize_method="lower_bound",
|
| 244 |
+
image_interpolation_method=cv2.INTER_AREA,
|
| 245 |
+
):
|
| 246 |
+
"""Init.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
width (int): desired output width
|
| 250 |
+
height (int): desired output height
|
| 251 |
+
resize_target (bool, optional):
|
| 252 |
+
True: Resize the full sample (image, mask, target).
|
| 253 |
+
False: Resize image only.
|
| 254 |
+
Defaults to True.
|
| 255 |
+
keep_aspect_ratio (bool, optional):
|
| 256 |
+
True: Keep the aspect ratio of the input sample.
|
| 257 |
+
Output sample might not have the given width and height, and
|
| 258 |
+
resize behaviour depends on the parameter 'resize_method'.
|
| 259 |
+
Defaults to False.
|
| 260 |
+
ensure_multiple_of (int, optional):
|
| 261 |
+
Output width and height is constrained to be multiple of this parameter.
|
| 262 |
+
Defaults to 1.
|
| 263 |
+
resize_method (str, optional):
|
| 264 |
+
"lower_bound": Output will be at least as large as the given size.
|
| 265 |
+
"upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
|
| 266 |
+
"minimal": Scale as least as possible. (Output size might be smaller than given size.)
|
| 267 |
+
Defaults to "lower_bound".
|
| 268 |
+
"""
|
| 269 |
+
self.__width = width
|
| 270 |
+
self.__height = height
|
| 271 |
+
|
| 272 |
+
self.__resize_target = resize_target
|
| 273 |
+
self.__keep_aspect_ratio = keep_aspect_ratio
|
| 274 |
+
self.__multiple_of = ensure_multiple_of
|
| 275 |
+
self.__resize_method = resize_method
|
| 276 |
+
self.__image_interpolation_method = image_interpolation_method
|
| 277 |
+
|
| 278 |
+
def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
|
| 279 |
+
y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 280 |
+
|
| 281 |
+
if max_val is not None and y > max_val:
|
| 282 |
+
y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 283 |
+
|
| 284 |
+
if y < min_val:
|
| 285 |
+
y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 286 |
+
|
| 287 |
+
return y
|
| 288 |
+
|
| 289 |
+
def get_size(self, width, height):
|
| 290 |
+
# determine new height and width
|
| 291 |
+
scale_height = self.__height / height
|
| 292 |
+
scale_width = self.__width / width
|
| 293 |
+
|
| 294 |
+
if self.__keep_aspect_ratio:
|
| 295 |
+
if self.__resize_method == "lower_bound":
|
| 296 |
+
# scale such that output size is lower bound
|
| 297 |
+
if scale_width > scale_height:
|
| 298 |
+
# fit width
|
| 299 |
+
scale_height = scale_width
|
| 300 |
+
else:
|
| 301 |
+
# fit height
|
| 302 |
+
scale_width = scale_height
|
| 303 |
+
elif self.__resize_method == "upper_bound":
|
| 304 |
+
# scale such that output size is upper bound
|
| 305 |
+
if scale_width < scale_height:
|
| 306 |
+
# fit width
|
| 307 |
+
scale_height = scale_width
|
| 308 |
+
else:
|
| 309 |
+
# fit height
|
| 310 |
+
scale_width = scale_height
|
| 311 |
+
elif self.__resize_method == "minimal":
|
| 312 |
+
# scale as least as possbile
|
| 313 |
+
if abs(1 - scale_width) < abs(1 - scale_height):
|
| 314 |
+
# fit width
|
| 315 |
+
scale_height = scale_width
|
| 316 |
+
else:
|
| 317 |
+
# fit height
|
| 318 |
+
scale_width = scale_height
|
| 319 |
+
else:
|
| 320 |
+
raise ValueError(
|
| 321 |
+
f"resize_method {self.__resize_method} not implemented"
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
if self.__resize_method == "lower_bound":
|
| 325 |
+
new_height = self.constrain_to_multiple_of(
|
| 326 |
+
scale_height * height, min_val=self.__height
|
| 327 |
+
)
|
| 328 |
+
new_width = self.constrain_to_multiple_of(
|
| 329 |
+
scale_width * width, min_val=self.__width
|
| 330 |
+
)
|
| 331 |
+
elif self.__resize_method == "upper_bound":
|
| 332 |
+
new_height = self.constrain_to_multiple_of(
|
| 333 |
+
scale_height * height, max_val=self.__height
|
| 334 |
+
)
|
| 335 |
+
new_width = self.constrain_to_multiple_of(
|
| 336 |
+
scale_width * width, max_val=self.__width
|
| 337 |
+
)
|
| 338 |
+
elif self.__resize_method == "minimal":
|
| 339 |
+
new_height = self.constrain_to_multiple_of(scale_height * height)
|
| 340 |
+
new_width = self.constrain_to_multiple_of(scale_width * width)
|
| 341 |
+
else:
|
| 342 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
| 343 |
+
|
| 344 |
+
return (new_width, new_height)
|
| 345 |
+
|
| 346 |
+
def __call__(self, sample):
|
| 347 |
+
width, height = self.get_size(
|
| 348 |
+
sample["image"].shape[1], sample["image"].shape[0]
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# resize sample
|
| 352 |
+
sample["image"] = cv2.resize(
|
| 353 |
+
sample["image"],
|
| 354 |
+
(width, height),
|
| 355 |
+
interpolation=self.__image_interpolation_method,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
if self.__resize_target:
|
| 359 |
+
if "depth" in sample:
|
| 360 |
+
sample["depth"] = cv2.resize(
|
| 361 |
+
sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
if "mask" in sample:
|
| 365 |
+
sample["mask"] = cv2.resize(
|
| 366 |
+
sample["mask"].astype(np.float32),
|
| 367 |
+
(width, height),
|
| 368 |
+
interpolation=cv2.INTER_NEAREST,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
return sample
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class NormalizeImage(object):
|
| 375 |
+
"""Normlize image by given mean and std."""
|
| 376 |
+
|
| 377 |
+
def __init__(self, mean, std):
|
| 378 |
+
self.__mean = mean
|
| 379 |
+
self.__std = std
|
| 380 |
+
|
| 381 |
+
def __call__(self, sample):
|
| 382 |
+
sample["image"] = (sample["image"] - self.__mean) / self.__std
|
| 383 |
+
|
| 384 |
+
return sample
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class PrepareForNet(object):
|
| 388 |
+
"""Prepare sample for usage as network input."""
|
| 389 |
+
|
| 390 |
+
def __init__(self):
|
| 391 |
+
pass
|
| 392 |
+
|
| 393 |
+
def __call__(self, sample):
|
| 394 |
+
image = np.transpose(sample["image"], (2, 0, 1))
|
| 395 |
+
sample["image"] = np.ascontiguousarray(image).astype(np.float32)
|
| 396 |
+
|
| 397 |
+
if "depth" in sample:
|
| 398 |
+
depth = sample["depth"].astype(np.float32)
|
| 399 |
+
sample["depth"] = np.ascontiguousarray(depth)
|
| 400 |
+
|
| 401 |
+
if "mask" in sample:
|
| 402 |
+
sample["mask"] = sample["mask"].astype(np.float32)
|
| 403 |
+
sample["mask"] = np.ascontiguousarray(sample["mask"])
|
| 404 |
+
|
| 405 |
+
return sample
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
# ==============================================================================================================
|
| 409 |
+
# rgbddepth/dpt.py
|
| 410 |
+
# ==============================================================================================================
|
| 411 |
+
#!/usr/bin/env python3
|
| 412 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
|
| 413 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 414 |
+
|
| 415 |
+
import cv2
|
| 416 |
+
import torch
|
| 417 |
+
import torch.nn as nn
|
| 418 |
+
import torch.nn.functional as F
|
| 419 |
+
from torchvision.transforms import Compose
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _make_fusion_block(features, use_bn, size=None):
|
| 424 |
+
return FeatureFusionBlock(
|
| 425 |
+
features,
|
| 426 |
+
nn.ReLU(False),
|
| 427 |
+
deconv=False,
|
| 428 |
+
bn=use_bn,
|
| 429 |
+
expand=False,
|
| 430 |
+
align_corners=True,
|
| 431 |
+
size=size,
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class ConvBlock(nn.Module):
|
| 436 |
+
def __init__(self, in_feature, out_feature):
|
| 437 |
+
super().__init__()
|
| 438 |
+
|
| 439 |
+
self.conv_block = nn.Sequential(
|
| 440 |
+
nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1),
|
| 441 |
+
nn.BatchNorm2d(out_feature),
|
| 442 |
+
nn.ReLU(True),
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
def forward(self, x):
|
| 446 |
+
return self.conv_block(x)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class DPTHead(nn.Module):
|
| 450 |
+
def __init__(
|
| 451 |
+
self,
|
| 452 |
+
in_channels,
|
| 453 |
+
features=256,
|
| 454 |
+
use_bn=False,
|
| 455 |
+
out_channels=[256, 512, 1024, 1024],
|
| 456 |
+
use_clstoken=False,
|
| 457 |
+
sigact_out=False,
|
| 458 |
+
):
|
| 459 |
+
super(DPTHead, self).__init__()
|
| 460 |
+
|
| 461 |
+
self.use_clstoken = use_clstoken
|
| 462 |
+
|
| 463 |
+
self.projects = nn.ModuleList(
|
| 464 |
+
[
|
| 465 |
+
nn.Conv2d(
|
| 466 |
+
in_channels=in_channels,
|
| 467 |
+
out_channels=out_channel,
|
| 468 |
+
kernel_size=1,
|
| 469 |
+
stride=1,
|
| 470 |
+
padding=0,
|
| 471 |
+
)
|
| 472 |
+
for out_channel in out_channels
|
| 473 |
+
]
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
self.resize_layers = nn.ModuleList(
|
| 477 |
+
[
|
| 478 |
+
nn.ConvTranspose2d(
|
| 479 |
+
in_channels=out_channels[0],
|
| 480 |
+
out_channels=out_channels[0],
|
| 481 |
+
kernel_size=4,
|
| 482 |
+
stride=4,
|
| 483 |
+
padding=0,
|
| 484 |
+
),
|
| 485 |
+
nn.ConvTranspose2d(
|
| 486 |
+
in_channels=out_channels[1],
|
| 487 |
+
out_channels=out_channels[1],
|
| 488 |
+
kernel_size=2,
|
| 489 |
+
stride=2,
|
| 490 |
+
padding=0,
|
| 491 |
+
),
|
| 492 |
+
nn.Identity(),
|
| 493 |
+
nn.Conv2d(
|
| 494 |
+
in_channels=out_channels[3],
|
| 495 |
+
out_channels=out_channels[3],
|
| 496 |
+
kernel_size=3,
|
| 497 |
+
stride=2,
|
| 498 |
+
padding=1,
|
| 499 |
+
),
|
| 500 |
+
]
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
if use_clstoken:
|
| 504 |
+
self.readout_projects = nn.ModuleList()
|
| 505 |
+
for _ in range(len(self.projects)):
|
| 506 |
+
self.readout_projects.append(
|
| 507 |
+
nn.Sequential(nn.Linear(2 * in_channels, in_channels), nn.GELU())
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
self.scratch = _make_scratch(
|
| 511 |
+
out_channels,
|
| 512 |
+
features,
|
| 513 |
+
groups=1,
|
| 514 |
+
expand=False,
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
self.scratch.stem_transpose = None
|
| 518 |
+
|
| 519 |
+
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
|
| 520 |
+
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
|
| 521 |
+
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
|
| 522 |
+
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
|
| 523 |
+
|
| 524 |
+
head_features_1 = features
|
| 525 |
+
head_features_2 = 32
|
| 526 |
+
|
| 527 |
+
self.scratch.output_conv1 = nn.Conv2d(
|
| 528 |
+
head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
if not sigact_out:
|
| 532 |
+
self.scratch.output_conv2 = nn.Sequential(
|
| 533 |
+
nn.Conv2d(
|
| 534 |
+
head_features_1 // 2,
|
| 535 |
+
head_features_2,
|
| 536 |
+
kernel_size=3,
|
| 537 |
+
stride=1,
|
| 538 |
+
padding=1,
|
| 539 |
+
),
|
| 540 |
+
nn.ReLU(True),
|
| 541 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
| 542 |
+
nn.ReLU(True),
|
| 543 |
+
nn.Identity(),
|
| 544 |
+
)
|
| 545 |
+
else:
|
| 546 |
+
self.scratch.output_conv2 = nn.Sequential(
|
| 547 |
+
nn.Conv2d(
|
| 548 |
+
head_features_1 // 2,
|
| 549 |
+
head_features_2,
|
| 550 |
+
kernel_size=3,
|
| 551 |
+
stride=1,
|
| 552 |
+
padding=1,
|
| 553 |
+
),
|
| 554 |
+
nn.ReLU(True),
|
| 555 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
| 556 |
+
nn.Sigmoid(),
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
def forward(self, out_features, patch_h, patch_w):
|
| 560 |
+
out = []
|
| 561 |
+
for i, x in enumerate(out_features):
|
| 562 |
+
if self.use_clstoken:
|
| 563 |
+
x, cls_token = x[0], x[1]
|
| 564 |
+
readout = cls_token.unsqueeze(1).expand_as(x)
|
| 565 |
+
x = self.readout_projects[i](torch.cat((x, readout), -1))
|
| 566 |
+
else:
|
| 567 |
+
x = x[0]
|
| 568 |
+
|
| 569 |
+
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
|
| 570 |
+
|
| 571 |
+
x = self.projects[i](x)
|
| 572 |
+
x = self.resize_layers[i](x)
|
| 573 |
+
|
| 574 |
+
out.append(x)
|
| 575 |
+
|
| 576 |
+
layer_1, layer_2, layer_3, layer_4 = out
|
| 577 |
+
|
| 578 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 579 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 580 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 581 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 582 |
+
|
| 583 |
+
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
|
| 584 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
|
| 585 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
|
| 586 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
| 587 |
+
|
| 588 |
+
out = self.scratch.output_conv1(path_1)
|
| 589 |
+
out = F.interpolate(
|
| 590 |
+
out,
|
| 591 |
+
(int(patch_h * 14), int(patch_w * 14)),
|
| 592 |
+
mode="bilinear",
|
| 593 |
+
align_corners=True,
|
| 594 |
+
)
|
| 595 |
+
out = self.scratch.output_conv2(out)
|
| 596 |
+
|
| 597 |
+
return out
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class RGBDDepth(nn.Module):
|
| 601 |
+
def __init__(
|
| 602 |
+
self,
|
| 603 |
+
encoder="vitl",
|
| 604 |
+
features=256,
|
| 605 |
+
out_channels=[256, 512, 1024, 1024],
|
| 606 |
+
use_bn=False,
|
| 607 |
+
use_clstoken=False,
|
| 608 |
+
max_depth=20.0,
|
| 609 |
+
):
|
| 610 |
+
super(RGBDDepth, self).__init__()
|
| 611 |
+
|
| 612 |
+
self.intermediate_layer_idx = {
|
| 613 |
+
"vits": [2, 5, 8, 11],
|
| 614 |
+
"vitb": [2, 5, 8, 11],
|
| 615 |
+
"vitl": [4, 11, 17, 23],
|
| 616 |
+
"vitg": [9, 19, 29, 39],
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
self.max_depth = max_depth
|
| 620 |
+
|
| 621 |
+
self.encoder = encoder
|
| 622 |
+
self.pretrained = DINOv2(model_name=encoder)
|
| 623 |
+
self.depth_pretrained = DINOv2(model_name=encoder)
|
| 624 |
+
|
| 625 |
+
# self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken, sigact_out=False)
|
| 626 |
+
self.depth_head_rgbd = DPTHead(
|
| 627 |
+
self.pretrained.embed_dim * 2,
|
| 628 |
+
features,
|
| 629 |
+
use_bn,
|
| 630 |
+
out_channels=out_channels,
|
| 631 |
+
use_clstoken=use_clstoken,
|
| 632 |
+
sigact_out=False,
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
# cross att
|
| 636 |
+
num_heads = 4
|
| 637 |
+
self.crossAtts = nn.ModuleList(
|
| 638 |
+
[
|
| 639 |
+
nn.MultiheadAttention(
|
| 640 |
+
self.pretrained.embed_dim, num_heads, batch_first=True
|
| 641 |
+
),
|
| 642 |
+
nn.MultiheadAttention(
|
| 643 |
+
self.pretrained.embed_dim, num_heads, batch_first=True
|
| 644 |
+
),
|
| 645 |
+
nn.MultiheadAttention(
|
| 646 |
+
self.pretrained.embed_dim, num_heads, batch_first=True
|
| 647 |
+
),
|
| 648 |
+
nn.MultiheadAttention(
|
| 649 |
+
self.pretrained.embed_dim, num_heads, batch_first=True
|
| 650 |
+
),
|
| 651 |
+
]
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
def forward(self, x):
|
| 655 |
+
rgb, depth = x[:, :3], x[:, 3:]
|
| 656 |
+
patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
|
| 657 |
+
|
| 658 |
+
with torch.no_grad():
|
| 659 |
+
features_rgb = self.pretrained.get_intermediate_layers(
|
| 660 |
+
rgb, self.intermediate_layer_idx[self.encoder], return_class_token=True
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
features_depth = self.depth_pretrained.get_intermediate_layers(
|
| 664 |
+
depth.repeat(1, 3, 1, 1),
|
| 665 |
+
self.intermediate_layer_idx[self.encoder],
|
| 666 |
+
return_class_token=True,
|
| 667 |
+
)
|
| 668 |
+
features = []
|
| 669 |
+
for f_rgb, f_depth, crossAtt in zip(
|
| 670 |
+
features_rgb, features_depth, self.crossAtts
|
| 671 |
+
):
|
| 672 |
+
B, N, C = f_rgb[0].shape
|
| 673 |
+
tf_rgb = f_rgb[0].reshape(B * N, 1, C)
|
| 674 |
+
tf_depth = f_depth[0].reshape(B * N, 1, C)
|
| 675 |
+
token_feat = torch.concat((tf_rgb, tf_depth), axis=1)
|
| 676 |
+
att_feat, _ = crossAtt(token_feat, token_feat, token_feat)
|
| 677 |
+
att_feat = att_feat.reshape(B * N, 2, C).sum(axis=1).reshape(B, N, C)
|
| 678 |
+
|
| 679 |
+
feat = torch.concat((f_rgb[0], att_feat), axis=2)
|
| 680 |
+
cls_t = torch.concat((f_rgb[1], f_depth[1]), axis=1)
|
| 681 |
+
tuples = (feat, cls_t)
|
| 682 |
+
features.append(tuples)
|
| 683 |
+
depth = self.depth_head_rgbd(features, patch_h, patch_w)
|
| 684 |
+
depth = F.relu(depth)
|
| 685 |
+
return depth.squeeze(1)
|
| 686 |
+
|
| 687 |
+
@torch.no_grad()
|
| 688 |
+
def infer_image(self, raw_image, depth_low_res, input_size=518):
|
| 689 |
+
inputs, (h, w) = self.image2tensor(raw_image, depth_low_res, input_size)
|
| 690 |
+
pred_depth = self.forward(inputs)
|
| 691 |
+
pred_depth = F.interpolate(pred_depth[:, None], (h, w), mode="nearest")[0, 0]
|
| 692 |
+
return pred_depth.cpu().numpy()
|
| 693 |
+
|
| 694 |
+
def image2tensor(self, raw_image, depth, input_size=518):
|
| 695 |
+
transform = Compose(
|
| 696 |
+
[
|
| 697 |
+
Resize(
|
| 698 |
+
width=input_size,
|
| 699 |
+
height=input_size,
|
| 700 |
+
resize_target=True,
|
| 701 |
+
keep_aspect_ratio=True,
|
| 702 |
+
ensure_multiple_of=14,
|
| 703 |
+
resize_method="lower_bound",
|
| 704 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 705 |
+
),
|
| 706 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 707 |
+
PrepareForNet(),
|
| 708 |
+
]
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
h, w = raw_image.shape[:2]
|
| 712 |
+
|
| 713 |
+
image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0
|
| 714 |
+
prepared = transform({"image": image, "depth": depth})
|
| 715 |
+
image = prepared["image"]
|
| 716 |
+
image = torch.from_numpy(image).unsqueeze(0)
|
| 717 |
+
|
| 718 |
+
depth = prepared["depth"]
|
| 719 |
+
depth = torch.from_numpy(depth).unsqueeze(0).unsqueeze(0)
|
| 720 |
+
|
| 721 |
+
inputs = torch.cat((image, depth), dim=1)
|
| 722 |
+
|
| 723 |
+
DEVICE = (
|
| 724 |
+
"cuda"
|
| 725 |
+
if torch.cuda.is_available()
|
| 726 |
+
else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 727 |
+
)
|
| 728 |
+
inputs = inputs.to(DEVICE)
|
| 729 |
+
|
| 730 |
+
return inputs, (h, w)
|
config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"CameraDepthModelForDepthEstimation"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_camera_depth_model.CameraDepthModelConfig",
|
| 7 |
+
"AutoModel": "modeling_camera_depth_model.CameraDepthModelForDepthEstimation",
|
| 8 |
+
"AutoModelForDepthEstimation": "modeling_camera_depth_model.CameraDepthModelForDepthEstimation"
|
| 9 |
+
},
|
| 10 |
+
"camera": "Intel RealSense D405",
|
| 11 |
+
"dtype": "float32",
|
| 12 |
+
"encoder": "vitl",
|
| 13 |
+
"features": 256,
|
| 14 |
+
"max_depth": 20.0,
|
| 15 |
+
"model_type": "camera_depth_model",
|
| 16 |
+
"out_channels": [
|
| 17 |
+
256,
|
| 18 |
+
512,
|
| 19 |
+
1024,
|
| 20 |
+
1024
|
| 21 |
+
],
|
| 22 |
+
"transformers_version": "5.20.2",
|
| 23 |
+
"use_bn": false,
|
| 24 |
+
"use_clstoken": false
|
| 25 |
+
}
|
configuration_camera_depth_model.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera Depth Model configuration: the constructor arguments of the official ``RGBDDepth``
|
| 2 |
+
(ByteDance-Seed/manip-as-in-sim-suite @ 757b2ea2, cdm/rgbddepth/dpt.py) and the preprocessing defaults of cdm/infer.py."""
|
| 3 |
+
|
| 4 |
+
from transformers import PreTrainedConfig
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CameraDepthModelConfig(PreTrainedConfig):
|
| 8 |
+
r"""
|
| 9 |
+
encoder: "vits" | "vitb" | "vitl" | "vitg" (infer.py model_configs; the released models are vitl).
|
| 10 |
+
features / out_channels / use_bn / use_clstoken: the DPT head arguments (infer.py model_configs).
|
| 11 |
+
max_depth: the ``RGBDDepth`` argument (stored; the forward does not use it).
|
| 12 |
+
camera: the depth camera the checkpoint is trained for (None for the base model).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
model_type = "camera_depth_model"
|
| 16 |
+
|
| 17 |
+
encoder: str = "vitl"
|
| 18 |
+
features: int = 256
|
| 19 |
+
out_channels: list | tuple = (256, 512, 1024, 1024)
|
| 20 |
+
use_bn: bool = False
|
| 21 |
+
use_clstoken: bool = False
|
| 22 |
+
max_depth: float = 20.0
|
| 23 |
+
camera: str | None = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
__all__ = ["CameraDepthModelConfig"]
|
image_processing_camera_depth_model.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera Depth Model preprocessing: cdm/infer.py ``load_images`` (raw depth / depth_scale, values above max_depth set
|
| 2 |
+
to 0, inverse depth where valid) and ``RGBDDepth.image2tensor`` (Resize lower_bound to 518 keeping the aspect ratio,
|
| 3 |
+
sides multiples of 14, cv2 bicubic for the image and nearest for the depth; ImageNet normalisation; vendored in
|
| 4 |
+
``cdm_dpt.py``) behind the transformers image-processor interface.
|
| 5 |
+
|
| 6 |
+
As in infer.py and the README API, the image is given as RGB and ``image2tensor`` applies ``cv2.COLOR_BGR2RGB`` to it,
|
| 7 |
+
so the network sees the channels swapped; this is kept unchanged. ``post_process_depth_estimation`` resizes to the
|
| 8 |
+
given sizes as ``infer_image`` does (nearest). The model predicts inverse depth: meters = 1 / prediction (infer.py)."""
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from torchvision.transforms import Compose
|
| 16 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 17 |
+
from transformers.image_processing_utils import BaseImageProcessor
|
| 18 |
+
|
| 19 |
+
from .cdm_dpt import NormalizeImage, PrepareForNet, Resize
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class CameraDepthModelImageProcessor(BaseImageProcessor):
|
| 23 |
+
model_input_names = ["pixel_values", "prompt_depth"]
|
| 24 |
+
|
| 25 |
+
def __init__(self, input_size: int = 518, depth_scale: float = 1000.0, max_depth: float = 25.0, **kwargs):
|
| 26 |
+
super().__init__(**kwargs)
|
| 27 |
+
self.input_size = input_size
|
| 28 |
+
self.depth_scale = depth_scale
|
| 29 |
+
self.max_depth = max_depth # infer.py calls load_images(..., 25.0)
|
| 30 |
+
|
| 31 |
+
def load_inverse_depth(self, depth, depth_scale: float, max_depth: float):
|
| 32 |
+
# infer.py load_images; a path is the raw camera image (cv2 IMREAD_UNCHANGED, / depth_scale), an array is meters
|
| 33 |
+
if isinstance(depth, str):
|
| 34 |
+
depth_low_res = cv2.imread(depth, cv2.IMREAD_UNCHANGED)
|
| 35 |
+
if depth_low_res is None:
|
| 36 |
+
raise ValueError(f"Could not load depth image from {depth}")
|
| 37 |
+
depth_low_res = np.asarray(depth_low_res).astype(np.float32) / depth_scale
|
| 38 |
+
else:
|
| 39 |
+
depth_low_res = np.array(depth, dtype=np.float32)
|
| 40 |
+
depth_low_res[depth_low_res > max_depth] = 0.0 # Remove values beyond max range
|
| 41 |
+
simi_depth_low_res = np.zeros_like(depth_low_res)
|
| 42 |
+
simi_depth_low_res[depth_low_res > 0] = 1 / depth_low_res[depth_low_res > 0]
|
| 43 |
+
return simi_depth_low_res
|
| 44 |
+
|
| 45 |
+
def preprocess(self, images, depth=None, input_size: int | None = None, depth_scale: float | None = None,
|
| 46 |
+
max_depth: float | None = None, return_tensors=None, **kwargs) -> BatchFeature:
|
| 47 |
+
"""images: one image or a list (paths, PIL images or RGB uint8 arrays); depth: one raw depth per image (paths
|
| 48 |
+
of the camera's depth png, or arrays in meters). pixel_values (B, 3, H, W); prompt_depth (B, 1, H, W): the
|
| 49 |
+
inverse depth resized with the image."""
|
| 50 |
+
if not isinstance(images, (list, tuple)):
|
| 51 |
+
images = [images]
|
| 52 |
+
if not isinstance(depth, (list, tuple)):
|
| 53 |
+
depth = [depth]
|
| 54 |
+
if len(depth) != len(images):
|
| 55 |
+
raise ValueError("give one depth per image")
|
| 56 |
+
size = input_size or self.input_size
|
| 57 |
+
transform = Compose([
|
| 58 |
+
Resize(width=size, height=size, resize_target=True, keep_aspect_ratio=True, ensure_multiple_of=14,
|
| 59 |
+
resize_method="lower_bound", image_interpolation_method=cv2.INTER_CUBIC),
|
| 60 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 61 |
+
PrepareForNet(),
|
| 62 |
+
])
|
| 63 |
+
pixel_values, prompt_depth = [], []
|
| 64 |
+
for image, raw_depth in zip(images, depth):
|
| 65 |
+
if isinstance(image, str):
|
| 66 |
+
raw_image = np.asarray(cv2.imread(image)[:, :, ::-1]) # infer.py load_images
|
| 67 |
+
else:
|
| 68 |
+
raw_image = np.asarray(image.convert("RGB") if isinstance(image, Image.Image) else image)
|
| 69 |
+
simi_depth = self.load_inverse_depth(raw_depth, depth_scale or self.depth_scale, max_depth or self.max_depth)
|
| 70 |
+
# RGBDDepth.image2tensor
|
| 71 |
+
prepared = transform({"image": cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0, "depth": simi_depth})
|
| 72 |
+
pixel_values.append(torch.from_numpy(prepared["image"]))
|
| 73 |
+
prompt_depth.append(torch.from_numpy(prepared["depth"]).unsqueeze(0))
|
| 74 |
+
if len({t.shape for t in pixel_values}) > 1:
|
| 75 |
+
raise ValueError("images resize to different shapes; process them one at a time")
|
| 76 |
+
return BatchFeature({"pixel_values": torch.stack(pixel_values), "prompt_depth": torch.stack(prompt_depth)},
|
| 77 |
+
tensor_type=return_tensors)
|
| 78 |
+
|
| 79 |
+
def post_process_depth_estimation(self, outputs, target_sizes=None) -> list:
|
| 80 |
+
"""``DepthEstimatorOutput`` -> ``[{"predicted_depth": (h, w)}]`` (inverse depth) per image; target_sizes:
|
| 81 |
+
(height, width) per image (e.g. the original sizes), None keeps the model resolution."""
|
| 82 |
+
predicted_depth = outputs.predicted_depth
|
| 83 |
+
if target_sizes is not None and len(predicted_depth) != len(target_sizes):
|
| 84 |
+
raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the predicted depth")
|
| 85 |
+
results = []
|
| 86 |
+
for depth, size in zip(predicted_depth, target_sizes if target_sizes is not None else [None] * len(predicted_depth)):
|
| 87 |
+
if size is not None: # infer_image
|
| 88 |
+
depth = F.interpolate(depth[None, None], (int(size[0]), int(size[1])), mode="nearest")[0, 0]
|
| 89 |
+
results.append({"predicted_depth": depth})
|
| 90 |
+
return results
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
__all__ = ["CameraDepthModelImageProcessor"]
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6f7fbe9d762d1bfc3a92796b756b48a7b37342a14f37d8ac02e877bdddf267cd
|
| 3 |
+
size 2637530508
|
modeling_camera_depth_model.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera Depth Model (ByteDance-Seed/manip-as-in-sim-suite @ 757b2ea2) as a transformers depth-estimation model.
|
| 2 |
+
|
| 3 |
+
``CameraDepthModelForDepthEstimation`` holds the submodules of the official ``RGBDDepth`` under the same names
|
| 4 |
+
(``pretrained``: the RGB DINOv2, ``depth_pretrained``: the depth DINOv2, ``crossAtts``, ``depth_head_rgbd``), so the
|
| 5 |
+
released checkpoints load by name, and computes depth with that class's own ``forward`` on the RGB + inverse-depth
|
| 6 |
+
input, returned as the standard ``DepthEstimatorOutput`` (``predicted_depth``: inverse depth). The official
|
| 7 |
+
``infer_image`` / ``image2tensor`` helpers are kept.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from transformers import PreTrainedModel
|
| 13 |
+
from transformers.modeling_outputs import DepthEstimatorOutput
|
| 14 |
+
|
| 15 |
+
from .cdm_dpt import RGBDDepth
|
| 16 |
+
from .configuration_camera_depth_model import CameraDepthModelConfig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CameraDepthModelPreTrainedModel(PreTrainedModel):
|
| 20 |
+
config_class = CameraDepthModelConfig
|
| 21 |
+
config: CameraDepthModelConfig
|
| 22 |
+
base_model_prefix = "camera_depth_model"
|
| 23 |
+
main_input_name = "pixel_values"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class CameraDepthModelForDepthEstimation(CameraDepthModelPreTrainedModel):
|
| 27 |
+
def __init__(self, config: CameraDepthModelConfig):
|
| 28 |
+
super().__init__(config)
|
| 29 |
+
net = RGBDDepth(encoder=config.encoder, features=config.features, out_channels=list(config.out_channels),
|
| 30 |
+
use_bn=config.use_bn, use_clstoken=config.use_clstoken, max_depth=config.max_depth)
|
| 31 |
+
# the official module's attributes, so its methods run on this object unchanged
|
| 32 |
+
self.intermediate_layer_idx = net.intermediate_layer_idx
|
| 33 |
+
self.max_depth = net.max_depth
|
| 34 |
+
self.encoder = net.encoder
|
| 35 |
+
self.pretrained = net.pretrained
|
| 36 |
+
self.depth_pretrained = net.depth_pretrained
|
| 37 |
+
self.depth_head_rgbd = net.depth_head_rgbd
|
| 38 |
+
self.crossAtts = net.crossAtts
|
| 39 |
+
self.post_init()
|
| 40 |
+
|
| 41 |
+
def forward(
|
| 42 |
+
self,
|
| 43 |
+
pixel_values: torch.Tensor,
|
| 44 |
+
prompt_depth: torch.Tensor | None = None,
|
| 45 |
+
labels: torch.Tensor | None = None,
|
| 46 |
+
output_attentions: bool | None = None,
|
| 47 |
+
output_hidden_states: bool | None = None,
|
| 48 |
+
return_dict: bool | None = None,
|
| 49 |
+
**kwargs,
|
| 50 |
+
) -> tuple | DepthEstimatorOutput:
|
| 51 |
+
"""pixel_values (B, 3, H, W), H and W multiples of 14, ImageNet-normalised; prompt_depth (B, 1, H, W): the
|
| 52 |
+
camera's inverse depth (1 / meters, 0 where invalid) at the same size; both from ``CameraDepthModelProcessor``.
|
| 53 |
+
``predicted_depth`` (B, H, W): inverse depth (meters = 1 / predicted_depth, as infer.py).
|
| 54 |
+
``output_hidden_states``: the DINOv2 features of the RGB and the depth branch (per layer, (patch tokens, class
|
| 55 |
+
token)), RGB layers first."""
|
| 56 |
+
if labels is not None:
|
| 57 |
+
raise NotImplementedError("Training is not implemented")
|
| 58 |
+
if output_attentions:
|
| 59 |
+
raise NotImplementedError("Attention weights are not returned (the original model does not expose them)")
|
| 60 |
+
if prompt_depth is None:
|
| 61 |
+
raise ValueError("prompt_depth (the camera's inverse depth) is required")
|
| 62 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 63 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 64 |
+
x = torch.cat((pixel_values, prompt_depth), dim=1) # image2tensor
|
| 65 |
+
predicted_depth = RGBDDepth.forward(self, x)
|
| 66 |
+
hidden_states = None
|
| 67 |
+
if output_hidden_states:
|
| 68 |
+
layers = self.intermediate_layer_idx[self.encoder]
|
| 69 |
+
hidden_states = tuple(self.pretrained.get_intermediate_layers(pixel_values, layers, return_class_token=True)) + tuple(
|
| 70 |
+
self.depth_pretrained.get_intermediate_layers(prompt_depth.repeat(1, 3, 1, 1), layers, return_class_token=True))
|
| 71 |
+
if not return_dict:
|
| 72 |
+
return (predicted_depth,) + ((hidden_states,) if hidden_states is not None else ())
|
| 73 |
+
return DepthEstimatorOutput(predicted_depth=predicted_depth, hidden_states=hidden_states)
|
| 74 |
+
|
| 75 |
+
# official helpers: RGB uint8 image + inverse depth (numpy) -> inverse depth at the image size (numpy)
|
| 76 |
+
@torch.no_grad()
|
| 77 |
+
def infer_image(self, raw_image, depth_low_res, input_size: int = 518):
|
| 78 |
+
# body of RGBDDepth.infer_image, calling the official forward (self.forward returns a DepthEstimatorOutput)
|
| 79 |
+
inputs, (h, w) = self.image2tensor(raw_image, depth_low_res, input_size)
|
| 80 |
+
pred_depth = RGBDDepth.forward(self, inputs)
|
| 81 |
+
pred_depth = F.interpolate(pred_depth[:, None], (h, w), mode="nearest")[0, 0]
|
| 82 |
+
return pred_depth.cpu().numpy()
|
| 83 |
+
|
| 84 |
+
def image2tensor(self, raw_image, depth, input_size: int = 518):
|
| 85 |
+
return RGBDDepth.image2tensor(self, raw_image, depth, input_size)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
__all__ = ["CameraDepthModelForDepthEstimation", "CameraDepthModelPreTrainedModel"]
|
processing_camera_depth_model.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera Depth Model processor: ``CameraDepthModelImageProcessor`` (infer.py load_images + image2tensor) as its only part."""
|
| 2 |
+
|
| 3 |
+
from transformers.processing_utils import ProcessorMixin
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CameraDepthModelProcessor(ProcessorMixin):
|
| 7 |
+
attributes = ["image_processor"]
|
| 8 |
+
|
| 9 |
+
def __init__(self, image_processor=None, **kwargs):
|
| 10 |
+
super().__init__(image_processor, **kwargs)
|
| 11 |
+
|
| 12 |
+
def __call__(self, images=None, depth=None, **kwargs):
|
| 13 |
+
return self.image_processor(images, depth=depth, **kwargs)
|
| 14 |
+
|
| 15 |
+
def post_process_depth_estimation(self, outputs, target_sizes=None):
|
| 16 |
+
return self.image_processor.post_process_depth_estimation(outputs, target_sizes)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["CameraDepthModelProcessor"]
|
processor_config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoProcessor": "processing_camera_depth_model.CameraDepthModelProcessor"
|
| 4 |
+
},
|
| 5 |
+
"image_processor": {
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoImageProcessor": "image_processing_camera_depth_model.CameraDepthModelImageProcessor",
|
| 8 |
+
"AutoProcessor": "processing_camera_depth_model.CameraDepthModelProcessor"
|
| 9 |
+
},
|
| 10 |
+
"depth_scale": 1000.0,
|
| 11 |
+
"image_processor_type": "CameraDepthModelImageProcessor",
|
| 12 |
+
"input_size": 518,
|
| 13 |
+
"max_depth": 25.0
|
| 14 |
+
},
|
| 15 |
+
"processor_class": "CameraDepthModelProcessor"
|
| 16 |
+
}
|