multimodalart HF Staff commited on
Commit
92e95ba
·
verified ·
1 Parent(s): 99a1808

Initial LingBot-Map 2.0 streaming demo

Browse files
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. LICENSE.txt +399 -0
  3. LICENSES/Apache-2.0.txt +202 -0
  4. LICENSES/DINOv3-License.txt +66 -0
  5. LICENSES/FAIR-Noncommercial-Research-License-v1.txt +123 -0
  6. LICENSES/THIRD_PARTY.md +53 -0
  7. README.md +26 -6
  8. app.py +395 -0
  9. examples/courthouse.mp4 +3 -0
  10. examples/loop.mp4 +3 -0
  11. examples/university.mp4 +3 -0
  12. lingbot_map2/__init__.py +16 -0
  13. lingbot_map2/aggregator/__init__.py +3 -0
  14. lingbot_map2/aggregator/base.py +130 -0
  15. lingbot_map2/aggregator/stream.py +210 -0
  16. lingbot_map2/heads/__init__.py +3 -0
  17. lingbot_map2/heads/camera_head.py +86 -0
  18. lingbot_map2/heads/dpt_head.py +591 -0
  19. lingbot_map2/heads/head_act.py +127 -0
  20. lingbot_map2/heads/utils.py +124 -0
  21. lingbot_map2/layers/__init__.py +3 -0
  22. lingbot_map2/layers/block.py +55 -0
  23. lingbot_map2/layers/dinov3/__init__.py +57 -0
  24. lingbot_map2/layers/dinov3/attention.py +105 -0
  25. lingbot_map2/layers/dinov3/block.py +82 -0
  26. lingbot_map2/layers/dinov3/ffn_layers.py +84 -0
  27. lingbot_map2/layers/dinov3/layer_scale.py +30 -0
  28. lingbot_map2/layers/dinov3/patch_embed.py +84 -0
  29. lingbot_map2/layers/dinov3/rms_norm.py +25 -0
  30. lingbot_map2/layers/dinov3/rope_position_encoding.py +124 -0
  31. lingbot_map2/layers/dinov3/utils.py +133 -0
  32. lingbot_map2/layers/dinov3/vision_transformer.py +360 -0
  33. lingbot_map2/layers/flashinfer_cache.py +180 -0
  34. lingbot_map2/layers/layer_scale.py +24 -0
  35. lingbot_map2/layers/mlp.py +40 -0
  36. lingbot_map2/layers/rope.py +349 -0
  37. lingbot_map2/models/__init__.py +7 -0
  38. lingbot_map2/models/gcr_base.py +23 -0
  39. lingbot_map2/models/gcr_stream.py +224 -0
  40. lingbot_map2/utils/__init__.py +3 -0
  41. lingbot_map2/utils/checkpoint.py +109 -0
  42. lingbot_map2/utils/compilation.py +62 -0
  43. lingbot_map2/utils/load_fn.py +127 -0
  44. lingbot_map2/utils/pose_enc.py +119 -0
  45. lingbot_map2/utils/rotation.py +37 -0
  46. lingbot_map2/vis/__init__.py +4 -0
  47. lingbot_map2/vis/glb_export.py +394 -0
  48. lingbot_map2/vis/sky_segmentation.py +505 -0
  49. lingbot_map2/vis/utils.py +173 -0
  50. requirements.txt +10 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/courthouse.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ examples/loop.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ examples/university.mp4 filter=lfs diff=lfs merge=lfs -text
LICENSE.txt ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial 4.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
+ Section 1 -- Definitions.
71
+
72
+ a. Adapted Material means material subject to Copyright and Similar
73
+ Rights that is derived from or based upon the Licensed Material
74
+ and in which the Licensed Material is translated, altered,
75
+ arranged, transformed, or otherwise modified in a manner requiring
76
+ permission under the Copyright and Similar Rights held by the
77
+ Licensor. For purposes of this Public License, where the Licensed
78
+ Material is a musical work, performance, or sound recording,
79
+ Adapted Material is always produced where the Licensed Material is
80
+ synched in timed relation with a moving image.
81
+
82
+ b. Adapter's License means the license You apply to Your Copyright
83
+ and Similar Rights in Your contributions to Adapted Material in
84
+ accordance with the terms and conditions of this Public License.
85
+
86
+ c. Copyright and Similar Rights means copyright and/or similar rights
87
+ closely related to copyright including, without limitation,
88
+ performance, broadcast, sound recording, and Sui Generis Database
89
+ Rights, without regard to how the rights are labeled or
90
+ categorized. For purposes of this Public License, the rights
91
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
92
+ Rights.
93
+ d. Effective Technological Measures means those measures that, in the
94
+ absence of proper authority, may not be circumvented under laws
95
+ fulfilling obligations under Article 11 of the WIPO Copyright
96
+ Treaty adopted on December 20, 1996, and/or similar international
97
+ agreements.
98
+
99
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
100
+ any other exception or limitation to Copyright and Similar Rights
101
+ that applies to Your use of the Licensed Material.
102
+
103
+ f. Licensed Material means the artistic or literary work, database,
104
+ or other material to which the Licensor applied this Public
105
+ License.
106
+
107
+ g. Licensed Rights means the rights granted to You subject to the
108
+ terms and conditions of this Public License, which are limited to
109
+ all Copyright and Similar Rights that apply to Your use of the
110
+ Licensed Material and that the Licensor has authority to license.
111
+
112
+ h. Licensor means the individual(s) or entity(ies) granting rights
113
+ under this Public License.
114
+
115
+ i. NonCommercial means not primarily intended for or directed towards
116
+ commercial advantage or monetary compensation. For purposes of
117
+ this Public License, the exchange of the Licensed Material for
118
+ other material subject to Copyright and Similar Rights by digital
119
+ file-sharing or similar means is NonCommercial provided there is
120
+ no payment of monetary compensation in connection with the
121
+ exchange.
122
+
123
+ j. Share means to provide material to the public by any means or
124
+ process that requires permission under the Licensed Rights, such
125
+ as reproduction, public display, public performance, distribution,
126
+ dissemination, communication, or importation, and to make material
127
+ available to the public including in ways that members of the
128
+ public may access the material from a place and at a time
129
+ individually chosen by them.
130
+
131
+ k. Sui Generis Database Rights means rights other than copyright
132
+ resulting from Directive 96/9/EC of the European Parliament and of
133
+ the Council of 11 March 1996 on the legal protection of databases,
134
+ as amended and/or succeeded, as well as other essentially
135
+ equivalent rights anywhere in the world.
136
+
137
+ l. You means the individual or entity exercising the Licensed Rights
138
+ under this Public License. Your has a corresponding meaning.
139
+
140
+ Section 2 -- Scope.
141
+
142
+ a. License grant.
143
+
144
+ 1. Subject to the terms and conditions of this Public License,
145
+ the Licensor hereby grants You a worldwide, royalty-free,
146
+ non-sublicensable, non-exclusive, irrevocable license to
147
+ exercise the Licensed Rights in the Licensed Material to:
148
+
149
+ a. reproduce and Share the Licensed Material, in whole or
150
+ in part, for NonCommercial purposes only; and
151
+
152
+ b. produce, reproduce, and Share Adapted Material for
153
+ NonCommercial purposes only.
154
+
155
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
156
+ Exceptions and Limitations apply to Your use, this Public
157
+ License does not apply, and You do not need to comply with
158
+ its terms and conditions.
159
+
160
+ 3. Term. The term of this Public License is specified in Section
161
+ 6(a).
162
+
163
+ 4. Media and formats; technical modifications allowed. The
164
+ Licensor authorizes You to exercise the Licensed Rights in
165
+ all media and formats whether now known or hereafter created,
166
+ and to make technical modifications necessary to do so. The
167
+ Licensor waives and/or agrees not to assert any right or
168
+ authority to forbid You from making technical modifications
169
+ necessary to exercise the Licensed Rights, including
170
+ technical modifications necessary to circumvent Effective
171
+ Technological Measures. For purposes of this Public License,
172
+ simply making modifications authorized by this Section 2(a)
173
+ (4) never produces Adapted Material.
174
+
175
+ 5. Downstream recipients.
176
+
177
+ a. Offer from the Licensor -- Licensed Material. Every
178
+ recipient of the Licensed Material automatically
179
+ receives an offer from the Licensor to exercise the
180
+ Licensed Rights under the terms and conditions of this
181
+ Public License.
182
+
183
+ b. No downstream restrictions. You may not offer or impose
184
+ any additional or different terms or conditions on, or
185
+ apply any Effective Technological Measures to, the
186
+ Licensed Material if doing so restricts exercise of the
187
+ Licensed Rights by any recipient of the Licensed
188
+ Material.
189
+
190
+ 6. No endorsement. Nothing in this Public License constitutes or
191
+ may be construed as permission to assert or imply that You
192
+ are, or that Your use of the Licensed Material is, connected
193
+ with, or sponsored, endorsed, or granted official status by,
194
+ the Licensor or others designated to receive attribution as
195
+ provided in Section 3(a)(1)(A)(i).
196
+
197
+ b. Other rights.
198
+
199
+ 1. Moral rights, such as the right of integrity, are not
200
+ licensed under this Public License, nor are publicity,
201
+ privacy, and/or other similar personality rights; however, to
202
+ the extent possible, the Licensor waives and/or agrees not to
203
+ assert any such rights held by the Licensor to the limited
204
+ extent necessary to allow You to exercise the Licensed
205
+ Rights, but not otherwise.
206
+
207
+ 2. Patent and trademark rights are not licensed under this
208
+ Public License.
209
+
210
+ 3. To the extent possible, the Licensor waives any right to
211
+ collect royalties from You for the exercise of the Licensed
212
+ Rights, whether directly or through a collecting society
213
+ under any voluntary or waivable statutory or compulsory
214
+ licensing scheme. In all other cases the Licensor expressly
215
+ reserves any right to collect such royalties, including when
216
+ the Licensed Material is used other than for NonCommercial
217
+ purposes.
218
+
219
+ Section 3 -- License Conditions.
220
+
221
+ Your exercise of the Licensed Rights is expressly made subject to the
222
+ following conditions.
223
+
224
+ a. Attribution.
225
+
226
+ 1. If You Share the Licensed Material (including in modified
227
+ form), You must:
228
+
229
+ a. retain the following if it is supplied by the Licensor
230
+ with the Licensed Material:
231
+
232
+ i. identification of the creator(s) of the Licensed
233
+ Material and any others designated to receive
234
+ attribution, in any reasonable manner requested by
235
+ the Licensor (including by pseudonym if
236
+ designated);
237
+
238
+ ii. a copyright notice;
239
+
240
+ iii. a notice that refers to this Public License;
241
+
242
+ iv. a notice that refers to the disclaimer of
243
+ warranties;
244
+
245
+ v. a URI or hyperlink to the Licensed Material to the
246
+ extent reasonably practicable;
247
+
248
+ b. indicate if You modified the Licensed Material and
249
+ retain an indication of any previous modifications; and
250
+
251
+ c. indicate the Licensed Material is licensed under this
252
+ Public License, and include the text of, or the URI or
253
+ hyperlink to, this Public License.
254
+
255
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
256
+ reasonable manner based on the medium, means, and context in
257
+ which You Share the Licensed Material. For example, it may be
258
+ reasonable to satisfy the conditions by providing a URI or
259
+ hyperlink to a resource that includes the required
260
+ information.
261
+
262
+ 3. If requested by the Licensor, You must remove any of the
263
+ information required by Section 3(a)(1)(A) to the extent
264
+ reasonably practicable.
265
+
266
+ 4. If You Share Adapted Material You produce, the Adapter's
267
+ License You apply must not prevent recipients of the Adapted
268
+ Material from complying with this Public License.
269
+
270
+ Section 4 -- Sui Generis Database Rights.
271
+
272
+ Where the Licensed Rights include Sui Generis Database Rights that
273
+ apply to Your use of the Licensed Material:
274
+
275
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
276
+ to extract, reuse, reproduce, and Share all or a substantial
277
+ portion of the contents of the database for NonCommercial purposes
278
+ only;
279
+
280
+ b. if You include all or a substantial portion of the database
281
+ contents in a database in which You have Sui Generis Database
282
+ Rights, then the database in which You have Sui Generis Database
283
+ Rights (but not its individual contents) is Adapted Material; and
284
+
285
+ c. You must comply with the conditions in Section 3(a) if You Share
286
+ all or a substantial portion of the contents of the database.
287
+
288
+ For the avoidance of doubt, this Section 4 supplements and does not
289
+ replace Your obligations under this Public License where the Licensed
290
+ Rights include other Copyright and Similar Rights.
291
+
292
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
293
+
294
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
295
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
296
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
297
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
298
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
299
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
300
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
301
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
302
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
303
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
304
+
305
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
306
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
307
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
308
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
309
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
310
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
311
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
312
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
313
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
314
+
315
+ c. The disclaimer of warranties and limitation of liability provided
316
+ above shall be interpreted in a manner that, to the extent
317
+ possible, most closely approximates an absolute disclaimer and
318
+ waiver of all liability.
319
+
320
+ Section 6 -- Term and Termination.
321
+
322
+ a. This Public License applies for the term of the Copyright and
323
+ Similar Rights licensed here. However, if You fail to comply with
324
+ this Public License, then Your rights under this Public License
325
+ terminate automatically.
326
+
327
+ b. Where Your right to use the Licensed Material has terminated under
328
+ Section 6(a), it reinstates:
329
+
330
+ 1. automatically as of the date the violation is cured, provided
331
+ it is cured within 30 days of Your discovery of the
332
+ violation; or
333
+
334
+ 2. upon express reinstatement by the Licensor.
335
+
336
+ For the avoidance of doubt, this Section 6(b) does not affect any
337
+ right the Licensor may have to seek remedies for Your violations
338
+ of this Public License.
339
+
340
+ c. For the avoidance of doubt, the Licensor may also offer the
341
+ Licensed Material under separate terms or conditions or stop
342
+ distributing the Licensed Material at any time; however, doing so
343
+ will not terminate this Public License.
344
+
345
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
346
+ License.
347
+
348
+ Section 7 -- Other Terms and Conditions.
349
+
350
+ a. The Licensor shall not be bound by any additional or different
351
+ terms or conditions communicated by You unless expressly agreed.
352
+
353
+ b. Any arrangements, understandings, or agreements regarding the
354
+ Licensed Material not stated herein are separate from and
355
+ independent of the terms and conditions of this Public License.
356
+
357
+ Section 8 -- Interpretation.
358
+
359
+ a. For the avoidance of doubt, this Public License does not, and
360
+ shall not be interpreted to, reduce, limit, restrict, or impose
361
+ conditions on any use of the Licensed Material that could lawfully
362
+ be made without permission under this Public License.
363
+
364
+ b. To the extent possible, if any provision of this Public License is
365
+ deemed unenforceable, it shall be automatically reformed to the
366
+ minimum extent necessary to make it enforceable. If the provision
367
+ cannot be reformed, it shall be severed from this Public License
368
+ without affecting the enforceability of the remaining terms and
369
+ conditions.
370
+
371
+ c. No term or condition of this Public License will be waived and no
372
+ failure to comply consented to unless expressly agreed to by the
373
+ Licensor.
374
+
375
+ d. Nothing in this Public License constitutes or may be interpreted
376
+ as a limitation upon, or waiver of, any privileges and immunities
377
+ that apply to the Licensor or You, including from the legal
378
+ processes of any jurisdiction or authority.
379
+
380
+ =======================================================================
381
+
382
+ Creative Commons is not a party to its public
383
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
384
+ its public licenses to material it publishes and in those instances
385
+ will be considered the “Licensor.” The text of the Creative Commons
386
+ public licenses is dedicated to the public domain under the CC0 Public
387
+ Domain Dedication. Except for the limited purpose of indicating that
388
+ material is shared under a Creative Commons public license or as
389
+ otherwise permitted by the Creative Commons policies published at
390
+ creativecommons.org/policies, Creative Commons does not authorize the
391
+ use of the trademark "Creative Commons" or any other trademark or logo
392
+ of Creative Commons without its prior written consent including,
393
+ without limitation, in connection with any unauthorized modifications
394
+ to any of its public licenses or any other arrangements,
395
+ understandings, or agreements concerning use of licensed material. For
396
+ the avoidance of doubt, this paragraph does not form part of the
397
+ public licenses.
398
+
399
+ Creative Commons may be contacted at creativecommons.org.
LICENSES/Apache-2.0.txt ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
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.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
LICENSES/DINOv3-License.txt ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DINOv3 License
2
+
3
+ *Last Updated: August 19, 2025*
4
+
5
+ **“Agreement”** means the terms and conditions for use, reproduction, distribution and modification of the DINO Materials set forth herein.
6
+
7
+ **“DINO Materials”** means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
8
+
9
+ **“Documentation”** means the specifications, manuals and documentation accompanying
10
+ DINO Materials distributed by Meta.
11
+
12
+ **“Licensee”** or **“you”** means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
13
+
14
+ **“Meta”** or **“we”** means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
15
+
16
+ **“Sanctions”** means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
17
+
18
+ **“Trade Controls”** means any of the following: Sanctions and applicable export and import controls.
19
+
20
+ By clicking “I Accept” below or by using or distributing any portion or element of the DINO Materials, you agree to be bound by this Agreement.
21
+
22
+ ## 1. License Rights and Redistribution.
23
+
24
+ a. <ins>Grant of Rights</ins>. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the DINO Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the DINO Materials.
25
+
26
+ b. <ins>Redistribution and Use</ins>.
27
+
28
+ i. Distribution of DINO Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the DINO Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such DINO Materials.
29
+
30
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with DINO Materials, you must acknowledge the use of DINO Materials in your publication.
31
+
32
+ iii. Your use of the DINO Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
33
+
34
+ iv. Your use of the DINO Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the DINO Materials.
35
+
36
+ v. You are not the target of Trade Controls and your use of DINO Materials must comply with Trade Controls. You agree not to use, or permit others to use, DINO Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
37
+
38
+ ## 2. User Support.
39
+
40
+ Your use of the DINO Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the DINO Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
41
+
42
+ ## 3. Disclaimer of Warranty.
43
+
44
+ UNLESS REQUIRED BY APPLICABLE LAW, THE DINO MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE DINO MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE DINO MATERIALS AND ANY OUTPUT AND RESULTS.
45
+
46
+ ## 4. Limitation of Liability.
47
+
48
+ IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
49
+
50
+ ## 5. Intellectual Property.
51
+
52
+ a. Subject to Meta’s ownership of DINO Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the DINO Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
53
+
54
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the DINO Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the DINO Materials.
55
+
56
+ ## 6. Term and Termination.
57
+
58
+ The term of this Agreement will commence upon your acceptance of this Agreement or access to the DINO Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the DINO Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
59
+
60
+ ## 7. Governing Law and Jurisdiction.
61
+
62
+ This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
63
+
64
+ ## 8. Modifications and Amendments.
65
+
66
+ Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the DINO Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
LICENSES/FAIR-Noncommercial-Research-License-v1.txt ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FAIR Noncommercial Research License
2
+ v1 Last Updated: October 16, 2024
3
+
4
+ “Acceptable Use Policy” means the FAIR Acceptable Use Policy, applicable to Research Materials, that is incorporated into this Agreement.
5
+
6
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the Research Materials set forth herein.
7
+
8
+
9
+ “Documentation” means the specifications, manuals and documentation accompanying
10
+ Research Materials distributed by Meta.
11
+
12
+
13
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
14
+
15
+
16
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) and Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
17
+
18
+ “Noncommercial Research Uses” means noncommercial research use cases related to research, development, education, processing, or analysis and in each case, is not primarily intended for commercial advantage or monetary compensation to you or others.
19
+
20
+ “Research Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, demonstration materials and other elements of the foregoing distributed by Meta and made available under this Agreement.
21
+
22
+ By clicking “I Accept” below or by using or distributing any portion or element of the Research Materials, you agree to be bound by this Agreement.
23
+
24
+
25
+ 1. License Rights and Redistribution.
26
+
27
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the Research Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Research Materials.
28
+
29
+ b. Redistribution and Use.
30
+ i. You will not use the Research Materials or any outputs or results of the Research Materials in connection with any commercial uses or for any uses other than Noncommercial Research Uses;
31
+
32
+ ii. Distribution of Research Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the Research Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement. You shall also provide a copy of this Agreement to such third party.
33
+
34
+ iii. If you submit for publication the results of research you perform on, using, or otherwise in connection with Research Materials, you must acknowledge the use of Research Materials in your publication.
35
+
36
+ iv. Your use of the Research Materials must comply with applicable laws and regulations (including Trade Control Laws) and adhere to the FAIR Acceptable Use Policy, which is hereby incorporated by reference into this Agreement.
37
+
38
+ 2. User Support. Your Noncommercial Research Use of the Research Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the Research Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
39
+
40
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE RESEARCH MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE RESEARCH MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE RESEARCH MATERIALS AND ANY OUTPUT AND RESULTS.
41
+
42
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
43
+
44
+ 5. Intellectual Property.
45
+
46
+ a. Subject to Meta’s ownership of Research Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the Research Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
47
+
48
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Research Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the Research Materials.
49
+
50
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the Research Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the Research Materials. Sections 5, 6 and 9 shall survive the termination of this Agreement.
51
+
52
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
53
+
54
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the Research Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
55
+
56
+
57
+ FAIR Acceptable Use Policy
58
+
59
+ The Fundamental AI Research (FAIR) team at Meta seeks to further understanding of new and existing research domains with the mission of advancing the state-of-the-art in artificial intelligence through open research for the benefit of all.
60
+
61
+ As part of this mission, Meta makes certain research materials available for noncommercial research use. Meta is committed to promoting the safe and responsible use of such research materials.
62
+
63
+ Prohibited Uses
64
+
65
+ You agree you will not use, or allow others to use, Research Materials to:
66
+
67
+ 1. Violate the law or others’ rights, including to:
68
+ a. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
69
+ i. Violence or terrorism
70
+
71
+ ii. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
72
+
73
+ iii. Human trafficking, exploitation, and sexual violence
74
+
75
+ iv. The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials.
76
+
77
+ v. Sexual solicitation
78
+
79
+ vi.Any other criminal activity
80
+
81
+ b. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
82
+
83
+ c. Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services
84
+
85
+ d. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
86
+
87
+ e. Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws
88
+
89
+ f. Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any technology using FAIR research materials
90
+
91
+ g. Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system
92
+
93
+ 2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of research artifacts related to the following:
94
+
95
+ a. Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State
96
+
97
+ b. Guns and illegal weapons (including weapon development)
98
+
99
+ c. Illegal drugs and regulated/controlled substances
100
+
101
+ d. Operation of critical infrastructure, transportation technologies, or heavy machinery
102
+
103
+ e. Self-harm or harm to others, including suicide, cutting, and eating disorders
104
+
105
+ f. Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
106
+
107
+ 3. Intentionally deceive or mislead others, including use of FAIR Research Materials related to the following:
108
+
109
+ a. Generating, promoting, or furthering fraud or the creation or promotion of disinformation
110
+
111
+ b. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
112
+
113
+ c. Generating, promoting, or further distributing spam
114
+
115
+ d. Impersonating another individual without consent, authorization, or legal right
116
+
117
+ e. Representing that outputs of FAIR research materials or outputs from technology using FAIR research materials are human-generated
118
+
119
+ f. Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
120
+
121
+ 4. Fail to appropriately disclose to end users any known dangers of your Research Materials.
122
+
123
+ Please report any violation of this Policy or other problems that could lead to a violation of this Policy by submitting a report here [https://docs.google.com/forms/d/e/1FAIpQLSeb11cryAopJ7LNrC4nxEUXrHY26hfkXQMf_uH-oFgA3WlYZQ/viewform].
LICENSES/THIRD_PARTY.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ Original code by The Robbyant Team Authors is licensed under CC BY-NC 4.0,
4
+ as provided in the root [LICENSE.txt](../LICENSE.txt), and is copyright 2026
5
+ The Robbyant Team Authors. This default does not replace the upstream licenses
6
+ of third-party files or their adaptations.
7
+
8
+ The encoder, transformer layers, DPT head, positional embeddings and pose utilities
9
+ include adaptations of the following public projects:
10
+
11
+ - [DINOv3](https://github.com/facebookresearch/dinov3) and
12
+ [DINOv2](https://github.com/facebookresearch/dinov2) by Meta.
13
+ - [VGGT](https://github.com/facebookresearch/vggt) by Meta and the University of Oxford.
14
+ - The DINOv3 encoder adaptation in
15
+ [VGGT-Omega](https://github.com/facebookresearch/vggt-omega).
16
+
17
+ Local adaptations provide online inference, checkpoint-compatible model assembly
18
+ and paged attention. Original copyright notices are retained in the source files.
19
+
20
+ Third-party files retain their upstream notices and license texts:
21
+
22
+ - CC BY-NC 4.0: root [LICENSE.txt](../LICENSE.txt).
23
+ - Apache-2.0 (including `lingbot_map2/layers/layer_scale.py`,
24
+ `lingbot_map2/layers/mlp.py`, and `lingbot_map2/vis/*`):
25
+ [LICENSES/Apache-2.0.txt](Apache-2.0.txt).
26
+ - DINOv3 License (`lingbot_map2/layers/dinov3/*`, adapted from
27
+ [DINOv3](https://github.com/facebookresearch/dinov3)):
28
+ [LICENSES/DINOv3-License.txt](DINOv3-License.txt).
29
+ - FAIR Noncommercial Research License v1 (`lingbot_map2/layers/dinov3/*`,
30
+ encoder adaptation from
31
+ [VGGT-Omega](https://github.com/facebookresearch/vggt-omega)):
32
+ [LICENSES/FAIR-Noncommercial-Research-License-v1.txt](FAIR-Noncommercial-Research-License-v1.txt).
33
+
34
+ The Robbyant Team licenses its original Base Streaming model weights under
35
+ [CC BY-NC 4.0](../LICENSE.txt). The upstream terms above continue to apply to
36
+ third-party components.
37
+
38
+ Visualization controls, point cloud/camera display, sky segmentation, GLB export
39
+ and color utilities in `lingbot_map2/vis/viewer.py`, `lingbot_map2/vis/glb_export.py`,
40
+ `lingbot_map2/vis/utils.py` and `lingbot_map2/vis/sky_segmentation.py` are adapted
41
+ from [LingBot-Map](https://github.com/Robbyant/lingbot-map/tree/b9dd1b1de535e6d36e777fb42b8433c781bfd783/lingbot_map/vis),
42
+ distributed under Apache-2.0. The original Meta copyright notices are retained;
43
+ the Apache-2.0 license is included in `LICENSES/Apache-2.0.txt`. These adaptations
44
+ connect the visualization layer to Online streaming outputs and saved-prediction
45
+ playback.
46
+ The optional skyseg ONNX weights are downloaded separately from
47
+ [JianyuanWang/skyseg](https://huggingface.co/JianyuanWang/skyseg) and are not bundled
48
+ with this source release.
49
+
50
+ The separately distributed `courthouse` and `university` example image sequences
51
+ are reproduced from the example inputs of the same LingBot-Map revision linked
52
+ above. Their original encoded contents are retained. See
53
+ [`example/README.md`](../example/README.md) for the source link and input inventory.
README.md CHANGED
@@ -1,13 +1,33 @@
1
  ---
2
- title: Lingbot Map V2 Streaming
3
- emoji: 🐠
4
  colorFrom: indigo
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: LingBot-Map 2.0 Streaming
3
+ emoji: 🗺️
4
  colorFrom: indigo
5
+ colorTo: blue
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ short_description: Streaming 3D reconstruction from video with LingBot-Map 2.0
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 30m
12
+ license: cc-by-nc-4.0
13
+ models:
14
+ - robbyant/lingbot-map-v2-base-streaming
15
+ - JianyuanWang/skyseg
16
  ---
17
 
18
+ # LingBot-Map 2.0 · Geometric Streaming Base Model
19
+
20
+ Causal online 3D reconstruction: upload a video or an ordered image sequence and get per-frame camera poses,
21
+ intrinsics and dense depth, fused into a colored point cloud with the camera trajectory.
22
+
23
+ - Model: [robbyant/lingbot-map-v2-base-streaming](https://huggingface.co/robbyant/lingbot-map-v2-base-streaming)
24
+ - Code: [Robbyant/lingbot-map-v2](https://github.com/Robbyant/lingbot-map-v2) (vendored in `lingbot_map2/`, CC BY-NC 4.0; third-party notices in `LICENSES/`)
25
+ - Paper: [Reconsolidatable Streaming 3D Reconstruction](https://arxiv.org/abs/2611.36099)
26
+
27
+ Implementation note: the reference paged KV attention uses FlashInfer's FA2 kernel; this Space uses an equivalent
28
+ PyTorch SDPA over the same paged cache, and runs eagerly (no `torch.compile`) for ZeroGPU compatibility.
29
+
30
+ Example sequences (`courthouse`, `university`, `loop`) are from the
31
+ [LingBot-Map repository](https://github.com/Robbyant/lingbot-map/tree/main/example) (Apache-2.0), re-encoded as 10 fps videos.
32
+
33
+ License: CC BY-NC 4.0 (non-commercial); DINOv3 components under the DINOv3 / FAIR Noncommercial Research License.
app.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
4
+
5
+ import spaces # must come before torch
6
+
7
+ import json
8
+ import math
9
+ import re
10
+ import shutil
11
+ import tempfile
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import cv2
16
+ import gradio as gr
17
+ import imageio.v2 as iio
18
+ import matplotlib
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+ import trimesh
23
+ from huggingface_hub import hf_hub_download
24
+
25
+ import lingbot_map2.aggregator.stream as stream_mod
26
+ from lingbot_map2.layers.flashinfer_cache import PagedKVCache
27
+ from lingbot_map2.models.gcr_base import NativeModel
28
+ from lingbot_map2.models.gcr_stream import GCRStream
29
+ from lingbot_map2.utils.checkpoint import CheckpointConfig
30
+ from lingbot_map2.utils.load_fn import uniform_keyframe_ids
31
+ from lingbot_map2.vis.glb_export import (
32
+ _extract_c2w_and_w2c,
33
+ _unproject_depth_to_world,
34
+ apply_scene_alignment,
35
+ integrate_camera_into_scene,
36
+ )
37
+ from lingbot_map2.vis.sky_segmentation import apply_sky_segmentation
38
+
39
+ MODEL_ID = "robbyant/lingbot-map-v2-base-streaming"
40
+ MAX_FRAMES_HARD = 320
41
+ MAX_POINTS = 1_500_000
42
+ MAX_FRUSTUMS = 120
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Paged KV cache: the reference implementation uses FlashInfer's paged FA2
47
+ # prefill kernel (JIT-compiled). This drop-in keeps the exact same page
48
+ # bookkeeping and replaces only the attention call with PyTorch SDPA over the
49
+ # gathered pages (non-causal, default 1/sqrt(d) scale) — mathematically the
50
+ # same attention, without needing a CUDA toolchain at runtime.
51
+ # ---------------------------------------------------------------------------
52
+ class TorchPagedKVCache(PagedKVCache):
53
+ def __init__(self, *, layers, heads, dim, patches, special=5, scale=8,
54
+ window=64, capacity=1024, device="cuda", dtype=torch.bfloat16,
55
+ offload_kv=False):
56
+ self.layers, self.heads, self.dim = layers, heads, dim
57
+ self.patches, self.special, self.scale, self.window = (
58
+ patches, special, scale, window)
59
+ self.capacity = capacity
60
+ self.device = torch.device(device)
61
+ self.dtype = dtype
62
+ self.offload_kv = False
63
+ self.patch_pages = min(scale + window, capacity) + 1
64
+ self.special_pages = math.ceil((capacity + 1) * special / patches)
65
+ layer_shape = (self.patch_pages + self.special_pages, 2, patches, heads, dim)
66
+ self.cpu_pool = None
67
+ self.gpu_buf = None
68
+ self.pool = [torch.empty(layer_shape, device=device, dtype=dtype)
69
+ for _ in range(layers)]
70
+ import collections
71
+ self.active = collections.deque()
72
+ self.free = list(range(self.patch_pages - 1, -1, -1))
73
+ self.count = 0
74
+ self.pending = None
75
+ self._index = None
76
+ self._length = 0
77
+
78
+ def begin(self):
79
+ if self.pending is not None:
80
+ raise RuntimeError("nested append")
81
+ if self.count >= self.capacity:
82
+ raise ValueError("keyframe capacity reached")
83
+ page = self.free[-1]
84
+ active = list(self.active) + [(self.count, page)]
85
+ active = [
86
+ (i, p) for i, p in active
87
+ if i < self.scale or i >= max(self.scale, self.count + 1 - self.window)
88
+ ]
89
+ tokens = (self.count + 1) * self.special
90
+ special_pages = math.ceil(tokens / self.patches)
91
+ pages = [p for _, p in active] + list(
92
+ range(self.patch_pages, self.patch_pages + special_pages))
93
+ last_len = tokens % self.patches or self.patches
94
+ self.pending = {"page": page, "active": active, "written": set()}
95
+ self._index = torch.tensor(pages, dtype=torch.long, device=self.device)
96
+ self._length = (len(pages) - 1) * self.patches + last_len
97
+
98
+ def run(self, layer, q):
99
+ if layer not in self.pending["written"]:
100
+ raise RuntimeError("query before write")
101
+ kv = self.pool[layer].index_select(0, self._index) # [P, 2, patches, H, D]
102
+ k = kv[:, 0].reshape(-1, self.heads, self.dim)[: self._length]
103
+ v = kv[:, 1].reshape(-1, self.heads, self.dim)[: self._length]
104
+ out = F.scaled_dot_product_attention(
105
+ q.transpose(0, 1)[None], k.transpose(0, 1)[None], v.transpose(0, 1)[None])
106
+ return out[0].transpose(0, 1).contiguous()
107
+
108
+
109
+ stream_mod.PagedKVCache = TorchPagedKVCache
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Model loading (module scope, eager .to("cuda"))
114
+ # ---------------------------------------------------------------------------
115
+ config_path = hf_hub_download(MODEL_ID, "config.json")
116
+ weights_path = hf_hub_download(MODEL_ID, "model_weights.pt")
117
+ SPEC = CheckpointConfig.read(config_path)
118
+ SKYSEG_PATH = hf_hub_download("JianyuanWang/skyseg", "skyseg.onnx")
119
+
120
+ native = NativeModel(SPEC.spatial_rope, max_frames=SPEC.max_frames)
121
+ _state = torch.load(weights_path, map_location="cpu", mmap=True, weights_only=True)
122
+ _state = _state.get("model", _state)
123
+ native.load_state_dict(_state, strict=True)
124
+ del _state
125
+ native.eval().to("cuda")
126
+ MODEL = GCRStream(native, SPEC, {"compile": False}) # eager: torch.compile is unsupported on ZeroGPU
127
+ print(f"Loaded {SPEC.name}: {SPEC.width}x{SPEC.height}, prefix={SPEC.scale_frames}, "
128
+ f"window={SPEC.sliding_window}")
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Input handling
133
+ # ---------------------------------------------------------------------------
134
+ def _natural_key(name):
135
+ return [(1, int(p)) if p.isdigit() else (0, p.lower())
136
+ for p in re.split(r"(\d+)", os.path.basename(name))]
137
+
138
+
139
+ def _frames_from_video(video_path, fps, out_dir):
140
+ cap = cv2.VideoCapture(video_path)
141
+ if not cap.isOpened():
142
+ raise gr.Error("Could not read the video.")
143
+ src_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
144
+ step = max(1, int(round(src_fps / max(fps, 0.1))))
145
+ paths, i = [], 0
146
+ while True:
147
+ ok, frame = cap.read()
148
+ if not ok:
149
+ break
150
+ if i % step == 0:
151
+ p = os.path.join(out_dir, f"{len(paths):06d}.png")
152
+ cv2.imwrite(p, frame)
153
+ paths.append(p)
154
+ i += 1
155
+ cap.release()
156
+ return paths
157
+
158
+
159
+ def _gather_paths(video, images, fps, max_frames, out_dir):
160
+ if images:
161
+ files = [f if isinstance(f, str) else f.name for f in images]
162
+ files = [f for f in files
163
+ if Path(f).suffix.lower() in {".png", ".jpg", ".jpeg", ".webp", ".bmp"}]
164
+ paths = sorted(files, key=_natural_key)
165
+ source = "images"
166
+ elif video:
167
+ paths = _frames_from_video(video, fps, out_dir)
168
+ source = "video"
169
+ else:
170
+ raise gr.Error("Upload a video or an ordered image sequence first.")
171
+ total = len(paths)
172
+ if total > max_frames: # uniform subsample, keep first/last
173
+ idx = np.linspace(0, total - 1, int(max_frames)).round().astype(int)
174
+ paths = [paths[i] for i in idx]
175
+ if len(paths) <= SPEC.scale_frames:
176
+ raise gr.Error(f"Need more than {SPEC.scale_frames} frames "
177
+ f"(got {len(paths)}). Raise the sampling FPS or use a longer clip.")
178
+ return paths, total, source
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # GPU inference
183
+ # ---------------------------------------------------------------------------
184
+ def _gpu_duration(paths, *args, **kwargs):
185
+ return int(min(240, 20 + 0.25 * len(paths)))
186
+
187
+
188
+ @spaces.GPU(duration=_gpu_duration)
189
+ def run_stream(paths):
190
+ """Causal streaming inference over an ordered list of image paths."""
191
+ torch.manual_seed(42)
192
+ keyframes = set(uniform_keyframe_ids(len(paths), prefix=SPEC.scale_frames))
193
+ preds = []
194
+ t0 = time.perf_counter()
195
+ with MODEL.create_stream(output_device="cpu") as stream:
196
+ for raw_id, path in enumerate(paths):
197
+ p = stream.online(path, persistent=raw_id in keyframes)
198
+ if p is not None:
199
+ preds.append(p)
200
+ torch.cuda.synchronize()
201
+ elapsed = time.perf_counter() - t0
202
+ out = {
203
+ k: np.concatenate([p[k] for p in preds], axis=0)
204
+ for k in ("poses_c2w", "intrinsics", "depth", "depth_conf")
205
+ }
206
+ out["depth"] = out["depth"].astype(np.float32)
207
+ out["depth_conf"] = out["depth_conf"].astype(np.float32)
208
+ return out, elapsed
209
+
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # Post-processing (CPU)
213
+ # ---------------------------------------------------------------------------
214
+ def _load_processed_images(paths):
215
+ from lingbot_map2.utils.load_fn import load_images
216
+ imgs = load_images(paths, SPEC.width, SPEC.height)[0] # [N,3,H,W] float in [0,1]
217
+ return imgs.permute(0, 2, 3, 1).numpy() # [N,H,W,3]
218
+
219
+
220
+ def _build_glb(pred, images, conf_percentile, mask_sky, show_cam, out_path):
221
+ c2w, w2c = _extract_c2w_and_w2c(pred)
222
+ world = _unproject_depth_to_world(pred["depth"], c2w, pred["intrinsics"])
223
+ conf = pred["depth_conf"].astype(np.float32)
224
+ if mask_sky:
225
+ try:
226
+ conf = apply_sky_segmentation(
227
+ conf, images=(images * 255).astype(np.uint8), skyseg_model_path=SKYSEG_PATH)
228
+ except Exception as e: # sky model download failure etc.
229
+ print(f"Sky masking skipped: {e!r}")
230
+ pts = world.reshape(-1, 3)
231
+ cols = np.clip(images.reshape(-1, 3) * 255, 0, 255).astype(np.uint8)
232
+ c = conf.reshape(-1)
233
+ valid = np.isfinite(pts).all(axis=1) & np.isfinite(c) & (c > 1e-5)
234
+ thr = np.percentile(c[valid], conf_percentile) if conf_percentile > 0 and valid.any() else 0.0
235
+ keep = np.flatnonzero(valid & (c >= thr))
236
+ if keep.size > MAX_POINTS:
237
+ rng = np.random.default_rng(0)
238
+ keep = np.sort(rng.choice(keep, MAX_POINTS, replace=False))
239
+ pts, cols = pts[keep], cols[keep]
240
+ if pts.size == 0:
241
+ pts = np.zeros((1, 3), np.float32)
242
+ cols = np.full((1, 3), 255, np.uint8)
243
+ scale = 1.0
244
+ else:
245
+ lo, hi = np.percentile(pts, 5, axis=0), np.percentile(pts, 95, axis=0)
246
+ scale = max(float(np.linalg.norm(hi - lo)), 0.1)
247
+ scene = trimesh.Scene()
248
+ scene.add_geometry(trimesh.PointCloud(vertices=pts, colors=cols))
249
+ if show_cam:
250
+ cmap = matplotlib.colormaps["gist_rainbow"]
251
+ n = len(c2w)
252
+ for i in np.unique(np.linspace(0, n - 1, min(n, MAX_FRUSTUMS)).round().astype(int)):
253
+ color = tuple(int(255 * x) for x in cmap(i / max(n, 1))[:3])
254
+ integrate_camera_into_scene(scene, c2w[i], color, scale)
255
+ scene = apply_scene_alignment(scene, w2c)
256
+ scene.export(out_path)
257
+ return int(len(pts))
258
+
259
+
260
+ def _depth_video(images, depth, out_path, fps=10):
261
+ d = depth[..., 0] if depth.ndim == 4 else depth
262
+ cmap = matplotlib.colormaps["turbo"]
263
+ writer = iio.get_writer(out_path, fps=fps, codec="libx264", quality=7,
264
+ macro_block_size=1, pixelformat="yuv420p")
265
+ for img, dm in zip(images, d):
266
+ inv = 1.0 / np.clip(dm, 1e-6, None)
267
+ lo, hi = np.percentile(inv, 2), np.percentile(inv, 98)
268
+ norm = np.clip((inv - lo) / max(hi - lo, 1e-8), 0, 1)
269
+ col = (cmap(norm)[..., :3] * 255).astype(np.uint8)
270
+ rgb = (np.clip(img, 0, 1) * 255).astype(np.uint8)
271
+ writer.append_data(np.concatenate([rgb, col], axis=1))
272
+ writer.close()
273
+
274
+
275
+ def reconstruct(
276
+ video: str | None,
277
+ images: list | None = None,
278
+ fps: float = 10.0,
279
+ max_frames: int = 160,
280
+ conf_percentile: float = 40.0,
281
+ mask_sky: bool = True,
282
+ show_cam: bool = True,
283
+ ):
284
+ """Streaming 3D reconstruction from a video or an ordered image sequence.
285
+
286
+ Frames are fed one by one to LingBot-Map 2.0 (causal streaming base model),
287
+ which predicts a camera pose, intrinsics and dense depth for every frame.
288
+
289
+ Args:
290
+ video: path to an input video (used when no images are given).
291
+ images: optional ordered list of RGB image files (natural filename order).
292
+ fps: frame sampling rate used when extracting frames from the video.
293
+ max_frames: maximum number of frames fed to the model (uniformly subsampled).
294
+ conf_percentile: drop points below this depth-confidence percentile.
295
+ mask_sky: remove sky points with an ONNX sky segmenter.
296
+ show_cam: draw predicted camera frustums in the 3D scene.
297
+
298
+ Returns:
299
+ GLB point cloud with cameras, RGB|depth preview video, NPZ with poses/intrinsics/depth, status text.
300
+ """
301
+ work = tempfile.mkdtemp(prefix="lingbot_")
302
+ frames_dir = os.path.join(work, "frames")
303
+ os.makedirs(frames_dir)
304
+ paths, total, source = _gather_paths(video, images, fps, int(max_frames), frames_dir)
305
+
306
+ pred, t_inf = run_stream(paths)
307
+ t1 = time.perf_counter()
308
+ imgs = _load_processed_images(paths)
309
+
310
+ glb_path = os.path.join(work, "reconstruction.glb")
311
+ n_pts = _build_glb(pred, imgs, float(conf_percentile), bool(mask_sky), bool(show_cam), glb_path)
312
+ vid_path = os.path.join(work, "depth.mp4")
313
+ _depth_video(imgs, pred["depth"], vid_path)
314
+ npz_path = os.path.join(work, "predictions.npz")
315
+ np.savez_compressed(
316
+ npz_path,
317
+ poses_c2w=pred["poses_c2w"].astype(np.float32),
318
+ intrinsics=pred["intrinsics"].astype(np.float32),
319
+ depth=pred["depth"][..., 0].astype(np.float16),
320
+ depth_conf=pred["depth_conf"].astype(np.float16),
321
+ )
322
+ shutil.rmtree(frames_dir, ignore_errors=True)
323
+ n = len(paths)
324
+ status = (
325
+ f"**{n} frames** ({source}, {total} available) at {SPEC.width}×{SPEC.height} · "
326
+ f"streaming inference **{t_inf:.1f}s** ({n / max(t_inf, 1e-6):.1f} FPS) · "
327
+ f"post-processing {time.perf_counter() - t1:.1f}s · {n_pts:,} points"
328
+ )
329
+ return glb_path, vid_path, npz_path, status
330
+
331
+
332
+ # ---------------------------------------------------------------------------
333
+ # UI
334
+ # ---------------------------------------------------------------------------
335
+ CSS = """
336
+ #col-container { max-width: 1280px; margin: 0 auto; }
337
+ .dark .gradio-container { color: var(--body-text-color); }
338
+ """
339
+
340
+ INTRO = """
341
+ # LingBot-Map 2.0 · Streaming 3D Reconstruction
342
+ Feed a video (or an ordered photo sequence) and the **geometric streaming base model** reconstructs the scene
343
+ causally, one frame at a time — predicting camera poses, intrinsics and dense depth, fused here into a colored
344
+ point cloud with the camera trajectory.
345
+ [Model](https://huggingface.co/robbyant/lingbot-map-v2-base-streaming) ·
346
+ [Code](https://github.com/Robbyant/lingbot-map-v2) ·
347
+ [Project](https://technology.robbyant.com/lingbot-map-v2) ·
348
+ [Paper](https://arxiv.org/abs/2611.36099) · License: CC BY-NC 4.0 (non-commercial)
349
+ """
350
+
351
+ with gr.Blocks(title="LingBot-Map 2.0 Streaming") as demo:
352
+ with gr.Column(elem_id="col-container"):
353
+ gr.Markdown(INTRO)
354
+ with gr.Row():
355
+ with gr.Column(scale=2):
356
+ video_in = gr.Video(label="Input video")
357
+ with gr.Accordion("…or upload an ordered image sequence", open=False):
358
+ images_in = gr.File(label="Images (sorted by filename)",
359
+ file_count="multiple", file_types=["image"])
360
+ run_btn = gr.Button("Reconstruct", variant="primary")
361
+ with gr.Accordion("Advanced settings", open=False):
362
+ fps_in = gr.Slider(1, 30, value=10, step=1, label="Video sampling FPS")
363
+ max_frames_in = gr.Slider(16, MAX_FRAMES_HARD, value=160, step=8,
364
+ label="Max frames (uniformly subsampled)")
365
+ conf_in = gr.Slider(0, 95, value=40, step=5,
366
+ label="Confidence filter (percentile of points dropped)")
367
+ sky_in = gr.Checkbox(value=True, label="Mask sky")
368
+ cam_in = gr.Checkbox(value=True, label="Show cameras")
369
+ with gr.Column(scale=3):
370
+ model_out = gr.Model3D(label="Point cloud + camera trajectory",
371
+ height=520)
372
+ status_out = gr.Markdown()
373
+ depth_out = gr.Video(label="Input | predicted depth", autoplay=True, loop=True)
374
+ npz_out = gr.File(label="Predictions (.npz: poses_c2w, intrinsics, depth, depth_conf)")
375
+
376
+ outputs = [model_out, depth_out, npz_out, status_out]
377
+ run_btn.click(
378
+ reconstruct,
379
+ inputs=[video_in, images_in, fps_in, max_frames_in, conf_in, sky_in, cam_in],
380
+ outputs=outputs,
381
+ api_name="reconstruct",
382
+ )
383
+ gr.Examples(
384
+ examples=[["examples/courthouse.mp4"], ["examples/university.mp4"],
385
+ ["examples/loop.mp4"]],
386
+ inputs=[video_in],
387
+ outputs=outputs,
388
+ fn=reconstruct,
389
+ cache_examples=True,
390
+ cache_mode="lazy",
391
+ label="Examples (sequences from the LingBot-Map repository)",
392
+ )
393
+
394
+ if __name__ == "__main__":
395
+ demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
examples/courthouse.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:361c913676e10a9e6f5bd03b96ef0b2cfd6c7ddad6871e9ac91f913eebd43386
3
+ size 14571531
examples/loop.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:065ae89b270c41f822925a448290b2d85d6e39885654f713e4fb3fcbf5d2fd21
3
+ size 7152990
examples/university.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c52f0853b3b6b77540d9557460bb0c2825a4a9e5d76533bcc247abba582c79b
3
+ size 18946914
lingbot_map2/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """LingBot-Map2 Streaming: pure causal online inference."""
4
+
5
+ __all__ = ["GCRStream", "load_model"]
6
+
7
+
8
+ def __getattr__(name):
9
+ # Data preparation and keyframe selection do not need PyTorch or CUDA.
10
+ if name in __all__:
11
+ from . import models
12
+
13
+ value = getattr(models, name)
14
+ globals()[name] = value
15
+ return value
16
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
lingbot_map2/aggregator/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Geometric context aggregation and streaming state."""
lingbot_map2/aggregator/base.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """DINOv3 image embedding and geometric context token layout."""
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ from ..layers.block import Block
9
+ from ..layers.dinov3 import build_encoder
10
+ from ..layers.rope import (
11
+ DinoV3RotaryPositionEmbedding2D,
12
+ PositionGetter,
13
+ WanRotaryPosEmbed,
14
+ )
15
+
16
+
17
+ class Aggregator(nn.Module):
18
+ def __init__(self, spatial_rope="max", max_frames=1024):
19
+ super().__init__()
20
+ self.patch_embed = build_encoder(patch_size=16, embed_dim=1024)
21
+ self.patch_embed.mask_token.requires_grad_(False)
22
+ self.rope = DinoV3RotaryPositionEmbedding2D(base=100)
23
+ self.position_getter = PositionGetter()
24
+ self.frame_blocks = nn.ModuleList(
25
+ [Block(1024, 16, rope=self.rope) for _ in range(24)]
26
+ )
27
+ self.global_blocks = nn.ModuleList(
28
+ [Block(1024, 16, rope=self.rope) for _ in range(24)]
29
+ )
30
+ self.camera_token = nn.Parameter(torch.empty(1, 2, 1, 1024))
31
+ self.register_token = nn.Parameter(torch.empty(1, 2, 4, 1024))
32
+ self.rope3d = WanRotaryPosEmbed(
33
+ attention_head_dim=64,
34
+ patch_size=(max_frames, 32, 32),
35
+ max_seq_len=max(1024, max_frames),
36
+ theta=10000.0,
37
+ spatial_normalize_coords=spatial_rope,
38
+ )
39
+ for name, value in (
40
+ ("_resnet_mean", [0.485, 0.456, 0.406]),
41
+ ("_resnet_std", [0.229, 0.224, 0.225]),
42
+ ):
43
+ self.register_buffer(
44
+ name, torch.tensor(value).view(1, 1, 3, 1, 1), persistent=False
45
+ )
46
+
47
+ def embed(self, images, start):
48
+ _, frames, _, height, width = images.shape
49
+ pixels = ((images - self._resnet_mean) / self._resnet_std).view(
50
+ frames, 3, height, width
51
+ )
52
+ patches = self.patch_embed(pixels)
53
+ if isinstance(patches, dict):
54
+ patches = patches["x_norm_patchtokens"]
55
+ special = []
56
+ for template in (self.camera_token, self.register_token):
57
+ if start == 0:
58
+ values = torch.cat(
59
+ (template[:, :1], template[:, 1:].expand(1, frames - 1, -1, -1)),
60
+ dim=1,
61
+ )
62
+ else:
63
+ values = template[:, 1:].expand(1, frames, -1, -1)
64
+ special.append(values.reshape(frames, -1, patches.shape[-1]))
65
+ tokens = torch.cat((*special, patches), dim=1)
66
+ positions = (
67
+ self.position_getter(
68
+ frames, height // 16, width // 16, device=images.device
69
+ )
70
+ + 1
71
+ )
72
+ positions = torch.cat(
73
+ (
74
+ torch.zeros(frames, 5, 2, dtype=positions.dtype, device=images.device),
75
+ positions,
76
+ ),
77
+ dim=1,
78
+ )
79
+ rope = self.rope3d(
80
+ frames,
81
+ height // 16,
82
+ width // 16,
83
+ 5,
84
+ device=images.device,
85
+ f_start=start,
86
+ f_end=start + frames,
87
+ )
88
+ return tokens, positions, rope
89
+
90
+
91
+ def join_images(images):
92
+ """Join arrivals without turning native HWC-backed inputs into CHW storage."""
93
+ if len(images) == 1:
94
+ return images[0]
95
+ if all(image.stride(-3) == 1 for image in images):
96
+ return torch.cat(
97
+ [image.permute(0, 1, 3, 4, 2) for image in images], dim=1
98
+ ).permute(0, 1, 4, 2, 3)
99
+ return torch.cat(images, dim=1)
100
+
101
+
102
+ def pack_tokens(tokens, special):
103
+ return torch.cat(
104
+ (
105
+ tokens[..., special:, :].flatten(-3, -2),
106
+ tokens[..., :special, :].flatten(-3, -2),
107
+ ),
108
+ dim=-2,
109
+ )
110
+
111
+
112
+ def unpack_tokens(tokens, frames, patches, special):
113
+ boundary = frames * (patches - special)
114
+ return torch.cat(
115
+ (
116
+ tokens[..., boundary:, :].unflatten(-2, (frames, special)),
117
+ tokens[..., :boundary, :].unflatten(-2, (frames, patches - special)),
118
+ ),
119
+ dim=-2,
120
+ )
121
+
122
+
123
+ def finish_global(block, x, output):
124
+ """Pure projection and FFN residuals, shared by eager and compiled online."""
125
+ attention = block.attn
126
+ output = output[None].transpose(1, 2)
127
+ output = output.transpose(1, 2).reshape(x.shape)
128
+ x = x + block.ls1(attention.proj_drop(attention.proj(output)))
129
+ x = x + block.ls2(block.mlp(block.norm2(x)))
130
+ return x
lingbot_map2/aggregator/stream.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Online streaming with a transactional paged KV cache."""
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn import functional as F
8
+
9
+ from ..layers.flashinfer_cache import PagedKVCache
10
+ from ..layers.rope import apply_rotary_emb
11
+ from ..utils.pose_enc import decode_predictions
12
+ from .base import finish_global, join_images, pack_tokens, unpack_tokens
13
+
14
+
15
+ def prepare_global(block, tokens, rope):
16
+ batch, frames, patches, channels = tokens.shape
17
+ packed = pack_tokens(tokens, 5)
18
+ frequencies = pack_tokens(rope.reshape(1, 1, frames, patches, -1), 5)
19
+ query, key, value = block.attn.project(block.norm1(packed))
20
+ return (
21
+ packed,
22
+ apply_rotary_emb(query, frequencies),
23
+ apply_rotary_emb(key, frequencies),
24
+ value,
25
+ )
26
+
27
+
28
+ class Stream:
29
+ """One stream owns one model. Only persistent arrivals advance its clock."""
30
+
31
+ def __init__(
32
+ self, model, *, output_device="cpu", offload_kv=False, depth_chunk_size=None
33
+ ):
34
+ self.model = model
35
+ self.output_device = model._output_device(output_device)
36
+ self._offload_kv = bool(offload_kv)
37
+ self._depth_chunk_size = depth_chunk_size
38
+ self._pending = []
39
+ self._count = 0
40
+ self._paged = None
41
+ self._camera = None
42
+ self._closed = False
43
+
44
+ @property
45
+ def frame_count(self):
46
+ return self._count + len(self._pending)
47
+
48
+ @property
49
+ def ready(self):
50
+ return self._count >= self.model.config.scale_frames
51
+
52
+ def _check(self):
53
+ if self._closed or self.model._stream is not self:
54
+ raise RuntimeError("stream is closed or no longer owns this model")
55
+ if self.model._native.training:
56
+ raise RuntimeError("model must remain in eval mode")
57
+
58
+ @torch.inference_mode()
59
+ def online(self, frame, *, persistent=True):
60
+ self._check()
61
+ if not persistent and not self.ready:
62
+ raise ValueError("the initialization prefix must be persistent")
63
+ if self.frame_count >= self.model.config.max_frames:
64
+ raise ValueError("committed temporal capacity reached; start a new stream")
65
+ if self.model._compiled is not None:
66
+ torch.compiler.cudagraph_mark_step_begin()
67
+ try:
68
+ return self._online(frame, persistent=persistent)
69
+ finally:
70
+ if self._paged is not None:
71
+ self._paged.rollback()
72
+
73
+ def _online(self, frame, *, persistent):
74
+ image = self.model.prepare(frame)
75
+ if image.shape[1] != 1:
76
+ raise ValueError("online accepts exactly one frame per call")
77
+ image = image.detach().to(self.model.device, copy=True)
78
+ if not self.ready and len(self._pending) + 1 < self.model.config.scale_frames:
79
+ self._pending.append(image)
80
+ return None
81
+ images = join_images([*self._pending, image])
82
+ count, height, width = images.shape[1], *images.shape[-2:]
83
+ native = self.model._native
84
+ agg = native.aggregator
85
+ needed = {4, 11, 17, 23} if native.depth_head is not None else {23}
86
+ features, prefix_kv = {}, []
87
+ if self._paged is not None:
88
+ self._paged.begin()
89
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=images.is_cuda):
90
+ tokens, spatial, temporal = agg.embed(images, self._count)
91
+ patches, channels = tokens.shape[-2:]
92
+ for layer, block in enumerate(agg.global_blocks):
93
+ frame_tokens = agg.frame_blocks[layer](
94
+ tokens.reshape(count, patches, channels), pos=spatial
95
+ ).reshape(1, count, patches, channels)
96
+ compiled = self.model._compiled
97
+ if compiled is None:
98
+ packed, query, key, value = prepare_global(
99
+ block, frame_tokens, temporal
100
+ )
101
+ else:
102
+ packed, query, key, value = compiled[layer][0](
103
+ frame_tokens, temporal
104
+ )
105
+ if self._paged is None:
106
+ output = F.scaled_dot_product_attention(query, key, value)
107
+ output = output[0].transpose(0, 1)
108
+ k_unpacked = unpack_tokens(key, count, patches, 5)
109
+ v_unpacked = unpack_tokens(value, count, patches, 5)
110
+ if self._offload_kv:
111
+ k_unpacked = k_unpacked.to(device="cpu", dtype=torch.bfloat16)
112
+ v_unpacked = v_unpacked.to(device="cpu", dtype=torch.bfloat16)
113
+ prefix_kv.append((k_unpacked, v_unpacked))
114
+ else:
115
+ dtype = self._paged.dtype
116
+ natural_key = unpack_tokens(key, 1, patches, 5)[0, :, 0].transpose(
117
+ 0, 1
118
+ )
119
+ natural_value = unpack_tokens(value, 1, patches, 5)[
120
+ 0, :, 0
121
+ ].transpose(0, 1)
122
+ self._paged.write(
123
+ layer, natural_key.to(dtype), natural_value.to(dtype)
124
+ )
125
+ output = self._paged.run(layer, query[0].transpose(0, 1).to(dtype))
126
+ tokens = (
127
+ finish_global(block, packed, output)
128
+ if compiled is None
129
+ else compiled[layer][1](packed, output)
130
+ )
131
+ tokens = unpack_tokens(tokens, count, patches, 5)
132
+ if layer in needed:
133
+ features[layer] = torch.cat((frame_tokens, tokens), dim=-1)
134
+ with torch.autocast("cuda", enabled=False):
135
+ poses, camera = native.camera_head(features[23].float(), self._camera)
136
+ output = {"pose_enc": poses}
137
+ if native.depth_head is not None:
138
+ dpt_kwargs = {}
139
+ if self._depth_chunk_size is not None:
140
+ dpt_kwargs["frames_chunk_size"] = self._depth_chunk_size
141
+ depth, confidence = native.depth_head(
142
+ [features[i].float() for i in (4, 11, 17, 23)],
143
+ images=images.float(),
144
+ patch_start_idx=5,
145
+ **dpt_kwargs,
146
+ )
147
+ output.update(depth=depth, depth_conf=confidence)
148
+ result = decode_predictions(
149
+ output, (height, width), output_device=self.output_device
150
+ )
151
+ del features, output, poses
152
+ result["frame_indices"] = (
153
+ np.arange(self._count, self._count + count)
154
+ if self.output_device.type == "cpu"
155
+ else torch.arange(
156
+ self._count, self._count + count, device=self.output_device
157
+ )
158
+ )
159
+ if not persistent:
160
+ return result
161
+ pool = self._paged
162
+ if pool is None:
163
+ key = prefix_kv[0][0]
164
+ pool = PagedKVCache(
165
+ layers=len(prefix_kv),
166
+ heads=key.shape[1],
167
+ dim=key.shape[-1],
168
+ patches=patches - 5,
169
+ scale=self.model.config.scale_frames,
170
+ window=self.model.config.sliding_window,
171
+ capacity=self.model.config.max_frames,
172
+ device=images.device,
173
+ offload_kv=self._offload_kv,
174
+ )
175
+ for index in range(count):
176
+ pool.begin()
177
+ for layer in range(len(prefix_kv)):
178
+ key, value = prefix_kv[layer]
179
+ pool.write(
180
+ layer,
181
+ key[0, :, index].transpose(0, 1).to(pool.dtype),
182
+ value[0, :, index].transpose(0, 1).to(pool.dtype),
183
+ )
184
+ if index == count - 1:
185
+ prefix_kv[layer] = None
186
+ pool.commit()
187
+ prefix_kv.clear()
188
+ else:
189
+ pool.commit()
190
+ self._paged = pool
191
+ self._camera = camera
192
+ self._count += count
193
+ self._pending.clear()
194
+ return result
195
+
196
+ def close(self):
197
+ if self._closed:
198
+ return
199
+ self._paged = self._camera = None
200
+ self._pending.clear()
201
+ self._closed = True
202
+ if self.model._stream is self:
203
+ self.model._stream = None
204
+
205
+ def __enter__(self):
206
+ self._check()
207
+ return self
208
+
209
+ def __exit__(self, *_exception):
210
+ self.close()
lingbot_map2/heads/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Camera and dense geometry prediction heads."""
lingbot_map2/heads/camera_head.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # Camera pose decoding for online inference. See LICENSES/THIRD_PARTY.md.
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ from ..layers.block import Block
9
+ from torch.nn import functional as F
10
+ from .head_act import activate_pose
11
+ from ..layers.mlp import Mlp
12
+
13
+
14
+ class CameraBlock(Block):
15
+ def __init__(self, dim, num_heads):
16
+ super().__init__(dim, num_heads, qk_norm=False)
17
+
18
+ def forward(self, x, bank, layer):
19
+ q, k, v = self.attn.project(self.norm1(x))
20
+ # Each iteration has its own chronological Camera cache. Assign fresh
21
+ # tensors, so the enclosing stream can discard a failed transaction.
22
+ for name, value in ((f"k_{layer}", k), (f"v_{layer}", v)):
23
+ value = value.unsqueeze(3)
24
+ old = bank.get(name)
25
+ bank[name] = value if old is None else torch.cat((old, value), dim=2)
26
+ key = bank[f"k_{layer}"].flatten(2, 3)
27
+ value = bank[f"v_{layer}"].flatten(2, 3)
28
+ # Compute FP32 Camera attention with an explicit visibility mask.
29
+ visible = torch.ones(
30
+ x.shape[0], 1, q.shape[2], key.shape[2], dtype=torch.bool, device=x.device
31
+ )
32
+ output = F.scaled_dot_product_attention(q, key, value, attn_mask=visible)
33
+ output = output.transpose(1, 2).reshape(x.shape)
34
+ x = x + self.ls1(self.attn.proj_drop(self.attn.proj(output)))
35
+ return x + self.ls2(self.mlp(self.norm2(x)))
36
+
37
+
38
+ class CameraHead(nn.Module):
39
+ """Four-stage camera pose decoder for incoming frames."""
40
+
41
+ def __init__(self, dim_in=2048, num_heads=16, trunk_depth=4):
42
+ super().__init__()
43
+ self.num_iterations = 4
44
+ self.trunk = nn.Sequential(
45
+ *[CameraBlock(dim_in, num_heads) for _ in range(trunk_depth)]
46
+ )
47
+ self.token_norm = nn.LayerNorm(dim_in)
48
+ self.trunk_norm = nn.LayerNorm(dim_in)
49
+ self.empty_pose_tokens = nn.Parameter(torch.zeros(1, 1, 9))
50
+ self.embed_pose = nn.Linear(9, dim_in)
51
+ self.poseLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim_in, 3 * dim_in))
52
+ self.adaln_norm = nn.LayerNorm(dim_in, elementwise_affine=False, eps=1e-6)
53
+ self.pose_branch = Mlp(
54
+ in_features=dim_in, hidden_features=dim_in // 2, out_features=9, drop=0
55
+ )
56
+
57
+ def forward(self, features, cache=None):
58
+ tokens = self.token_norm(features[:, :, 0])
59
+ banks = (
60
+ [dict(bank) for bank in cache]
61
+ if cache is not None
62
+ else [{} for _ in range(self.num_iterations)]
63
+ )
64
+ prediction = None
65
+ poses = []
66
+ for iteration, bank in enumerate(banks):
67
+ conditioning = (
68
+ self.empty_pose_tokens.expand(*tokens.shape[:2], -1)
69
+ if prediction is None
70
+ else prediction.detach()
71
+ )
72
+ shift, scale, gate = self.poseLN_modulation(
73
+ self.embed_pose(conditioning)
74
+ ).chunk(3, dim=-1)
75
+ modulated = gate * (self.adaln_norm(tokens) * (1 + scale) + shift)
76
+ modulated = modulated + tokens
77
+ for layer, block in enumerate(self.trunk):
78
+ modulated = block(modulated, bank, layer)
79
+ delta = self.pose_branch(self.trunk_norm(modulated))
80
+ prediction = delta if prediction is None else prediction + delta
81
+ poses.append(
82
+ activate_pose(
83
+ prediction, trans_act="linear", quat_act="linear", fl_act="relu"
84
+ )
85
+ )
86
+ return poses, banks
lingbot_map2/heads/dpt_head.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE.txt file in the root directory of this source tree.
7
+
8
+
9
+ # Inspired by https://github.com/DepthAnything/Depth-Anything-V2
10
+
11
+
12
+ from typing import List, Tuple, Union
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ from .head_act import activate_head
17
+ from .utils import create_uv_grid, position_grid_to_embed
18
+
19
+
20
+ class DPTHead(nn.Module):
21
+ """
22
+ DPT Head for dense prediction tasks.
23
+
24
+ This implementation follows the architecture described in "Vision Transformers for Dense Prediction"
25
+ (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer
26
+ backbone and produces dense predictions by fusing multi-scale features.
27
+
28
+ Args:
29
+ dim_in (int): Input dimension (channels).
30
+ patch_size (int, optional): Patch size. Default is 14.
31
+ output_dim (int, optional): Number of output channels. Default is 4.
32
+ activation (str, optional): Activation type. Default is "inv_log".
33
+ conf_activation (str, optional): Confidence activation type. Default is "expp1".
34
+ features (int, optional): Feature channels for intermediate representations. Default is 256.
35
+ out_channels (List[int], optional): Output channels for each intermediate layer.
36
+ intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT.
37
+ pos_embed (bool, optional): Whether to use positional embedding. Default is True.
38
+ feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False.
39
+ down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ dim_in: int,
45
+ patch_size: int = 14,
46
+ output_dim: int = 4,
47
+ activation: str = "inv_log",
48
+ conf_activation: str = "expp1",
49
+ features: int = 256,
50
+ out_channels: List[int] = [256, 512, 1024, 1024],
51
+ intermediate_layer_idx: List[int] = [0, 1, 2, 3],
52
+ pos_embed: bool = True,
53
+ feature_only: bool = False,
54
+ down_ratio: int = 1,
55
+ ) -> None:
56
+ super(DPTHead, self).__init__()
57
+ self.patch_size = patch_size
58
+ self.activation = activation
59
+ self.conf_activation = conf_activation
60
+ self.pos_embed = pos_embed
61
+ self.feature_only = feature_only
62
+ self.down_ratio = down_ratio
63
+ self.intermediate_layer_idx = intermediate_layer_idx
64
+
65
+ self.norm = nn.LayerNorm(dim_in)
66
+
67
+ # Projection layers for each output channel from tokens.
68
+ self.projects = nn.ModuleList(
69
+ [
70
+ nn.Conv2d(
71
+ in_channels=dim_in,
72
+ out_channels=oc,
73
+ kernel_size=1,
74
+ stride=1,
75
+ padding=0,
76
+ )
77
+ for oc in out_channels
78
+ ]
79
+ )
80
+
81
+ # Resize layers for upsampling feature maps.
82
+ self.resize_layers = nn.ModuleList(
83
+ [
84
+ nn.ConvTranspose2d(
85
+ in_channels=out_channels[0],
86
+ out_channels=out_channels[0],
87
+ kernel_size=4,
88
+ stride=4,
89
+ padding=0,
90
+ ),
91
+ nn.ConvTranspose2d(
92
+ in_channels=out_channels[1],
93
+ out_channels=out_channels[1],
94
+ kernel_size=2,
95
+ stride=2,
96
+ padding=0,
97
+ ),
98
+ nn.Identity(),
99
+ nn.Conv2d(
100
+ in_channels=out_channels[3],
101
+ out_channels=out_channels[3],
102
+ kernel_size=3,
103
+ stride=2,
104
+ padding=1,
105
+ ),
106
+ ]
107
+ )
108
+
109
+ self.scratch = _make_scratch(out_channels, features, expand=False)
110
+
111
+ # Attach additional modules to scratch.
112
+ self.scratch.stem_transpose = None
113
+ self.scratch.refinenet1 = _make_fusion_block(features)
114
+ self.scratch.refinenet2 = _make_fusion_block(features)
115
+ self.scratch.refinenet3 = _make_fusion_block(features)
116
+ self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False)
117
+
118
+ head_features_1 = features
119
+ head_features_2 = 32
120
+
121
+ if feature_only:
122
+ self.scratch.output_conv1 = nn.Conv2d(
123
+ head_features_1, head_features_1, kernel_size=3, stride=1, padding=1
124
+ )
125
+ else:
126
+ self.scratch.output_conv1 = nn.Conv2d(
127
+ head_features_1,
128
+ head_features_1 // 2,
129
+ kernel_size=3,
130
+ stride=1,
131
+ padding=1,
132
+ )
133
+ conv2_in_channels = head_features_1 // 2
134
+
135
+ self.scratch.output_conv2 = nn.Sequential(
136
+ nn.Conv2d(
137
+ conv2_in_channels,
138
+ head_features_2,
139
+ kernel_size=3,
140
+ stride=1,
141
+ padding=1,
142
+ ),
143
+ nn.ReLU(inplace=True),
144
+ nn.Conv2d(
145
+ head_features_2, output_dim, kernel_size=1, stride=1, padding=0
146
+ ),
147
+ )
148
+
149
+ def forward(
150
+ self,
151
+ aggregated_tokens_list: List[torch.Tensor],
152
+ images: torch.Tensor,
153
+ patch_start_idx: int,
154
+ frames_chunk_size: int = 8,
155
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
156
+ """
157
+ Forward pass through the DPT head, supports processing by chunking frames.
158
+ Args:
159
+ aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers.
160
+ images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1].
161
+ patch_start_idx (int): Starting index for patch tokens in the token sequence.
162
+ Used to separate patch tokens from other tokens (e.g., camera or register tokens).
163
+ frames_chunk_size (int, optional): Number of frames to process in each chunk.
164
+ If None or larger than S, all frames are processed at once. Default: 8.
165
+
166
+ Returns:
167
+ Tensor or Tuple[Tensor, Tensor]:
168
+ - If feature_only=True: Feature maps with shape [B, S, C, H, W]
169
+ - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W]
170
+ """
171
+ B, _, _, H, W = images.shape
172
+
173
+ S = aggregated_tokens_list[0].shape[1]
174
+ def run_chunk(frames_start_idx=None, frames_end_idx=None):
175
+ return self._forward_impl(
176
+ aggregated_tokens_list,
177
+ images,
178
+ patch_start_idx,
179
+ frames_start_idx,
180
+ frames_end_idx,
181
+ )
182
+
183
+ # If frames_chunk_size is not specified or greater than S, process all frames at once
184
+ if frames_chunk_size is None or frames_chunk_size >= S:
185
+ return run_chunk()
186
+
187
+ # Otherwise, process frames in chunks to manage memory usage
188
+ assert frames_chunk_size > 0
189
+
190
+ # Process frames in batches
191
+ all_preds = []
192
+ all_conf = []
193
+
194
+ for frames_start_idx in range(0, S, frames_chunk_size):
195
+ frames_end_idx = min(frames_start_idx + frames_chunk_size, S)
196
+ chunk_output = run_chunk(frames_start_idx, frames_end_idx)
197
+ if self.feature_only:
198
+ all_preds.append(chunk_output)
199
+ else:
200
+ chunk_preds, chunk_conf = chunk_output
201
+ all_preds.append(chunk_preds)
202
+ all_conf.append(chunk_conf)
203
+
204
+ # Concatenate results along the sequence dimension
205
+ if self.feature_only:
206
+ return torch.cat(all_preds, dim=1)
207
+ else:
208
+ return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1)
209
+
210
+ def _forward_impl(
211
+ self,
212
+ aggregated_tokens_list: List[torch.Tensor],
213
+ images: torch.Tensor,
214
+ patch_start_idx: int,
215
+ frames_start_idx: int = None,
216
+ frames_end_idx: int = None,
217
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
218
+ """
219
+ Implementation of the forward pass through the DPT head.
220
+
221
+ This method processes a specific chunk of frames from the sequence.
222
+
223
+ Args:
224
+ aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers.
225
+ images (Tensor): Input images with shape [B, S, 3, H, W].
226
+ patch_start_idx (int): Starting index for patch tokens.
227
+ frames_start_idx (int, optional): Starting index for frames to process.
228
+ frames_end_idx (int, optional): Ending index for frames to process.
229
+
230
+ Returns:
231
+ Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence).
232
+ """
233
+
234
+ B, _, _, H, W = images.shape
235
+
236
+ patch_h, patch_w = H // self.patch_size, W // self.patch_size
237
+
238
+ out = []
239
+ dpt_idx = 0
240
+
241
+ for layer_idx in self.intermediate_layer_idx:
242
+ x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:]
243
+
244
+ if frames_start_idx is not None and frames_end_idx is not None:
245
+ x = x[:, frames_start_idx:frames_end_idx]
246
+
247
+ B, S = x.shape[0], x.shape[1]
248
+
249
+ x = x.reshape(B * S, -1, x.shape[-1])
250
+
251
+ x = self.norm(x)
252
+
253
+ x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
254
+
255
+ x = self.projects[dpt_idx](x)
256
+ if self.pos_embed:
257
+ x = self._apply_pos_embed(x, W, H)
258
+ x = self.resize_layers[dpt_idx](x)
259
+
260
+ out.append(x)
261
+ dpt_idx += 1
262
+
263
+ # Fuse features from multiple layers.
264
+ out = self.scratch_forward(out)
265
+ # Interpolate fused output to match target image resolution.
266
+ out = custom_interpolate(
267
+ out,
268
+ (
269
+ int(patch_h * self.patch_size / self.down_ratio),
270
+ int(patch_w * self.patch_size / self.down_ratio),
271
+ ),
272
+ mode="bilinear",
273
+ align_corners=True,
274
+ )
275
+
276
+ if self.pos_embed:
277
+ out = self._apply_pos_embed(out, W, H)
278
+
279
+ if self.feature_only:
280
+ return out.view(B, S, *out.shape[1:])
281
+
282
+ out = self.scratch.output_conv2(out)
283
+ preds, conf = activate_head(
284
+ out, activation=self.activation, conf_activation=self.conf_activation
285
+ )
286
+
287
+ preds = preds.view(B, S, *preds.shape[1:])
288
+ conf = conf.view(B, S, *conf.shape[1:])
289
+ return preds, conf
290
+
291
+ def _apply_pos_embed(
292
+ self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1
293
+ ) -> torch.Tensor:
294
+ """
295
+ Apply positional embedding to tensor x.
296
+ """
297
+ patch_w = x.shape[-1]
298
+ patch_h = x.shape[-2]
299
+ pos_embed = create_uv_grid(
300
+ patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device
301
+ )
302
+ pos_embed = position_grid_to_embed(pos_embed, x.shape[1])
303
+ pos_embed = pos_embed * ratio
304
+ pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)
305
+ return x + pos_embed
306
+
307
+ def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor:
308
+ """
309
+ Forward pass through the fusion blocks.
310
+
311
+ Args:
312
+ features (List[Tensor]): List of feature maps from different layers.
313
+
314
+ Returns:
315
+ Tensor: Fused feature map.
316
+ """
317
+ layer_1, layer_2, layer_3, layer_4 = features
318
+
319
+ layer_1_rn = self.scratch.layer1_rn(layer_1)
320
+ layer_2_rn = self.scratch.layer2_rn(layer_2)
321
+ layer_3_rn = self.scratch.layer3_rn(layer_3)
322
+ layer_4_rn = self.scratch.layer4_rn(layer_4)
323
+
324
+ out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
325
+ del layer_4_rn, layer_4
326
+
327
+ out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:])
328
+ del layer_3_rn, layer_3
329
+
330
+ out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:])
331
+ del layer_2_rn, layer_2
332
+
333
+ out = self.scratch.refinenet1(out, layer_1_rn)
334
+ del layer_1_rn, layer_1
335
+
336
+ out = self.scratch.output_conv1(out)
337
+ return out
338
+
339
+
340
+ ################################################################################
341
+ # Modules
342
+ ################################################################################
343
+
344
+
345
+ def _make_fusion_block(
346
+ features: int, size: int = None, has_residual: bool = True, groups: int = 1
347
+ ) -> nn.Module:
348
+ return FeatureFusionBlock(
349
+ features,
350
+ nn.ReLU(inplace=True),
351
+ deconv=False,
352
+ bn=False,
353
+ expand=False,
354
+ align_corners=True,
355
+ size=size,
356
+ has_residual=has_residual,
357
+ groups=groups,
358
+ )
359
+
360
+
361
+ def _make_scratch(
362
+ in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False
363
+ ) -> nn.Module:
364
+ scratch = nn.Module()
365
+ out_shape1 = out_shape
366
+ out_shape2 = out_shape
367
+ out_shape3 = out_shape
368
+ if len(in_shape) >= 4:
369
+ out_shape4 = out_shape
370
+
371
+ if expand:
372
+ out_shape1 = out_shape
373
+ out_shape2 = out_shape * 2
374
+ out_shape3 = out_shape * 4
375
+ if len(in_shape) >= 4:
376
+ out_shape4 = out_shape * 8
377
+
378
+ scratch.layer1_rn = nn.Conv2d(
379
+ in_shape[0],
380
+ out_shape1,
381
+ kernel_size=3,
382
+ stride=1,
383
+ padding=1,
384
+ bias=False,
385
+ groups=groups,
386
+ )
387
+ scratch.layer2_rn = nn.Conv2d(
388
+ in_shape[1],
389
+ out_shape2,
390
+ kernel_size=3,
391
+ stride=1,
392
+ padding=1,
393
+ bias=False,
394
+ groups=groups,
395
+ )
396
+ scratch.layer3_rn = nn.Conv2d(
397
+ in_shape[2],
398
+ out_shape3,
399
+ kernel_size=3,
400
+ stride=1,
401
+ padding=1,
402
+ bias=False,
403
+ groups=groups,
404
+ )
405
+ if len(in_shape) >= 4:
406
+ scratch.layer4_rn = nn.Conv2d(
407
+ in_shape[3],
408
+ out_shape4,
409
+ kernel_size=3,
410
+ stride=1,
411
+ padding=1,
412
+ bias=False,
413
+ groups=groups,
414
+ )
415
+ return scratch
416
+
417
+
418
+ class ResidualConvUnit(nn.Module):
419
+ """Residual convolution module."""
420
+
421
+ def __init__(self, features, activation, bn, groups=1):
422
+ """Init.
423
+
424
+ Args:
425
+ features (int): number of features
426
+ """
427
+ super().__init__()
428
+
429
+ self.bn = bn
430
+ self.groups = groups
431
+ self.conv1 = nn.Conv2d(
432
+ features,
433
+ features,
434
+ kernel_size=3,
435
+ stride=1,
436
+ padding=1,
437
+ bias=True,
438
+ groups=self.groups,
439
+ )
440
+ self.conv2 = nn.Conv2d(
441
+ features,
442
+ features,
443
+ kernel_size=3,
444
+ stride=1,
445
+ padding=1,
446
+ bias=True,
447
+ groups=self.groups,
448
+ )
449
+
450
+ self.norm1 = None
451
+ self.norm2 = None
452
+
453
+ self.activation = activation
454
+ self.skip_add = nn.quantized.FloatFunctional()
455
+
456
+ def forward(self, x):
457
+ """Forward pass.
458
+
459
+ Args:
460
+ x (tensor): input
461
+
462
+ Returns:
463
+ tensor: output
464
+ """
465
+
466
+ out = self.activation(x)
467
+ out = self.conv1(out)
468
+ if self.norm1 is not None:
469
+ out = self.norm1(out)
470
+
471
+ out = self.activation(out)
472
+ out = self.conv2(out)
473
+ if self.norm2 is not None:
474
+ out = self.norm2(out)
475
+
476
+ return self.skip_add.add(out, x)
477
+
478
+
479
+ class FeatureFusionBlock(nn.Module):
480
+ """Feature fusion block."""
481
+
482
+ def __init__(
483
+ self,
484
+ features,
485
+ activation,
486
+ deconv=False,
487
+ bn=False,
488
+ expand=False,
489
+ align_corners=True,
490
+ size=None,
491
+ has_residual=True,
492
+ groups=1,
493
+ ):
494
+ """Init.
495
+
496
+ Args:
497
+ features (int): number of features
498
+ """
499
+ super(FeatureFusionBlock, self).__init__()
500
+
501
+ self.deconv = deconv
502
+ self.align_corners = align_corners
503
+ self.groups = groups
504
+ self.expand = expand
505
+ out_features = features
506
+ if self.expand == True:
507
+ out_features = features // 2
508
+
509
+ self.out_conv = nn.Conv2d(
510
+ features,
511
+ out_features,
512
+ kernel_size=1,
513
+ stride=1,
514
+ padding=0,
515
+ bias=True,
516
+ groups=self.groups,
517
+ )
518
+
519
+ if has_residual:
520
+ self.resConfUnit1 = ResidualConvUnit(
521
+ features, activation, bn, groups=self.groups
522
+ )
523
+
524
+ self.has_residual = has_residual
525
+ self.resConfUnit2 = ResidualConvUnit(
526
+ features, activation, bn, groups=self.groups
527
+ )
528
+
529
+ self.skip_add = nn.quantized.FloatFunctional()
530
+ self.size = size
531
+
532
+ def forward(self, *xs, size=None):
533
+ """Forward pass.
534
+
535
+ Returns:
536
+ tensor: output
537
+ """
538
+ output = xs[0]
539
+
540
+ if self.has_residual:
541
+ res = self.resConfUnit1(xs[1])
542
+ output = self.skip_add.add(output, res)
543
+
544
+ output = self.resConfUnit2(output)
545
+
546
+ if (size is None) and (self.size is None):
547
+ modifier = {"scale_factor": 2}
548
+ elif size is None:
549
+ modifier = {"size": self.size}
550
+ else:
551
+ modifier = {"size": size}
552
+
553
+ output = custom_interpolate(
554
+ output, **modifier, mode="bilinear", align_corners=self.align_corners
555
+ )
556
+ output = self.out_conv(output)
557
+
558
+ return output
559
+
560
+
561
+ def custom_interpolate(
562
+ x: torch.Tensor,
563
+ size: Tuple[int, int] = None,
564
+ scale_factor: float = None,
565
+ mode: str = "bilinear",
566
+ align_corners: bool = True,
567
+ ) -> torch.Tensor:
568
+ """
569
+ Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate.
570
+ """
571
+ if size is None:
572
+ size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor))
573
+
574
+ INT_MAX = 1610612736
575
+
576
+ input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
577
+
578
+ if input_elements > INT_MAX:
579
+ chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0)
580
+ interpolated_chunks = [
581
+ nn.functional.interpolate(
582
+ chunk, size=size, mode=mode, align_corners=align_corners
583
+ )
584
+ for chunk in chunks
585
+ ]
586
+ x = torch.cat(interpolated_chunks, dim=0)
587
+ return x.contiguous()
588
+ else:
589
+ return nn.functional.interpolate(
590
+ x, size=size, mode=mode, align_corners=align_corners
591
+ )
lingbot_map2/heads/head_act.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE.txt file in the root directory of this source tree.
6
+
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+
11
+
12
+ def activate_pose(
13
+ pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"
14
+ ):
15
+ """
16
+ Activate pose parameters with specified activation functions.
17
+
18
+ Args:
19
+ pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length]
20
+ trans_act: Activation type for translation component
21
+ quat_act: Activation type for quaternion component
22
+ fl_act: Activation type for focal length component
23
+
24
+ Returns:
25
+ Activated pose parameters tensor
26
+ """
27
+ T = pred_pose_enc[..., :3]
28
+ quat = pred_pose_enc[..., 3:7]
29
+ fl = pred_pose_enc[..., 7:] # or fov
30
+
31
+ T = base_pose_act(T, trans_act)
32
+ quat = base_pose_act(quat, quat_act)
33
+ fl = base_pose_act(fl, fl_act) # or fov
34
+
35
+ pred_pose_enc = torch.cat([T, quat, fl], dim=-1)
36
+
37
+ return pred_pose_enc
38
+
39
+
40
+ def base_pose_act(pose_enc, act_type="linear"):
41
+ """
42
+ Apply basic activation function to pose parameters.
43
+
44
+ Args:
45
+ pose_enc: Tensor containing encoded pose parameters
46
+ act_type: Activation type ("linear", "inv_log", "exp", "relu")
47
+
48
+ Returns:
49
+ Activated pose parameters
50
+ """
51
+ if act_type == "linear":
52
+ return pose_enc
53
+ elif act_type == "inv_log":
54
+ return inverse_log_transform(pose_enc)
55
+ elif act_type == "exp":
56
+ return torch.exp(pose_enc)
57
+ elif act_type == "relu":
58
+ return F.relu(pose_enc)
59
+ else:
60
+ raise ValueError(f"Unknown act_type: {act_type}")
61
+
62
+
63
+ def activate_head(out, activation="norm_exp", conf_activation="expp1"):
64
+ """
65
+ Process network output to extract 3D points and confidence values.
66
+
67
+ Args:
68
+ out: Network output tensor (B, C, H, W)
69
+ activation: Activation type for 3D points
70
+ conf_activation: Activation type for confidence values
71
+
72
+ Returns:
73
+ Tuple of (3D points tensor, confidence tensor)
74
+ """
75
+ # Move channels from last dim to the 4th dimension => (B, H, W, C)
76
+ fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected
77
+
78
+ # Split into xyz (first C-1 channels) and confidence (last channel)
79
+ xyz = fmap[:, :, :, :-1]
80
+ conf = fmap[:, :, :, -1]
81
+
82
+ if activation == "norm_exp":
83
+ d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8)
84
+ xyz_normed = xyz / d
85
+ pts3d = xyz_normed * torch.expm1(d)
86
+ elif activation == "norm":
87
+ pts3d = xyz / xyz.norm(dim=-1, keepdim=True)
88
+ elif activation == "exp":
89
+ pts3d = torch.exp(xyz)
90
+ elif activation == "relu":
91
+ pts3d = F.relu(xyz)
92
+ elif activation == "inv_log":
93
+ pts3d = inverse_log_transform(xyz)
94
+ elif activation == "xy_inv_log":
95
+ xy, z = xyz.split([2, 1], dim=-1)
96
+ z = inverse_log_transform(z)
97
+ pts3d = torch.cat([xy * z, z], dim=-1)
98
+ elif activation == "sigmoid":
99
+ pts3d = torch.sigmoid(xyz)
100
+ elif activation == "linear":
101
+ pts3d = xyz
102
+ else:
103
+ raise ValueError(f"Unknown activation: {activation}")
104
+
105
+ if conf_activation == "expp1":
106
+ conf_out = 1 + conf.exp()
107
+ elif conf_activation == "expp0":
108
+ conf_out = conf.exp()
109
+ elif conf_activation == "sigmoid":
110
+ conf_out = torch.sigmoid(conf)
111
+ else:
112
+ raise ValueError(f"Unknown conf_activation: {conf_activation}")
113
+
114
+ return pts3d, conf_out
115
+
116
+
117
+ def inverse_log_transform(y):
118
+ """
119
+ Apply inverse log transform: sign(y) * (exp(|y|) - 1)
120
+
121
+ Args:
122
+ y: Input tensor
123
+
124
+ Returns:
125
+ Transformed tensor
126
+ """
127
+ return torch.sign(y) * (torch.expm1(torch.abs(y)))
lingbot_map2/heads/utils.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE.txt file in the root directory of this source tree.
6
+
7
+ import torch
8
+
9
+
10
+ def position_grid_to_embed(
11
+ pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100
12
+ ) -> torch.Tensor:
13
+ """
14
+ Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC)
15
+
16
+ Args:
17
+ pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates
18
+ embed_dim: Output channel dimension for embeddings
19
+
20
+ Returns:
21
+ Tensor of shape (H, W, embed_dim) with positional embeddings
22
+ """
23
+ H, W, grid_dim = pos_grid.shape
24
+ assert grid_dim == 2
25
+ pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2)
26
+
27
+ # Process x and y coordinates separately
28
+ emb_x = make_sincos_pos_embed(
29
+ embed_dim // 2, pos_flat[:, 0], omega_0=omega_0
30
+ ) # [1, H*W, D/2]
31
+ emb_y = make_sincos_pos_embed(
32
+ embed_dim // 2, pos_flat[:, 1], omega_0=omega_0
33
+ ) # [1, H*W, D/2]
34
+
35
+ # Combine and reshape
36
+ emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D]
37
+
38
+ return emb.view(H, W, embed_dim) # [H, W, D]
39
+
40
+
41
+ def make_sincos_pos_embed(
42
+ embed_dim: int, pos: torch.Tensor, omega_0: float = 100
43
+ ) -> torch.Tensor:
44
+ """
45
+ This function generates a 1D positional embedding from a given grid using sine and cosine functions.
46
+
47
+ Args:
48
+ - embed_dim: The embedding dimension.
49
+ - pos: The position to generate the embedding from.
50
+
51
+ Returns:
52
+ - emb: The generated 1D positional embedding.
53
+ """
54
+ assert embed_dim % 2 == 0
55
+ device = pos.device
56
+ omega = torch.arange(
57
+ embed_dim // 2,
58
+ dtype=torch.float32 if device.type == "mps" else torch.double,
59
+ device=device,
60
+ )
61
+ omega /= embed_dim / 2.0
62
+ omega = 1.0 / omega_0**omega # (D/2,)
63
+
64
+ pos = pos.reshape(-1) # (M,)
65
+ out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
66
+
67
+ emb_sin = torch.sin(out) # (M, D/2)
68
+ emb_cos = torch.cos(out) # (M, D/2)
69
+
70
+ emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
71
+ return emb.float()
72
+
73
+
74
+ # Inspired by https://github.com/microsoft/moge
75
+
76
+
77
+ def create_uv_grid(
78
+ width: int,
79
+ height: int,
80
+ aspect_ratio: float = None,
81
+ dtype: torch.dtype = None,
82
+ device: torch.device = None,
83
+ ) -> torch.Tensor:
84
+ """
85
+ Create a normalized UV grid of shape (width, height, 2).
86
+
87
+ The grid spans horizontally and vertically according to an aspect ratio,
88
+ ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right
89
+ corner is at (x_span, y_span), normalized by the diagonal of the plane.
90
+
91
+ Args:
92
+ width (int): Number of points horizontally.
93
+ height (int): Number of points vertically.
94
+ aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height.
95
+ dtype (torch.dtype, optional): Data type of the resulting tensor.
96
+ device (torch.device, optional): Device on which the tensor is created.
97
+
98
+ Returns:
99
+ torch.Tensor: A (width, height, 2) tensor of UV coordinates.
100
+ """
101
+ # Derive aspect ratio if not explicitly provided
102
+ if aspect_ratio is None:
103
+ aspect_ratio = float(width) / float(height)
104
+
105
+ # Compute normalized spans for X and Y
106
+ diag_factor = (aspect_ratio**2 + 1.0) ** 0.5
107
+ span_x = aspect_ratio / diag_factor
108
+ span_y = 1.0 / diag_factor
109
+
110
+ # Establish the linspace boundaries
111
+ left_x = -span_x * (width - 1) / width
112
+ right_x = span_x * (width - 1) / width
113
+ top_y = -span_y * (height - 1) / height
114
+ bottom_y = span_y * (height - 1) / height
115
+
116
+ # Generate 1D coordinates
117
+ x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device)
118
+ y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device)
119
+
120
+ # Create 2D meshgrid (width x height) and stack into UV
121
+ uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy")
122
+ uv_grid = torch.stack((uu, vv), dim=-1)
123
+
124
+ return uv_grid
lingbot_map2/layers/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Transformer layers, positional embeddings and the DINOv3 encoder."""
lingbot_map2/layers/block.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # Transformer blocks for online inference. See LICENSES/THIRD_PARTY.md.
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from .layer_scale import LayerScale
10
+ from .mlp import Mlp
11
+
12
+
13
+ class Attention(nn.Module):
14
+ def __init__(self, dim, num_heads, *, qk_norm=False, rope=None):
15
+ super().__init__()
16
+ self.num_heads = num_heads
17
+ self.head_dim = dim // num_heads
18
+ self.qkv = nn.Linear(dim, 3 * dim)
19
+ self.q_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
20
+ self.k_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
21
+ self.proj = nn.Linear(dim, dim)
22
+ self.proj_drop = nn.Dropout(0.0)
23
+ self.rope = rope
24
+
25
+ def project(self, x):
26
+ batch, tokens, _ = x.shape
27
+ q, k, v = (
28
+ self.qkv(x)
29
+ .reshape(batch, tokens, 3, self.num_heads, self.head_dim)
30
+ .permute(2, 0, 3, 1, 4)
31
+ .unbind(0)
32
+ )
33
+ return self.q_norm(q), self.k_norm(k), v
34
+
35
+ def forward(self, x, pos=None):
36
+ q, k, v = self.project(x)
37
+ if self.rope is not None:
38
+ q, k = self.rope(q, pos), self.rope(k, pos)
39
+ output = F.scaled_dot_product_attention(q, k, v)
40
+ return self.proj_drop(self.proj(output.transpose(1, 2).reshape(x.shape)))
41
+
42
+
43
+ class Block(nn.Module):
44
+ def __init__(self, dim, num_heads, *, qk_norm=True, rope=None):
45
+ super().__init__()
46
+ self.norm1 = nn.LayerNorm(dim)
47
+ self.attn = Attention(dim, num_heads, qk_norm=qk_norm, rope=rope)
48
+ self.ls1 = LayerScale(dim, init_values=0.01)
49
+ self.norm2 = nn.LayerNorm(dim)
50
+ self.mlp = Mlp(in_features=dim, hidden_features=dim * 4)
51
+ self.ls2 = LayerScale(dim, init_values=0.01)
52
+
53
+ def forward(self, x, pos=None):
54
+ x = x + self.ls1(self.attn(self.norm1(x), pos))
55
+ return x + self.ls2(self.mlp(self.norm2(x)))
lingbot_map2/layers/dinov3/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the FAIR Noncommercial Research License v1
6
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
7
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
8
+
9
+ from .attention import LinearKMaskedBias, SelfAttention
10
+ from .block import SelfAttentionBlock
11
+ from .ffn_layers import Mlp, SwiGLUFFN
12
+ from .layer_scale import LayerScale
13
+ from .patch_embed import PatchEmbed
14
+ from .rms_norm import RMSNorm
15
+ from .rope_position_encoding import RopePositionEmbedding
16
+
17
+ __all__ = [
18
+ "LayerScale",
19
+ "LinearKMaskedBias",
20
+ "Mlp",
21
+ "PatchEmbed",
22
+ "RMSNorm",
23
+ "RopePositionEmbedding",
24
+ "SelfAttention",
25
+ "SelfAttentionBlock",
26
+ "SwiGLUFFN",
27
+ ]
28
+
29
+
30
+ from .vision_transformer import DinoVisionTransformer
31
+
32
+
33
+ def build_encoder(patch_size: int, embed_dim: int) -> DinoVisionTransformer:
34
+ """Build the DINOv3 ViT-L/16 image encoder."""
35
+ model = DinoVisionTransformer(
36
+ img_size=224,
37
+ patch_size=patch_size,
38
+ in_chans=3,
39
+ pos_embed_rope_base=100,
40
+ pos_embed_rope_normalize_coords="max",
41
+ pos_embed_rope_dtype="fp32",
42
+ embed_dim=embed_dim,
43
+ depth=24,
44
+ num_heads=16,
45
+ ffn_ratio=4,
46
+ qkv_bias=True,
47
+ drop_path_rate=0.0,
48
+ layerscale_init=1.0e-5,
49
+ norm_layer="layernormbf16",
50
+ ffn_layer="mlp",
51
+ ffn_bias=True,
52
+ proj_bias=True,
53
+ n_storage_tokens=4,
54
+ mask_k_bias=True,
55
+ )
56
+ model.init_weights()
57
+ return model
lingbot_map2/layers/dinov3/attention.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ import math
8
+ from typing import Tuple
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from torch import Tensor, nn
13
+
14
+
15
+ def rope_rotate_half(x: Tensor) -> Tensor:
16
+ x1, x2 = x.chunk(2, dim=-1)
17
+ return torch.cat([-x2, x1], dim=-1)
18
+
19
+
20
+ def rope_apply(x: Tensor, sin: Tensor, cos: Tensor) -> Tensor:
21
+ return (x * cos) + (rope_rotate_half(x) * sin)
22
+
23
+
24
+ class LinearKMaskedBias(nn.Linear):
25
+ def __init__(self, *args, **kwargs):
26
+ super().__init__(*args, **kwargs)
27
+ o = self.out_features
28
+ assert o % 3 == 0
29
+ if self.bias is not None:
30
+ self.register_buffer(
31
+ "bias_mask", torch.full_like(self.bias, fill_value=math.nan)
32
+ )
33
+
34
+ def forward(self, input: Tensor) -> Tensor:
35
+ masked_bias = (
36
+ self.bias * self.bias_mask.to(self.bias.dtype)
37
+ if self.bias is not None
38
+ else None
39
+ )
40
+ return F.linear(input, self.weight, masked_bias)
41
+
42
+
43
+ class SelfAttention(nn.Module):
44
+ def __init__(
45
+ self,
46
+ dim: int,
47
+ num_heads: int = 8,
48
+ qkv_bias: bool = False,
49
+ proj_bias: bool = True,
50
+ attn_drop: float = 0.0,
51
+ proj_drop: float = 0.0,
52
+ mask_k_bias: bool = False,
53
+ use_qk_norm: bool = False,
54
+ device=None,
55
+ ) -> None:
56
+ super().__init__()
57
+ self.num_heads = num_heads
58
+ head_dim = dim // num_heads
59
+ self.scale = head_dim**-0.5
60
+ self.use_qk_norm = use_qk_norm
61
+ if self.use_qk_norm:
62
+ self.q_norm = nn.LayerNorm(head_dim, eps=1e-5)
63
+ self.k_norm = nn.LayerNorm(head_dim, eps=1e-5)
64
+ else:
65
+ self.q_norm = None
66
+ self.k_norm = None
67
+
68
+ linear_class = LinearKMaskedBias if mask_k_bias else nn.Linear
69
+ self.qkv = linear_class(dim, dim * 3, bias=qkv_bias, device=device)
70
+ self.attn_drop = nn.Dropout(attn_drop)
71
+ self.proj = nn.Linear(dim, dim, bias=proj_bias, device=device)
72
+ self.proj_drop = nn.Dropout(proj_drop)
73
+
74
+ def apply_rope(
75
+ self, q: Tensor, k: Tensor, rope: Tensor | Tuple[Tensor, Tensor]
76
+ ) -> Tuple[Tensor, Tensor]:
77
+ q_dtype = q.dtype
78
+ k_dtype = k.dtype
79
+ sin, cos = rope
80
+ rope_dtype = sin.dtype
81
+ q = q.to(dtype=rope_dtype)
82
+ k = k.to(dtype=rope_dtype)
83
+ N = q.shape[-2]
84
+ prefix = N - sin.shape[-2]
85
+ assert prefix >= 0
86
+ q_prefix = q[:, :, :prefix, :]
87
+ q = rope_apply(q[:, :, prefix:, :], sin, cos)
88
+ q = torch.cat((q_prefix, q), dim=-2)
89
+ k_prefix = k[:, :, :prefix, :]
90
+ k = rope_apply(k[:, :, prefix:, :], sin, cos)
91
+ k = torch.cat((k_prefix, k), dim=-2)
92
+ q = q.to(dtype=q_dtype)
93
+ k = k.to(dtype=k_dtype)
94
+ return q, k
95
+
96
+ def forward(self, x: Tensor, rope=None) -> Tensor:
97
+ B, N, C = x.shape
98
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
99
+ q, k, v = [t.transpose(1, 2) for t in torch.unbind(qkv, 2)]
100
+ if self.use_qk_norm:
101
+ q, k = self.q_norm(q), self.k_norm(k)
102
+ if rope is not None:
103
+ q, k = self.apply_rope(q, k, rope)
104
+ output = F.scaled_dot_product_attention(q, k, v)
105
+ return self.proj_drop(self.proj(output.transpose(1, 2).reshape(B, N, C)))
lingbot_map2/layers/dinov3/block.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ from typing import Callable
8
+
9
+ from torch import Tensor, nn
10
+
11
+ from .attention import SelfAttention
12
+ from .ffn_layers import Mlp
13
+ from .layer_scale import LayerScale
14
+
15
+
16
+ class SelfAttentionBlock(nn.Module):
17
+ def __init__(
18
+ self,
19
+ dim: int,
20
+ num_heads: int,
21
+ ffn_ratio: float = 4.0,
22
+ qkv_bias: bool = False,
23
+ proj_bias: bool = True,
24
+ ffn_bias: bool = True,
25
+ drop: float = 0.0,
26
+ attn_drop: float = 0.0,
27
+ init_values=None,
28
+ drop_path: float = 0.0,
29
+ act_layer: Callable[..., nn.Module] = nn.GELU,
30
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
31
+ attn_class: Callable[..., nn.Module] = SelfAttention,
32
+ ffn_layer: Callable[..., nn.Module] = Mlp,
33
+ mask_k_bias: bool = False,
34
+ use_qk_norm: bool = False,
35
+ device=None,
36
+ ) -> None:
37
+ super().__init__()
38
+ self.norm1 = norm_layer(dim)
39
+ self.attn = attn_class(
40
+ dim,
41
+ num_heads=num_heads,
42
+ qkv_bias=qkv_bias,
43
+ proj_bias=proj_bias,
44
+ attn_drop=attn_drop,
45
+ proj_drop=drop,
46
+ mask_k_bias=mask_k_bias,
47
+ use_qk_norm=use_qk_norm,
48
+ device=device,
49
+ )
50
+ self.ls1 = (
51
+ LayerScale(dim, init_values=init_values, device=device)
52
+ if init_values
53
+ else nn.Identity()
54
+ )
55
+
56
+ self.norm2 = norm_layer(dim)
57
+ mlp_hidden_dim = int(dim * ffn_ratio)
58
+ self.mlp = ffn_layer(
59
+ in_features=dim,
60
+ hidden_features=mlp_hidden_dim,
61
+ act_layer=act_layer,
62
+ drop=drop,
63
+ bias=ffn_bias,
64
+ device=device,
65
+ )
66
+ self.ls2 = (
67
+ LayerScale(dim, init_values=init_values, device=device)
68
+ if init_values
69
+ else nn.Identity()
70
+ )
71
+
72
+ self.sample_drop_ratio = drop_path
73
+
74
+ def forward(self, x_or_x_list, rope_or_rope_list=None):
75
+ def block(x, rope):
76
+ x_attn = x + self.ls1(self.attn(self.norm1(x), rope=rope))
77
+ return x_attn + self.ls2(self.mlp(self.norm2(x_attn)))
78
+
79
+ if isinstance(x_or_x_list, Tensor):
80
+ return block(x_or_x_list, rope_or_rope_list)
81
+ ropes = rope_or_rope_list or [None] * len(x_or_x_list)
82
+ return [block(x, rope) for x, rope in zip(x_or_x_list, ropes)]
lingbot_map2/layers/dinov3/ffn_layers.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ from typing import Callable, List, Optional
8
+
9
+ import torch.nn.functional as F
10
+ from torch import Tensor, nn
11
+
12
+ from .utils import cat_keep_shapes, uncat_with_shapes
13
+
14
+
15
+ class ListForwardMixin(object):
16
+ def forward(self, x: Tensor):
17
+ raise NotImplementedError
18
+
19
+ def forward_list(self, x_list: List[Tensor]) -> List[Tensor]:
20
+ x_flat, shapes, num_tokens = cat_keep_shapes(x_list)
21
+ x_flat = self.forward(x_flat)
22
+ return uncat_with_shapes(x_flat, shapes, num_tokens)
23
+
24
+
25
+ class Mlp(nn.Module, ListForwardMixin):
26
+ def __init__(
27
+ self,
28
+ in_features: int,
29
+ hidden_features: Optional[int] = None,
30
+ out_features: Optional[int] = None,
31
+ act_layer: Callable[..., nn.Module] = nn.GELU,
32
+ drop: float = 0.0,
33
+ bias: bool = True,
34
+ device=None,
35
+ ) -> None:
36
+ super().__init__()
37
+ out_features = out_features or in_features
38
+ hidden_features = hidden_features or in_features
39
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias, device=device)
40
+ self.act = act_layer()
41
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias, device=device)
42
+ self.drop = nn.Dropout(drop)
43
+
44
+ def forward(self, x: Tensor) -> Tensor:
45
+ x = self.fc1(x)
46
+ x = self.act(x)
47
+ x = self.drop(x)
48
+ x = self.fc2(x)
49
+ x = self.drop(x)
50
+ return x
51
+
52
+
53
+ class SwiGLUFFN(nn.Module, ListForwardMixin):
54
+ def __init__(
55
+ self,
56
+ in_features: int,
57
+ hidden_features: Optional[int] = None,
58
+ out_features: Optional[int] = None,
59
+ act_layer: Optional[Callable[..., nn.Module]] = None,
60
+ drop: float = 0.0,
61
+ bias: bool = True,
62
+ align_to: int = 8,
63
+ device=None,
64
+ ) -> None:
65
+ super().__init__()
66
+ out_features = out_features or in_features
67
+ hidden_features = hidden_features or in_features
68
+ d = int(hidden_features * 2 / 3)
69
+ swiglu_hidden_features = d + (-d % align_to)
70
+ self.w1 = nn.Linear(
71
+ in_features, swiglu_hidden_features, bias=bias, device=device
72
+ )
73
+ self.w2 = nn.Linear(
74
+ in_features, swiglu_hidden_features, bias=bias, device=device
75
+ )
76
+ self.w3 = nn.Linear(
77
+ swiglu_hidden_features, out_features, bias=bias, device=device
78
+ )
79
+
80
+ def forward(self, x: Tensor) -> Tensor:
81
+ x1 = self.w1(x)
82
+ x2 = self.w2(x)
83
+ hidden = F.silu(x1) * x2
84
+ return self.w3(hidden)
lingbot_map2/layers/dinov3/layer_scale.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ from typing import Union
8
+
9
+ import torch
10
+ from torch import Tensor, nn
11
+
12
+
13
+ class LayerScale(nn.Module):
14
+ def __init__(
15
+ self,
16
+ dim: int,
17
+ init_values: Union[float, Tensor] = 1e-5,
18
+ inplace: bool = False,
19
+ device=None,
20
+ ) -> None:
21
+ super().__init__()
22
+ self.inplace = inplace
23
+ self.gamma = nn.Parameter(torch.empty(dim, device=device))
24
+ self.init_values = init_values
25
+
26
+ def reset_parameters(self):
27
+ nn.init.constant_(self.gamma, self.init_values)
28
+
29
+ def forward(self, x: Tensor) -> Tensor:
30
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
lingbot_map2/layers/dinov3/patch_embed.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ import math
8
+ from typing import Callable, Tuple, Union
9
+
10
+ from torch import Tensor, nn
11
+
12
+
13
+ def make_2tuple(x):
14
+ if isinstance(x, tuple):
15
+ assert len(x) == 2
16
+ return x
17
+ assert isinstance(x, int)
18
+ return (x, x)
19
+
20
+
21
+ class PatchEmbed(nn.Module):
22
+ """2D image to patch embedding: (B,C,H,W) -> (B,N,D)"""
23
+
24
+ def __init__(
25
+ self,
26
+ img_size: Union[int, Tuple[int, int]] = 224,
27
+ patch_size: Union[int, Tuple[int, int]] = 16,
28
+ in_chans: int = 3,
29
+ embed_dim: int = 768,
30
+ norm_layer: Callable | None = None,
31
+ flatten_embedding: bool = True,
32
+ ) -> None:
33
+ super().__init__()
34
+
35
+ image_HW = make_2tuple(img_size)
36
+ patch_HW = make_2tuple(patch_size)
37
+ patch_grid_size = (
38
+ image_HW[0] // patch_HW[0],
39
+ image_HW[1] // patch_HW[1],
40
+ )
41
+
42
+ self.img_size = image_HW
43
+ self.patch_size = patch_HW
44
+ self.patches_resolution = patch_grid_size
45
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
46
+
47
+ self.in_chans = in_chans
48
+ self.embed_dim = embed_dim
49
+
50
+ self.flatten_embedding = flatten_embedding
51
+
52
+ self.proj = nn.Conv2d(
53
+ in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW
54
+ )
55
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
56
+
57
+ def forward(self, x: Tensor) -> Tensor:
58
+ _, _, H, W = x.shape
59
+ x = self.proj(x)
60
+ H, W = x.size(2), x.size(3)
61
+ x = x.flatten(2).transpose(1, 2)
62
+ x = self.norm(x)
63
+ if not self.flatten_embedding:
64
+ x = x.reshape(-1, H, W, self.embed_dim)
65
+ return x
66
+
67
+ def flops(self) -> float:
68
+ Ho, Wo = self.patches_resolution
69
+ flops = (
70
+ Ho
71
+ * Wo
72
+ * self.embed_dim
73
+ * self.in_chans
74
+ * (self.patch_size[0] * self.patch_size[1])
75
+ )
76
+ if self.norm is not None:
77
+ flops += Ho * Wo * self.embed_dim
78
+ return flops
79
+
80
+ def reset_parameters(self):
81
+ k = 1 / (self.in_chans * (self.patch_size[0] ** 2))
82
+ nn.init.uniform_(self.proj.weight, -math.sqrt(k), math.sqrt(k))
83
+ if self.proj.bias is not None:
84
+ nn.init.uniform_(self.proj.bias, -math.sqrt(k), math.sqrt(k))
lingbot_map2/layers/dinov3/rms_norm.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ import torch
8
+ from torch import Tensor, nn
9
+
10
+
11
+ class RMSNorm(nn.Module):
12
+ def __init__(self, dim: int, eps: float = 1e-5):
13
+ super().__init__()
14
+ self.weight = nn.Parameter(torch.ones(dim))
15
+ self.eps = eps
16
+
17
+ def reset_parameters(self) -> None:
18
+ nn.init.constant_(self.weight, 1)
19
+
20
+ def _norm(self, x: Tensor) -> Tensor:
21
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
22
+
23
+ def forward(self, x: Tensor) -> Tensor:
24
+ output = self._norm(x.float()).type_as(x)
25
+ return output * self.weight
lingbot_map2/layers/dinov3/rope_position_encoding.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the FAIR Noncommercial Research License v1
5
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
6
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
7
+ import math
8
+ from typing import Literal
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torch import Tensor, nn
13
+
14
+
15
+ class RopePositionEmbedding(nn.Module):
16
+ """2D axial RoPE used by the VGGT-Omega DINOv3 backbone and aggregator."""
17
+
18
+ def __init__(
19
+ self,
20
+ embed_dim: int,
21
+ *,
22
+ num_heads: int,
23
+ base: float | None = 100.0,
24
+ min_period: float | None = None,
25
+ max_period: float | None = None,
26
+ normalize_coords: Literal["min", "max", "separate"] = "separate",
27
+ shift_coords: float | None = None,
28
+ jitter_coords: float | None = None,
29
+ rescale_coords: float | None = None,
30
+ dtype: torch.dtype | None = None,
31
+ device: torch.device | None = None,
32
+ ):
33
+ super().__init__()
34
+ assert embed_dim % (4 * num_heads) == 0
35
+ both_periods = min_period is not None and max_period is not None
36
+ if (base is None and not both_periods) or (base is not None and both_periods):
37
+ raise ValueError(
38
+ "Either `base` or `min_period`+`max_period` must be provided."
39
+ )
40
+
41
+ D_head = embed_dim // num_heads
42
+ self.base = base
43
+ self.min_period = min_period
44
+ self.max_period = max_period
45
+ self.D_head = D_head
46
+ self.normalize_coords = normalize_coords
47
+ self.shift_coords = shift_coords
48
+ self.jitter_coords = jitter_coords
49
+ self.rescale_coords = rescale_coords
50
+
51
+ self.dtype = dtype
52
+ self.register_buffer(
53
+ "periods",
54
+ torch.empty(D_head // 4, device=device, dtype=dtype),
55
+ persistent=True,
56
+ )
57
+ self._init_weights()
58
+
59
+ def forward(self, *, H: int, W: int) -> tuple[Tensor, Tensor]:
60
+ device = self.periods.device
61
+ dtype = self.dtype
62
+ dd = {"device": device, "dtype": dtype}
63
+
64
+ if self.normalize_coords == "max":
65
+ max_HW = max(H, W)
66
+ coords_h = torch.arange(0.5, H, **dd) / max_HW
67
+ coords_w = torch.arange(0.5, W, **dd) / max_HW
68
+ elif self.normalize_coords == "min":
69
+ min_HW = min(H, W)
70
+ coords_h = torch.arange(0.5, H, **dd) / min_HW
71
+ coords_w = torch.arange(0.5, W, **dd) / min_HW
72
+ elif self.normalize_coords == "separate":
73
+ coords_h = torch.arange(0.5, H, **dd) / H
74
+ coords_w = torch.arange(0.5, W, **dd) / W
75
+ else:
76
+ raise ValueError(f"Unknown normalize_coords: {self.normalize_coords}")
77
+ coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
78
+ coords = coords.flatten(0, 1)
79
+ coords = 2.0 * coords - 1.0
80
+
81
+ if self.training and self.shift_coords is not None:
82
+ shift_hw = torch.empty(2, **dd).uniform_(
83
+ -self.shift_coords, self.shift_coords
84
+ )
85
+ coords += shift_hw[None, :]
86
+
87
+ if self.training and self.jitter_coords is not None:
88
+ jitter_max = np.log(self.jitter_coords)
89
+ jitter_min = -jitter_max
90
+ jitter_hw = torch.empty(2, **dd).uniform_(jitter_min, jitter_max).exp()
91
+ coords *= jitter_hw[None, :]
92
+
93
+ if self.training and self.rescale_coords is not None:
94
+ rescale_max = np.log(self.rescale_coords)
95
+ rescale_min = -rescale_max
96
+ rescale_hw = torch.empty(1, **dd).uniform_(rescale_min, rescale_max).exp()
97
+ coords *= rescale_hw
98
+
99
+ angles = 2 * math.pi * coords[:, :, None] / self.periods[None, None, :]
100
+ angles = angles.flatten(1, 2)
101
+ angles = angles.tile(2)
102
+ cos = torch.cos(angles)
103
+ sin = torch.sin(angles)
104
+
105
+ return (sin, cos)
106
+
107
+ def _init_weights(self):
108
+ device = self.periods.device
109
+ dtype = self.dtype
110
+ if self.base is not None:
111
+ periods = self.base ** (
112
+ 2
113
+ * torch.arange(self.D_head // 4, device=device, dtype=dtype)
114
+ / (self.D_head // 2)
115
+ )
116
+ else:
117
+ base = self.max_period / self.min_period
118
+ exponents = torch.linspace(
119
+ 0, 1, self.D_head // 4, device=device, dtype=dtype
120
+ )
121
+ periods = base**exponents
122
+ periods = periods / base
123
+ periods = periods * self.max_period
124
+ self.periods.data = periods
lingbot_map2/layers/dinov3/utils.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the FAIR Noncommercial Research License v1
6
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
7
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
8
+
9
+ import logging
10
+ import os
11
+ import random
12
+ import subprocess
13
+ from typing import Callable, List, Optional, Tuple
14
+
15
+ import numpy as np
16
+ import torch
17
+ from torch import Tensor, nn
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def cat_keep_shapes(x_list: List[Tensor]) -> Tuple[Tensor, List[Tuple[int]], List[int]]:
23
+ shapes = [x.shape for x in x_list]
24
+ num_tokens = [x.select(dim=-1, index=0).numel() for x in x_list]
25
+ flattened = torch.cat([x.flatten(0, -2) for x in x_list])
26
+ return flattened, shapes, num_tokens
27
+
28
+
29
+ def uncat_with_shapes(
30
+ flattened: Tensor, shapes: List[Tuple[int]], num_tokens: List[int]
31
+ ) -> List[Tensor]:
32
+ outputs_splitted = torch.split_with_sizes(flattened, num_tokens, dim=0)
33
+ shapes_adjusted = [
34
+ shape[:-1] + torch.Size([flattened.shape[-1]]) for shape in shapes
35
+ ]
36
+ outputs_reshaped = [
37
+ o.reshape(shape) for o, shape in zip(outputs_splitted, shapes_adjusted)
38
+ ]
39
+ return outputs_reshaped
40
+
41
+
42
+ def named_replace(
43
+ fn: Callable,
44
+ module: nn.Module,
45
+ name: str = "",
46
+ depth_first: bool = True,
47
+ include_root: bool = False,
48
+ ) -> nn.Module:
49
+ if not depth_first and include_root:
50
+ module = fn(module=module, name=name)
51
+ for child_name_o, child_module in list(module.named_children()):
52
+ child_name = ".".join((name, child_name_o)) if name else child_name_o
53
+ new_child = named_replace(
54
+ fn=fn,
55
+ module=child_module,
56
+ name=child_name,
57
+ depth_first=depth_first,
58
+ include_root=True,
59
+ )
60
+ setattr(module, child_name_o, new_child)
61
+
62
+ if depth_first and include_root:
63
+ module = fn(module=module, name=name)
64
+ return module
65
+
66
+
67
+ def named_apply(
68
+ fn: Callable,
69
+ module: nn.Module,
70
+ name: str = "",
71
+ depth_first: bool = True,
72
+ include_root: bool = False,
73
+ ) -> nn.Module:
74
+ if not depth_first and include_root:
75
+ fn(module=module, name=name)
76
+ for child_name, child_module in module.named_children():
77
+ child_name = ".".join((name, child_name)) if name else child_name
78
+ named_apply(
79
+ fn=fn,
80
+ module=child_module,
81
+ name=child_name,
82
+ depth_first=depth_first,
83
+ include_root=True,
84
+ )
85
+ if depth_first and include_root:
86
+ fn(module=module, name=name)
87
+ return module
88
+
89
+
90
+ def fix_random_seeds(seed: int = 31):
91
+ torch.manual_seed(seed)
92
+ torch.cuda.manual_seed_all(seed)
93
+ np.random.seed(seed)
94
+ random.seed(seed)
95
+
96
+
97
+ def get_sha() -> str:
98
+ cwd = os.path.dirname(os.path.abspath(__file__))
99
+
100
+ def _run(command):
101
+ return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
102
+
103
+ sha = "N/A"
104
+ diff = "clean"
105
+ branch = "N/A"
106
+ try:
107
+ sha = _run(["git", "rev-parse", "HEAD"])
108
+ subprocess.check_output(["git", "diff"], cwd=cwd)
109
+ diff = _run(["git", "diff-index", "HEAD"])
110
+ diff = "has uncommited changes" if diff else "clean"
111
+ branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"])
112
+ except Exception:
113
+ pass
114
+ return f"sha: {sha}, status: {diff}, branch: {branch}"
115
+
116
+
117
+ def get_conda_env() -> Tuple[Optional[str], Optional[str]]:
118
+ return os.environ.get("CONDA_DEFAULT_ENV"), os.environ.get("CONDA_PREFIX")
119
+
120
+
121
+ def count_parameters(module: nn.Module) -> int:
122
+ c = 0
123
+ for m in module.parameters():
124
+ c += m.nelement()
125
+ return c
126
+
127
+
128
+ def has_batchnorms(model: nn.Module) -> bool:
129
+ bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)
130
+ for _, module in model.named_modules():
131
+ if isinstance(module, bn_types):
132
+ return True
133
+ return False
lingbot_map2/layers/dinov3/vision_transformer.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the FAIR Noncommercial Research License v1
6
+ # (LICENSES/FAIR-Noncommercial-Research-License-v1.txt) and the DINOv3 License
7
+ # Agreement (LICENSES/DINOv3-License.txt). See LICENSES/THIRD_PARTY.md.
8
+ import logging
9
+ from functools import partial
10
+ from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union
11
+
12
+ import torch
13
+ import torch.nn.init
14
+ from torch import Tensor, nn
15
+
16
+ from . import (
17
+ LayerScale,
18
+ Mlp,
19
+ PatchEmbed,
20
+ RMSNorm,
21
+ RopePositionEmbedding,
22
+ SelfAttentionBlock,
23
+ SwiGLUFFN,
24
+ )
25
+ from .utils import named_apply
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ ffn_layer_dict = {
30
+ "mlp": Mlp,
31
+ "swiglu": SwiGLUFFN,
32
+ "swiglu32": partial(SwiGLUFFN, align_to=32),
33
+ "swiglu64": partial(SwiGLUFFN, align_to=64),
34
+ "swiglu128": partial(SwiGLUFFN, align_to=128),
35
+ }
36
+
37
+ norm_layer_dict = {
38
+ "layernorm": partial(nn.LayerNorm, eps=1e-6),
39
+ "layernormbf16": partial(nn.LayerNorm, eps=1e-5),
40
+ "rmsnorm": RMSNorm,
41
+ }
42
+
43
+ dtype_dict = {
44
+ "fp32": torch.float32,
45
+ "fp16": torch.float16,
46
+ "bf16": torch.bfloat16,
47
+ }
48
+
49
+
50
+ def init_weights_vit(module: nn.Module, name: str = ""):
51
+ if isinstance(module, nn.Linear):
52
+ torch.nn.init.trunc_normal_(module.weight, std=0.02)
53
+ if module.bias is not None:
54
+ nn.init.zeros_(module.bias)
55
+ if hasattr(module, "bias_mask") and module.bias_mask is not None:
56
+ o = module.out_features
57
+ module.bias_mask.fill_(1)
58
+ module.bias_mask[o // 3 : 2 * o // 3].fill_(0)
59
+ if isinstance(module, nn.LayerNorm):
60
+ module.reset_parameters()
61
+ if isinstance(module, LayerScale):
62
+ module.reset_parameters()
63
+ if isinstance(module, PatchEmbed):
64
+ module.reset_parameters()
65
+ if isinstance(module, RMSNorm):
66
+ module.reset_parameters()
67
+
68
+
69
+ class DinoVisionTransformer(nn.Module):
70
+ def __init__(
71
+ self,
72
+ *,
73
+ img_size: int = 224,
74
+ patch_size: int = 16,
75
+ in_chans: int = 3,
76
+ pos_embed_rope_base: float = 100.0,
77
+ pos_embed_rope_min_period: float | None = None,
78
+ pos_embed_rope_max_period: float | None = None,
79
+ pos_embed_rope_normalize_coords: Literal["min", "max", "separate"] = "separate",
80
+ pos_embed_rope_shift_coords: float | None = None,
81
+ pos_embed_rope_jitter_coords: float | None = None,
82
+ pos_embed_rope_rescale_coords: float | None = None,
83
+ pos_embed_rope_dtype: str = "bf16",
84
+ embed_dim: int = 768,
85
+ depth: int = 12,
86
+ num_heads: int = 12,
87
+ ffn_ratio: float = 4.0,
88
+ qkv_bias: bool = True,
89
+ drop_path_rate: float = 0.0,
90
+ layerscale_init: float | None = None,
91
+ norm_layer: str = "layernorm",
92
+ ffn_layer: str = "mlp",
93
+ ffn_bias: bool = True,
94
+ proj_bias: bool = True,
95
+ n_storage_tokens: int = 0,
96
+ mask_k_bias: bool = False,
97
+ untie_cls_and_patch_norms: bool = False,
98
+ untie_global_and_local_cls_norm: bool = False,
99
+ device: Any | None = None,
100
+ **ignored_kwargs,
101
+ ):
102
+ super().__init__()
103
+ if len(ignored_kwargs) > 0:
104
+ logger.warning(f"Ignored kwargs: {ignored_kwargs}")
105
+ del ignored_kwargs
106
+
107
+ norm_layer_cls = norm_layer_dict[norm_layer]
108
+
109
+ self.num_features = self.embed_dim = embed_dim
110
+ self.n_blocks = depth
111
+ self.num_heads = num_heads
112
+ self.patch_size = patch_size
113
+
114
+ self.patch_embed = PatchEmbed(
115
+ img_size=img_size,
116
+ patch_size=patch_size,
117
+ in_chans=in_chans,
118
+ embed_dim=embed_dim,
119
+ flatten_embedding=False,
120
+ )
121
+
122
+ self.cls_token = nn.Parameter(torch.empty(1, 1, embed_dim, device=device))
123
+ self.n_storage_tokens = n_storage_tokens
124
+ if self.n_storage_tokens > 0:
125
+ self.storage_tokens = nn.Parameter(
126
+ torch.empty(1, n_storage_tokens, embed_dim, device=device)
127
+ )
128
+ self.rope_embed = RopePositionEmbedding(
129
+ embed_dim=embed_dim,
130
+ num_heads=num_heads,
131
+ base=pos_embed_rope_base,
132
+ min_period=pos_embed_rope_min_period,
133
+ max_period=pos_embed_rope_max_period,
134
+ normalize_coords=pos_embed_rope_normalize_coords,
135
+ shift_coords=pos_embed_rope_shift_coords,
136
+ jitter_coords=pos_embed_rope_jitter_coords,
137
+ rescale_coords=pos_embed_rope_rescale_coords,
138
+ dtype=dtype_dict[pos_embed_rope_dtype],
139
+ device=device,
140
+ )
141
+ ffn_layer_cls = ffn_layer_dict[ffn_layer]
142
+ ffn_ratio_sequence = [ffn_ratio] * depth
143
+ blocks_list = [
144
+ SelfAttentionBlock(
145
+ dim=embed_dim,
146
+ num_heads=num_heads,
147
+ ffn_ratio=ffn_ratio_sequence[i],
148
+ qkv_bias=qkv_bias,
149
+ proj_bias=proj_bias,
150
+ ffn_bias=ffn_bias,
151
+ drop_path=drop_path_rate,
152
+ norm_layer=norm_layer_cls,
153
+ act_layer=nn.GELU,
154
+ ffn_layer=ffn_layer_cls,
155
+ init_values=layerscale_init,
156
+ mask_k_bias=mask_k_bias,
157
+ device=device,
158
+ )
159
+ for i in range(depth)
160
+ ]
161
+
162
+ self.chunked_blocks = False
163
+ self.blocks = nn.ModuleList(blocks_list)
164
+
165
+ self.norm = norm_layer_cls(embed_dim)
166
+
167
+ self.untie_cls_and_patch_norms = untie_cls_and_patch_norms
168
+ if untie_cls_and_patch_norms:
169
+ self.cls_norm = norm_layer_cls(embed_dim)
170
+ else:
171
+ self.cls_norm = None
172
+
173
+ self.untie_global_and_local_cls_norm = untie_global_and_local_cls_norm
174
+ if untie_global_and_local_cls_norm:
175
+ self.local_cls_norm = norm_layer_cls(embed_dim)
176
+ else:
177
+ self.local_cls_norm = None
178
+ self.head = nn.Identity()
179
+ self.mask_token = nn.Parameter(torch.empty(1, embed_dim, device=device))
180
+
181
+ def init_weights(self):
182
+ self.rope_embed._init_weights()
183
+ nn.init.normal_(self.cls_token, std=0.02)
184
+ if self.n_storage_tokens > 0:
185
+ nn.init.normal_(self.storage_tokens, std=0.02)
186
+ nn.init.zeros_(self.mask_token)
187
+ named_apply(init_weights_vit, self)
188
+
189
+ def prepare_tokens_with_masks(
190
+ self, x: Tensor, masks=None
191
+ ) -> Tuple[Tensor, Tuple[int]]:
192
+ x = self.patch_embed(x)
193
+ B, H, W, _ = x.shape
194
+ x = x.flatten(1, 2)
195
+
196
+ if masks is not None:
197
+ x = torch.where(
198
+ masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x
199
+ )
200
+ cls_token = self.cls_token
201
+ else:
202
+ cls_token = self.cls_token + 0 * self.mask_token
203
+ if self.n_storage_tokens > 0:
204
+ storage_tokens = self.storage_tokens
205
+ else:
206
+ storage_tokens = torch.empty(
207
+ 1,
208
+ 0,
209
+ cls_token.shape[-1],
210
+ dtype=cls_token.dtype,
211
+ device=cls_token.device,
212
+ )
213
+
214
+ x = torch.cat(
215
+ [
216
+ cls_token.expand(B, -1, -1),
217
+ storage_tokens.expand(B, -1, -1),
218
+ x,
219
+ ],
220
+ dim=1,
221
+ )
222
+
223
+ return x, (H, W)
224
+
225
+ def forward_features_list(
226
+ self, x_list: List[Tensor], masks_list: List[Tensor]
227
+ ) -> List[Dict[str, Tensor]]:
228
+ x = []
229
+ rope = []
230
+ for t_x, t_masks in zip(x_list, masks_list):
231
+ t2_x, hw_tuple = self.prepare_tokens_with_masks(t_x, t_masks)
232
+ x.append(t2_x)
233
+ rope.append(hw_tuple)
234
+ for _, blk in enumerate(self.blocks):
235
+ if self.rope_embed is not None:
236
+ rope_sincos = [self.rope_embed(H=H, W=W) for H, W in rope]
237
+ else:
238
+ rope_sincos = [None for r in rope]
239
+ x = blk(x, rope_sincos)
240
+ all_x = x
241
+ output = []
242
+ for idx, (x, masks) in enumerate(zip(all_x, masks_list)):
243
+ if self.untie_cls_and_patch_norms or self.untie_global_and_local_cls_norm:
244
+ if self.untie_global_and_local_cls_norm and self.training and idx == 1:
245
+ x_norm_cls_reg = self.local_cls_norm(
246
+ x[:, : self.n_storage_tokens + 1]
247
+ )
248
+ elif self.untie_cls_and_patch_norms:
249
+ x_norm_cls_reg = self.cls_norm(x[:, : self.n_storage_tokens + 1])
250
+ else:
251
+ x_norm_cls_reg = self.norm(x[:, : self.n_storage_tokens + 1])
252
+ x_norm_patch = self.norm(x[:, self.n_storage_tokens + 1 :])
253
+ else:
254
+ x_norm = self.norm(x)
255
+ x_norm_cls_reg = x_norm[:, : self.n_storage_tokens + 1]
256
+ x_norm_patch = x_norm[:, self.n_storage_tokens + 1 :]
257
+ output.append(
258
+ {
259
+ "x_norm_clstoken": x_norm_cls_reg[:, 0],
260
+ "x_storage_tokens": x_norm_cls_reg[:, 1:],
261
+ "x_norm_patchtokens": x_norm_patch,
262
+ "x_prenorm": x,
263
+ "masks": masks,
264
+ }
265
+ )
266
+ return output
267
+
268
+ def forward_features(
269
+ self, x: Tensor | List[Tensor], masks: Optional[Tensor] = None
270
+ ) -> List[Dict[str, Tensor]]:
271
+ if isinstance(x, torch.Tensor):
272
+ return self.forward_features_list([x], [masks])[0]
273
+ else:
274
+ return self.forward_features_list(x, masks)
275
+
276
+ def _get_intermediate_layers_not_chunked(
277
+ self, x: Tensor, n: int = 1
278
+ ) -> List[Tensor]:
279
+ x, (H, W) = self.prepare_tokens_with_masks(x)
280
+ output, total_block_len = [], len(self.blocks)
281
+ blocks_to_take = (
282
+ range(total_block_len - n, total_block_len) if isinstance(n, int) else n
283
+ )
284
+ for i, blk in enumerate(self.blocks):
285
+ if self.rope_embed is not None:
286
+ rope_sincos = self.rope_embed(H=H, W=W)
287
+ else:
288
+ rope_sincos = None
289
+ x = blk(x, rope_sincos)
290
+ if i in blocks_to_take:
291
+ output.append(x)
292
+ assert len(output) == len(blocks_to_take), (
293
+ f"only {len(output)} / {len(blocks_to_take)} blocks found"
294
+ )
295
+ return output
296
+
297
+ def get_intermediate_layers(
298
+ self,
299
+ x: torch.Tensor,
300
+ *,
301
+ n: Union[int, Sequence] = 1,
302
+ reshape: bool = False,
303
+ return_class_token: bool = False,
304
+ return_extra_tokens: bool = False,
305
+ norm: bool = True,
306
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor, ...]]]:
307
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
308
+ if norm:
309
+ outputs_normed = []
310
+ for out in outputs:
311
+ if self.untie_cls_and_patch_norms:
312
+ x_norm_cls_reg = self.cls_norm(out[:, : self.n_storage_tokens + 1])
313
+ x_norm_patch = self.norm(out[:, self.n_storage_tokens + 1 :])
314
+ outputs_normed.append(
315
+ torch.cat((x_norm_cls_reg, x_norm_patch), dim=1)
316
+ )
317
+ else:
318
+ outputs_normed.append(self.norm(out))
319
+ outputs = outputs_normed
320
+ class_tokens = [out[:, 0] for out in outputs]
321
+ extra_tokens = [out[:, 1 : self.n_storage_tokens + 1] for out in outputs]
322
+ outputs = [out[:, self.n_storage_tokens + 1 :] for out in outputs]
323
+ if reshape:
324
+ B, _, h, w = x.shape
325
+ outputs = [
326
+ out.reshape(B, h // self.patch_size, w // self.patch_size, -1)
327
+ .permute(0, 3, 1, 2)
328
+ .contiguous()
329
+ for out in outputs
330
+ ]
331
+ if not return_class_token and not return_extra_tokens:
332
+ return tuple(outputs)
333
+ elif return_class_token and not return_extra_tokens:
334
+ return tuple(zip(outputs, class_tokens))
335
+ elif not return_class_token and return_extra_tokens:
336
+ return tuple(zip(outputs, extra_tokens))
337
+ elif return_class_token and return_extra_tokens:
338
+ return tuple(zip(outputs, class_tokens, extra_tokens))
339
+
340
+ def forward(
341
+ self, *args, is_training: bool = True, **kwargs
342
+ ) -> List[Dict[str, Tensor]] | Tensor:
343
+ # VGGT-Omega change: the aggregator consumes DINOv3 patch-token
344
+ # features directly, so the default forward returns the feature dict.
345
+ ret = self.forward_features(*args, **kwargs)
346
+ if is_training:
347
+ return ret
348
+ else:
349
+ return self.head(ret["x_norm_clstoken"])
350
+
351
+
352
+ def vit_large(patch_size=16, **kwargs):
353
+ return DinoVisionTransformer(
354
+ patch_size=patch_size,
355
+ embed_dim=1024,
356
+ depth=24,
357
+ num_heads=16,
358
+ ffn_ratio=4,
359
+ **kwargs,
360
+ )
lingbot_map2/layers/flashinfer_cache.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Paged patch/special KV storage for the native Map2 streaming runtime."""
4
+
5
+ import collections
6
+ import math
7
+
8
+ import torch
9
+
10
+
11
+ class PagedKVCache:
12
+ """An all-layer append transaction with prefix, window and special-token pages.
13
+
14
+ One physical page per frame's patch tokens; all chronological special tokens
15
+ occupy a packed tail. Only page IDs change on eviction or rollback. One free
16
+ patch page and uncommitted special slots protect live state from failed heads.
17
+ Metadata and one FlashInfer plan are shared across all layers.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ *,
23
+ layers,
24
+ heads,
25
+ dim,
26
+ patches,
27
+ special=5,
28
+ scale=8,
29
+ window=64,
30
+ capacity=1024,
31
+ device="cuda",
32
+ dtype=torch.bfloat16,
33
+ offload_kv=False,
34
+ ):
35
+ import flashinfer
36
+
37
+ if min(layers, heads, dim, patches, special, scale, window) <= 0:
38
+ raise ValueError(
39
+ "paged cache dimensions, prefix and window must be positive"
40
+ )
41
+ if capacity < scale:
42
+ raise ValueError("capacity must accommodate the initialization prefix")
43
+ self.layers, self.heads, self.dim = layers, heads, dim
44
+ self.patches, self.special, self.scale, self.window = (
45
+ patches,
46
+ special,
47
+ scale,
48
+ window,
49
+ )
50
+ self.capacity = capacity
51
+ self.device = torch.device(device)
52
+ self.dtype = dtype
53
+ self.offload_kv = bool(offload_kv)
54
+ # One extra patch page makes failed/transient steps independent of eviction.
55
+ self.patch_pages = min(scale + window, capacity) + 1
56
+ self.special_pages = math.ceil((capacity + 1) * special / patches)
57
+ layer_shape = (self.patch_pages + self.special_pages, 2, patches, heads, dim)
58
+ if self.offload_kv:
59
+ try:
60
+ self.cpu_pool = [
61
+ torch.empty(layer_shape, device="cpu", dtype=dtype, pin_memory=True)
62
+ for _ in range(layers)
63
+ ]
64
+ except RuntimeError:
65
+ self.cpu_pool = [
66
+ torch.empty(layer_shape, device="cpu", dtype=dtype)
67
+ for _ in range(layers)
68
+ ]
69
+ self.gpu_buf = torch.empty(layer_shape, device=device, dtype=dtype)
70
+ self.pool = None
71
+ else:
72
+ self.cpu_pool = None
73
+ self.gpu_buf = None
74
+ self.pool = [
75
+ torch.empty(layer_shape, device=device, dtype=dtype)
76
+ for _ in range(layers)
77
+ ]
78
+ self.active = collections.deque()
79
+ self.free = list(range(self.patch_pages - 1, -1, -1))
80
+ self.count = 0
81
+ self.pending = None
82
+ self.workspace = torch.empty(64 << 20, dtype=torch.uint8, device=device)
83
+ self.wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(
84
+ self.workspace, kv_layout="NHD", backend="fa2"
85
+ )
86
+
87
+ def begin(self):
88
+ if self.pending is not None:
89
+ raise RuntimeError("nested append")
90
+ if self.count >= self.capacity:
91
+ raise ValueError("keyframe capacity reached")
92
+ page = self.free[-1]
93
+ active = list(self.active) + [(self.count, page)]
94
+ active = [
95
+ (i, p)
96
+ for i, p in active
97
+ if i < self.scale or i >= max(self.scale, self.count + 1 - self.window)
98
+ ]
99
+ tokens = (self.count + 1) * self.special
100
+ pages = [p for _, p in active] + list(
101
+ range(self.patch_pages, self.patch_pages + math.ceil(tokens / self.patches))
102
+ )
103
+ self.pending = {"page": page, "active": active, "written": set()}
104
+ self.wrapper.plan(
105
+ torch.tensor(
106
+ [0, self.patches + self.special], dtype=torch.int32, device=self.device
107
+ ),
108
+ torch.tensor([0, len(pages)], dtype=torch.int32, device=self.device),
109
+ torch.tensor(pages, dtype=torch.int32, device=self.device),
110
+ torch.tensor(
111
+ [tokens % self.patches or self.patches],
112
+ dtype=torch.int32,
113
+ device=self.device,
114
+ ),
115
+ self.heads,
116
+ self.heads,
117
+ self.dim,
118
+ self.patches,
119
+ causal=False,
120
+ pos_encoding_mode="NONE",
121
+ q_data_type=self.dtype,
122
+ kv_data_type=self.dtype,
123
+ )
124
+
125
+ def write(self, layer, k, v):
126
+ """[patches+special, heads, dim], specials first, post-RoPE K."""
127
+ if self.pending is None or layer in self.pending["written"]:
128
+ raise RuntimeError("invalid write")
129
+ if k.dtype != self.dtype or v.dtype != self.dtype:
130
+ raise TypeError("no silent KV conversion")
131
+ target_pool = self.cpu_pool[layer] if self.offload_kv else self.pool[layer]
132
+ page = self.pending["page"]
133
+ for bank, x in enumerate((k, v)):
134
+ target_pool[page, bank].copy_(x[self.special :])
135
+ start = self.count * self.special
136
+ done = 0
137
+ while done < self.special:
138
+ p, off = divmod(start + done, self.patches)
139
+ take = min(self.special - done, self.patches - off)
140
+ target_pool[self.patch_pages + p, bank, off : off + take].copy_(
141
+ x[done : done + take]
142
+ )
143
+ done += take
144
+ self.pending["written"].add(layer)
145
+
146
+ def run(self, layer, q):
147
+ if layer not in self.pending["written"]:
148
+ raise RuntimeError("query before write")
149
+ if q.dtype != self.dtype:
150
+ raise TypeError("query dtype mismatch")
151
+ if self.offload_kv:
152
+ pool_l = self.cpu_pool[layer]
153
+ used_patch_max = max(p for _, p in self.pending["active"]) + 1
154
+ used_spec = math.ceil((self.count + 1) * self.special / self.patches)
155
+ self.gpu_buf[:used_patch_max].copy_(
156
+ pool_l[:used_patch_max], non_blocking=True
157
+ )
158
+ self.gpu_buf[self.patch_pages : self.patch_pages + used_spec].copy_(
159
+ pool_l[self.patch_pages : self.patch_pages + used_spec],
160
+ non_blocking=True,
161
+ )
162
+ return self.wrapper.run(q.contiguous(), self.gpu_buf)
163
+ return self.wrapper.run(q.contiguous(), self.pool[layer])
164
+
165
+ def commit(self):
166
+ if self.pending is None or len(self.pending["written"]) != self.layers:
167
+ raise RuntimeError("incomplete append")
168
+ page = self.free.pop()
169
+ assert page == self.pending["page"]
170
+ self.active.append((self.count, page))
171
+ self.count += 1
172
+ while len(self.active) > self.scale + self.window:
173
+ index, page = self.active[self.scale]
174
+ del self.active[self.scale]
175
+ self.free.append(page)
176
+ self.pending = None
177
+
178
+ def rollback(self):
179
+ # Writes affected only a free patch page and invisible special tail slots.
180
+ self.pending = None
lingbot_map2/layers/layer_scale.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in LICENSES/Apache-2.0.txt in the repository root.
5
+
6
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
7
+
8
+ from typing import Union
9
+
10
+ import torch
11
+ from torch import Tensor
12
+ from torch import nn
13
+
14
+
15
+ class LayerScale(nn.Module):
16
+ def __init__(
17
+ self, dim: int, init_values: Union[float, Tensor] = 1e-5, inplace: bool = False
18
+ ) -> None:
19
+ super().__init__()
20
+ self.inplace = inplace
21
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
22
+
23
+ def forward(self, x: Tensor) -> Tensor:
24
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
lingbot_map2/layers/mlp.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in LICENSES/Apache-2.0.txt in the repository root.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
9
+
10
+
11
+ from typing import Callable, Optional
12
+
13
+ from torch import Tensor, nn
14
+
15
+
16
+ class Mlp(nn.Module):
17
+ def __init__(
18
+ self,
19
+ in_features: int,
20
+ hidden_features: Optional[int] = None,
21
+ out_features: Optional[int] = None,
22
+ act_layer: Callable[..., nn.Module] = nn.GELU,
23
+ drop: float = 0.0,
24
+ bias: bool = True,
25
+ ) -> None:
26
+ super().__init__()
27
+ out_features = out_features or in_features
28
+ hidden_features = hidden_features or in_features
29
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
30
+ self.act = act_layer()
31
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
32
+ self.drop = nn.Dropout(drop)
33
+
34
+ def forward(self, x: Tensor) -> Tensor:
35
+ x = self.fc1(x)
36
+ x = self.act(x)
37
+ x = self.drop(x)
38
+ x = self.fc2(x)
39
+ x = self.drop(x)
40
+ return x
lingbot_map2/layers/rope.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved. See LICENSE.txt and LICENSES/THIRD_PARTY.md.
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+ from typing import Dict, Tuple, Optional, Union
9
+
10
+
11
+ class PositionGetter:
12
+ """Generates and caches 2D spatial positions for patches in a grid.
13
+
14
+ This class efficiently manages the generation of spatial coordinates for patches
15
+ in a 2D grid, caching results to avoid redundant computations.
16
+
17
+ Attributes:
18
+ position_cache: Dictionary storing precomputed position tensors for different
19
+ grid dimensions.
20
+ """
21
+
22
+ def __init__(self):
23
+ """Initializes the position generator with an empty cache."""
24
+ self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {}
25
+
26
+ def __call__(
27
+ self, batch_size: int, height: int, width: int, device: torch.device
28
+ ) -> torch.Tensor:
29
+ """Generates spatial positions for a batch of patches.
30
+
31
+ Args:
32
+ batch_size: Number of samples in the batch.
33
+ height: Height of the grid in patches.
34
+ width: Width of the grid in patches.
35
+ device: Target device for the position tensor.
36
+
37
+ Returns:
38
+ Tensor of shape (batch_size, height*width, 2) containing y,x coordinates
39
+ for each position in the grid, repeated for each batch item.
40
+ """
41
+ if (height, width) not in self.position_cache:
42
+ y_coords = torch.arange(height, device=device)
43
+ x_coords = torch.arange(width, device=device)
44
+ positions = torch.cartesian_prod(y_coords, x_coords)
45
+ self.position_cache[height, width] = positions
46
+
47
+ cached_positions = self.position_cache[height, width]
48
+ return (
49
+ cached_positions.view(1, height * width, 2)
50
+ .expand(batch_size, -1, -1)
51
+ .clone()
52
+ )
53
+
54
+
55
+ class DinoV3RotaryPositionEmbedding2D(nn.Module):
56
+ """Checkpoint-native DINOv3 RoPE for frame-local aggregator attention.
57
+
58
+ Patch centres use max(H, W) normalization. PositionGetter positions are
59
+ offset by one; special tokens at (0, 0) are left unrotated.
60
+ The positional embedding has no learned parameters.
61
+ """
62
+
63
+ def __init__(self, base: float = 100.0):
64
+ super().__init__()
65
+ self.base = base
66
+
67
+ def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
68
+ dim = tokens.size(-1)
69
+ if dim % 4:
70
+ raise ValueError("DINOv3 RoPE requires head dimension divisible by four")
71
+ if positions.ndim != 3 or positions.shape[-1] != 2:
72
+ raise ValueError("positions must have shape (batch, tokens, 2)")
73
+ is_patch = (positions > 0).all(dim=-1)
74
+ max_hw = positions.amax(dim=(1, 2)).clamp(min=1).float()
75
+ coords = 2.0 * (positions.float() - 0.5) / max_hw[:, None, None] - 1.0
76
+ periods = self.base ** (
77
+ 2
78
+ * torch.arange(dim // 4, device=tokens.device, dtype=torch.float32)
79
+ / (dim // 2)
80
+ )
81
+ angles = (2 * np.pi * coords[..., None] / periods).flatten(-2).tile(2)
82
+ cos = torch.where(is_patch[..., None], angles.cos(), 1.0)[:, None]
83
+ sin = torch.where(is_patch[..., None], angles.sin(), 0.0)[:, None]
84
+ x = tokens.float()
85
+ x1, x2 = x.chunk(2, dim=-1)
86
+ rotated = torch.cat((-x2, x1), dim=-1)
87
+ return (x * cos + rotated * sin).to(tokens.dtype)
88
+
89
+
90
+ def get_1d_rotary_pos_embed(
91
+ dim: int,
92
+ pos: Union[np.ndarray, int],
93
+ theta: float = 10000.0,
94
+ use_real=False,
95
+ linear_factor=1.0,
96
+ ntk_factor=1.0,
97
+ repeat_interleave_real=True,
98
+ freqs_dtype=torch.float32, # torch.float32, torch.float64 (flux)
99
+ ):
100
+ """Construct real or complex rotary phases at the supplied positions."""
101
+
102
+ assert dim % 2 == 0
103
+
104
+ if isinstance(pos, int):
105
+ pos = torch.arange(pos)
106
+ if isinstance(pos, np.ndarray):
107
+ pos = torch.from_numpy(pos) # [S]
108
+
109
+ theta = theta * ntk_factor
110
+
111
+ freqs = (
112
+ 1.0
113
+ / (
114
+ theta
115
+ ** (
116
+ torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device)[
117
+ : (dim // 2)
118
+ ]
119
+ / dim
120
+ )
121
+ )
122
+ / linear_factor
123
+ )
124
+
125
+ freqs = torch.outer(pos, freqs) # [S, D/2]
126
+
127
+ if use_real and repeat_interleave_real:
128
+ freqs_cos = (
129
+ freqs.cos()
130
+ .repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2)
131
+ .float()
132
+ ) # [S, D]
133
+ freqs_sin = (
134
+ freqs.sin()
135
+ .repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2)
136
+ .float()
137
+ ) # [S, D]
138
+ return freqs_cos, freqs_sin
139
+ elif use_real:
140
+ freqs_cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).float() # [S, D]
141
+ freqs_sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).float() # [S, D]
142
+ return freqs_cos, freqs_sin
143
+ else:
144
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64: [S, D/2]
145
+ return freqs_cis
146
+
147
+
148
+ class WanRotaryPosEmbed(nn.Module):
149
+ """Temporal and spatial RoPE with checkpoint-native phase construction."""
150
+
151
+ def __init__(
152
+ self,
153
+ attention_head_dim: int,
154
+ patch_size: Tuple[int, int, int],
155
+ max_seq_len: int = 1024,
156
+ theta: float = 10000.0,
157
+ fhw_dim: Optional[Tuple[int, int, int]] = [20, 22, 22],
158
+ complex_dtype: torch.dtype = torch.complex128,
159
+ spatial_normalize_coords: str = "none",
160
+ ):
161
+ super().__init__()
162
+
163
+ if spatial_normalize_coords not in ("none", "max"):
164
+ raise ValueError("spatial_normalize_coords must be 'none' or 'max'")
165
+ self.spatial_normalize_coords = spatial_normalize_coords
166
+ self.theta = theta
167
+
168
+ if complex_dtype not in (torch.complex64, torch.complex128):
169
+ raise ValueError(
170
+ "complex_dtype must be torch.complex64 or torch.complex128, "
171
+ f"got {complex_dtype}"
172
+ )
173
+
174
+ self.attention_head_dim = attention_head_dim
175
+ self.patch_size = patch_size
176
+ self.max_seq_len = max_seq_len
177
+
178
+ if fhw_dim is not None:
179
+ assert attention_head_dim == sum(fhw_dim), (
180
+ f"attention_head_dim {attention_head_dim} must match sum(fhw_dim) {sum(fhw_dim)}"
181
+ )
182
+ t_dim, h_dim, w_dim = fhw_dim
183
+ else:
184
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
185
+ t_dim = attention_head_dim - h_dim - w_dim
186
+
187
+ self.fhw_dim = (t_dim, h_dim, w_dim)
188
+
189
+ freqs = []
190
+ for dim in [t_dim, h_dim, w_dim]:
191
+ freq = get_1d_rotary_pos_embed(
192
+ dim,
193
+ max_seq_len,
194
+ theta,
195
+ use_real=False,
196
+ repeat_interleave_real=False,
197
+ freqs_dtype=torch.float64,
198
+ )
199
+ freqs.append(freq)
200
+
201
+ # Generate phases in float64 above, then optionally store them as complex64.
202
+ # The latter halves runtime RoPE storage and enables float32 complex math while
203
+ # preserving the higher-precision phase construction.
204
+ self.freqs = torch.cat(freqs, dim=1).to(complex_dtype)
205
+
206
+ def forward(
207
+ self,
208
+ ppf,
209
+ pph,
210
+ ppw,
211
+ patch_start_idx,
212
+ device: torch.device,
213
+ f_start: int = 0,
214
+ f_end: Optional[int] = None,
215
+ ) -> torch.Tensor:
216
+ """Build frame-major phases for five special tokens and a spatial patch grid."""
217
+
218
+ self.freqs = self.freqs.to(device)
219
+
220
+ if hasattr(self, "fhw_dim") and self.fhw_dim is not None:
221
+ t_dim, h_dim, w_dim = self.fhw_dim
222
+ else:
223
+ h_dim = w_dim = 2 * (self.attention_head_dim // 6)
224
+ t_dim = self.attention_head_dim - h_dim - w_dim
225
+
226
+ freqs = self.freqs.split_with_sizes(
227
+ [
228
+ t_dim // 2,
229
+ h_dim // 2,
230
+ w_dim // 2,
231
+ ],
232
+ dim=1,
233
+ )
234
+
235
+ if f_end is not None:
236
+ ppf = f_end - f_start
237
+ frame_slice = slice(f_start, f_end)
238
+ else:
239
+ frame_slice = slice(0, ppf)
240
+
241
+ max_pos = max(
242
+ f_end if f_end is not None else ppf, max(pph, ppw) + patch_start_idx
243
+ )
244
+ if max_pos > self.max_seq_len:
245
+ raise RuntimeError(
246
+ f"WanRotaryPosEmbed: requested position {max_pos} exceeds "
247
+ f"max_seq_len={self.max_seq_len}. Increase max_frames when loading the model "
248
+ f"(ppf={ppf}, pph={pph}, ppw={ppw}, patch_start_idx={patch_start_idx})."
249
+ )
250
+
251
+ if self.spatial_normalize_coords == "max":
252
+ # Normalize patch centres only, without the special-token offset.
253
+ # Time and special-token phases use their indexed frequencies.
254
+ spatial_freqs = []
255
+ for size, dim in ((pph, h_dim), (ppw, w_dim)):
256
+ coords = torch.arange(size, dtype=torch.float64, device=device)
257
+ coords = 2.0 * (coords + 0.5) / max(pph, ppw) - 1.0
258
+ spatial_freqs.append(
259
+ get_1d_rotary_pos_embed(
260
+ dim,
261
+ coords,
262
+ self.theta,
263
+ use_real=False,
264
+ freqs_dtype=torch.float64,
265
+ ).to(self.freqs.dtype)
266
+ )
267
+ patch_freqs_h, patch_freqs_w = spatial_freqs
268
+ else:
269
+ # Keep the default path bitwise identical, including its offset.
270
+ patch_freqs_h = freqs[1][patch_start_idx : patch_start_idx + pph]
271
+ patch_freqs_w = freqs[2][patch_start_idx : patch_start_idx + ppw]
272
+
273
+ ## For other tokens
274
+ if patch_start_idx > 0:
275
+ # camera: (f, 0, 0); registers 0..3: (f, 1, 1) through (f, 4, 4)
276
+ # Shape: (ppf, patch_start_idx, dim)
277
+ freqs_special_f = (
278
+ freqs[0][frame_slice]
279
+ .reshape(ppf, 1, -1)
280
+ .expand(ppf, patch_start_idx, -1)
281
+ )
282
+ freqs_special_h = (
283
+ freqs[1][:patch_start_idx]
284
+ .reshape(1, patch_start_idx, -1)
285
+ .expand(ppf, patch_start_idx, -1)
286
+ )
287
+ freqs_special_w = (
288
+ freqs[2][:patch_start_idx]
289
+ .reshape(1, patch_start_idx, -1)
290
+ .expand(ppf, patch_start_idx, -1)
291
+ )
292
+ freqs_special = torch.cat(
293
+ [freqs_special_f, freqs_special_h, freqs_special_w], dim=-1
294
+ )
295
+ freqs_special = freqs_special.reshape(
296
+ ppf, patch_start_idx, -1
297
+ ) # (ppf, patch_start_idx, dim)
298
+
299
+ # Indexed spatial patches use the special-token offset; max mode instead
300
+ # uses the normalized patch centres computed above.
301
+ # Shape: (ppf, pph, ppw, dim)
302
+ freqs_f = (
303
+ freqs[0][frame_slice].reshape(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
304
+ )
305
+ freqs_h = patch_freqs_h.reshape(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
306
+ freqs_w = patch_freqs_w.reshape(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
307
+ freqs_patches = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1)
308
+ freqs_patches = freqs_patches.reshape(ppf, pph * ppw, -1)
309
+
310
+ # Concatenate special tokens and patches for each frame along the second dimension
311
+ # Shape: (ppf, patch_start_idx + pph * ppw, dim)
312
+ freqs = torch.cat(
313
+ [freqs_special, freqs_patches], dim=1
314
+ ) # (ppf, patch_start_idx + pph * ppw, dim)
315
+
316
+ # Flatten to get final shape: (ppf * (patch_start_idx + pph * ppw), dim)
317
+ freqs = freqs.reshape(ppf * (patch_start_idx + pph * ppw), -1)
318
+ freqs = freqs.unsqueeze(0).unsqueeze(0)
319
+ return freqs
320
+
321
+ freqs_f = freqs[0][frame_slice].reshape(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
322
+ freqs_h = patch_freqs_h.reshape(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
323
+ freqs_w = patch_freqs_w.reshape(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
324
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(
325
+ 1, 1, ppf * pph * ppw, -1
326
+ ) # (1, 1, ppf * pph * ppw, dim)
327
+ return freqs
328
+
329
+
330
+ def apply_rotary_emb(x, freqs):
331
+ """Apply complex rotary phases to the paired channels of Q or K."""
332
+
333
+ if freqs.dtype == torch.complex128:
334
+ work_dtype = torch.float64
335
+ elif freqs.dtype == torch.complex64:
336
+ work_dtype = torch.float32
337
+ else:
338
+ raise TypeError(f"freqs must be complex64 or complex128, got {freqs.dtype}")
339
+ x_reshaped = x.to(work_dtype).reshape(x.shape[0], x.shape[1], x.shape[2], -1, 2)
340
+
341
+ x_complex = torch.view_as_complex(x_reshaped)
342
+
343
+ x_rotated = x_complex * freqs.to(device=x.device, dtype=x_complex.dtype)
344
+
345
+ x_real = torch.view_as_real(x_rotated)
346
+
347
+ x_out = x_real.flatten(3)
348
+
349
+ return x_out.to(x.dtype)
lingbot_map2/models/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Pure causal LingBot-Map2 inference models."""
4
+
5
+ from .gcr_stream import GCRStream, load_model
6
+
7
+ __all__ = ["GCRStream", "load_model"]
lingbot_map2/models/gcr_base.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Checkpoint-native modules shared by the streaming model."""
4
+
5
+ from torch import nn
6
+
7
+ from ..aggregator.base import Aggregator
8
+ from ..heads.camera_head import CameraHead
9
+ from ..heads.dpt_head import DPTHead
10
+
11
+
12
+ class NativeModel(nn.Module):
13
+ def __init__(self, spatial_rope="max", max_frames=1024):
14
+ super().__init__()
15
+ self.aggregator = Aggregator(spatial_rope, max_frames=max_frames)
16
+ self.camera_head = CameraHead()
17
+ self.depth_head = DPTHead(
18
+ dim_in=2048,
19
+ patch_size=16,
20
+ output_dim=2,
21
+ activation="exp",
22
+ conf_activation="expp1",
23
+ )
lingbot_map2/models/gcr_stream.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Public API for the pure causal LingBot-Map2 streaming release."""
4
+
5
+ from dataclasses import replace
6
+ from functools import partial
7
+ from pathlib import Path
8
+ import numpy as np
9
+ import torch
10
+
11
+ from ..utils.checkpoint import resolve_checkpoint
12
+ from ..utils.compilation import _cached_encoder_rope, _cached_depth_position
13
+ from ..utils.load_fn import cover_resize, load_images
14
+
15
+
16
+ class GCRStream:
17
+ """Online reconstruction model with one active stream."""
18
+
19
+ def __init__(self, native, config, metadata=None, *, width=None, height=None):
20
+ self._native = native
21
+ self.config = config
22
+ self.metadata = metadata or {}
23
+ self.width = config.width if width is None else width
24
+ self.height = config.height if height is None else height
25
+ if any(
26
+ type(x) is not int or x <= 0 or x % 16 for x in (self.width, self.height)
27
+ ):
28
+ raise ValueError("width and height must be positive multiples of 16")
29
+ self._stream = None
30
+ self._compiled = None
31
+
32
+ @property
33
+ def device(self):
34
+ return next(self._native.parameters()).device
35
+
36
+ def prepare(self, frames):
37
+ """Paths, one uint8 HWC RGB array, or already preprocessed float32 CHW tensors.
38
+
39
+ Tensors must already have the configured geometry. No implicit resize,
40
+ range conversion, EXIF rotation or layout conversion is applied to them.
41
+ """
42
+ if isinstance(frames, (str, Path)):
43
+ frames = [frames]
44
+ if isinstance(frames, np.ndarray):
45
+ if frames.dtype != np.uint8 or frames.ndim != 3 or frames.shape[-1] != 3:
46
+ raise ValueError("array input must be one uint8 HWC RGB frame")
47
+ rgb = cover_resize(frames.astype(np.float32), (self.width, self.height))
48
+ frames = (torch.from_numpy(rgb).permute(2, 0, 1).float() / 255)[None, None]
49
+ elif not torch.is_tensor(frames):
50
+ frames = load_images(list(frames), self.width, self.height)
51
+ if frames.ndim == 3:
52
+ frames = frames[None, None]
53
+ elif frames.ndim == 4:
54
+ frames = frames[None]
55
+ if (
56
+ frames.ndim != 5
57
+ or frames.shape[0] != 1
58
+ or frames.shape[2] != 3
59
+ or tuple(frames.shape[-2:]) != (self.height, self.width)
60
+ or frames.shape[1] == 0
61
+ or frames.dtype != torch.float32
62
+ ):
63
+ raise ValueError(
64
+ "expected float32 [1, N, 3, height, width] at configured geometry"
65
+ )
66
+ valid = (
67
+ torch.isfinite(frames).all()
68
+ & (frames.min() >= -1e-6)
69
+ & (frames.max() <= 1 + 1e-6)
70
+ )
71
+ if not bool(valid):
72
+ raise ValueError("expected finite RGB in [0, 1]")
73
+ return frames
74
+
75
+ def _output_device(self, output_device):
76
+ target = self.device if output_device is None else torch.device(output_device)
77
+ if (
78
+ target.type == "cuda"
79
+ and target.index is None
80
+ and self.device.type == "cuda"
81
+ ):
82
+ target = self.device
83
+ if target.type != "cpu" and target != self.device:
84
+ raise ValueError("output_device must be cpu or the model device")
85
+ return target
86
+
87
+ def compile(self):
88
+ """Compile pure streaming compute; page transactions remain explicit."""
89
+ if self._stream is not None:
90
+ raise RuntimeError("close the active stream before enabling compilation")
91
+ if self.device.type != "cuda":
92
+ raise ValueError("compilation requires a CUDA model")
93
+ if self._compiled is not None:
94
+ return self
95
+ from ..aggregator.stream import prepare_global
96
+ from ..aggregator.base import finish_global
97
+
98
+ agg = self._native.aggregator
99
+ for block in [*agg.frame_blocks, *agg.patch_embed.blocks]:
100
+ block.forward = torch.compile(block.forward, mode="reduce-overhead")
101
+ if agg.patch_embed.rope_embed is not None:
102
+ rope = agg.patch_embed.rope_embed
103
+ rope.forward = _cached_encoder_rope(rope)
104
+ if self._native.depth_head is not None:
105
+ head = self._native.depth_head
106
+ head._apply_pos_embed = _cached_depth_position(head)
107
+ self._compiled = [
108
+ (
109
+ torch.compile(partial(prepare_global, block), mode="reduce-overhead"),
110
+ torch.compile(partial(finish_global, block), mode="reduce-overhead"),
111
+ )
112
+ for block in agg.global_blocks
113
+ ]
114
+ self.metadata["compile"] = "reduce-overhead; lazy shape-dependent capture"
115
+ return self
116
+
117
+ def create_stream(
118
+ self, *, output_device="cpu", offload_kv=False, depth_chunk_size=None
119
+ ):
120
+ from ..aggregator.stream import Stream
121
+
122
+ if self._stream is not None:
123
+ raise RuntimeError("close the active stream before creating another")
124
+ stream = Stream(
125
+ self,
126
+ output_device=output_device,
127
+ offload_kv=offload_kv,
128
+ depth_chunk_size=depth_chunk_size,
129
+ )
130
+ self._stream = stream
131
+ return stream
132
+
133
+ def warmup(self, frames, *, output_device="cpu", depth_chunk_size=None):
134
+ """Use disposable streams on real geometry before measuring throughput."""
135
+ if self._stream is not None:
136
+ raise RuntimeError("close the active stream before warmup")
137
+ images = self.prepare(frames).to(self.device)
138
+ if not self.config.scale_frames < images.shape[1] <= self.config.max_frames:
139
+ raise ValueError(
140
+ "warmup needs the full prefix plus at least one online frame"
141
+ )
142
+ passes = 3 if self._compiled is not None else 1
143
+ for _ in range(passes):
144
+ with self.create_stream(
145
+ output_device=output_device, depth_chunk_size=depth_chunk_size
146
+ ) as stream:
147
+ for frame in images[0]:
148
+ stream.online(frame)
149
+ if self.device.type == "cuda":
150
+ torch.cuda.synchronize(self.device)
151
+ self.metadata["last_warmup"] = {
152
+ "frames": images.shape[1],
153
+ "passes": passes,
154
+ "input_wh": [self.width, self.height],
155
+ }
156
+
157
+
158
+ def load_model(
159
+ checkpoint,
160
+ *,
161
+ config=None,
162
+ device="cuda:0",
163
+ depth=True,
164
+ width=None,
165
+ height=None,
166
+ compile=True,
167
+ max_frames=None,
168
+ backbone_bf16=False,
169
+ ):
170
+ """Load the published causal weights/config pair. No default weights exist."""
171
+ path, spec, config_path = resolve_checkpoint(checkpoint, config)
172
+ target = torch.device(device)
173
+ if target.type != "cuda" or not torch.cuda.is_available():
174
+ raise RuntimeError("streaming inference requires a BF16-capable CUDA GPU")
175
+ with torch.cuda.device(target):
176
+ if not torch.cuda.is_bf16_supported():
177
+ raise RuntimeError("this model requires BF16 support")
178
+ for value in (width, height):
179
+ if value is not None and (type(value) is not int or value <= 0 or value % 16):
180
+ raise ValueError("width and height must be positive multiples of 16")
181
+ from .gcr_base import NativeModel
182
+
183
+ capacity = spec.max_frames if max_frames is None else max_frames
184
+ if type(capacity) is not int or capacity < spec.scale_frames:
185
+ raise ValueError("max_frames must accommodate the initialization prefix")
186
+ native = NativeModel(spec.spatial_rope, max_frames=capacity)
187
+ # Only model-only tensor exports are supported; never unpickle training objects.
188
+ checkpoint_data = torch.load(path, map_location="cpu", mmap=True, weights_only=True)
189
+ if not isinstance(checkpoint_data, dict):
190
+ raise ValueError("expected a model state dictionary or a model-only export")
191
+ if checkpoint_data.get("training_mode", "causal") != "causal":
192
+ raise ValueError("checkpoint metadata contradicts the causal configuration")
193
+ state = checkpoint_data.get("model", checkpoint_data)
194
+ native.load_state_dict(state, strict=True)
195
+ del state, checkpoint_data
196
+ # Audit every head before applying an explicitly requested pose-only option.
197
+ if not depth:
198
+ native.depth_head = None
199
+ if backbone_bf16:
200
+ # Cast only Linear/Conv2d backbone weights to BF16 before moving to GPU:
201
+ # autocast already executes these ops in BF16 while keeping norms/RoPE/heads in FP32.
202
+ for module in native.aggregator.modules():
203
+ if isinstance(module, (torch.nn.Linear, torch.nn.Conv2d)):
204
+ module.to(dtype=torch.bfloat16)
205
+ native.eval().to(target)
206
+ metadata = {
207
+ "release": "LingBot-Map2 Streaming (causal-only)",
208
+ "checkpoint_sha256": spec.sha256,
209
+ "checkpoint_config": spec.to_dict(),
210
+ "checkpoint_config_path": str(config_path),
211
+ "temporal_capacity": capacity,
212
+ "depth_enabled": depth,
213
+ "attention": "SDPA initialization/frame attention; FlashInfer FA2 paged online",
214
+ "precision": (
215
+ "BF16 backbone Linear/Conv2d weights; FP32 norms, Camera4 and DPT"
216
+ if backbone_bf16
217
+ else "BF16 backbone; FP32 Camera4 and DPT"
218
+ ),
219
+ "compile": False,
220
+ }
221
+ model = GCRStream(
222
+ native, replace(spec, max_frames=capacity), metadata, width=width, height=height
223
+ )
224
+ return model.compile() if compile else model
lingbot_map2/utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Input/output, checkpoint and command-line utilities."""
lingbot_map2/utils/checkpoint.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+
3
+ """Explicit identity and training contract for the causal-only weight release."""
4
+
5
+ from dataclasses import asdict, dataclass
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class CheckpointConfig:
13
+ name: str
14
+ sha256: str
15
+ schema_version: int = 1
16
+ training_mode: str = "causal"
17
+ architecture: str = "dinov3_vitl16_causal24"
18
+ spatial_rope: str = "max"
19
+ scale_frames: int = 8
20
+ sliding_window: int = 64
21
+ camera_iterations: int = 4
22
+ max_frames: int = 1024
23
+ width: int = 512
24
+ height: int = 288
25
+
26
+ @classmethod
27
+ def read(cls, path):
28
+ data = json.loads(Path(path).read_text())
29
+ fields = set(cls.__dataclass_fields__)
30
+ if not isinstance(data, dict) or set(data) != fields:
31
+ raise ValueError(f"checkpoint config must contain exactly {sorted(fields)}")
32
+ config = cls(**data)
33
+ if config.schema_version != 1 or type(config.schema_version) is not int:
34
+ raise ValueError("unsupported checkpoint schema")
35
+ if (
36
+ config.training_mode != "causal"
37
+ or config.architecture != "dinov3_vitl16_causal24"
38
+ ):
39
+ raise ValueError(
40
+ "this release accepts only pure causal LingBot-Map2 weights"
41
+ )
42
+ if config.spatial_rope not in {"max", "none"}:
43
+ raise ValueError("unsupported global spatial RoPE contract")
44
+ if not isinstance(config.name, str) or not config.name.strip():
45
+ raise ValueError("checkpoint name must be non-empty")
46
+ if (
47
+ not isinstance(config.sha256, str)
48
+ or len(config.sha256) != 64
49
+ or any(c not in "0123456789abcdef" for c in config.sha256)
50
+ or config.sha256 == "0" * 64
51
+ ):
52
+ raise ValueError(
53
+ "provide the published SHA256; placeholders are not weights"
54
+ )
55
+ for field in (
56
+ "scale_frames",
57
+ "sliding_window",
58
+ "camera_iterations",
59
+ "max_frames",
60
+ "width",
61
+ "height",
62
+ ):
63
+ value = getattr(config, field)
64
+ if type(value) is not int or value <= 0:
65
+ raise ValueError(f"{field} must be a positive integer")
66
+ if (
67
+ config.camera_iterations != 4
68
+ or config.max_frames > 1024
69
+ or config.scale_frames > config.max_frames
70
+ ):
71
+ raise ValueError("require Camera4 and scale_frames <= max_frames <= 1024")
72
+ if config.width % 16 or config.height % 16:
73
+ raise ValueError("input dimensions must be multiples of 16")
74
+ return config
75
+
76
+ def to_dict(self):
77
+ return asdict(self)
78
+
79
+
80
+ def sha256_file(path):
81
+ digest = hashlib.sha256()
82
+ with Path(path).open("rb") as source:
83
+ for chunk in iter(lambda: source.read(8 << 20), b""):
84
+ digest.update(chunk)
85
+ return digest.hexdigest()
86
+
87
+
88
+ def checkpoint_paths(checkpoint, config=None):
89
+ """Resolve aliases before looking for the checkpoint's adjacent JSON."""
90
+ path = Path(checkpoint).expanduser().resolve(strict=True)
91
+ config_path = (
92
+ Path(config).expanduser() if config is not None else Path(str(path) + ".json")
93
+ )
94
+ if not config_path.is_file():
95
+ raise FileNotFoundError(
96
+ "provide the published causal checkpoint config with --config "
97
+ "or as <checkpoint>.json; there is no bundled weight preset"
98
+ )
99
+ return path, config_path.resolve()
100
+
101
+
102
+ def resolve_checkpoint(checkpoint, config=None):
103
+ path, config_path = checkpoint_paths(checkpoint, config)
104
+ spec = CheckpointConfig.read(config_path)
105
+ if sha256_file(path) != spec.sha256:
106
+ raise ValueError(
107
+ "checkpoint SHA256 mismatch; use the matching published weights/config pair"
108
+ )
109
+ return path, spec, config_path
lingbot_map2/utils/compilation.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved. See LICENSE.txt and LICENSES/THIRD_PARTY.md.
4
+
5
+ import torch
6
+
7
+
8
+ def _cached_encoder_rope(module):
9
+ """Cache spatial frequencies for inference."""
10
+ original = module.forward
11
+ cached_key = cached_value = None
12
+
13
+ def forward(*, H, W):
14
+ nonlocal cached_key, cached_value
15
+ periods = module.periods
16
+ if module.training or torch.is_inference(periods):
17
+ return original(H=H, W=W)
18
+ key = (
19
+ H,
20
+ W,
21
+ periods.device,
22
+ periods.dtype,
23
+ periods.data_ptr(),
24
+ periods._version,
25
+ module.dtype,
26
+ module.normalize_coords,
27
+ )
28
+ if key != cached_key:
29
+ cached_value = original(H=H, W=W)
30
+ cached_key = key
31
+ return cached_value
32
+
33
+ return forward
34
+
35
+
36
+ def _cached_depth_position(module):
37
+ """Reuse native eval-only DPT grids for the current geometry and device."""
38
+ from ..heads.utils import create_uv_grid, position_grid_to_embed
39
+
40
+ original = module._apply_pos_embed
41
+ geometry = None
42
+ embeddings = {}
43
+
44
+ def forward(x, W, H, ratio=0.1):
45
+ nonlocal geometry
46
+ if module.training or torch.is_grad_enabled():
47
+ return original(x, W, H, ratio)
48
+ current = (W, H, x.device, x.dtype)
49
+ if current != geometry:
50
+ embeddings.clear()
51
+ geometry = current
52
+ channels, height, width = x.shape[1:]
53
+ key = (channels, height, width, ratio)
54
+ if key not in embeddings:
55
+ grid = create_uv_grid(
56
+ width, height, aspect_ratio=W / H, dtype=x.dtype, device=x.device
57
+ )
58
+ embedding = position_grid_to_embed(grid, channels) * ratio
59
+ embeddings[key] = embedding.permute(2, 0, 1)[None]
60
+ return x + embeddings[key]
61
+
62
+ return forward
lingbot_map2/utils/load_fn.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved. See LICENSE.txt and LICENSES/THIRD_PARTY.md.
4
+
5
+ """Image loading, preprocessing and deterministic keyframe selection."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import json
12
+ import math
13
+ import re
14
+ from pathlib import Path
15
+
16
+
17
+ def uniform_keyframe_ids(count, *, prefix=8, interval=None):
18
+ """Keep the prefix, then every ceil(N/320)-th frame unless overridden.
19
+
20
+ This is a nominal budget, not an exact 320-frame cap. IDs address the input
21
+ sequence; the model's committed-frame clock is a separate coordinate.
22
+ """
23
+ if type(count) is not int or type(prefix) is not int or not 0 < prefix <= count:
24
+ raise ValueError("input count must accommodate a positive prefix")
25
+ if interval is None:
26
+ interval = math.ceil(count / 320)
27
+ if type(interval) is not int or interval < 1:
28
+ raise ValueError("keyframe interval must be a positive integer")
29
+ return list(range(prefix)) + list(range(prefix, count, interval))
30
+
31
+
32
+ def exact_keyframe_ids(count, *, prefix=8, num_keyframes=320):
33
+ """Keep all frames up to num_keyframes, or keep the prefix plus uniformly
34
+ spaced frames so the persistent KV-cache budget equals num_keyframes.
35
+
36
+ When count > num_keyframes:
37
+ - num_keyframes == prefix retains only the initialization prefix [0..prefix-1].
38
+ - num_keyframes == prefix + 1 retains the prefix plus the final frame count - 1.
39
+ - num_keyframes >= prefix + 2 retains the prefix plus uniformly spaced frames
40
+ spanning [prefix, count - 1] (inclusive).
41
+ """
42
+ if type(count) is not int or type(prefix) is not int or not 0 < prefix <= count:
43
+ raise ValueError("input count must accommodate a positive prefix")
44
+ if type(num_keyframes) is not int or num_keyframes < prefix:
45
+ raise ValueError(f"num_keyframes must be an integer >= prefix ({prefix})")
46
+ if count <= num_keyframes:
47
+ return list(range(count))
48
+ remaining = num_keyframes - prefix
49
+ if remaining == 0:
50
+ return list(range(prefix))
51
+ if remaining == 1:
52
+ return list(range(prefix)) + [count - 1]
53
+ span = count - 1 - prefix
54
+ denom = remaining - 1
55
+ # Exact half-up integer rounding guarantees strictly increasing indices
56
+ # spanning [prefix, count - 1] since count > num_keyframes implies span > denom.
57
+ tail = [prefix + (2 * i * span + denom) // (2 * denom) for i in range(remaining)]
58
+ return list(range(prefix)) + tail
59
+
60
+
61
+ def image_paths(folder: str | None, image_list: str | None) -> list[Path]:
62
+ if image_list:
63
+ source = Path(image_list).resolve(strict=True)
64
+ values = json.loads(source.read_text())
65
+ if (
66
+ not isinstance(values, list)
67
+ or not values
68
+ or any(not isinstance(value, str) for value in values)
69
+ ):
70
+ raise ValueError("image-list must be a non-empty JSON array of paths")
71
+ paths = [(source.parent / value).resolve(strict=True) for value in values]
72
+ else:
73
+ root = Path(folder).resolve(strict=True)
74
+
75
+ def natural_key(path):
76
+ return [
77
+ (1, int(part)) if part.isdigit() else (0, part.lower())
78
+ for part in re.split(r"(\d+)", path.name)
79
+ ]
80
+
81
+ paths = sorted(
82
+ (
83
+ path
84
+ for path in root.iterdir()
85
+ if path.is_file() and path.suffix.lower() in {".png", ".jpg", ".jpeg"}
86
+ ),
87
+ key=natural_key,
88
+ )
89
+ if not paths or any(not path.is_file() for path in paths):
90
+ raise ValueError("input must contain readable image files")
91
+ return paths
92
+
93
+
94
+ def cover_resize(rgb, output_wh):
95
+ """Keep input dtype, cover the target, then center crop without padding."""
96
+ import cv2
97
+
98
+ width, height = output_wh
99
+ raw_height, raw_width = rgb.shape[:2]
100
+ scale = max(width / raw_width, height / raw_height)
101
+ resized_width, resized_height = round(raw_width * scale), round(raw_height * scale)
102
+ resized = cv2.resize(
103
+ rgb, (resized_width, resized_height), interpolation=cv2.INTER_AREA
104
+ )
105
+ left, top = (resized_width - width) // 2, (resized_height - height) // 2
106
+ return resized[top : top + height, left : left + width].copy()
107
+
108
+
109
+ def load_images(paths: Sequence[str | Path], width: int = 512, height: int = 288):
110
+ """RGB float32 AREA cover-resize / center-crop, then divide by 255.
111
+
112
+ Preserve channels-last tensor strides and floating-point resized pixels.
113
+ """
114
+ import numpy as np
115
+ import torch
116
+ from PIL import Image
117
+
118
+ if width <= 0 or height <= 0 or width % 16 or height % 16:
119
+ raise ValueError("width and height must be positive multiples of 16")
120
+ if not paths:
121
+ raise ValueError("no input images")
122
+ frames = []
123
+ for path in paths:
124
+ with Image.open(path) as image:
125
+ rgb = np.asarray(image.convert("RGB"), dtype=np.float32)
126
+ frames.append(cover_resize(rgb, (width, height)))
127
+ return (torch.from_numpy(np.stack(frames)).permute(0, 3, 1, 2).float() / 255)[None]
lingbot_map2/utils/pose_enc.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications copyright 2026 The Robbyant Team Authors.
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved. See LICENSE.txt and LICENSES/THIRD_PARTY.md.
4
+
5
+ import numpy as np
6
+ import torch
7
+ from .rotation import quat_to_mat
8
+
9
+
10
+ def pose_encoding_to_extri_intri(
11
+ pose_encoding,
12
+ image_size_hw=None,
13
+ pose_encoding_type="absT_quaR_FoV",
14
+ build_intrinsics=True, # e.g., (256, 512)
15
+ ):
16
+ """Convert a pose encoding back to camera extrinsics and intrinsics.
17
+
18
+ This function performs the inverse operation of extri_intri_to_pose_encoding,
19
+ reconstructing the full camera parameters from the compact encoding.
20
+
21
+ Args:
22
+ pose_encoding (torch.Tensor): Encoded camera pose parameters with shape BxSx9,
23
+ where B is batch size and S is sequence length.
24
+ For "absT_quaR_FoV" type, the 9 dimensions are:
25
+ - [:3] = absolute translation vector T (3D)
26
+ - [3:7] = rotation as quaternion quat (4D)
27
+ - [7:] = field of view (2D)
28
+ image_size_hw (tuple): Tuple of (height, width) of the image in pixels.
29
+ Required for reconstructing intrinsics from field of view values.
30
+ For example: (256, 512).
31
+ pose_encoding_type (str): Type of pose encoding used. Currently only
32
+ supports "absT_quaR_FoV" (absolute translation, quaternion rotation, field of view).
33
+ build_intrinsics (bool): Whether to reconstruct the intrinsics matrix.
34
+ If False, only extrinsics are returned and intrinsics will be None.
35
+
36
+ Returns:
37
+ tuple: (extrinsics, intrinsics)
38
+ - extrinsics (torch.Tensor): Camera pose matrices with shape BxSx3x4.
39
+ In OpenCV coordinate system (x-right, y-down, z-forward), representing the
40
+ camera-to-world (C2W) transformation `[R|t]` in this model (mapping
41
+ camera-frame points to world coordinates, matching `poses_c2w` returned
42
+ by `decode_predictions`).
43
+ - intrinsics (torch.Tensor or None): Camera intrinsic parameters with shape BxSx3x3,
44
+ or None if build_intrinsics is False. Defined in pixels, with format:
45
+ [[fx, 0, cx],
46
+ [0, fy, cy],
47
+ [0, 0, 1]]
48
+ where fx, fy are focal lengths and (cx, cy) is the principal point,
49
+ assumed to be at the center of the image (W/2, H/2).
50
+ """
51
+
52
+ intrinsics = None
53
+
54
+ if pose_encoding_type == "absT_quaR_FoV":
55
+ T = pose_encoding[..., :3]
56
+ quat = pose_encoding[..., 3:7]
57
+ fov_h = pose_encoding[..., 7]
58
+ fov_w = pose_encoding[..., 8]
59
+
60
+ R = quat_to_mat(quat)
61
+ extrinsics = torch.cat([R, T[..., None]], dim=-1)
62
+
63
+ if build_intrinsics:
64
+ H, W = image_size_hw
65
+ fy = (H / 2.0) / torch.tan(fov_h / 2.0)
66
+ fx = (W / 2.0) / torch.tan(fov_w / 2.0)
67
+ intrinsics = torch.zeros(
68
+ pose_encoding.shape[:2] + (3, 3), device=pose_encoding.device
69
+ )
70
+ intrinsics[..., 0, 0] = fx
71
+ intrinsics[..., 1, 1] = fy
72
+ intrinsics[..., 0, 2] = W / 2
73
+ intrinsics[..., 1, 2] = H / 2
74
+ intrinsics[..., 2, 2] = 1.0 # Set the homogeneous coordinate to 1
75
+ elif pose_encoding_type == "absT_quaR":
76
+ T = pose_encoding[..., :3]
77
+ quat = pose_encoding[..., 3:7]
78
+
79
+ R = quat_to_mat(quat)
80
+ extrinsics = torch.cat([R, T[..., None]], dim=-1)
81
+
82
+ intrinsics = None
83
+
84
+ return extrinsics, intrinsics
85
+
86
+
87
+ def decode_predictions(output, image_hw, *, output_device="cpu"):
88
+ """Decode native pose and geometry outputs for a completed streaming step."""
89
+ height, width = image_hw
90
+ encoding = output["pose_enc"]
91
+ if isinstance(encoding, (list, tuple)):
92
+ encoding = encoding[-1]
93
+ encoding = encoding.float()
94
+ frames = encoding.shape[1]
95
+ extrinsics, intrinsics = pose_encoding_to_extri_intri(encoding, (height, width))
96
+ # Native pose encoding is C2W. No inverse, GT alignment or rescaling.
97
+ poses = torch.eye(4, device=extrinsics.device).repeat(frames, 1, 1)
98
+ poses[:, :3] = extrinsics[0]
99
+ result = {
100
+ "poses_c2w": poses,
101
+ "intrinsics": intrinsics[0],
102
+ "pose_enc": encoding[0],
103
+ }
104
+ for key in ("depth", "depth_conf"):
105
+ if key in output:
106
+ result[key] = output[key][0].float()
107
+ target = poses.device if output_device is None else torch.device(output_device)
108
+ if target.type == "cpu":
109
+ result = {key: value.cpu().numpy() for key, value in result.items()}
110
+ finite = all(np.isfinite(value).all() for value in result.values())
111
+ else:
112
+ result = {key: value.to(target) for key, value in result.items()}
113
+ # One scalar validation barrier, without transferring full predictions.
114
+ finite = bool(
115
+ torch.stack([torch.isfinite(x).all() for x in result.values()]).all()
116
+ )
117
+ if not finite:
118
+ raise RuntimeError("model produced non-finite predictions")
119
+ return result
lingbot_map2/utils/rotation.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved. See LICENSE.txt and LICENSES/THIRD_PARTY.md.
3
+
4
+ import torch
5
+
6
+
7
+ def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor:
8
+ """
9
+ Quaternion Order: XYZW or say ijkr, scalar-last
10
+
11
+ Convert rotations given as quaternions to rotation matrices.
12
+ Args:
13
+ quaternions: quaternions with real part last,
14
+ as tensor of shape (..., 4).
15
+
16
+ Returns:
17
+ Rotation matrices as tensor of shape (..., 3, 3).
18
+ """
19
+ i, j, k, r = torch.unbind(quaternions, -1)
20
+ # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
21
+ two_s = 2.0 / (quaternions * quaternions).sum(-1)
22
+
23
+ o = torch.stack(
24
+ (
25
+ 1 - two_s * (j * j + k * k),
26
+ two_s * (i * j - k * r),
27
+ two_s * (i * k + j * r),
28
+ two_s * (i * j + k * r),
29
+ 1 - two_s * (i * i + k * k),
30
+ two_s * (j * k - i * r),
31
+ two_s * (i * k - j * r),
32
+ two_s * (j * k + i * r),
33
+ 1 - two_s * (i * i + j * j),
34
+ ),
35
+ -1,
36
+ )
37
+ return o.reshape(quaternions.shape[:-1] + (3, 3))
lingbot_map2/vis/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
2
+ # Space note: the Viser viewer is omitted; only GLB export and sky masking are used.
3
+
4
+ """GLB export and sky masking for Online reconstruction."""
lingbot_map2/vis/glb_export.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
4
+ # Adapted from Robbyant/lingbot-map, lingbot_map/vis/glb_export.py
5
+ # (b9dd1b1de535e6d36e777fb42b8433c781bfd783). See LICENSES/THIRD_PARTY.md.
6
+
7
+ """GLB 3D export utilities for Online and batch reconstruction predictions."""
8
+
9
+ import os
10
+ from typing import Optional, Tuple
11
+
12
+ import matplotlib
13
+ import numpy as np
14
+
15
+ from .sky_segmentation import apply_sky_segmentation
16
+
17
+ try:
18
+ import trimesh
19
+ except ImportError:
20
+ trimesh = None
21
+
22
+
23
+ def _rot_y(degrees: float) -> np.ndarray:
24
+ rad = np.deg2rad(degrees)
25
+ c, s = float(np.cos(rad)), float(np.sin(rad))
26
+ return np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]], dtype=np.float64)
27
+
28
+
29
+ def _rot_z(degrees: float) -> np.ndarray:
30
+ rad = np.deg2rad(degrees)
31
+ c, s = float(np.cos(rad)), float(np.sin(rad))
32
+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]], dtype=np.float64)
33
+
34
+
35
+ def _se3_inverse(matrices: np.ndarray) -> np.ndarray:
36
+ """Invert a batch of [N, 4, 4] or [N, 3, 4] rigid transforms."""
37
+ matrices = np.asarray(matrices, dtype=np.float64)
38
+ n = matrices.shape[0]
39
+ rot = matrices[:, :3, :3]
40
+ trans = matrices[:, :3, 3]
41
+ inv = np.broadcast_to(np.eye(4, dtype=np.float64), (n, 4, 4)).copy()
42
+ rot_t = np.swapaxes(rot, -1, -2)
43
+ inv[:, :3, :3] = rot_t
44
+ inv[:, :3, 3] = -np.einsum("nij,nj->ni", rot_t, trans)
45
+ return inv
46
+
47
+
48
+ def _extract_c2w_and_w2c(predictions: dict) -> Tuple[np.ndarray, np.ndarray]:
49
+ """Return (c2w [S,4,4], w2c [S,4,4]) from either V2 poses_c2w or V1 extrinsic."""
50
+ if predictions.get("poses_c2w") is not None:
51
+ poses = np.asarray(predictions["poses_c2w"], dtype=np.float64)
52
+ c2w = np.broadcast_to(np.eye(4, dtype=np.float64), (len(poses), 4, 4)).copy()
53
+ c2w[:, :3, :4] = poses[:, :3, :4]
54
+ w2c = _se3_inverse(c2w)
55
+ return c2w, w2c
56
+ if predictions.get("extrinsic") is not None:
57
+ ext = np.asarray(predictions["extrinsic"], dtype=np.float64)
58
+ w2c = np.broadcast_to(np.eye(4, dtype=np.float64), (len(ext), 4, 4)).copy()
59
+ w2c[:, :3, :4] = ext[:, :3, :4]
60
+ c2w = _se3_inverse(w2c)
61
+ return c2w, w2c
62
+ raise ValueError("Predictions must contain 'poses_c2w' or 'extrinsic'")
63
+
64
+
65
+ def _unproject_depth_to_world(
66
+ depth: np.ndarray,
67
+ poses_c2w: np.ndarray,
68
+ intrinsics: np.ndarray,
69
+ ) -> np.ndarray:
70
+ """Unproject [S, H, W] or [S, H, W, 1] depth maps to [S, H, W, 3] world points."""
71
+ depth = np.asarray(depth, dtype=np.float32)
72
+ if depth.ndim == 4 and depth.shape[-1] == 1:
73
+ depth = depth[..., 0]
74
+ if depth.ndim != 3:
75
+ raise ValueError(f"Expected depth with shape (S, H, W[, 1]), got {depth.shape}")
76
+ num_frames, height, width = depth.shape
77
+ yy, xx = np.mgrid[0:height, 0:width]
78
+ pixels = np.stack([xx, yy, np.ones_like(xx)], axis=-1).reshape(-1, 3).astype(np.float32)
79
+ points = np.empty((num_frames, height, width, 3), dtype=np.float32)
80
+ for i in range(num_frames):
81
+ inv_k = np.linalg.inv(np.asarray(intrinsics[i], dtype=np.float64)).astype(np.float32)
82
+ rot_t = np.asarray(poses_c2w[i, :3, :3], dtype=np.float32).T
83
+ trans = np.asarray(poses_c2w[i, :3, 3], dtype=np.float32)
84
+ rays = pixels @ inv_k.T
85
+ rays *= depth[i].reshape(-1, 1)
86
+ world_pts = rays @ rot_t
87
+ world_pts += trans
88
+ points[i] = world_pts.reshape(height, width, 3)
89
+ return points
90
+
91
+
92
+ def predictions_to_glb(
93
+ predictions: dict,
94
+ conf_thres: float = 50.0,
95
+ filter_by_frames: str = "all",
96
+ mask_black_bg: bool = False,
97
+ mask_white_bg: bool = False,
98
+ show_cam: bool = True,
99
+ mask_sky: bool = False,
100
+ target_dir: Optional[str] = None,
101
+ prediction_mode: str = "Predicted Depthmap",
102
+ skyseg_model_path: str = "skyseg.onnx",
103
+ sky_mask_dir: Optional[str] = None,
104
+ sky_mask_visualization_dir: Optional[str] = None,
105
+ ) -> "trimesh.Scene":
106
+ """Convert predictions to a 3D scene represented as a trimesh.Scene for GLB export."""
107
+ if trimesh is None:
108
+ raise ImportError(
109
+ "trimesh is required for GLB export. Install with: pip install trimesh"
110
+ )
111
+ if not isinstance(predictions, dict):
112
+ raise ValueError("predictions must be a dictionary")
113
+ if conf_thres is None:
114
+ conf_thres = 10.0
115
+
116
+ selected_frame_idx = None
117
+ if filter_by_frames not in ("all", "All"):
118
+ try:
119
+ selected_frame_idx = int(str(filter_by_frames).split(":")[0])
120
+ except (ValueError, IndexError):
121
+ pass
122
+
123
+ c2w_all, w2c_all = _extract_c2w_and_w2c(predictions)
124
+ intrinsics = predictions.get("intrinsics", predictions.get("intrinsic"))
125
+
126
+ if "Pointmap" in prediction_mode and predictions.get("world_points") is not None:
127
+ pred_world_points = np.asarray(predictions["world_points"])
128
+ pred_world_points_conf = np.asarray(
129
+ predictions.get("world_points_conf", np.ones_like(pred_world_points[..., 0]))
130
+ )
131
+ else:
132
+ if predictions.get("world_points_from_depth") is not None:
133
+ pred_world_points = np.asarray(predictions["world_points_from_depth"])
134
+ else:
135
+ if predictions.get("depth") is None or intrinsics is None:
136
+ raise ValueError(
137
+ "Depth-based GLB export requires depth, poses_c2w/extrinsic, and intrinsics"
138
+ )
139
+ pred_world_points = _unproject_depth_to_world(
140
+ predictions["depth"], c2w_all, intrinsics
141
+ )
142
+ pred_world_points_conf = np.asarray(
143
+ predictions.get("depth_conf", np.ones_like(pred_world_points[..., 0]))
144
+ )
145
+
146
+ images = np.asarray(predictions["images"])
147
+
148
+ if mask_sky:
149
+ pred_world_points_conf = _apply_sky_mask(
150
+ pred_world_points_conf,
151
+ target_dir,
152
+ images,
153
+ skyseg_model_path=skyseg_model_path,
154
+ sky_mask_dir=sky_mask_dir,
155
+ sky_mask_visualization_dir=sky_mask_visualization_dir,
156
+ )
157
+
158
+ if selected_frame_idx is not None:
159
+ pred_world_points = pred_world_points[selected_frame_idx][None]
160
+ pred_world_points_conf = pred_world_points_conf[selected_frame_idx][None]
161
+ images = images[selected_frame_idx][None]
162
+ c2w_all = c2w_all[selected_frame_idx][None]
163
+ w2c_all = w2c_all[selected_frame_idx][None]
164
+
165
+ vertices_3d = pred_world_points.reshape(-1, 3)
166
+
167
+ if images.ndim == 4 and images.shape[1] == 3 and images.shape[-1] != 3:
168
+ colors_rgb = np.transpose(images, (0, 2, 3, 1))
169
+ else:
170
+ colors_rgb = images
171
+ colors_rgb = colors_rgb.reshape(-1, 3)
172
+ if colors_rgb.dtype != np.uint8:
173
+ scale = 255.0 if colors_rgb.size > 0 and colors_rgb.max() <= 1.0 else 1.0
174
+ colors_rgb = np.clip(colors_rgb * scale, 0, 255).astype(np.uint8)
175
+
176
+ conf = pred_world_points_conf.reshape(-1)
177
+ valid = np.isfinite(vertices_3d).all(axis=1) & np.isfinite(conf)
178
+ conf_threshold = np.percentile(conf[valid], conf_thres) if conf_thres > 0 and valid.any() else 0.0
179
+ conf_mask = valid & (conf >= conf_threshold) & (conf > 1e-5)
180
+
181
+ if mask_black_bg:
182
+ conf_mask &= colors_rgb.sum(axis=1) >= 16
183
+ if mask_white_bg:
184
+ conf_mask &= ~(
185
+ (colors_rgb[:, 0] > 240)
186
+ & (colors_rgb[:, 1] > 240)
187
+ & (colors_rgb[:, 2] > 240)
188
+ )
189
+
190
+ vertices_3d = vertices_3d[conf_mask]
191
+ colors_rgb = colors_rgb[conf_mask]
192
+
193
+ if vertices_3d.size == 0:
194
+ vertices_3d = np.array([[1.0, 0.0, 0.0]], dtype=np.float32)
195
+ colors_rgb = np.array([[255, 255, 255]], dtype=np.uint8)
196
+ scene_scale = 1.0
197
+ else:
198
+ lower = np.percentile(vertices_3d, 5, axis=0)
199
+ upper = np.percentile(vertices_3d, 95, axis=0)
200
+ scene_scale = max(float(np.linalg.norm(upper - lower)), 0.1)
201
+
202
+ colormap = matplotlib.colormaps["gist_rainbow"]
203
+
204
+ scene_3d = trimesh.Scene()
205
+ scene_3d.add_geometry(trimesh.PointCloud(vertices=vertices_3d, colors=colors_rgb))
206
+
207
+ num_cameras = len(c2w_all)
208
+ if show_cam:
209
+ for i in range(num_cameras):
210
+ rgba_color = colormap(i / max(num_cameras, 1))
211
+ current_color = tuple(int(255 * x) for x in rgba_color[:3])
212
+ integrate_camera_into_scene(scene_3d, c2w_all[i], current_color, scene_scale)
213
+
214
+ return apply_scene_alignment(scene_3d, w2c_all)
215
+
216
+
217
+ def _apply_sky_mask(
218
+ conf: np.ndarray,
219
+ target_dir: Optional[str],
220
+ images: np.ndarray,
221
+ skyseg_model_path: str = "skyseg.onnx",
222
+ sky_mask_dir: Optional[str] = None,
223
+ sky_mask_visualization_dir: Optional[str] = None,
224
+ ) -> np.ndarray:
225
+ image_folder = None
226
+ if target_dir is not None:
227
+ candidate = os.path.join(target_dir, "images")
228
+ if os.path.isdir(candidate):
229
+ image_folder = candidate
230
+ if sky_mask_dir is None:
231
+ sky_mask_dir = os.path.join(target_dir, "sky_masks")
232
+
233
+ return apply_sky_segmentation(
234
+ conf,
235
+ image_folder=image_folder,
236
+ images=images,
237
+ skyseg_model_path=skyseg_model_path,
238
+ sky_mask_dir=sky_mask_dir,
239
+ sky_mask_visualization_dir=sky_mask_visualization_dir,
240
+ )
241
+
242
+
243
+ def integrate_camera_into_scene(
244
+ scene: "trimesh.Scene",
245
+ transform: np.ndarray,
246
+ face_colors: Tuple[int, int, int],
247
+ scene_scale: float,
248
+ frustum_thickness: float = 1.0,
249
+ ):
250
+ """Integrate a camera frustum mesh into the 3D scene."""
251
+ cam_width = scene_scale * 0.05
252
+ cam_height = scene_scale * 0.1
253
+
254
+ rot_45_degree = np.eye(4)
255
+ rot_45_degree[:3, :3] = _rot_z(45.0)
256
+ rot_45_degree[2, 3] = -cam_height
257
+
258
+ opengl_transform = get_opengl_conversion_matrix()
259
+ complete_transform = transform @ opengl_transform @ rot_45_degree
260
+ camera_cone_shape = trimesh.creation.cone(cam_width, cam_height, sections=4)
261
+
262
+ slight_rotation = np.eye(4)
263
+ slight_rotation[:3, :3] = _rot_z(2.0)
264
+
265
+ shell_scales = [1.0, 0.95]
266
+ shell_transforms = [np.eye(4), slight_rotation]
267
+ if frustum_thickness > 1.0:
268
+ n_extra = max(1, int(frustum_thickness - 1))
269
+ for k in range(1, n_extra + 1):
270
+ angle = 2.0 + k * 2.0
271
+ scale = 1.0 + k * 0.02
272
+ rot = np.eye(4)
273
+ rot[:3, :3] = _rot_z(angle)
274
+ shell_scales.append(scale)
275
+ shell_transforms.append(rot)
276
+ rot_neg = np.eye(4)
277
+ rot_neg[:3, :3] = _rot_z(-angle)
278
+ shell_scales.append(scale)
279
+ shell_transforms.append(rot_neg)
280
+
281
+ vertices_parts = [
282
+ transform_points(t_mat, s * camera_cone_shape.vertices)
283
+ for s, t_mat in zip(shell_scales, shell_transforms)
284
+ ]
285
+ vertices_combined = np.concatenate(vertices_parts)
286
+ vertices_transformed = transform_points(complete_transform, vertices_combined)
287
+
288
+ mesh_faces = compute_camera_faces_multi(camera_cone_shape, len(shell_scales))
289
+ camera_mesh = trimesh.Trimesh(vertices=vertices_transformed, faces=mesh_faces)
290
+ camera_mesh.visual.face_colors[:, :3] = face_colors
291
+ scene.add_geometry(camera_mesh)
292
+
293
+
294
+ def build_trajectory_tube(positions, radius, colormap, num_cameras):
295
+ """Build a gradient-colored cylinder tube mesh connecting camera positions."""
296
+ if trimesh is None:
297
+ return None
298
+ segments = []
299
+ for i in range(len(positions) - 1):
300
+ p0, p1 = positions[i], positions[i + 1]
301
+ seg_len = float(np.linalg.norm(p1 - p0))
302
+ if seg_len < 1e-8:
303
+ continue
304
+ cyl = trimesh.creation.cylinder(radius=radius, height=seg_len, sections=8)
305
+ direction = (p1 - p0) / seg_len
306
+ mid = (p0 + p1) / 2.0
307
+
308
+ z_axis = np.array([0.0, 0.0, 1.0])
309
+ v = np.cross(z_axis, direction)
310
+ c = float(np.dot(z_axis, direction))
311
+ if np.linalg.norm(v) < 1e-8:
312
+ rot = np.eye(3) if c > 0 else np.diag([1.0, -1.0, -1.0])
313
+ else:
314
+ vx = np.array(
315
+ [[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]]
316
+ )
317
+ rot = np.eye(3) + vx + vx @ vx / (1.0 + c)
318
+
319
+ transform = np.eye(4)
320
+ transform[:3, :3] = rot
321
+ transform[:3, 3] = mid
322
+ cyl.apply_transform(transform)
323
+
324
+ t_color = (i + 0.5) / max(num_cameras - 1, 1)
325
+ rgba = colormap(t_color)
326
+ cyl.visual.face_colors[:, :3] = tuple(int(255 * x) for x in rgba[:3])
327
+ segments.append(cyl)
328
+
329
+ if not segments:
330
+ return None
331
+ return trimesh.util.concatenate(segments)
332
+
333
+
334
+ def apply_scene_alignment(
335
+ scene_3d: "trimesh.Scene",
336
+ extrinsics_matrices: np.ndarray,
337
+ ) -> "trimesh.Scene":
338
+ """Bring world coordinates into camera 0's frame (W2C), then apply display axes."""
339
+ opengl_conversion_matrix = get_opengl_conversion_matrix()
340
+ align_rotation = np.eye(4)
341
+ align_rotation[:3, :3] = _rot_y(180.0)
342
+
343
+ initial_transformation = (
344
+ align_rotation @ opengl_conversion_matrix @ extrinsics_matrices[0]
345
+ )
346
+ scene_3d.apply_transform(initial_transformation)
347
+ return scene_3d
348
+
349
+
350
+ def get_opengl_conversion_matrix() -> np.ndarray:
351
+ """Return the OpenGL conversion matrix (flips Y and Z axes)."""
352
+ matrix = np.identity(4)
353
+ matrix[1, 1] = -1
354
+ matrix[2, 2] = -1
355
+ return matrix
356
+
357
+
358
+ def transform_points(
359
+ transformation: np.ndarray,
360
+ points: np.ndarray,
361
+ dim: Optional[int] = None,
362
+ ) -> np.ndarray:
363
+ """Apply a 4x4 transformation matrix to a set of 3D points."""
364
+ points = np.asarray(points)
365
+ initial_shape = points.shape[:-1]
366
+ dim = dim or points.shape[-1]
367
+
368
+ transformation = transformation.swapaxes(-1, -2)
369
+ points = points @ transformation[..., :-1, :] + transformation[..., -1:, :]
370
+ return points[..., :dim].reshape(*initial_shape, dim)
371
+
372
+
373
+ def compute_camera_faces_multi(
374
+ cone_shape: "trimesh.Trimesh", num_shells: int
375
+ ) -> np.ndarray:
376
+ """Compute faces for a camera mesh with multiple shells (for thicker frustums)."""
377
+ faces_list = []
378
+ nv = len(cone_shape.vertices)
379
+ for s in range(num_shells - 1):
380
+ off_a = s * nv
381
+ off_b = (s + 1) * nv
382
+ for face in cone_shape.faces:
383
+ if 0 in face:
384
+ continue
385
+ v1, v2, v3 = face
386
+ faces_list.extend(
387
+ [
388
+ (v1 + off_a, v2 + off_a, v2 + off_b),
389
+ (v1 + off_a, v1 + off_b, v3 + off_a),
390
+ (v3 + off_b, v2 + off_a, v3 + off_a),
391
+ ]
392
+ )
393
+ faces_list += [(v3, v2, v1) for v1, v2, v3 in faces_list]
394
+ return np.array(faces_list)
lingbot_map2/vis/sky_segmentation.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
4
+ # Adapted from Robbyant/lingbot-map, lingbot_map/vis/sky_segmentation.py
5
+ # (b9dd1b1de535e6d36e777fb42b8433c781bfd783). See LICENSES/THIRD_PARTY.md.
6
+
7
+ """Sky segmentation utilities for filtering sky points from point clouds."""
8
+
9
+ import glob
10
+ import hashlib
11
+ import os
12
+ from pathlib import Path
13
+ import tempfile
14
+ from typing import Optional, Tuple
15
+ from urllib.request import urlopen
16
+
17
+ import cv2
18
+ import numpy as np
19
+
20
+ try:
21
+ import onnxruntime
22
+ except ImportError:
23
+ onnxruntime = None
24
+
25
+ _SKYSEG_INPUT_SIZE = (320, 320)
26
+ # Non-sky confidence threshold; > 0.875 keeps raw skyseg scores < 32/255, matching V1/VGGT.
27
+ _SKYSEG_SOFT_THRESHOLD = 0.875
28
+ _SKYSEG_CACHE_VERSION = "imagenet_norm_softmap_inverted_v6"
29
+ _SKYSEG_MODEL_URL = (
30
+ "https://huggingface.co/JianyuanWang/skyseg/resolve/main/skyseg.onnx"
31
+ )
32
+ _DEFAULT_SKYSEG_PATH = Path.home() / ".cache/lingbot-map2/skyseg.onnx"
33
+
34
+
35
+ def _get_cache_version_path(sky_mask_dir: str) -> str:
36
+ return os.path.join(sky_mask_dir, ".skyseg_cache_version")
37
+
38
+
39
+ def _prepare_sky_mask_cache(sky_mask_dir: Optional[str]) -> bool:
40
+ """Ensure the sky mask cache directory exists; return True if cached masks are stale."""
41
+ if sky_mask_dir is None:
42
+ return False
43
+ os.makedirs(sky_mask_dir, exist_ok=True)
44
+ version_path = _get_cache_version_path(sky_mask_dir)
45
+ refresh_cache = True
46
+ if os.path.exists(version_path):
47
+ with open(version_path, "r", encoding="utf-8") as f:
48
+ refresh_cache = f.read().strip() != _SKYSEG_CACHE_VERSION
49
+ if refresh_cache:
50
+ with open(version_path, "w", encoding="utf-8") as f:
51
+ f.write(_SKYSEG_CACHE_VERSION)
52
+ return refresh_cache
53
+
54
+
55
+ def download_skyseg_model(output_path: Optional[str] = None) -> str:
56
+ """Download the sky segmentation ONNX model from Hugging Face atomically."""
57
+ path = Path(output_path).expanduser() if output_path else _DEFAULT_SKYSEG_PATH
58
+ path.parent.mkdir(parents=True, exist_ok=True)
59
+ temporary = None
60
+ try:
61
+ with urlopen(_SKYSEG_MODEL_URL, timeout=60) as response:
62
+ with tempfile.NamedTemporaryFile(
63
+ dir=path.parent,
64
+ prefix=f".{path.name}.",
65
+ suffix=".tmp",
66
+ delete=False,
67
+ ) as output:
68
+ temporary = Path(output.name)
69
+ while chunk := response.read(1 << 20):
70
+ output.write(chunk)
71
+ temporary.replace(path)
72
+ temporary = None
73
+ finally:
74
+ if temporary is not None:
75
+ temporary.unlink(missing_ok=True)
76
+ return str(path)
77
+
78
+
79
+ def _ensure_skyseg_model(skyseg_model_path: Optional[str]) -> str:
80
+ """Download the skyseg model when the requested path is not a regular file."""
81
+ path = (
82
+ Path(skyseg_model_path).expanduser()
83
+ if skyseg_model_path
84
+ else _DEFAULT_SKYSEG_PATH
85
+ )
86
+ if path.is_file():
87
+ return str(path)
88
+ try:
89
+ download_skyseg_model(str(path))
90
+ except Exception as error:
91
+ raise RuntimeError(
92
+ f"Failed to download the sky segmentation model to {path} "
93
+ f"from {_SKYSEG_MODEL_URL}: {error}. Download it manually from "
94
+ f"{_SKYSEG_MODEL_URL} and pass --sky-model /path/to/skyseg.onnx."
95
+ ) from error
96
+ if not path.is_file():
97
+ raise RuntimeError(
98
+ f"Sky segmentation model download to {path} did not create a file."
99
+ )
100
+ return str(path)
101
+
102
+
103
+ def _create_ort_session(model_path: str):
104
+ if onnxruntime is None:
105
+ raise ModuleNotFoundError(
106
+ "onnxruntime is required for --mask-sky; install with: pip install -e '.[vis]'",
107
+ name="onnxruntime",
108
+ )
109
+ options = onnxruntime.SessionOptions()
110
+ options.intra_op_num_threads = 4
111
+ options.inter_op_num_threads = 1
112
+ return onnxruntime.InferenceSession(
113
+ str(model_path), sess_options=options, providers=["CPUExecutionProvider"]
114
+ )
115
+
116
+
117
+ def run_skyseg(
118
+ onnx_session,
119
+ input_size: Tuple[int, int],
120
+ image: np.ndarray,
121
+ ) -> np.ndarray:
122
+ """Run ONNX sky segmentation on a BGR image and return an 8-bit score map."""
123
+ resize_image = cv2.resize(image, dsize=(input_size[0], input_size[1]))
124
+ x = cv2.cvtColor(resize_image, cv2.COLOR_BGR2RGB).astype(np.float32)
125
+ mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
126
+ std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
127
+ x = (x / 255.0 - mean) / std
128
+ x = x.transpose(2, 0, 1)
129
+ x = x.reshape(-1, 3, input_size[1], input_size[0]).astype("float32")
130
+
131
+ input_name = onnx_session.get_inputs()[0].name
132
+ output_name = onnx_session.get_outputs()[0].name
133
+ onnx_result = onnx_session.run([output_name], {input_name: x})
134
+
135
+ onnx_result = np.array(onnx_result).squeeze()
136
+ min_value = np.min(onnx_result)
137
+ max_value = np.max(onnx_result)
138
+ denom = max(max_value - min_value, 1e-8)
139
+ onnx_result = (onnx_result - min_value) / denom
140
+ onnx_result *= 255.0
141
+ return onnx_result.astype(np.uint8)
142
+
143
+
144
+ def _mask_to_float(mask: np.ndarray) -> np.ndarray:
145
+ if mask.dtype == np.uint8:
146
+ return mask.astype(np.float32) / 255.0
147
+ mask = mask.astype(np.float32)
148
+ if mask.size == 0:
149
+ return mask
150
+ return np.clip(mask, 0.0, 1.0)
151
+
152
+
153
+ def _mask_to_uint8(mask: np.ndarray) -> np.ndarray:
154
+ mask = np.asarray(mask)
155
+ if mask.dtype == np.uint8:
156
+ return mask
157
+ mask = mask.astype(np.float32)
158
+ if mask.size > 0 and mask.max() <= 1.0:
159
+ mask = mask * 255.0
160
+ return np.clip(mask, 0.0, 255.0).astype(np.uint8)
161
+
162
+
163
+ def _result_map_to_non_sky_conf(result_map: np.ndarray) -> np.ndarray:
164
+ # The raw skyseg map is higher on sky and lower on non-sky.
165
+ return 1.0 - _mask_to_float(result_map)
166
+
167
+
168
+ def _image_to_rgb_uint8(image: np.ndarray) -> np.ndarray:
169
+ if image.ndim == 3 and image.shape[0] == 3 and image.shape[-1] != 3:
170
+ image = image.transpose(1, 2, 0)
171
+
172
+ if image.ndim != 3 or image.shape[2] != 3:
173
+ raise ValueError(
174
+ f"Expected image with shape (H, W, 3) or (3, H, W), got {image.shape}"
175
+ )
176
+
177
+ if image.dtype != np.uint8:
178
+ image = image.astype(np.float32)
179
+ if image.size > 0 and image.max() <= 1.0:
180
+ image = image * 255.0
181
+ image = np.clip(image, 0.0, 255.0).astype(np.uint8)
182
+
183
+ return image
184
+
185
+
186
+ def segment_sky_from_array(
187
+ image: np.ndarray,
188
+ skyseg_session,
189
+ target_h: int,
190
+ target_w: int,
191
+ ) -> np.ndarray:
192
+ """Segment sky from an image array and return a [0, 1] non-sky confidence map."""
193
+ image_rgb = _image_to_rgb_uint8(image)
194
+ image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
195
+ result_map = run_skyseg(skyseg_session, _SKYSEG_INPUT_SIZE, image_bgr)
196
+ result_map = cv2.resize(
197
+ result_map, (target_w, target_h), interpolation=cv2.INTER_LINEAR
198
+ )
199
+ return _result_map_to_non_sky_conf(result_map)
200
+
201
+
202
+ def segment_sky(
203
+ image_path: str,
204
+ skyseg_session,
205
+ output_path: Optional[str] = None,
206
+ ) -> np.ndarray:
207
+ """Segment sky from an image file and return a [0, 1] non-sky confidence map."""
208
+ image = cv2.imread(image_path)
209
+ if image is None:
210
+ raise ValueError(f"Failed to read image: {image_path}")
211
+
212
+ result_map = run_skyseg(skyseg_session, _SKYSEG_INPUT_SIZE, image)
213
+ result_map = cv2.resize(
214
+ result_map, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_LINEAR
215
+ )
216
+ mask = _result_map_to_non_sky_conf(result_map)
217
+
218
+ if output_path is not None:
219
+ output_dir = os.path.dirname(output_path)
220
+ if output_dir:
221
+ os.makedirs(output_dir, exist_ok=True)
222
+ if not cv2.imwrite(output_path, _mask_to_uint8(mask)):
223
+ raise OSError(f"Failed to write sky mask: {output_path}")
224
+
225
+ return mask
226
+
227
+
228
+ def _list_image_files(image_folder: str) -> list[str]:
229
+ image_files = sorted(glob.glob(os.path.join(image_folder, "*")))
230
+ image_extensions = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".webp"}
231
+ return [
232
+ f for f in image_files if os.path.splitext(f.lower())[1] in image_extensions
233
+ ]
234
+
235
+
236
+ def _get_model_fingerprint(model_path: str) -> str:
237
+ """Compute a short fingerprint combining resolved model path and file bytes."""
238
+ resolved = str(Path(model_path).resolve(strict=False))
239
+ hasher = hashlib.sha256()
240
+ hasher.update(b"model_path:")
241
+ hasher.update(resolved.encode("utf-8"))
242
+ if os.path.isfile(model_path):
243
+ hasher.update(b"\0model_bytes:")
244
+ with open(model_path, "rb") as f:
245
+ while chunk := f.read(1 << 20):
246
+ hasher.update(chunk)
247
+ return hasher.hexdigest()[:16]
248
+
249
+
250
+ def _get_mask_filename(
251
+ image_paths: Optional[list[str]],
252
+ index: int,
253
+ image_rgb: Optional[np.ndarray] = None,
254
+ model_fingerprint: Optional[str] = None,
255
+ ) -> str:
256
+ """Build a collision-resistant cache filename incorporating model, path, and content."""
257
+ hasher = hashlib.sha256()
258
+ has_path = image_paths is not None and index < len(image_paths)
259
+ if has_path:
260
+ path = Path(image_paths[index])
261
+ resolved = str(path.resolve(strict=False))
262
+ hasher.update(b"path:")
263
+ hasher.update(resolved.encode("utf-8"))
264
+ stem = path.stem
265
+ else:
266
+ stem = f"frame_{index:06d}"
267
+
268
+ if image_rgb is not None:
269
+ contig = np.ascontiguousarray(image_rgb)
270
+ hasher.update(f"\0shape:{contig.shape}\0".encode("utf-8"))
271
+ hasher.update(contig.data)
272
+
273
+ if model_fingerprint:
274
+ hasher.update(b"\0model:")
275
+ hasher.update(model_fingerprint.encode("utf-8"))
276
+
277
+ if has_path or image_rgb is not None or model_fingerprint:
278
+ return f"{stem}_{hasher.hexdigest()[:16]}.png"
279
+ return f"{stem}.png"
280
+
281
+
282
+ def _get_visualization_filename(image_paths: Optional[list[str]], index: int) -> str:
283
+ if image_paths is not None and index < len(image_paths):
284
+ return f"{index:06d}_{Path(image_paths[index]).stem}.png"
285
+ return f"frame_{index:06d}.png"
286
+
287
+
288
+ def _save_sky_mask_visualization(
289
+ image: np.ndarray,
290
+ sky_mask: np.ndarray,
291
+ output_path: str,
292
+ ) -> None:
293
+ image_rgb = _image_to_rgb_uint8(image)
294
+ if sky_mask.shape[:2] != image_rgb.shape[:2]:
295
+ sky_mask = cv2.resize(
296
+ sky_mask.astype(np.float32),
297
+ (image_rgb.shape[1], image_rgb.shape[0]),
298
+ interpolation=cv2.INTER_NEAREST,
299
+ )
300
+
301
+ mask_uint8 = _mask_to_uint8(sky_mask)
302
+ mask_rgb = np.repeat(mask_uint8[..., None], 3, axis=2)
303
+ overlay = image_rgb.astype(np.float32).copy()
304
+ sky_pixels = (
305
+ ~sky_mask
306
+ if sky_mask.dtype == bool
307
+ else _mask_to_float(sky_mask) <= _SKYSEG_SOFT_THRESHOLD
308
+ )
309
+ overlay[sky_pixels] = (
310
+ overlay[sky_pixels] * 0.35 + np.array([255, 64, 64], dtype=np.float32) * 0.65
311
+ )
312
+ overlay = np.clip(overlay, 0.0, 255.0).astype(np.uint8)
313
+
314
+ panel = np.concatenate([image_rgb, mask_rgb, overlay], axis=1)
315
+ output_dir = os.path.dirname(output_path)
316
+ if output_dir:
317
+ os.makedirs(output_dir, exist_ok=True)
318
+ cv2.imwrite(output_path, cv2.cvtColor(panel, cv2.COLOR_RGB2BGR))
319
+
320
+
321
+ def load_or_create_sky_masks(
322
+ image_folder: Optional[str] = None,
323
+ image_paths: Optional[list[str]] = None,
324
+ images: Optional[np.ndarray] = None,
325
+ skyseg_model_path: Optional[str] = None,
326
+ sky_mask_dir: Optional[str] = None,
327
+ sky_mask_visualization_dir: Optional[str] = None,
328
+ target_shape: Optional[Tuple[int, int]] = None,
329
+ num_frames: Optional[int] = None,
330
+ ) -> Optional[np.ndarray]:
331
+ """Load cached sky masks or generate them with the ONNX model."""
332
+ if onnxruntime is None:
333
+ print("Warning: onnxruntime not available, skipping sky segmentation")
334
+ return None
335
+
336
+ if image_folder is None and image_paths is None and images is None:
337
+ print(
338
+ "Warning: Neither image_folder/image_paths nor images provided, skipping sky segmentation"
339
+ )
340
+ return None
341
+
342
+ resolved_model = _ensure_skyseg_model(skyseg_model_path)
343
+ model_fingerprint = _get_model_fingerprint(resolved_model)
344
+ skyseg_session = _create_ort_session(resolved_model)
345
+ sky_masks = []
346
+
347
+ if sky_mask_visualization_dir is not None:
348
+ os.makedirs(sky_mask_visualization_dir, exist_ok=True)
349
+
350
+ if images is not None:
351
+ if image_paths is None and image_folder is not None:
352
+ image_paths = _list_image_files(image_folder)
353
+
354
+ num_images = images.shape[0]
355
+ if num_frames is not None:
356
+ num_images = min(num_images, num_frames)
357
+ if image_paths is not None:
358
+ image_paths = image_paths[:num_images]
359
+
360
+ if sky_mask_dir is None and image_folder is not None:
361
+ sky_mask_dir = image_folder.rstrip("/") + "_sky_masks"
362
+ refresh_cache = _prepare_sky_mask_cache(sky_mask_dir)
363
+
364
+ for i in range(num_images):
365
+ image_rgb = _image_to_rgb_uint8(images[i])
366
+ image_h, image_w = image_rgb.shape[:2]
367
+ image_name = _get_mask_filename(
368
+ image_paths,
369
+ i,
370
+ image_rgb=image_rgb,
371
+ model_fingerprint=model_fingerprint,
372
+ )
373
+ mask_filepath = (
374
+ os.path.join(sky_mask_dir, image_name)
375
+ if sky_mask_dir is not None
376
+ else None
377
+ )
378
+
379
+ if (
380
+ mask_filepath is not None
381
+ and not refresh_cache
382
+ and os.path.exists(mask_filepath)
383
+ ):
384
+ sky_mask = cv2.imread(mask_filepath, cv2.IMREAD_GRAYSCALE)
385
+ if sky_mask is None or sky_mask.shape[:2] != (image_h, image_w):
386
+ sky_mask = segment_sky_from_array(
387
+ image_rgb, skyseg_session, image_h, image_w
388
+ )
389
+ if not cv2.imwrite(mask_filepath, _mask_to_uint8(sky_mask)):
390
+ raise OSError(f"Failed to write sky mask: {mask_filepath}")
391
+ else:
392
+ sky_mask = segment_sky_from_array(
393
+ image_rgb, skyseg_session, image_h, image_w
394
+ )
395
+ if mask_filepath is not None:
396
+ if not cv2.imwrite(mask_filepath, _mask_to_uint8(sky_mask)):
397
+ raise OSError(f"Failed to write sky mask: {mask_filepath}")
398
+
399
+ if sky_mask_visualization_dir is not None:
400
+ vis_name = _get_visualization_filename(image_paths, i)
401
+ _save_sky_mask_visualization(
402
+ image_rgb,
403
+ sky_mask,
404
+ os.path.join(sky_mask_visualization_dir, vis_name),
405
+ )
406
+
407
+ if target_shape is not None and sky_mask.shape[:2] != target_shape:
408
+ sky_mask = cv2.resize(
409
+ sky_mask,
410
+ (target_shape[1], target_shape[0]),
411
+ interpolation=cv2.INTER_LINEAR,
412
+ )
413
+
414
+ sky_masks.append(_mask_to_float(sky_mask))
415
+ else:
416
+ if image_paths is None and image_folder is not None:
417
+ image_paths = _list_image_files(image_folder)
418
+
419
+ if images is None and image_paths is not None:
420
+ if len(image_paths) == 0:
421
+ return None
422
+ if num_frames is not None:
423
+ image_paths = image_paths[:num_frames]
424
+ if sky_mask_dir is None:
425
+ if image_folder is None:
426
+ image_folder = os.path.dirname(image_paths[0])
427
+ sky_mask_dir = image_folder.rstrip("/") + "_sky_masks"
428
+ refresh_cache = _prepare_sky_mask_cache(sky_mask_dir)
429
+
430
+ for i, image_path in enumerate(image_paths):
431
+ image_name = _get_mask_filename(
432
+ image_paths, i, model_fingerprint=model_fingerprint
433
+ )
434
+ mask_filepath = os.path.join(sky_mask_dir, image_name)
435
+
436
+ if not refresh_cache and os.path.exists(mask_filepath):
437
+ sky_mask = cv2.imread(mask_filepath, cv2.IMREAD_GRAYSCALE)
438
+ if sky_mask is None:
439
+ sky_mask = segment_sky(image_path, skyseg_session, mask_filepath)
440
+ else:
441
+ sky_mask = segment_sky(image_path, skyseg_session, mask_filepath)
442
+
443
+ if sky_mask is None:
444
+ continue
445
+
446
+ if sky_mask_visualization_dir is not None:
447
+ image_bgr = cv2.imread(image_path)
448
+ if image_bgr is not None:
449
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
450
+ vis_name = _get_visualization_filename(image_paths, i)
451
+ _save_sky_mask_visualization(
452
+ image_rgb,
453
+ sky_mask,
454
+ os.path.join(sky_mask_visualization_dir, vis_name),
455
+ )
456
+
457
+ if target_shape is not None and sky_mask.shape[:2] != target_shape:
458
+ sky_mask = cv2.resize(
459
+ sky_mask,
460
+ (target_shape[1], target_shape[0]),
461
+ interpolation=cv2.INTER_LINEAR,
462
+ )
463
+
464
+ sky_masks.append(_mask_to_float(sky_mask))
465
+
466
+ if not sky_masks:
467
+ return None
468
+ try:
469
+ return np.stack(sky_masks, axis=0)
470
+ except ValueError:
471
+ return np.array(sky_masks, dtype=object)
472
+
473
+
474
+ def apply_sky_segmentation(
475
+ conf: np.ndarray,
476
+ image_folder: Optional[str] = None,
477
+ image_paths: Optional[list[str]] = None,
478
+ images: Optional[np.ndarray] = None,
479
+ skyseg_model_path: Optional[str] = None,
480
+ sky_mask_dir: Optional[str] = None,
481
+ sky_mask_visualization_dir: Optional[str] = None,
482
+ ) -> np.ndarray:
483
+ """Apply sky segmentation to a (S, H, W) confidence array."""
484
+ num_frames, height, width = conf.shape
485
+
486
+ sky_mask_array = load_or_create_sky_masks(
487
+ image_folder=image_folder,
488
+ image_paths=image_paths,
489
+ images=images,
490
+ skyseg_model_path=skyseg_model_path,
491
+ sky_mask_dir=sky_mask_dir,
492
+ sky_mask_visualization_dir=sky_mask_visualization_dir,
493
+ target_shape=(height, width),
494
+ num_frames=num_frames,
495
+ )
496
+ if sky_mask_array is None:
497
+ return conf
498
+
499
+ masked = np.array(conf, dtype=np.float32, copy=True)
500
+ valid_frames = min(num_frames, sky_mask_array.shape[0])
501
+ for i in range(valid_frames):
502
+ masked[i][sky_mask_array[i] <= _SKYSEG_SOFT_THRESHOLD] = 0.0
503
+ if valid_frames < num_frames:
504
+ masked[valid_frames:] = 0.0
505
+ return masked
lingbot_map2/vis/utils.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ # Copyright 2026 The Robbyant Team Authors. All rights reserved.
4
+ # Adapted from Robbyant/lingbot-map, lingbot_map/vis/utils.py
5
+ # (b9dd1b1de535e6d36e777fb42b8433c781bfd783). See LICENSES/THIRD_PARTY.md.
6
+
7
+ """Visualization utility functions for camera states, colorization and color bars."""
8
+
9
+ import dataclasses
10
+ from typing import Optional, Tuple
11
+
12
+ import cv2
13
+ import matplotlib
14
+ import numpy as np
15
+
16
+
17
+ def _get_colormap(cmap_name: str):
18
+ return matplotlib.colormaps[cmap_name]
19
+
20
+
21
+ @dataclasses.dataclass
22
+ class CameraState:
23
+ """Camera state for rendering."""
24
+
25
+ fov: float
26
+ aspect: float
27
+ c2w: np.ndarray
28
+
29
+ def get_K(self, img_wh: Tuple[int, int]) -> np.ndarray:
30
+ """Get camera intrinsic matrix from FOV and image size."""
31
+ width, height = img_wh
32
+ focal_length = height / 2.0 / np.tan(self.fov / 2.0)
33
+ return np.array(
34
+ [
35
+ [focal_length, 0.0, width / 2.0],
36
+ [0.0, focal_length, height / 2.0],
37
+ [0.0, 0.0, 1.0],
38
+ ]
39
+ )
40
+
41
+
42
+ def get_vertical_colorbar(
43
+ h: int,
44
+ vmin: float,
45
+ vmax: float,
46
+ cmap_name: str = "jet",
47
+ label: Optional[str] = None,
48
+ cbar_precision: int = 2,
49
+ ) -> np.ndarray:
50
+ """Create a vertical colorbar image as an (H, W, 3) float32 array in [0, 1]."""
51
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
52
+ from matplotlib.figure import Figure
53
+
54
+ fig = Figure(figsize=(2, 8), dpi=100)
55
+ fig.subplots_adjust(right=1.5)
56
+ canvas = FigureCanvasAgg(fig)
57
+
58
+ ax = fig.add_subplot(111)
59
+ cmap = _get_colormap(cmap_name)
60
+ norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
61
+
62
+ tick_loc = np.linspace(vmin, vmax, 6)
63
+ cb1 = matplotlib.colorbar.ColorbarBase(
64
+ ax, cmap=cmap, norm=norm, ticks=tick_loc, orientation="vertical"
65
+ )
66
+
67
+ tick_label = [str(np.round(x, cbar_precision)) for x in tick_loc]
68
+ if cbar_precision == 0:
69
+ tick_label = [x[:-2] for x in tick_label]
70
+
71
+ cb1.set_ticklabels(tick_label)
72
+ cb1.ax.tick_params(labelsize=18, rotation=0)
73
+ if label is not None:
74
+ cb1.set_label(label)
75
+
76
+ canvas.draw()
77
+ buf, (width, height) = canvas.print_to_buffer()
78
+
79
+ im = np.frombuffer(buf, np.uint8).reshape((height, width, 4))
80
+ im = im[:, :, :3].astype(np.float32) / 255.0
81
+
82
+ if h != im.shape[0]:
83
+ w = int(im.shape[1] / im.shape[0] * h)
84
+ im = cv2.resize(im, (w, h), interpolation=cv2.INTER_AREA)
85
+
86
+ return im
87
+
88
+
89
+ def colorize_np(
90
+ x: np.ndarray,
91
+ cmap_name: str = "jet",
92
+ mask: Optional[np.ndarray] = None,
93
+ range: Optional[Tuple[float, float]] = None,
94
+ append_cbar: bool = False,
95
+ cbar_in_image: bool = False,
96
+ cbar_precision: int = 2,
97
+ ) -> np.ndarray:
98
+ """Turn a grayscale image [H, W] into a color image [H, W, 3]."""
99
+ x = np.array(x, copy=True)
100
+ if range is not None:
101
+ vmin, vmax = range
102
+ elif mask is not None:
103
+ vmin = np.min(x[mask][np.nonzero(x[mask])])
104
+ vmax = np.max(x[mask])
105
+ x[np.logical_not(mask)] = vmin
106
+ else:
107
+ vmin, vmax = np.percentile(x, (1, 100))
108
+ vmax += 1e-6
109
+
110
+ x = np.clip(x, vmin, vmax)
111
+ x = (x - vmin) / max(vmax - vmin, 1e-12)
112
+
113
+ cmap = _get_colormap(cmap_name)
114
+ x_new = cmap(x)[:, :, :3]
115
+
116
+ if mask is not None:
117
+ mask_f = np.float32(mask[:, :, np.newaxis])
118
+ x_new = x_new * mask_f + np.ones_like(x_new) * (1.0 - mask_f)
119
+
120
+ if append_cbar:
121
+ cbar = get_vertical_colorbar(
122
+ h=x.shape[0],
123
+ vmin=vmin,
124
+ vmax=vmax,
125
+ cmap_name=cmap_name,
126
+ cbar_precision=cbar_precision,
127
+ )
128
+ if cbar_in_image:
129
+ x_new[:, -cbar.shape[1] :, :] = cbar
130
+ else:
131
+ x_new = np.concatenate(
132
+ (x_new, np.zeros_like(x_new[:, :5, :]), cbar), axis=1
133
+ )
134
+ return x_new
135
+
136
+
137
+ def colorize(
138
+ x,
139
+ cmap_name: str = "jet",
140
+ mask=None,
141
+ range: Optional[Tuple[float, float]] = None,
142
+ append_cbar: bool = False,
143
+ cbar_in_image: bool = False,
144
+ ):
145
+ """Turn a grayscale PyTorch tensor [H, W] or [B, H, W] into a color tensor."""
146
+ import torch
147
+
148
+ device = x.device
149
+ x_np = x.detach().cpu().numpy()
150
+ if mask is not None:
151
+ mask_np = mask.detach().cpu().numpy() > 0.99
152
+ kernel = np.ones((3, 3), np.uint8)
153
+ else:
154
+ mask_np = None
155
+ kernel = None
156
+
157
+ if x_np.ndim == 2:
158
+ x_np = x_np[None]
159
+ if mask_np is not None:
160
+ mask_np = mask_np[None]
161
+
162
+ out = []
163
+ for idx, frame in enumerate(x_np):
164
+ frame_mask = None
165
+ if mask_np is not None:
166
+ frame_mask = cv2.erode(
167
+ mask_np[idx].astype(np.uint8), kernel, iterations=1
168
+ ).astype(bool)
169
+ colored = colorize_np(
170
+ frame, cmap_name, frame_mask, range, append_cbar, cbar_in_image
171
+ )
172
+ out.append(torch.from_numpy(colored).to(device).float())
173
+ return torch.stack(out).squeeze(0)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torchvision
2
+ numpy
3
+ Pillow
4
+ opencv-python-headless
5
+ einops
6
+ trimesh
7
+ matplotlib
8
+ onnxruntime
9
+ imageio
10
+ imageio-ffmpeg