DarioVajda commited on
Commit
ad74a95
·
verified ·
1 Parent(s): 7ec0426

Add SpaceTimeVLM-2B

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ SpaceTimeVLM model weights and code
2
+
3
+ The model as a whole is licensed under the Creative Commons Attribution-NonCommercial 4.0 International license
4
+ (CC BY-NC 4.0): https://creativecommons.org/licenses/by-nc/4.0/legalcode
5
+
6
+ It contains components under their own licenses:
7
+ - Qwen3.5 (weights, tokenizer and processor files): Apache License 2.0, see LICENSE-QWEN.
8
+ - VGGT (vggt_*.py, copied from https://github.com/facebookresearch/vggt with only their imports changed): VGGT
9
+ License, see LICENSE-VGGT. The VGGT-1B weights are released by Meta for non-commercial use.
LICENSE-QWEN 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 2026 Alibaba Cloud
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.
LICENSE-VGGT ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ VGGT License
2
+
3
+ v1 Last Updated: July 29, 2025
4
+
5
+ “Acceptable Use Policy” means the Acceptable Use Policy, applicable to Research Materials, that is incorporated into this Agreement.
6
+
7
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the Research Materials set forth herein.
8
+
9
+
10
+ “Documentation” means the specifications, manuals and documentation accompanying
11
+ Research Materials distributed by Meta.
12
+
13
+
14
+ “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.
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
+ “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.
18
+
19
+ 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.
20
+
21
+
22
+ 1. License Rights and Redistribution.
23
+
24
+
25
+ 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.
26
+
27
+ b. Redistribution and Use.
28
+
29
+
30
+ i. 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.
31
+
32
+
33
+ ii. 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.
34
+
35
+
36
+ iii. Your use of the Research Materials must comply with applicable laws and regulations (including Trade Control Laws) and adhere to the Acceptable Use Policy, which is hereby incorporated by reference into this Agreement.
37
+ 2. User Support. Your 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.
38
+
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
+
47
+ 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.
48
+
49
+ 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.
50
+
51
+ 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.
52
+
53
+ 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.
54
+
55
+
56
+ 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.
57
+
58
+
59
+ Acceptable Use Policy
60
+
61
+ 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.
62
+
63
+ As part of this mission, Meta makes certain research materials available for use in accordance with this Agreement (including the Acceptable Use Policy). Meta is committed to promoting the safe and responsible use of such research materials.
64
+
65
+ Prohibited Uses
66
+
67
+ You agree you will not use, or allow others to use, Research Materials to:
68
+
69
+ Violate the law or others’ rights, including to:
70
+ Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
71
+ Violence or terrorism
72
+ Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
73
+ Human trafficking, exploitation, and sexual violence
74
+ 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.
75
+ Sexual solicitation
76
+ Any other criminal activity
77
+
78
+ Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
79
+
80
+ 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
81
+
82
+ Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
83
+
84
+ 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
85
+
86
+ 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 Research Materials
87
+
88
+ 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
89
+
90
+ 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:
91
+
92
+ 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
93
+
94
+ Guns and illegal weapons (including weapon development)
95
+
96
+ Illegal drugs and regulated/controlled substances
97
+ Operation of critical infrastructure, transportation technologies, or heavy machinery
98
+
99
+ Self-harm or harm to others, including suicide, cutting, and eating disorders
100
+ Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
101
+
102
+ 3. Intentionally deceive or mislead others, including use of Research Materials related to the following:
103
+
104
+ Generating, promoting, or furthering fraud or the creation or promotion of disinformation
105
+ Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
106
+
107
+ Generating, promoting, or further distributing spam
108
+
109
+ Impersonating another individual without consent, authorization, or legal right
110
+
111
+ Representing that outputs of research materials or outputs from technology using Research Materials are human-generated
112
+
113
+ Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
114
+
115
+ 4. Fail to appropriately disclose to end users any known dangers of your Research Materials.
README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ library_name: transformers
4
+ pipeline_tag: video-text-to-text
5
+ base_model:
6
+ - Qwen/Qwen3.5-2B
7
+ - facebook/VGGT-1B
8
+ tags:
9
+ - spatial-reasoning
10
+ - 3d
11
+ - video
12
+ - multimodal
13
+ - vggt
14
+ - qwen3.5
15
+ ---
16
+
17
+ # SpaceTimeVLM-2B
18
+
19
+ SpaceTimeVLM gives a video language model a 3D view of the scene. It is [Qwen/Qwen3.5-2B](https://huggingface.co/Qwen/Qwen3.5-2B)
20
+ with the frozen geometry encoder of [VGGT-1B](https://huggingface.co/facebook/VGGT-1B) read through a 3D-aware
21
+ cross-attention:
22
+
23
+ 1. Qwen3.5's vision encoder turns each frame into visual tokens (one per 28 x 28 px cell).
24
+ 2. VGGT-1B runs on the same frames. Its point head gives a 3D point per pixel, which is averaged per cell, so every
25
+ visual token gets a position in the scene.
26
+ 3. After decoder layers 0, 1 and 2, every visual token attends over the geometry tokens of all frames (VGGT layers
27
+ 11, 17 and 23, one token per cell), with a rotary embedding on (frame, x, y, z) and a learned 3D-distance bias.
28
+ The result is added to the visual token.
29
+
30
+ The language model was fine-tuned with LoRA (merged into the weights here); the mergers and the cross-attention were
31
+ trained from scratch; VGGT is unchanged. VSI-Bench: **69.22** (32 frames).
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ from transformers import AutoModel
37
+
38
+ model = AutoModel.from_pretrained("DarioVajda/SpaceTimeVLM-2B", trust_remote_code=True, device_map="cuda")
39
+ print(model.chat("room.mp4", "How many chairs are in this room?"))
40
+ ```
41
+
42
+ `chat` takes a video file, a directory of frames, or a list of images (paths or PIL images), and one question or a
43
+ list of questions about the same video (answered in one batch). It samples 32 uniformly spaced frames by default
44
+ (`num_frames=...`). Answers are greedy; `max_new_tokens` defaults to 256. For full control, `model.prepare(frames,
45
+ questions)` builds the inputs and `model.answer(batch, **generate_kwargs)` decodes them.
46
+
47
+ The benchmark scores below use the lmms-eval prompts, for example for VSI-Bench:
48
+
49
+ ```python
50
+ q = "These are frames of a video.\nHow many chairs are in this room?\nPlease answer the question using a single word or phrase."
51
+ q = "These are frames of a video.\nWhich is closer to the sofa, the lamp or the table?\nOptions:\nA. lamp\nB. table\nAnswer with the option's letter from the given choices directly."
52
+ ```
53
+
54
+ **Requirements:** a CUDA GPU, `transformers==5.20.1` (the version it was tested with), `torch`, `torchvision`, and
55
+ `decord` or `av` to read videos. Install `flash-linear-attention` and `causal-conv1d` for Qwen3.5's fast linear-attention
56
+ kernels; without them it falls back to a slow PyTorch path. Qwen3.5 runs in bfloat16; VGGT and the cross-attention
57
+ keep float32 weights and run under bfloat16 autocast, as in training.
58
+
59
+ ## Results
60
+
61
+ Results across six spatial benchmarks (%). Avg. is the mean of the six overall scores. Higher is better. **Bold** and
62
+ <u>underlined</u> mark the best and second best results in each column.
63
+
64
+ | Model | Avg. | VSI-Bench | MMSI-Bench | MindCube | ViewSpatial | SITE | CV-Bench |
65
+ |---|---:|---:|---:|---:|---:|---:|---:|
66
+ | Qwen2.5-VL-7B | 40.31 | 29.30 | 26.80 | 36.00 | 36.80 | 37.60 | 75.40 |
67
+ | Qwen3-VL-8B | 47.73 | 57.90 | 28.80 | 29.80 | 39.00 | 45.80 | 85.10 |
68
+ | Qwen3.5-2B | 42.83 | 45.72 | 26.30 | 34.86 | 36.28 | 31.45 | 82.34 |
69
+ | Qwen3.5-4B | 50.36 | 53.00 | 31.80 | 44.67 | 40.22 | 45.36 | 87.11 |
70
+ | Qwen3.5-9B | 52.87 | 60.80 | 31.90 | 44.10 | 44.07 | 48.27 | 88.06 |
71
+ | Qwen3.5-35B-A3B | 55.18 | 63.79 | <u>34.60</u> | 39.81 | 47.79 | 56.09 | **89.01** |
72
+ | | | | | | | | |
73
+ | Cambrian-S-7B | 47.28 | 67.50 | 25.80 | 39.60 | 40.90 | 33.00 | 76.90 |
74
+ | VLM-3R-7B | 45.40 | 60.90 | 27.90 | 40.00 | 40.50 | 31.30 | 71.80 |
75
+ | VG-LLM-8B | 51.05 | 62.20 | 30.00 | 36.10 | 45.80 | 50.50 | 81.70 |
76
+ | GeoThinker-7B | 60.43 | 68.50 | 31.70 | 83.60 | 41.90 | 54.80 | 82.10 |
77
+ | GeoThinker-8B | 62.23 | 72.60 | 30.90 | 83.00 | 45.90 | 55.90 | 85.10 |
78
+ | DK-VLM-7B | 60.84 | 69.42 | 29.95 | 83.81 | 44.98 | <u>57.47</u> | 79.38 |
79
+ | DK-VLM-8B | 64.09 | **74.33** | 30.79 | 83.83 | <u>51.25</u> | **59.81** | 84.52 |
80
+ | | | | | | | | |
81
+ | ➡️ **SpaceTimeVLM-2B (this model)** | 57.85 | 69.22 | 27.40 | 90.95 | 46.44 | 34.40 | 78.67 |
82
+ | SpaceTimeVLM-4B | 61.94 | 71.97 | 30.60 | 92.57 | 47.23 | 44.74 | 84.54 |
83
+ | SpaceTimeVLM-9B | <u>64.50</u> | <u>73.29</u> | 32.20 | <u>94.19</u> | 49.66 | 50.56 | 87.08 |
84
+ | SpaceTimeVLM-35B-A3B | **66.95** | 73.22 | **35.90** | **94.95** | **53.77** | 55.54 | <u>88.31</u> |
85
+
86
+ ## Training
87
+
88
+ - Base: Qwen/Qwen3.5-2B (revision `15852e8c1636`), VGGT-1B (revision `860abec7937d`, frozen).
89
+ - LoRA rank 64, alpha 128 on all linear layers of the language model; the vision encoder is frozen.
90
+ - 500k question-answer pairs over videos and image sets (spatial and general video understanding), with 8, 16 or 32
91
+ frames per sample (60 / 30 / 10 %); 17,201 steps (warmup-stable-decay schedule).
92
+
93
+ ## License and credits
94
+
95
+ This model combines:
96
+ - [Qwen3.5](https://huggingface.co/Qwen/Qwen3.5-2B) by the Qwen team (Apache 2.0, `LICENSE-QWEN`);
97
+ - [VGGT](https://github.com/facebookresearch/vggt) by Meta (the code is under the VGGT License, `LICENSE-VGGT`; the
98
+ VGGT-1B weights are released for non-commercial use). The VGGT modules in `vggt_*.py` are copied from the VGGT
99
+ repository with only their imports changed.
100
+
101
+ Because of the VGGT weights, the model as a whole is released under
102
+ [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/) (non-commercial use only).
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SpaceTimeVLMForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_spacetimevlm.SpaceTimeVLMConfig",
7
+ "AutoModel": "modeling_spacetimevlm.SpaceTimeVLMForConditionalGeneration",
8
+ "AutoModelForImageTextToText": "modeling_spacetimevlm.SpaceTimeVLMForConditionalGeneration"
9
+ },
10
+ "dtype": "bfloat16",
11
+ "geometry": {
12
+ "bias_nu": [
13
+ 0.1,
14
+ 6.0
15
+ ],
16
+ "fusion_after": [
17
+ 0,
18
+ 1,
19
+ 2
20
+ ],
21
+ "local_bias": true,
22
+ "max_pixels": 1605632,
23
+ "merger_hidden": 4096,
24
+ "min_pixels": 200704,
25
+ "num_frames": 32,
26
+ "pe_dmax": 10.0,
27
+ "rope3": true,
28
+ "theta": 100.0,
29
+ "train_frames": 8,
30
+ "vggt_dim": 2048,
31
+ "vggt_embed_dim": 1024,
32
+ "vggt_img_size": 518,
33
+ "vggt_layers": [
34
+ 11,
35
+ 17,
36
+ 23
37
+ ],
38
+ "vggt_patch_size": 14
39
+ },
40
+ "image_token_id": 248056,
41
+ "model_type": "spacetimevlm",
42
+ "text_config": {
43
+ "attention_bias": false,
44
+ "attention_dropout": 0.0,
45
+ "attn_output_gate": true,
46
+ "bos_token_id": null,
47
+ "dtype": "bfloat16",
48
+ "eos_token_id": 248044,
49
+ "full_attention_interval": 4,
50
+ "head_dim": 256,
51
+ "hidden_act": "silu",
52
+ "hidden_size": 2048,
53
+ "initializer_range": 0.02,
54
+ "intermediate_size": 6144,
55
+ "layer_types": [
56
+ "linear_attention",
57
+ "linear_attention",
58
+ "linear_attention",
59
+ "full_attention",
60
+ "linear_attention",
61
+ "linear_attention",
62
+ "linear_attention",
63
+ "full_attention",
64
+ "linear_attention",
65
+ "linear_attention",
66
+ "linear_attention",
67
+ "full_attention",
68
+ "linear_attention",
69
+ "linear_attention",
70
+ "linear_attention",
71
+ "full_attention",
72
+ "linear_attention",
73
+ "linear_attention",
74
+ "linear_attention",
75
+ "full_attention",
76
+ "linear_attention",
77
+ "linear_attention",
78
+ "linear_attention",
79
+ "full_attention"
80
+ ],
81
+ "linear_conv_kernel_dim": 4,
82
+ "linear_key_head_dim": 128,
83
+ "linear_num_key_heads": 16,
84
+ "linear_num_value_heads": 16,
85
+ "linear_value_head_dim": 128,
86
+ "mamba_ssm_dtype": "float32",
87
+ "max_position_embeddings": 262144,
88
+ "mlp_only_layers": [],
89
+ "model_type": "qwen3_5_text",
90
+ "mtp_num_hidden_layers": 1,
91
+ "mtp_use_dedicated_embeddings": false,
92
+ "num_attention_heads": 8,
93
+ "num_hidden_layers": 24,
94
+ "num_key_value_heads": 2,
95
+ "pad_token_id": null,
96
+ "rms_norm_eps": 1e-06,
97
+ "rope_parameters": {
98
+ "mrope_interleaved": true,
99
+ "mrope_section": [
100
+ 11,
101
+ 11,
102
+ 10
103
+ ],
104
+ "partial_rotary_factor": 0.25,
105
+ "rope_theta": 10000000,
106
+ "rope_type": "default"
107
+ },
108
+ "tie_word_embeddings": true,
109
+ "use_cache": true,
110
+ "vocab_size": 248320
111
+ },
112
+ "tie_word_embeddings": true,
113
+ "transformers_version": "5.20.1",
114
+ "video_token_id": 248057,
115
+ "vision_config": {
116
+ "deepstack_visual_indexes": [],
117
+ "depth": 24,
118
+ "hidden_act": "gelu_pytorch_tanh",
119
+ "hidden_size": 1024,
120
+ "in_channels": 3,
121
+ "initializer_range": 0.02,
122
+ "intermediate_size": 4096,
123
+ "model_type": "qwen3_5_vision",
124
+ "num_heads": 16,
125
+ "num_position_embeddings": 2304,
126
+ "out_hidden_size": 2048,
127
+ "patch_size": 16,
128
+ "rope_parameters": {
129
+ "rope_theta": 10000.0,
130
+ "rope_type": "axial"
131
+ },
132
+ "spatial_merge_size": 2,
133
+ "temporal_patch_size": 2
134
+ },
135
+ "vision_end_token_id": 248054,
136
+ "vision_start_token_id": 248053
137
+ }
configuration_spacetimevlm.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SpaceTimeVLM configuration: a Qwen3.5 configuration plus the geometry branch (VGGT-1B and the 3D cross-attention).
2
+
3
+ The dense models (2B, 4B, 9B) extend Qwen3_5Config, the mixture-of-experts model (35B-A3B) Qwen3_5MoeConfig. All
4
+ geometry settings are in one dict, `geometry`; the defaults below are the released models' settings.
5
+ """
6
+ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Config
7
+ from transformers.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeConfig
8
+
9
+ GEOMETRY_DEFAULTS = {
10
+ "vggt_layers": [11, 17, 23], # VGGT aggregator layers read by the cross-attention, paired in order with
11
+ "fusion_after": [0, 1, 2], # the decoder layers whose output receives them
12
+ "vggt_img_size": 518, # VGGT-1B's aggregator settings
13
+ "vggt_patch_size": 14,
14
+ "vggt_embed_dim": 1024,
15
+ "vggt_dim": 2048, # aggregator output width (frame + global attention, concatenated)
16
+ "merger_hidden": 4096, # geometry merger: 2x2 VGGT patches -> hidden -> LLM width
17
+ "rope3": True, # 3D RoPE on (frame, x, y, z) in the cross-attention
18
+ "local_bias": True, # learned 3D-distance attention bias
19
+ "bias_nu": [0.1, 6.0], # its initial slopes (log-spaced over the heads); the learned ones are in the weights
20
+ "pe_dmax": 10.0, # distance clip, in merged-cell units
21
+ "train_frames": 8, # frames per video in training: the frame axis of RoPE is rescaled to this range
22
+ "theta": 100.0, # RoPE base of the frame axis
23
+ "min_pixels": 256 * 28 * 28, # evaluation pixel limits per frame (Qwen image processor)
24
+ "max_pixels": 1605632,
25
+ "num_frames": 32, # frames sampled per video by default (the evaluation setting)
26
+ }
27
+
28
+
29
+ class SpaceTimeVLMConfig(Qwen3_5Config):
30
+ model_type = "spacetimevlm"
31
+ geometry: dict | None = None
32
+
33
+ def __post_init__(self, **kwargs):
34
+ self.geometry = {**GEOMETRY_DEFAULTS, **(self.geometry or {})}
35
+ super().__post_init__(**kwargs)
36
+
37
+
38
+ class SpaceTimeVLMMoeConfig(Qwen3_5MoeConfig):
39
+ model_type = "spacetimevlm_moe"
40
+ geometry: dict | None = None
41
+
42
+ def __post_init__(self, **kwargs):
43
+ self.geometry = {**GEOMETRY_DEFAULTS, **(self.geometry or {})}
44
+ super().__post_init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": false,
3
+ "eos_token_id": [
4
+ 248046,
5
+ 248044
6
+ ],
7
+ "pad_token_id": 248044,
8
+ "transformers_version": "5.20.1"
9
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e23b1f9a68daacc71157a80a2215ba3ff57bfe541493626b1041de0f9bae76d
3
+ size 4989000144
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d893b373639bf27d313aaac358cdcd174aadb36ffe0d423d7f637b9e37eca3a7
3
+ size 3909621376
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_spacetimevlm.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SpaceTimeVLM: Qwen3.5 with 3D geometry from VGGT-1B, read through cross-attention after the first decoder layers.
2
+
3
+ For one video (a list of frames):
4
+ 1. Qwen3.5's vision encoder turns each frame into visual tokens (one per 28 x 28 px cell);
5
+ 2. VGGT-1B's aggregator runs on the same frames (resized to the same cell grid); its point head gives a 3D point per
6
+ pixel, averaged per cell and rescaled so that one unit is about one cell on a typical surface;
7
+ 3. after decoder layers 0, 1 and 2, every visual token attends over geometry tokens of all frames (VGGT layers
8
+ 11, 17 and 23, one merged token per cell) with a 3D RoPE on (frame, x, y, z) and a learned 3D-distance bias, and
9
+ the result is added to the visual token.
10
+
11
+ Usage:
12
+ model = AutoModel.from_pretrained("DarioVajda/SpaceTimeVLM-2B", trust_remote_code=True, device_map="cuda")
13
+ model.chat("room.mp4", "How many chairs are in the room?")
14
+
15
+ VGGT and the cross-attention run in float32 weights under bfloat16 autocast, as in training; Qwen3.5 runs in bfloat16.
16
+ """
17
+ import importlib
18
+ import math
19
+ import os
20
+ from dataclasses import dataclass
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.nn as nn
25
+ import torch.nn.functional as F
26
+ from PIL import Image
27
+ from transformers import AutoProcessor
28
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
29
+ from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForConditionalGeneration
30
+ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeForConditionalGeneration
31
+
32
+ from .configuration_spacetimevlm import SpaceTimeVLMConfig, SpaceTimeVLMMoeConfig
33
+ from .vggt_heads_dpt_head import DPTHead
34
+ from .vggt_models_aggregator import _RESNET_MEAN, _RESNET_STD, Aggregator
35
+
36
+ SYSTEM_PROMPT = "You are a helpful assistant."
37
+ VGGT_PATCH = 14
38
+ IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png")
39
+
40
+
41
+ # ---- frames ----
42
+ def _indices(n, k):
43
+ """k uniformly spaced indices of n (all of them if n <= k)."""
44
+ return np.arange(n) if n <= k else np.linspace(0, n - 1, k).astype(int)
45
+
46
+
47
+ def load_frames(video, num_frames=32):
48
+ """k uniformly spaced frames as RGB PIL images, from a video file (decord, or PyAV if decord is not installed or
49
+ fails), a directory of frame images (sorted by name), a list of image paths or a list of PIL images."""
50
+ if isinstance(video, (list, tuple)):
51
+ items = [v if isinstance(v, Image.Image) else Image.open(v) for v in (video[i] for i in _indices(len(video), num_frames))]
52
+ return [im.convert("RGB") for im in items]
53
+ video = str(video)
54
+ if os.path.isdir(video):
55
+ paths = sorted(os.path.join(video, p) for p in os.listdir(video) if p.lower().endswith(IMAGE_SUFFIXES))
56
+ assert paths, f"no images in {video}"
57
+ return [Image.open(paths[i]).convert("RGB") for i in _indices(len(paths), num_frames)]
58
+ # decord and PyAV are optional (imported by name, so that transformers does not require them for remote code)
59
+ try:
60
+ decord = importlib.import_module("decord")
61
+ vr = decord.VideoReader(video, ctx=decord.cpu(0))
62
+ idx = _indices(len(vr), num_frames)
63
+ return [Image.fromarray(f) for f in vr.get_batch(idx.tolist()).asnumpy()]
64
+ except Exception: # decord missing, or its decoder fails on this file (some VP9 videos)
65
+ av = importlib.import_module("av")
66
+ with av.open(video) as c:
67
+ n = sum(1 for _ in c.decode(video=0))
68
+ assert n, f"no frames in {video}"
69
+ want, out = set(_indices(n, num_frames).tolist()), {}
70
+ with av.open(video) as c:
71
+ for i, f in enumerate(c.decode(video=0)):
72
+ if i in want:
73
+ out[i] = f.to_image().convert("RGB")
74
+ return [out[i] for i in sorted(want)]
75
+
76
+
77
+ # ---- 3D points of the merged cells (VGGT point head) ----
78
+ @dataclass
79
+ class ScenePoints:
80
+ xyz: torch.Tensor # [N, 3] float32, cell units, first camera's frame
81
+ low: torch.Tensor # [N] bool, low-confidence cells
82
+ dist: torch.Tensor # [N, N] float32, clipped 3D distance between cells, low-confidence keys at d_max
83
+ scale: float # VGGT units per cell
84
+
85
+
86
+ CONF_FLOOR = 1 + 1e-6 # cell confidence at or below this: every pixel of the cell at VGGT's confidence floor
87
+
88
+
89
+ def pairwise_dist(xyz, block=16384):
90
+ """Exact Euclidean distances [N, N], in blocks (one cdist over more than 65,535 points exceeds a CUDA limit)."""
91
+ return torch.cat([torch.cat([torch.cdist(xyz[i:i + block], xyz[j:j + block], compute_mode="donot_use_mm_for_euclid_dist")
92
+ for j in range(0, len(xyz), block)], 1) for i in range(0, len(xyz), block)])
93
+
94
+
95
+ def cell_points(points, conf, grid, d_max=10.0, patch=14, merge=2, low_q=0.1):
96
+ """points [T, H, W, 3], conf [T, H, W] of one video (VGGT point head); grid: image_grid_thw [T, 3] in patches.
97
+ Per merged cell (2 x 2 patches, one visual token): the mean point, rescaled by the median distance between
98
+ horizontally adjacent confident cells; cells at the confidence floor or below the 10th percentile are low."""
99
+ cell = patch * merge
100
+ xyz, cconf, pairs = [], [], []
101
+ for t, (_, h, w) in enumerate(grid.tolist()):
102
+ hc, wc = h // merge, w // merge
103
+ p = points[t, :hc * cell, :wc * cell].float().reshape(hc, cell, wc, cell, 3).mean((1, 3))
104
+ c = conf[t, :hc * cell, :wc * cell].float().reshape(hc, cell, wc, cell).mean((1, 3))
105
+ xyz.append(p.reshape(-1, 3))
106
+ cconf.append(c.reshape(-1))
107
+ pairs.append((p, c))
108
+ xyz, cconf = torch.cat(xyz), torch.cat(cconf)
109
+ floor = cconf <= CONF_FLOOR
110
+ rest = cconf[~floor]
111
+ thr = torch.quantile(rest, low_q) if len(rest) else cconf.new_tensor(float("inf"))
112
+ low = floor | (cconf < thr)
113
+ gaps = []
114
+ for p, c in pairs:
115
+ good = (c > CONF_FLOOR) & (c >= thr)
116
+ ok = good[:, :-1] & good[:, 1:]
117
+ gaps.append((p[:, 1:] - p[:, :-1]).norm(dim=-1)[ok])
118
+ gaps = torch.cat(gaps)
119
+ scale = (gaps.median() if len(gaps) else (xyz[1:] - xyz[:-1]).norm(dim=-1).median()).clamp_min(1e-6)
120
+ xyz = xyz / scale
121
+ dist = pairwise_dist(xyz).clamp_max(d_max)
122
+ dist[:, low] = d_max
123
+ dist.fill_diagonal_(0.0)
124
+ return ScenePoints(xyz=xyz, low=low, dist=dist, scale=scale.item())
125
+
126
+
127
+ # ---- geometry modules ----
128
+ class RMSNorm(nn.Module):
129
+ def __init__(self, dim, eps=1e-6):
130
+ super().__init__()
131
+ self.weight = nn.Parameter(torch.ones(dim))
132
+ self.eps = eps
133
+
134
+ def forward(self, x):
135
+ x32 = x.float()
136
+ return (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight
137
+
138
+
139
+ class GeometryMerger(nn.Module):
140
+ """VGGT patch tokens of one frame [h, w, in_dim] -> one geometry token per 2x2 window [(h/2)*(w/2), out_dim], in the
141
+ row-major order of Qwen's merged visual tokens: RMSNorm, 2x2 concat, MLP."""
142
+
143
+ def __init__(self, in_dim=2048, hidden=4096, out_dim=2048, merge=2):
144
+ super().__init__()
145
+ self.merge = merge
146
+ self.ln = RMSNorm(in_dim)
147
+ self.mlp = nn.Sequential(nn.Linear(in_dim * merge * merge, hidden), nn.GELU(), nn.Linear(hidden, out_dim))
148
+
149
+ def forward(self, grid):
150
+ h, w, c = grid.shape
151
+ m = self.merge
152
+ return self.mlp(self.ln(grid).view(h // m, m, w // m, m, c).permute(0, 2, 1, 3, 4).reshape(-1, m * m * c))
153
+
154
+
155
+ def per_head(init, heads):
156
+ if isinstance(init, (int, float)):
157
+ return torch.full((heads,), float(init))
158
+ lo, hi = init
159
+ return torch.logspace(math.log10(lo), math.log10(hi), heads)
160
+
161
+
162
+ class AlignedXAttn(nn.Module):
163
+ """Visual tokens (queries) attend over the geometry tokens of the whole video (keys / values):
164
+
165
+ out = W_o softmax(Q K^T / sqrt(d) - nu_h * min(|xyz_i - xyz_j|, d_max)) V
166
+
167
+ with Q, K rotated by a 3D RoPE: 8 rotary pairs each for (t~, x, y, z); t~ = t * (train_frames - 1) / (T - 1) puts
168
+ any number of frames on the training range, x, y, z in cell units with wavelengths 1.5 to 100 cells. The update is
169
+ added to the visual tokens only."""
170
+
171
+ AXES_3D = (8, 8, 8, 8)
172
+ W3D = (1.5, 100.0)
173
+ QUERY_CHUNK = 4096 # query rows per attention call on long videos
174
+
175
+ def __init__(self, dim, heads, rope=True, local_bias=True, train_frames=8, theta=100.0, nu=1.5):
176
+ super().__init__()
177
+ self.heads, self.head_dim = heads, dim // heads
178
+ self.rope, self.local_bias, self.train_frames, self.theta = rope, local_bias, train_frames, theta
179
+ self.norm_q, self.norm_kv = nn.LayerNorm(dim), nn.LayerNorm(dim)
180
+ self.q, self.k, self.v, self.o = (nn.Linear(dim, dim, bias=False) for _ in range(4))
181
+ if local_bias:
182
+ self.nu = nn.Parameter(per_head(nu, heads))
183
+ if rope:
184
+ assert 2 * sum(self.AXES_3D) <= self.head_dim, (self.AXES_3D, self.head_dim)
185
+ axis, freq = self.rope_tables()
186
+ self.register_buffer("rope_axis", axis, persistent=False)
187
+ self.register_buffer("rope_freq", freq, persistent=False)
188
+
189
+ def rope_tables(self, device=None):
190
+ """(axis index, frequency) of each rotary pair. Constants: not in the weights, rebuilt on load."""
191
+ n_t, n_s = self.AXES_3D[0], self.AXES_3D[1]
192
+ axis = torch.cat([torch.full((n,), a) for a, n in enumerate(self.AXES_3D)])
193
+ w = torch.logspace(math.log10(self.W3D[0]), math.log10(self.W3D[1]), n_s)
194
+ freq = torch.cat([self.theta ** (-torch.arange(n_t, dtype=torch.float) / n_t)] + [2 * math.pi / w] * 3)
195
+ return axis.to(device), freq.to(device)
196
+
197
+ @staticmethod
198
+ def positions(grid, merge=2):
199
+ """(t, r, c) of the merged visual tokens of one video, in token order: [N, 3]."""
200
+ out = []
201
+ for t, (_, h, w) in enumerate(grid.tolist()):
202
+ r, c = torch.meshgrid(torch.arange(h // merge), torch.arange(w // merge), indexing="ij")
203
+ out.append(torch.stack([torch.full_like(r, t), r, c], -1).reshape(-1, 3))
204
+ return torch.cat(out).to(grid.device)
205
+
206
+ def rotary(self, pos, pts):
207
+ T = int(pos[:, 0].max()) + 1
208
+ p = pos.float()
209
+ p[:, 0] = p[:, 0] * (self.train_frames - 1) / max(T - 1, 1)
210
+ p = torch.cat([p[:, :1], pts.xyz.float()], 1)
211
+ ang = p[:, self.rope_axis] * self.rope_freq
212
+ return ang.cos(), ang.sin()
213
+
214
+ @staticmethod
215
+ def apply_rotary(x, cos, sin):
216
+ n = cos.shape[-1]
217
+ x1, x2, rest = x[..., :n], x[..., n:2 * n], x[..., 2 * n:]
218
+ cos, sin = cos.to(x.dtype), sin.to(x.dtype)
219
+ return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin, rest], -1)
220
+
221
+ def bias(self, dtype, pts, rows=slice(None)):
222
+ return -(self.nu[:, None, None] * pts.dist[rows])[None].to(dtype)
223
+
224
+ def keys(self, g, pos, pts):
225
+ """Rotated keys and values of the geometry tokens g [N, D]: [1, H, N, d] each."""
226
+ split = lambda t: t.view(1, len(g), self.heads, self.head_dim).transpose(1, 2)
227
+ gn = self.norm_kv(g)[None]
228
+ k, v = split(self.k(gn)), split(self.v(gn))
229
+ if self.rope:
230
+ k = self.apply_rotary(k, *self.rotary(pos, pts))
231
+ return k, v
232
+
233
+ def forward(self, y, pos, pts, kv): # y [B, N, D] visual tokens of one video; kv = keys(...)
234
+ B, N, D = y.shape
235
+ k, v = kv
236
+ q = self.q(self.norm_q(y)).view(B, N, self.heads, self.head_dim).transpose(1, 2)
237
+ if self.rope:
238
+ q = self.apply_rotary(q, *self.rotary(pos, pts))
239
+ k, v = k.expand(B, -1, -1, -1), v.expand(B, -1, -1, -1)
240
+ if self.local_bias and N > self.QUERY_CHUNK: # the [B, H, N, N] bias is built a block of query rows at a time
241
+ out = torch.cat([F.scaled_dot_product_attention(q[:, :, i:i + self.QUERY_CHUNK], k, v,
242
+ attn_mask=self.bias(q.dtype, pts, slice(i, i + self.QUERY_CHUNK)))
243
+ for i in range(0, N, self.QUERY_CHUNK)], 2)
244
+ else:
245
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=self.bias(q.dtype, pts) if self.local_bias else None)
246
+ return self.o(out.transpose(1, 2).reshape(B, N, D))
247
+
248
+
249
+ class Geometry(nn.Module):
250
+ """VGGT-1B's aggregator and point head (frozen, from facebook/VGGT-1B) and, per injection point, a merger and the
251
+ cross-attention."""
252
+
253
+ def __init__(self, config):
254
+ super().__init__()
255
+ g, tc = config.geometry, config.text_config
256
+ self.vggt = Aggregator(img_size=g["vggt_img_size"], patch_size=g["vggt_patch_size"], embed_dim=g["vggt_embed_dim"])
257
+ self.point_head = DPTHead(dim_in=2 * g["vggt_embed_dim"], output_dim=4, activation="inv_log", conf_activation="expp1")
258
+ self.vggt.cached_layer_indices = set(g["vggt_layers"]) | set(self.point_head.intermediate_layer_idx)
259
+ D = tc.hidden_size
260
+ keys = [str(k) for k in g["fusion_after"]]
261
+ self.mergers = nn.ModuleDict({k: GeometryMerger(g["vggt_dim"], g["merger_hidden"], D) for k in keys})
262
+ self.aligned = nn.ModuleDict({k: AlignedXAttn(D, D // 128, g["rope3"], g["local_bias"], g["train_frames"],
263
+ g["theta"], g["bias_nu"]) for k in keys})
264
+
265
+
266
+ class SpaceTimeVLMMixin:
267
+ """The geometry branch on top of a Qwen3.5 conditional-generation model (dense or MoE)."""
268
+
269
+ _keep_in_fp32_modules_strict = ["geometry"]
270
+
271
+ def _setup_geometry(self, config):
272
+ g = config.geometry
273
+ self.geometry = Geometry(config)
274
+ self.pairs = dict(zip(g["fusion_after"], g["vggt_layers"]))
275
+ self.pe_dmax = g["pe_dmax"]
276
+ self.merge = config.vision_config.spatial_merge_size
277
+ self._geo = self._pos = self._pts = self._visual_mask = None
278
+ self._processor = None
279
+ layers = self.model.language_model.layers
280
+ for k in g["fusion_after"]:
281
+ layers[k].register_forward_hook(self._make_hook(str(k)))
282
+ self.model.register_forward_pre_hook(self._capture_ids, with_kwargs=True)
283
+
284
+ def _init_weights(self, module):
285
+ # Non-persistent constants are not in the checkpoint: rebuild them (also for a freshly built model).
286
+ if isinstance(module, Aggregator):
287
+ dev = module.camera_token.device
288
+ module._resnet_mean = torch.tensor(_RESNET_MEAN, device=dev).view(1, 1, 3, 1, 1)
289
+ module._resnet_std = torch.tensor(_RESNET_STD, device=dev).view(1, 1, 3, 1, 1)
290
+ elif isinstance(module, AlignedXAttn):
291
+ if module.rope:
292
+ module.rope_axis, module.rope_freq = module.rope_tables(module.q.weight.device)
293
+ else:
294
+ super()._init_weights(module)
295
+
296
+ # ---- inputs ----
297
+ @property
298
+ def processor(self):
299
+ if self._processor is None:
300
+ g = self.config.geometry
301
+ self._processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True,
302
+ min_pixels=g["min_pixels"], max_pixels=g["max_pixels"])
303
+ self._processor.tokenizer.padding_side = "left"
304
+ return self._processor
305
+
306
+ def visual_inputs(self, frames):
307
+ """Qwen pixel values and grids of the frames, and VGGT's input [T, 3, H, W] in [0, 1]: each frame resized to
308
+ Qwen's patch grid x 14 px, padded with 1.0 at the bottom / right if the frames differ in size."""
309
+ from torchvision.transforms import functional as TF
310
+ out = self.processor.image_processor(images=frames, return_tensors="pt")
311
+ grid = out["image_grid_thw"]
312
+ vggt = [TF.to_tensor(f.convert("RGB").resize((int(w) * VGGT_PATCH, int(h) * VGGT_PATCH), Image.Resampling.BICUBIC))
313
+ for f, (_, h, w) in zip(frames, grid.tolist())]
314
+ H, W = max(t.shape[1] for t in vggt), max(t.shape[2] for t in vggt)
315
+ vggt = torch.stack([F.pad(t, (0, W - t.shape[2], 0, H - t.shape[1]), value=1.0) for t in vggt])
316
+ return {"pixel_values": out["pixel_values"], "image_grid_thw": grid, "vggt_images": vggt}
317
+
318
+ def prompt_text(self, question, n_images):
319
+ """System prompt, the frames as images, then the question; thinking off. A question with one "<image>"
320
+ placeholder per frame gets each frame at its placeholder instead."""
321
+ parts = question.split("<image>")
322
+ if len(parts) == 1:
323
+ content = [{"type": "image"} for _ in range(n_images)] + [{"type": "text", "text": question}]
324
+ else:
325
+ assert len(parts) == n_images + 1, (len(parts) - 1, n_images)
326
+ content = [{"type": "text", "text": parts[0]}] if parts[0] else []
327
+ for p in parts[1:]:
328
+ content += [{"type": "image"}] + ([{"type": "text", "text": p}] if p else [])
329
+ msgs = [{"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}, {"role": "user", "content": content}]
330
+ return self.processor.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
331
+
332
+ def text_inputs(self, questions, grid):
333
+ """Left-padded token ids of B questions about the same frames."""
334
+ tok = self.processor.tokenizer
335
+ image_token = self.processor.image_token
336
+ n_tok = (grid.prod(-1) // self.merge ** 2).tolist()
337
+ rows = []
338
+ for q in questions:
339
+ parts = self.prompt_text(q, len(grid)).split(image_token)
340
+ assert len(parts) == len(grid) + 1, (len(parts) - 1, len(grid))
341
+ text = parts[0] + "".join(image_token * n + p for n, p in zip(n_tok, parts[1:]))
342
+ rows.append(tok(text, add_special_tokens=False).input_ids)
343
+ L = max(map(len, rows))
344
+ ids = torch.full((len(rows), L), tok.pad_token_id, dtype=torch.long)
345
+ mask = torch.zeros((len(rows), L), dtype=torch.long)
346
+ for i, r in enumerate(rows):
347
+ ids[i, L - len(r):] = torch.tensor(r)
348
+ mask[i, L - len(r):] = 1
349
+ return {"input_ids": ids, "attention_mask": mask, "mm_token_type_ids": (ids == self.config.image_token_id).int()}
350
+
351
+ def prepare(self, frames, questions):
352
+ """Model inputs for B questions (a list of strings) about one list of frames."""
353
+ vis = self.visual_inputs(frames)
354
+ return {**vis, **self.text_inputs(questions, vis["image_grid_thw"])}
355
+
356
+ # ---- geometry ----
357
+ @torch.no_grad()
358
+ def set_geometry(self, images, grid):
359
+ """Runs VGGT on the frames [T, 3, H, W] and the mergers: the geometry tokens, positions and 3D points of one
360
+ video, read by the hooks in the next forward passes."""
361
+ geo_mod = self.geometry
362
+ with torch.autocast("cuda", dtype=torch.bfloat16):
363
+ out, ps = geo_mod.vggt(images[None])
364
+ with torch.autocast("cuda", enabled=False): # VGGT runs its heads in float32
365
+ toks = [o.float() if o is not None else None for o in out]
366
+ pts, conf = geo_mod.point_head(toks, images=images[None].float(), patch_start_idx=ps)
367
+ self._pts = cell_points(pts[0], conf[0], grid, self.pe_dmax, merge=self.merge)
368
+ Hp, Wp = images.shape[-2] // VGGT_PATCH, images.shape[-1] // VGGT_PATCH
369
+ self._geo = {}
370
+ with torch.autocast("cuda", dtype=torch.bfloat16):
371
+ for k, L in self.pairs.items():
372
+ tok = out[L][0] # [T, 5 + P, 2048]
373
+ patches = tok[:, ps:].reshape(len(tok), Hp, Wp, -1)
374
+ self._geo[str(k)] = torch.cat([geo_mod.mergers[str(k)](patches[t, :h, :w])
375
+ for t, (_, h, w) in enumerate(grid.tolist())])
376
+ self._pos = AlignedXAttn.positions(grid, self.merge)
377
+
378
+ def clear_geometry(self):
379
+ self._geo = self._pos = self._pts = None
380
+
381
+ def _capture_ids(self, module, args, kwargs):
382
+ ids = kwargs.get("input_ids", args[0] if args else None)
383
+ self._visual_mask = None if ids is None else ids == self.config.image_token_id
384
+
385
+ def _make_hook(self, key):
386
+ def hook(module, args, out):
387
+ """Decoder layer k: add the cross-attention update to the visual tokens of its output."""
388
+ h = out[0] if isinstance(out, tuple) else out
389
+ m = self._visual_mask
390
+ if self._geo is None or m is None or m.shape != h.shape[:2] or not m.any():
391
+ return None # no geometry set, or a decoding step (no visual tokens)
392
+ geo = self._geo[key]
393
+ n = int(m[0].sum())
394
+ assert n == len(geo) and bool((m.sum(1) == n).all()), "visual tokens != geometry tokens"
395
+ att = self.geometry.aligned[key]
396
+ with torch.autocast("cuda", dtype=torch.bfloat16):
397
+ kv = att.keys(geo, self._pos, self._pts)
398
+ delta = torch.zeros_like(h)
399
+ delta[m] = att(h[m].view(h.shape[0], n, -1), self._pos, self._pts, kv).reshape(-1, h.shape[-1]).to(h.dtype)
400
+ new = h + delta
401
+ return (new, *out[1:]) if isinstance(out, tuple) else new
402
+ return hook
403
+
404
+ # ---- generation ----
405
+ def _llm_inputs(self, batch):
406
+ B = batch["input_ids"].shape[0]
407
+ feats = self.model.get_image_features(batch["pixel_values"], batch["image_grid_thw"], return_dict=True)
408
+ feats = tuple(feats.pooler_output) * B # the vision encoder runs once; its tokens are shared by the B questions
409
+ return dict(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"],
410
+ mm_token_type_ids=batch["mm_token_type_ids"], image_grid_thw=batch["image_grid_thw"].repeat(B, 1),
411
+ mm_encoder_outputs={"image": BaseModelOutputWithPooling(pooler_output=feats)})
412
+
413
+ @torch.no_grad()
414
+ def answer(self, batch, max_new_tokens=256, return_outputs=False, **generate_kwargs):
415
+ """Greedy answers to the questions of a prepare() batch. return_outputs: the generate() output instead."""
416
+ batch = {k: v.to(self.device) for k, v in batch.items()}
417
+ tok = self.processor.tokenizer
418
+ stop = [tok.convert_tokens_to_ids(t) for t in ("<|im_end|>", "<|endoftext|>")]
419
+ self.set_geometry(batch["vggt_images"], batch["image_grid_thw"])
420
+ try:
421
+ with torch.autocast("cuda", dtype=torch.bfloat16):
422
+ out = self.generate(**self._llm_inputs(batch), max_new_tokens=max_new_tokens, do_sample=False,
423
+ temperature=None, top_p=None, top_k=None, eos_token_id=stop,
424
+ pad_token_id=tok.pad_token_id, **generate_kwargs)
425
+ finally:
426
+ self.clear_geometry()
427
+ if return_outputs:
428
+ return out
429
+ seqs = out.sequences if hasattr(out, "sequences") else out
430
+ return [s.strip() for s in tok.batch_decode(seqs[:, batch["input_ids"].shape[1]:], skip_special_tokens=True)]
431
+
432
+ def chat(self, video, question, num_frames=None, max_new_tokens=256, **generate_kwargs):
433
+ """Answer one question (a string) or several (a list, batched) about a video: a video file, a directory of
434
+ frames, or a list of images / image paths. num_frames uniformly spaced frames are used (32 by default)."""
435
+ frames = load_frames(video, num_frames or self.config.geometry["num_frames"])
436
+ questions = [question] if isinstance(question, str) else list(question)
437
+ answers = self.answer(self.prepare(frames, questions), max_new_tokens=max_new_tokens, **generate_kwargs)
438
+ return answers[0] if isinstance(question, str) else answers
439
+
440
+
441
+ class SpaceTimeVLMForConditionalGeneration(SpaceTimeVLMMixin, Qwen3_5ForConditionalGeneration):
442
+ config_class = SpaceTimeVLMConfig
443
+
444
+ def __init__(self, config):
445
+ super().__init__(config)
446
+ self._setup_geometry(config)
447
+ self.post_init()
448
+
449
+
450
+ class SpaceTimeVLMMoeForConditionalGeneration(SpaceTimeVLMMixin, Qwen3_5MoeForConditionalGeneration):
451
+ config_class = SpaceTimeVLMMoeConfig
452
+
453
+ def __init__(self, config):
454
+ super().__init__(config)
455
+ self._setup_geometry(config)
456
+ self.post_init()
processor_config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "do_convert_rgb": true,
4
+ "do_normalize": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.5,
9
+ 0.5,
10
+ 0.5
11
+ ],
12
+ "image_processor_type": "Qwen2VLImageProcessor",
13
+ "image_std": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "merge_size": 2,
19
+ "patch_size": 16,
20
+ "resample": 3,
21
+ "rescale_factor": 0.00392156862745098,
22
+ "size": {
23
+ "longest_edge": 1605632,
24
+ "shortest_edge": 200704
25
+ },
26
+ "temporal_patch_size": 2
27
+ },
28
+ "processor_class": "Qwen3VLProcessor",
29
+ "video_processor": {
30
+ "do_convert_rgb": true,
31
+ "do_normalize": true,
32
+ "do_rescale": true,
33
+ "do_resize": true,
34
+ "do_sample_frames": true,
35
+ "fps": 2,
36
+ "image_mean": [
37
+ 0.5,
38
+ 0.5,
39
+ 0.5
40
+ ],
41
+ "image_std": [
42
+ 0.5,
43
+ 0.5,
44
+ 0.5
45
+ ],
46
+ "max_frames": 768,
47
+ "max_video_tokens": 768,
48
+ "merge_size": 2,
49
+ "min_frames": 4,
50
+ "patch_size": 16,
51
+ "resample": 3,
52
+ "rescale_factor": 0.00392156862745098,
53
+ "return_metadata": false,
54
+ "size": {
55
+ "longest_edge": 25165824,
56
+ "shortest_edge": 4096
57
+ },
58
+ "temporal_patch_size": 2,
59
+ "video_processor_type": "Qwen3VLVideoProcessor"
60
+ }
61
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f
3
+ size 19989339
tokenizer_config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|im_end|>",
10
+ "errors": "replace",
11
+ "extra_special_tokens": [
12
+ "<|im_start|>",
13
+ "<|im_end|>",
14
+ "<|object_ref_start|>",
15
+ "<|object_ref_end|>",
16
+ "<|box_start|>",
17
+ "<|box_end|>",
18
+ "<|quad_start|>",
19
+ "<|quad_end|>",
20
+ "<|vision_start|>",
21
+ "<|vision_end|>",
22
+ "<|vision_pad|>",
23
+ "<|image_pad|>",
24
+ "<|video_pad|>"
25
+ ],
26
+ "image_token": "<|image_pad|>",
27
+ "is_local": false,
28
+ "local_files_only": true,
29
+ "max_pixels": 1605632,
30
+ "merges_file": null,
31
+ "min_pixels": 200704,
32
+ "model_max_length": 262144,
33
+ "model_specific_special_tokens": {
34
+ "audio_bos_token": "<|audio_start|>",
35
+ "audio_eos_token": "<|audio_end|>",
36
+ "audio_token": "<|audio_pad|>",
37
+ "image_token": "<|image_pad|>",
38
+ "video_token": "<|video_pad|>",
39
+ "vision_bos_token": "<|vision_start|>",
40
+ "vision_eos_token": "<|vision_end|>"
41
+ },
42
+ "pad_token": "<|endoftext|>",
43
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
44
+ "processor_class": "Qwen3VLProcessor",
45
+ "split_special_tokens": false,
46
+ "tokenizer_class": "Qwen3_5Tokenizer",
47
+ "unk_token": null,
48
+ "video_token": "<|video_pad|>",
49
+ "vision_bos_token": "<|vision_start|>",
50
+ "vision_eos_token": "<|vision_end|>"
51
+ }
vggt_heads_dpt_head.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/heads/dpt_head.py; only the imports are changed (flat module names).
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 file in the root directory of this source tree.
7
+
8
+
9
+ # Inspired by https://github.com/DepthAnything/Depth-Anything-V2
10
+
11
+
12
+ import os
13
+ from typing import List, Dict, Tuple, Union
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from .vggt_heads_head_act import activate_head
19
+ from .vggt_heads_utils import create_uv_grid, position_grid_to_embed
20
+
21
+
22
+ class DPTHead(nn.Module):
23
+ """
24
+ DPT Head for dense prediction tasks.
25
+
26
+ This implementation follows the architecture described in "Vision Transformers for Dense Prediction"
27
+ (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer
28
+ backbone and produces dense predictions by fusing multi-scale features.
29
+
30
+ Args:
31
+ dim_in (int): Input dimension (channels).
32
+ patch_size (int, optional): Patch size. Default is 14.
33
+ output_dim (int, optional): Number of output channels. Default is 4.
34
+ activation (str, optional): Activation type. Default is "inv_log".
35
+ conf_activation (str, optional): Confidence activation type. Default is "expp1".
36
+ features (int, optional): Feature channels for intermediate representations. Default is 256.
37
+ out_channels (List[int], optional): Output channels for each intermediate layer.
38
+ intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT.
39
+ pos_embed (bool, optional): Whether to use positional embedding. Default is True.
40
+ feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False.
41
+ down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ dim_in: int,
47
+ patch_size: int = 14,
48
+ output_dim: int = 4,
49
+ activation: str = "inv_log",
50
+ conf_activation: str = "expp1",
51
+ features: int = 256,
52
+ out_channels: List[int] = [256, 512, 1024, 1024],
53
+ intermediate_layer_idx: List[int] = [4, 11, 17, 23],
54
+ pos_embed: bool = True,
55
+ feature_only: bool = False,
56
+ down_ratio: int = 1,
57
+ ) -> None:
58
+ super(DPTHead, self).__init__()
59
+ self.patch_size = patch_size
60
+ self.activation = activation
61
+ self.conf_activation = conf_activation
62
+ self.pos_embed = pos_embed
63
+ self.feature_only = feature_only
64
+ self.down_ratio = down_ratio
65
+ self.intermediate_layer_idx = intermediate_layer_idx
66
+
67
+ self.norm = nn.LayerNorm(dim_in)
68
+
69
+ # Projection layers for each output channel from tokens.
70
+ self.projects = nn.ModuleList(
71
+ [nn.Conv2d(in_channels=dim_in, out_channels=oc, kernel_size=1, stride=1, padding=0) for oc in out_channels]
72
+ )
73
+
74
+ # Resize layers for upsampling feature maps.
75
+ self.resize_layers = nn.ModuleList(
76
+ [
77
+ nn.ConvTranspose2d(
78
+ in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0
79
+ ),
80
+ nn.ConvTranspose2d(
81
+ in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0
82
+ ),
83
+ nn.Identity(),
84
+ nn.Conv2d(
85
+ in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1
86
+ ),
87
+ ]
88
+ )
89
+
90
+ self.scratch = _make_scratch(out_channels, features, expand=False)
91
+
92
+ # Attach additional modules to scratch.
93
+ self.scratch.stem_transpose = None
94
+ self.scratch.refinenet1 = _make_fusion_block(features)
95
+ self.scratch.refinenet2 = _make_fusion_block(features)
96
+ self.scratch.refinenet3 = _make_fusion_block(features)
97
+ self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False)
98
+
99
+ head_features_1 = features
100
+ head_features_2 = 32
101
+
102
+ if feature_only:
103
+ self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1)
104
+ else:
105
+ self.scratch.output_conv1 = nn.Conv2d(
106
+ head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1
107
+ )
108
+ conv2_in_channels = head_features_1 // 2
109
+
110
+ self.scratch.output_conv2 = nn.Sequential(
111
+ nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1),
112
+ nn.ReLU(inplace=True),
113
+ nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0),
114
+ )
115
+
116
+ def forward(
117
+ self,
118
+ aggregated_tokens_list: List[torch.Tensor],
119
+ images: torch.Tensor,
120
+ patch_start_idx: int,
121
+ frames_chunk_size: int = 8,
122
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
123
+ """
124
+ Forward pass through the DPT head, supports processing by chunking frames.
125
+ Args:
126
+ aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers.
127
+ images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1].
128
+ patch_start_idx (int): Starting index for patch tokens in the token sequence.
129
+ Used to separate patch tokens from other tokens (e.g., camera or register tokens).
130
+ frames_chunk_size (int, optional): Number of frames to process in each chunk.
131
+ If None or larger than S, all frames are processed at once. Default: 8.
132
+
133
+ Returns:
134
+ Tensor or Tuple[Tensor, Tensor]:
135
+ - If feature_only=True: Feature maps with shape [B, S, C, H, W]
136
+ - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W]
137
+ """
138
+ B, S, _, H, W = images.shape
139
+
140
+ # If frames_chunk_size is not specified or greater than S, process all frames at once
141
+ if frames_chunk_size is None or frames_chunk_size >= S:
142
+ return self._forward_impl(aggregated_tokens_list, images, patch_start_idx)
143
+
144
+ # Otherwise, process frames in chunks to manage memory usage
145
+ assert frames_chunk_size > 0
146
+
147
+ # Process frames in batches
148
+ all_preds = []
149
+ all_conf = []
150
+
151
+ for frames_start_idx in range(0, S, frames_chunk_size):
152
+ frames_end_idx = min(frames_start_idx + frames_chunk_size, S)
153
+
154
+ # Process batch of frames
155
+ if self.feature_only:
156
+ chunk_output = self._forward_impl(
157
+ aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx
158
+ )
159
+ all_preds.append(chunk_output)
160
+ else:
161
+ chunk_preds, chunk_conf = self._forward_impl(
162
+ aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx
163
+ )
164
+ all_preds.append(chunk_preds)
165
+ all_conf.append(chunk_conf)
166
+
167
+ # Concatenate results along the sequence dimension
168
+ if self.feature_only:
169
+ return torch.cat(all_preds, dim=1)
170
+ else:
171
+ return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1)
172
+
173
+ def _forward_impl(
174
+ self,
175
+ aggregated_tokens_list: List[torch.Tensor],
176
+ images: torch.Tensor,
177
+ patch_start_idx: int,
178
+ frames_start_idx: int = None,
179
+ frames_end_idx: int = None,
180
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
181
+ """
182
+ Implementation of the forward pass through the DPT head.
183
+
184
+ This method processes a specific chunk of frames from the sequence.
185
+
186
+ Args:
187
+ aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers.
188
+ images (Tensor): Input images with shape [B, S, 3, H, W].
189
+ patch_start_idx (int): Starting index for patch tokens.
190
+ frames_start_idx (int, optional): Starting index for frames to process.
191
+ frames_end_idx (int, optional): Ending index for frames to process.
192
+
193
+ Returns:
194
+ Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence).
195
+ """
196
+ if frames_start_idx is not None and frames_end_idx is not None:
197
+ images = images[:, frames_start_idx:frames_end_idx].contiguous()
198
+
199
+ B, S, _, H, W = images.shape
200
+
201
+ patch_h, patch_w = H // self.patch_size, W // self.patch_size
202
+
203
+ out = []
204
+ dpt_idx = 0
205
+
206
+ for layer_idx in self.intermediate_layer_idx:
207
+ x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:]
208
+
209
+ # Select frames if processing a chunk
210
+ if frames_start_idx is not None and frames_end_idx is not None:
211
+ x = x[:, frames_start_idx:frames_end_idx]
212
+
213
+ x = x.reshape(B * S, -1, x.shape[-1])
214
+
215
+ x = self.norm(x)
216
+
217
+ x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
218
+
219
+ x = self.projects[dpt_idx](x)
220
+ if self.pos_embed:
221
+ x = self._apply_pos_embed(x, W, H)
222
+ x = self.resize_layers[dpt_idx](x)
223
+
224
+ out.append(x)
225
+ dpt_idx += 1
226
+
227
+ # Fuse features from multiple layers.
228
+ out = self.scratch_forward(out)
229
+ # Interpolate fused output to match target image resolution.
230
+ out = custom_interpolate(
231
+ out,
232
+ (int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)),
233
+ mode="bilinear",
234
+ align_corners=True,
235
+ )
236
+
237
+ if self.pos_embed:
238
+ out = self._apply_pos_embed(out, W, H)
239
+
240
+ if self.feature_only:
241
+ return out.view(B, S, *out.shape[1:])
242
+
243
+ out = self.scratch.output_conv2(out)
244
+ preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation)
245
+
246
+ preds = preds.view(B, S, *preds.shape[1:])
247
+ conf = conf.view(B, S, *conf.shape[1:])
248
+ return preds, conf
249
+
250
+ def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor:
251
+ """
252
+ Apply positional embedding to tensor x.
253
+ """
254
+ patch_w = x.shape[-1]
255
+ patch_h = x.shape[-2]
256
+ pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device)
257
+ pos_embed = position_grid_to_embed(pos_embed, x.shape[1])
258
+ pos_embed = pos_embed * ratio
259
+ pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)
260
+ return x + pos_embed
261
+
262
+ def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor:
263
+ """
264
+ Forward pass through the fusion blocks.
265
+
266
+ Args:
267
+ features (List[Tensor]): List of feature maps from different layers.
268
+
269
+ Returns:
270
+ Tensor: Fused feature map.
271
+ """
272
+ layer_1, layer_2, layer_3, layer_4 = features
273
+
274
+ layer_1_rn = self.scratch.layer1_rn(layer_1)
275
+ layer_2_rn = self.scratch.layer2_rn(layer_2)
276
+ layer_3_rn = self.scratch.layer3_rn(layer_3)
277
+ layer_4_rn = self.scratch.layer4_rn(layer_4)
278
+
279
+ out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
280
+ del layer_4_rn, layer_4
281
+
282
+ out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:])
283
+ del layer_3_rn, layer_3
284
+
285
+ out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:])
286
+ del layer_2_rn, layer_2
287
+
288
+ out = self.scratch.refinenet1(out, layer_1_rn)
289
+ del layer_1_rn, layer_1
290
+
291
+ out = self.scratch.output_conv1(out)
292
+ return out
293
+
294
+
295
+ ################################################################################
296
+ # Modules
297
+ ################################################################################
298
+
299
+
300
+ def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module:
301
+ return FeatureFusionBlock(
302
+ features,
303
+ nn.ReLU(inplace=True),
304
+ deconv=False,
305
+ bn=False,
306
+ expand=False,
307
+ align_corners=True,
308
+ size=size,
309
+ has_residual=has_residual,
310
+ groups=groups,
311
+ )
312
+
313
+
314
+ def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module:
315
+ scratch = nn.Module()
316
+ out_shape1 = out_shape
317
+ out_shape2 = out_shape
318
+ out_shape3 = out_shape
319
+ if len(in_shape) >= 4:
320
+ out_shape4 = out_shape
321
+
322
+ if expand:
323
+ out_shape1 = out_shape
324
+ out_shape2 = out_shape * 2
325
+ out_shape3 = out_shape * 4
326
+ if len(in_shape) >= 4:
327
+ out_shape4 = out_shape * 8
328
+
329
+ scratch.layer1_rn = nn.Conv2d(
330
+ in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
331
+ )
332
+ scratch.layer2_rn = nn.Conv2d(
333
+ in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
334
+ )
335
+ scratch.layer3_rn = nn.Conv2d(
336
+ in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
337
+ )
338
+ if len(in_shape) >= 4:
339
+ scratch.layer4_rn = nn.Conv2d(
340
+ in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
341
+ )
342
+ return scratch
343
+
344
+
345
+ class ResidualConvUnit(nn.Module):
346
+ """Residual convolution module."""
347
+
348
+ def __init__(self, features, activation, bn, groups=1):
349
+ """Init.
350
+
351
+ Args:
352
+ features (int): number of features
353
+ """
354
+ super().__init__()
355
+
356
+ self.bn = bn
357
+ self.groups = groups
358
+ self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
359
+ self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
360
+
361
+ self.norm1 = None
362
+ self.norm2 = None
363
+
364
+ self.activation = activation
365
+ self.skip_add = nn.quantized.FloatFunctional()
366
+
367
+ def forward(self, x):
368
+ """Forward pass.
369
+
370
+ Args:
371
+ x (tensor): input
372
+
373
+ Returns:
374
+ tensor: output
375
+ """
376
+
377
+ out = self.activation(x)
378
+ out = self.conv1(out)
379
+ if self.norm1 is not None:
380
+ out = self.norm1(out)
381
+
382
+ out = self.activation(out)
383
+ out = self.conv2(out)
384
+ if self.norm2 is not None:
385
+ out = self.norm2(out)
386
+
387
+ return self.skip_add.add(out, x)
388
+
389
+
390
+ class FeatureFusionBlock(nn.Module):
391
+ """Feature fusion block."""
392
+
393
+ def __init__(
394
+ self,
395
+ features,
396
+ activation,
397
+ deconv=False,
398
+ bn=False,
399
+ expand=False,
400
+ align_corners=True,
401
+ size=None,
402
+ has_residual=True,
403
+ groups=1,
404
+ ):
405
+ """Init.
406
+
407
+ Args:
408
+ features (int): number of features
409
+ """
410
+ super(FeatureFusionBlock, self).__init__()
411
+
412
+ self.deconv = deconv
413
+ self.align_corners = align_corners
414
+ self.groups = groups
415
+ self.expand = expand
416
+ out_features = features
417
+ if self.expand == True:
418
+ out_features = features // 2
419
+
420
+ self.out_conv = nn.Conv2d(
421
+ features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=self.groups
422
+ )
423
+
424
+ if has_residual:
425
+ self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups)
426
+
427
+ self.has_residual = has_residual
428
+ self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups)
429
+
430
+ self.skip_add = nn.quantized.FloatFunctional()
431
+ self.size = size
432
+
433
+ def forward(self, *xs, size=None):
434
+ """Forward pass.
435
+
436
+ Returns:
437
+ tensor: output
438
+ """
439
+ output = xs[0]
440
+
441
+ if self.has_residual:
442
+ res = self.resConfUnit1(xs[1])
443
+ output = self.skip_add.add(output, res)
444
+
445
+ output = self.resConfUnit2(output)
446
+
447
+ if (size is None) and (self.size is None):
448
+ modifier = {"scale_factor": 2}
449
+ elif size is None:
450
+ modifier = {"size": self.size}
451
+ else:
452
+ modifier = {"size": size}
453
+
454
+ output = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
455
+ output = self.out_conv(output)
456
+
457
+ return output
458
+
459
+
460
+ def custom_interpolate(
461
+ x: torch.Tensor,
462
+ size: Tuple[int, int] = None,
463
+ scale_factor: float = None,
464
+ mode: str = "bilinear",
465
+ align_corners: bool = True,
466
+ ) -> torch.Tensor:
467
+ """
468
+ Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate.
469
+ """
470
+ if size is None:
471
+ size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor))
472
+
473
+ INT_MAX = 1610612736
474
+
475
+ input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
476
+
477
+ if input_elements > INT_MAX:
478
+ chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0)
479
+ interpolated_chunks = [
480
+ nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks
481
+ ]
482
+ x = torch.cat(interpolated_chunks, dim=0)
483
+ return x.contiguous()
484
+ else:
485
+ return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners)
vggt_heads_head_act.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/heads/head_act.py; only the imports are changed (flat module names).
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 file in the root directory of this source tree.
7
+
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+
12
+
13
+ def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"):
14
+ """
15
+ Activate pose parameters with specified activation functions.
16
+
17
+ Args:
18
+ pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length]
19
+ trans_act: Activation type for translation component
20
+ quat_act: Activation type for quaternion component
21
+ fl_act: Activation type for focal length component
22
+
23
+ Returns:
24
+ Activated pose parameters tensor
25
+ """
26
+ T = pred_pose_enc[..., :3]
27
+ quat = pred_pose_enc[..., 3:7]
28
+ fl = pred_pose_enc[..., 7:] # or fov
29
+
30
+ T = base_pose_act(T, trans_act)
31
+ quat = base_pose_act(quat, quat_act)
32
+ fl = base_pose_act(fl, fl_act) # or fov
33
+
34
+ pred_pose_enc = torch.cat([T, quat, fl], dim=-1)
35
+
36
+ return pred_pose_enc
37
+
38
+
39
+ def base_pose_act(pose_enc, act_type="linear"):
40
+ """
41
+ Apply basic activation function to pose parameters.
42
+
43
+ Args:
44
+ pose_enc: Tensor containing encoded pose parameters
45
+ act_type: Activation type ("linear", "inv_log", "exp", "relu")
46
+
47
+ Returns:
48
+ Activated pose parameters
49
+ """
50
+ if act_type == "linear":
51
+ return pose_enc
52
+ elif act_type == "inv_log":
53
+ return inverse_log_transform(pose_enc)
54
+ elif act_type == "exp":
55
+ return torch.exp(pose_enc)
56
+ elif act_type == "relu":
57
+ return F.relu(pose_enc)
58
+ else:
59
+ raise ValueError(f"Unknown act_type: {act_type}")
60
+
61
+
62
+ def activate_head(out, activation="norm_exp", conf_activation="expp1"):
63
+ """
64
+ Process network output to extract 3D points and confidence values.
65
+
66
+ Args:
67
+ out: Network output tensor (B, C, H, W)
68
+ activation: Activation type for 3D points
69
+ conf_activation: Activation type for confidence values
70
+
71
+ Returns:
72
+ Tuple of (3D points tensor, confidence tensor)
73
+ """
74
+ # Move channels from last dim to the 4th dimension => (B, H, W, C)
75
+ fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected
76
+
77
+ # Split into xyz (first C-1 channels) and confidence (last channel)
78
+ xyz = fmap[:, :, :, :-1]
79
+ conf = fmap[:, :, :, -1]
80
+
81
+ if activation == "norm_exp":
82
+ d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8)
83
+ xyz_normed = xyz / d
84
+ pts3d = xyz_normed * torch.expm1(d)
85
+ elif activation == "norm":
86
+ pts3d = xyz / xyz.norm(dim=-1, keepdim=True)
87
+ elif activation == "exp":
88
+ pts3d = torch.exp(xyz)
89
+ elif activation == "relu":
90
+ pts3d = F.relu(xyz)
91
+ elif activation == "inv_log":
92
+ pts3d = inverse_log_transform(xyz)
93
+ elif activation == "xy_inv_log":
94
+ xy, z = xyz.split([2, 1], dim=-1)
95
+ z = inverse_log_transform(z)
96
+ pts3d = torch.cat([xy * z, z], dim=-1)
97
+ elif activation == "sigmoid":
98
+ pts3d = torch.sigmoid(xyz)
99
+ elif activation == "linear":
100
+ pts3d = xyz
101
+ else:
102
+ raise ValueError(f"Unknown activation: {activation}")
103
+
104
+ if conf_activation == "expp1":
105
+ conf_out = 1 + conf.exp()
106
+ elif conf_activation == "expp0":
107
+ conf_out = conf.exp()
108
+ elif conf_activation == "sigmoid":
109
+ conf_out = torch.sigmoid(conf)
110
+ else:
111
+ raise ValueError(f"Unknown conf_activation: {conf_activation}")
112
+
113
+ return pts3d, conf_out
114
+
115
+
116
+ def inverse_log_transform(y):
117
+ """
118
+ Apply inverse log transform: sign(y) * (exp(|y|) - 1)
119
+
120
+ Args:
121
+ y: Input tensor
122
+
123
+ Returns:
124
+ Transformed tensor
125
+ """
126
+ return torch.sign(y) * (torch.expm1(torch.abs(y)))
vggt_heads_utils.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/heads/utils.py; only the imports are changed (flat module names).
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 file in the root directory of this source tree.
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+
12
+ def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> 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(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2]
29
+ emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2]
30
+
31
+ # Combine and reshape
32
+ emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D]
33
+
34
+ return emb.view(H, W, embed_dim) # [H, W, D]
35
+
36
+
37
+ def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor:
38
+ """
39
+ This function generates a 1D positional embedding from a given grid using sine and cosine functions.
40
+
41
+ Args:
42
+ - embed_dim: The embedding dimension.
43
+ - pos: The position to generate the embedding from.
44
+
45
+ Returns:
46
+ - emb: The generated 1D positional embedding.
47
+ """
48
+ assert embed_dim % 2 == 0
49
+ device = pos.device
50
+ omega = torch.arange(embed_dim // 2, dtype=torch.float32 if device.type == "mps" else torch.double, device=device)
51
+ omega /= embed_dim / 2.0
52
+ omega = 1.0 / omega_0**omega # (D/2,)
53
+
54
+ pos = pos.reshape(-1) # (M,)
55
+ out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
56
+
57
+ emb_sin = torch.sin(out) # (M, D/2)
58
+ emb_cos = torch.cos(out) # (M, D/2)
59
+
60
+ emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
61
+ return emb.float()
62
+
63
+
64
+ # Inspired by https://github.com/microsoft/moge
65
+
66
+
67
+ def create_uv_grid(
68
+ width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None
69
+ ) -> torch.Tensor:
70
+ """
71
+ Create a normalized UV grid of shape (width, height, 2).
72
+
73
+ The grid spans horizontally and vertically according to an aspect ratio,
74
+ ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right
75
+ corner is at (x_span, y_span), normalized by the diagonal of the plane.
76
+
77
+ Args:
78
+ width (int): Number of points horizontally.
79
+ height (int): Number of points vertically.
80
+ aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height.
81
+ dtype (torch.dtype, optional): Data type of the resulting tensor.
82
+ device (torch.device, optional): Device on which the tensor is created.
83
+
84
+ Returns:
85
+ torch.Tensor: A (width, height, 2) tensor of UV coordinates.
86
+ """
87
+ # Derive aspect ratio if not explicitly provided
88
+ if aspect_ratio is None:
89
+ aspect_ratio = float(width) / float(height)
90
+
91
+ # Compute normalized spans for X and Y
92
+ diag_factor = (aspect_ratio**2 + 1.0) ** 0.5
93
+ span_x = aspect_ratio / diag_factor
94
+ span_y = 1.0 / diag_factor
95
+
96
+ # Establish the linspace boundaries
97
+ left_x = -span_x * (width - 1) / width
98
+ right_x = span_x * (width - 1) / width
99
+ top_y = -span_y * (height - 1) / height
100
+ bottom_y = span_y * (height - 1) / height
101
+
102
+ # Generate 1D coordinates
103
+ x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device)
104
+ y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device)
105
+
106
+ # Create 2D meshgrid (width x height) and stack into UV
107
+ uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy")
108
+ uv_grid = torch.stack((uu, vv), dim=-1)
109
+
110
+ return uv_grid
vggt_layers.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/__init__.py; only the imports are changed (flat module names).
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 file in the root directory of this source tree.
7
+
8
+ from .vggt_layers_mlp import Mlp
9
+ from .vggt_layers_patch_embed import PatchEmbed
10
+ from .vggt_layers_swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
11
+ from .vggt_layers_block import NestedTensorBlock
12
+ from .vggt_layers_attention import MemEffAttention
vggt_layers_attention.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/attention.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
10
+
11
+ import logging
12
+ import os
13
+ import warnings
14
+
15
+ from torch import Tensor
16
+ from torch import nn
17
+ import torch.nn.functional as F
18
+
19
+ XFORMERS_AVAILABLE = False
20
+
21
+
22
+ class Attention(nn.Module):
23
+ def __init__(
24
+ self,
25
+ dim: int,
26
+ num_heads: int = 8,
27
+ qkv_bias: bool = True,
28
+ proj_bias: bool = True,
29
+ attn_drop: float = 0.0,
30
+ proj_drop: float = 0.0,
31
+ norm_layer: nn.Module = nn.LayerNorm,
32
+ qk_norm: bool = False,
33
+ fused_attn: bool = True, # use F.scaled_dot_product_attention or not
34
+ rope=None,
35
+ ) -> None:
36
+ super().__init__()
37
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
38
+ self.num_heads = num_heads
39
+ self.head_dim = dim // num_heads
40
+ self.scale = self.head_dim**-0.5
41
+ self.fused_attn = fused_attn
42
+
43
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
44
+ self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
45
+ self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
46
+ self.attn_drop = nn.Dropout(attn_drop)
47
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
48
+ self.proj_drop = nn.Dropout(proj_drop)
49
+ self.rope = rope
50
+
51
+ def forward(self, x: Tensor, pos=None) -> Tensor:
52
+ B, N, C = x.shape
53
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
54
+ q, k, v = qkv.unbind(0)
55
+ q, k = self.q_norm(q), self.k_norm(k)
56
+
57
+ if self.rope is not None:
58
+ q = self.rope(q, pos)
59
+ k = self.rope(k, pos)
60
+
61
+ if self.fused_attn:
62
+ x = F.scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0)
63
+ else:
64
+ q = q * self.scale
65
+ attn = q @ k.transpose(-2, -1)
66
+ attn = attn.softmax(dim=-1)
67
+ attn = self.attn_drop(attn)
68
+ x = attn @ v
69
+
70
+ x = x.transpose(1, 2).reshape(B, N, C)
71
+ x = self.proj(x)
72
+ x = self.proj_drop(x)
73
+ return x
74
+
75
+
76
+ class MemEffAttention(Attention):
77
+ def forward(self, x: Tensor, attn_bias=None, pos=None) -> Tensor:
78
+ assert pos is None
79
+ if not XFORMERS_AVAILABLE:
80
+ if attn_bias is not None:
81
+ raise AssertionError("xFormers is required for using nested tensors")
82
+ return super().forward(x)
83
+
84
+ B, N, C = x.shape
85
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
86
+
87
+ q, k, v = unbind(qkv, 2)
88
+
89
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
90
+ x = x.reshape([B, N, C])
91
+
92
+ x = self.proj(x)
93
+ x = self.proj_drop(x)
94
+ return x
vggt_layers_block.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/block.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ import logging
12
+ import os
13
+ from typing import Callable, List, Any, Tuple, Dict
14
+ import warnings
15
+
16
+ import torch
17
+ from torch import nn, Tensor
18
+
19
+ from .vggt_layers_attention import Attention
20
+ from .vggt_layers_drop_path import DropPath
21
+ from .vggt_layers_layer_scale import LayerScale
22
+ from .vggt_layers_mlp import Mlp
23
+
24
+
25
+ XFORMERS_AVAILABLE = False
26
+
27
+
28
+ class Block(nn.Module):
29
+ def __init__(
30
+ self,
31
+ dim: int,
32
+ num_heads: int,
33
+ mlp_ratio: float = 4.0,
34
+ qkv_bias: bool = True,
35
+ proj_bias: bool = True,
36
+ ffn_bias: bool = True,
37
+ drop: float = 0.0,
38
+ attn_drop: float = 0.0,
39
+ init_values=None,
40
+ drop_path: float = 0.0,
41
+ act_layer: Callable[..., nn.Module] = nn.GELU,
42
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
43
+ attn_class: Callable[..., nn.Module] = Attention,
44
+ ffn_layer: Callable[..., nn.Module] = Mlp,
45
+ qk_norm: bool = False,
46
+ fused_attn: bool = True, # use F.scaled_dot_product_attention or not
47
+ rope=None,
48
+ ) -> None:
49
+ super().__init__()
50
+
51
+ self.norm1 = norm_layer(dim)
52
+
53
+ self.attn = attn_class(
54
+ dim,
55
+ num_heads=num_heads,
56
+ qkv_bias=qkv_bias,
57
+ proj_bias=proj_bias,
58
+ attn_drop=attn_drop,
59
+ proj_drop=drop,
60
+ qk_norm=qk_norm,
61
+ fused_attn=fused_attn,
62
+ rope=rope,
63
+ )
64
+
65
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
66
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
67
+
68
+ self.norm2 = norm_layer(dim)
69
+ mlp_hidden_dim = int(dim * mlp_ratio)
70
+ self.mlp = ffn_layer(
71
+ in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, bias=ffn_bias
72
+ )
73
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
74
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
75
+
76
+ self.sample_drop_ratio = drop_path
77
+
78
+ def forward(self, x: Tensor, pos=None) -> Tensor:
79
+ def attn_residual_func(x: Tensor, pos=None) -> Tensor:
80
+ return self.ls1(self.attn(self.norm1(x), pos=pos))
81
+
82
+ def ffn_residual_func(x: Tensor) -> Tensor:
83
+ return self.ls2(self.mlp(self.norm2(x)))
84
+
85
+ if self.training and self.sample_drop_ratio > 0.1:
86
+ # the overhead is compensated only for a drop path rate larger than 0.1
87
+ x = drop_add_residual_stochastic_depth(
88
+ x, pos=pos, residual_func=attn_residual_func, sample_drop_ratio=self.sample_drop_ratio
89
+ )
90
+ x = drop_add_residual_stochastic_depth(
91
+ x, residual_func=ffn_residual_func, sample_drop_ratio=self.sample_drop_ratio
92
+ )
93
+ elif self.training and self.sample_drop_ratio > 0.0:
94
+ x = x + self.drop_path1(attn_residual_func(x, pos=pos))
95
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
96
+ else:
97
+ x = x + attn_residual_func(x, pos=pos)
98
+ x = x + ffn_residual_func(x)
99
+ return x
100
+
101
+
102
+ def drop_add_residual_stochastic_depth(
103
+ x: Tensor, residual_func: Callable[[Tensor], Tensor], sample_drop_ratio: float = 0.0, pos=None
104
+ ) -> Tensor:
105
+ # 1) extract subset using permutation
106
+ b, n, d = x.shape
107
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
108
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
109
+ x_subset = x[brange]
110
+
111
+ # 2) apply residual_func to get residual
112
+ if pos is not None:
113
+ # if necessary, apply rope to the subset
114
+ pos = pos[brange]
115
+ residual = residual_func(x_subset, pos=pos)
116
+ else:
117
+ residual = residual_func(x_subset)
118
+
119
+ x_flat = x.flatten(1)
120
+ residual = residual.flatten(1)
121
+
122
+ residual_scale_factor = b / sample_subset_size
123
+
124
+ # 3) add the residual
125
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
126
+ return x_plus_residual.view_as(x)
127
+
128
+
129
+ def get_branges_scales(x, sample_drop_ratio=0.0):
130
+ b, n, d = x.shape
131
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
132
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
133
+ residual_scale_factor = b / sample_subset_size
134
+ return brange, residual_scale_factor
135
+
136
+
137
+ def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
138
+ if scaling_vector is None:
139
+ x_flat = x.flatten(1)
140
+ residual = residual.flatten(1)
141
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
142
+ else:
143
+ x_plus_residual = scaled_index_add(
144
+ x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
145
+ )
146
+ return x_plus_residual
147
+
148
+
149
+ attn_bias_cache: Dict[Tuple, Any] = {}
150
+
151
+
152
+ def get_attn_bias_and_cat(x_list, branges=None):
153
+ """
154
+ this will perform the index select, cat the tensors, and provide the attn_bias from cache
155
+ """
156
+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
157
+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
158
+ if all_shapes not in attn_bias_cache.keys():
159
+ seqlens = []
160
+ for b, x in zip(batch_sizes, x_list):
161
+ for _ in range(b):
162
+ seqlens.append(x.shape[1])
163
+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
164
+ attn_bias._batch_sizes = batch_sizes
165
+ attn_bias_cache[all_shapes] = attn_bias
166
+
167
+ if branges is not None:
168
+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
169
+ else:
170
+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
171
+ cat_tensors = torch.cat(tensors_bs1, dim=1)
172
+
173
+ return attn_bias_cache[all_shapes], cat_tensors
174
+
175
+
176
+ def drop_add_residual_stochastic_depth_list(
177
+ x_list: List[Tensor],
178
+ residual_func: Callable[[Tensor, Any], Tensor],
179
+ sample_drop_ratio: float = 0.0,
180
+ scaling_vector=None,
181
+ ) -> Tensor:
182
+ # 1) generate random set of indices for dropping samples in the batch
183
+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
184
+ branges = [s[0] for s in branges_scales]
185
+ residual_scale_factors = [s[1] for s in branges_scales]
186
+
187
+ # 2) get attention bias and index+concat the tensors
188
+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
189
+
190
+ # 3) apply residual_func to get residual, and split the result
191
+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
192
+
193
+ outputs = []
194
+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
195
+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
196
+ return outputs
197
+
198
+
199
+ class NestedTensorBlock(Block):
200
+ def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
201
+ """
202
+ x_list contains a list of tensors to nest together and run
203
+ """
204
+ assert isinstance(self.attn, MemEffAttention)
205
+
206
+ if self.training and self.sample_drop_ratio > 0.0:
207
+
208
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
209
+ return self.attn(self.norm1(x), attn_bias=attn_bias)
210
+
211
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
212
+ return self.mlp(self.norm2(x))
213
+
214
+ x_list = drop_add_residual_stochastic_depth_list(
215
+ x_list,
216
+ residual_func=attn_residual_func,
217
+ sample_drop_ratio=self.sample_drop_ratio,
218
+ scaling_vector=(self.ls1.gamma if isinstance(self.ls1, LayerScale) else None),
219
+ )
220
+ x_list = drop_add_residual_stochastic_depth_list(
221
+ x_list,
222
+ residual_func=ffn_residual_func,
223
+ sample_drop_ratio=self.sample_drop_ratio,
224
+ scaling_vector=(self.ls2.gamma if isinstance(self.ls1, LayerScale) else None),
225
+ )
226
+ return x_list
227
+ else:
228
+
229
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
230
+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
231
+
232
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
233
+ return self.ls2(self.mlp(self.norm2(x)))
234
+
235
+ attn_bias, x = get_attn_bias_and_cat(x_list)
236
+ x = x + attn_residual_func(x, attn_bias=attn_bias)
237
+ x = x + ffn_residual_func(x)
238
+ return attn_bias.split(x)
239
+
240
+ def forward(self, x_or_x_list):
241
+ if isinstance(x_or_x_list, Tensor):
242
+ return super().forward(x_or_x_list)
243
+ elif isinstance(x_or_x_list, list):
244
+ if not XFORMERS_AVAILABLE:
245
+ raise AssertionError("xFormers is required for using nested tensors")
246
+ return self.forward_nested(x_or_x_list)
247
+ else:
248
+ raise AssertionError
vggt_layers_drop_path.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/drop_path.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
10
+
11
+
12
+ from torch import nn
13
+
14
+
15
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
16
+ if drop_prob == 0.0 or not training:
17
+ return x
18
+ keep_prob = 1 - drop_prob
19
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
20
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
21
+ if keep_prob > 0.0:
22
+ random_tensor.div_(keep_prob)
23
+ output = x * random_tensor
24
+ return output
25
+
26
+
27
+ class DropPath(nn.Module):
28
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
29
+
30
+ def __init__(self, drop_prob=None):
31
+ super(DropPath, self).__init__()
32
+ self.drop_prob = drop_prob
33
+
34
+ def forward(self, x):
35
+ return drop_path(x, self.drop_prob, self.training)
vggt_layers_layer_scale.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/layer_scale.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
8
+
9
+ from typing import Union
10
+
11
+ import torch
12
+ from torch import Tensor
13
+ from torch import nn
14
+
15
+
16
+ class LayerScale(nn.Module):
17
+ def __init__(self, dim: int, init_values: Union[float, Tensor] = 1e-5, inplace: bool = False) -> None:
18
+ super().__init__()
19
+ self.inplace = inplace
20
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
21
+
22
+ def forward(self, x: Tensor) -> Tensor:
23
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
vggt_layers_mlp.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/mlp.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
10
+
11
+
12
+ from typing import Callable, Optional
13
+
14
+ from torch import Tensor, nn
15
+
16
+
17
+ class Mlp(nn.Module):
18
+ def __init__(
19
+ self,
20
+ in_features: int,
21
+ hidden_features: Optional[int] = None,
22
+ out_features: Optional[int] = None,
23
+ act_layer: Callable[..., nn.Module] = nn.GELU,
24
+ drop: float = 0.0,
25
+ bias: bool = True,
26
+ ) -> None:
27
+ super().__init__()
28
+ out_features = out_features or in_features
29
+ hidden_features = hidden_features or in_features
30
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
31
+ self.act = act_layer()
32
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
33
+ self.drop = nn.Dropout(drop)
34
+
35
+ def forward(self, x: Tensor) -> Tensor:
36
+ x = self.fc1(x)
37
+ x = self.act(x)
38
+ x = self.drop(x)
39
+ x = self.fc2(x)
40
+ x = self.drop(x)
41
+ return x
vggt_layers_patch_embed.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/patch_embed.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ from typing import Callable, Optional, Tuple, Union
12
+
13
+ from torch import Tensor
14
+ import torch.nn as nn
15
+
16
+
17
+ def make_2tuple(x):
18
+ if isinstance(x, tuple):
19
+ assert len(x) == 2
20
+ return x
21
+
22
+ assert isinstance(x, int)
23
+ return (x, x)
24
+
25
+
26
+ class PatchEmbed(nn.Module):
27
+ """
28
+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
29
+
30
+ Args:
31
+ img_size: Image size.
32
+ patch_size: Patch token size.
33
+ in_chans: Number of input image channels.
34
+ embed_dim: Number of linear projection output channels.
35
+ norm_layer: Normalization layer.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ img_size: Union[int, Tuple[int, int]] = 224,
41
+ patch_size: Union[int, Tuple[int, int]] = 16,
42
+ in_chans: int = 3,
43
+ embed_dim: int = 768,
44
+ norm_layer: Optional[Callable] = None,
45
+ flatten_embedding: bool = True,
46
+ ) -> None:
47
+ super().__init__()
48
+
49
+ image_HW = make_2tuple(img_size)
50
+ patch_HW = make_2tuple(patch_size)
51
+ patch_grid_size = (image_HW[0] // patch_HW[0], image_HW[1] // patch_HW[1])
52
+
53
+ self.img_size = image_HW
54
+ self.patch_size = patch_HW
55
+ self.patches_resolution = patch_grid_size
56
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
57
+
58
+ self.in_chans = in_chans
59
+ self.embed_dim = embed_dim
60
+
61
+ self.flatten_embedding = flatten_embedding
62
+
63
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
64
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
65
+
66
+ def forward(self, x: Tensor) -> Tensor:
67
+ _, _, H, W = x.shape
68
+ patch_H, patch_W = self.patch_size
69
+
70
+ assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
71
+ assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
72
+
73
+ x = self.proj(x) # B C H W
74
+ H, W = x.size(2), x.size(3)
75
+ x = x.flatten(2).transpose(1, 2) # B HW C
76
+ x = self.norm(x)
77
+ if not self.flatten_embedding:
78
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
79
+ return x
80
+
81
+ def flops(self) -> float:
82
+ Ho, Wo = self.patches_resolution
83
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
84
+ if self.norm is not None:
85
+ flops += Ho * Wo * self.embed_dim
86
+ return flops
vggt_layers_rope.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/rope.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ # Implementation of 2D Rotary Position Embeddings (RoPE).
9
+
10
+ # This module provides a clean implementation of 2D Rotary Position Embeddings,
11
+ # which extends the original RoPE concept to handle 2D spatial positions.
12
+
13
+ # Inspired by:
14
+ # https://github.com/meta-llama/codellama/blob/main/llama/model.py
15
+ # https://github.com/naver-ai/rope-vit
16
+
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ from typing import Dict, Tuple
23
+
24
+
25
+ class PositionGetter:
26
+ """Generates and caches 2D spatial positions for patches in a grid.
27
+
28
+ This class efficiently manages the generation of spatial coordinates for patches
29
+ in a 2D grid, caching results to avoid redundant computations.
30
+
31
+ Attributes:
32
+ position_cache: Dictionary storing precomputed position tensors for different
33
+ grid dimensions.
34
+ """
35
+
36
+ def __init__(self):
37
+ """Initializes the position generator with an empty cache."""
38
+ self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {}
39
+
40
+ def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor:
41
+ """Generates spatial positions for a batch of patches.
42
+
43
+ Args:
44
+ batch_size: Number of samples in the batch.
45
+ height: Height of the grid in patches.
46
+ width: Width of the grid in patches.
47
+ device: Target device for the position tensor.
48
+
49
+ Returns:
50
+ Tensor of shape (batch_size, height*width, 2) containing y,x coordinates
51
+ for each position in the grid, repeated for each batch item.
52
+ """
53
+ if (height, width) not in self.position_cache:
54
+ y_coords = torch.arange(height, device=device)
55
+ x_coords = torch.arange(width, device=device)
56
+ positions = torch.cartesian_prod(y_coords, x_coords)
57
+ self.position_cache[height, width] = positions
58
+
59
+ cached_positions = self.position_cache[height, width]
60
+ return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone()
61
+
62
+
63
+ class RotaryPositionEmbedding2D(nn.Module):
64
+ """2D Rotary Position Embedding implementation.
65
+
66
+ This module applies rotary position embeddings to input tokens based on their
67
+ 2D spatial positions. It handles the position-dependent rotation of features
68
+ separately for vertical and horizontal dimensions.
69
+
70
+ Args:
71
+ frequency: Base frequency for the position embeddings. Default: 100.0
72
+ scaling_factor: Scaling factor for frequency computation. Default: 1.0
73
+
74
+ Attributes:
75
+ base_frequency: Base frequency for computing position embeddings.
76
+ scaling_factor: Factor to scale the computed frequencies.
77
+ frequency_cache: Cache for storing precomputed frequency components.
78
+ """
79
+
80
+ def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0):
81
+ """Initializes the 2D RoPE module."""
82
+ super().__init__()
83
+ self.base_frequency = frequency
84
+ self.scaling_factor = scaling_factor
85
+ self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {}
86
+
87
+ def _compute_frequency_components(
88
+ self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype
89
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
90
+ """Computes frequency components for rotary embeddings.
91
+
92
+ Args:
93
+ dim: Feature dimension (must be even).
94
+ seq_len: Maximum sequence length.
95
+ device: Target device for computations.
96
+ dtype: Data type for the computed tensors.
97
+
98
+ Returns:
99
+ Tuple of (cosine, sine) tensors for frequency components.
100
+ """
101
+ cache_key = (dim, seq_len, device, dtype)
102
+ if cache_key not in self.frequency_cache:
103
+ # Compute frequency bands
104
+ exponents = torch.arange(0, dim, 2, device=device).float() / dim
105
+ inv_freq = 1.0 / (self.base_frequency**exponents)
106
+
107
+ # Generate position-dependent frequencies
108
+ positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype)
109
+ angles = torch.einsum("i,j->ij", positions, inv_freq)
110
+
111
+ # Compute and cache frequency components
112
+ angles = angles.to(dtype)
113
+ angles = torch.cat((angles, angles), dim=-1)
114
+ cos_components = angles.cos().to(dtype)
115
+ sin_components = angles.sin().to(dtype)
116
+ self.frequency_cache[cache_key] = (cos_components, sin_components)
117
+
118
+ return self.frequency_cache[cache_key]
119
+
120
+ @staticmethod
121
+ def _rotate_features(x: torch.Tensor) -> torch.Tensor:
122
+ """Performs feature rotation by splitting and recombining feature dimensions.
123
+
124
+ Args:
125
+ x: Input tensor to rotate.
126
+
127
+ Returns:
128
+ Rotated feature tensor.
129
+ """
130
+ feature_dim = x.shape[-1]
131
+ x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :]
132
+ return torch.cat((-x2, x1), dim=-1)
133
+
134
+ def _apply_1d_rope(
135
+ self, tokens: torch.Tensor, positions: torch.Tensor, cos_comp: torch.Tensor, sin_comp: torch.Tensor
136
+ ) -> torch.Tensor:
137
+ """Applies 1D rotary position embeddings along one dimension.
138
+
139
+ Args:
140
+ tokens: Input token features.
141
+ positions: Position indices.
142
+ cos_comp: Cosine components for rotation.
143
+ sin_comp: Sine components for rotation.
144
+
145
+ Returns:
146
+ Tokens with applied rotary position embeddings.
147
+ """
148
+ # Embed positions with frequency components
149
+ cos = F.embedding(positions, cos_comp)[:, None, :, :]
150
+ sin = F.embedding(positions, sin_comp)[:, None, :, :]
151
+
152
+ # Apply rotation
153
+ return (tokens * cos) + (self._rotate_features(tokens) * sin)
154
+
155
+ def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
156
+ """Applies 2D rotary position embeddings to input tokens.
157
+
158
+ Args:
159
+ tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim).
160
+ The feature dimension (dim) must be divisible by 4.
161
+ positions: Position tensor of shape (batch_size, n_tokens, 2) containing
162
+ the y and x coordinates for each token.
163
+
164
+ Returns:
165
+ Tensor of same shape as input with applied 2D rotary position embeddings.
166
+
167
+ Raises:
168
+ AssertionError: If input dimensions are invalid or positions are malformed.
169
+ """
170
+ # Validate inputs
171
+ assert tokens.size(-1) % 2 == 0, "Feature dimension must be even"
172
+ assert positions.ndim == 3 and positions.shape[-1] == 2, "Positions must have shape (batch_size, n_tokens, 2)"
173
+
174
+ # Compute feature dimension for each spatial direction
175
+ feature_dim = tokens.size(-1) // 2
176
+
177
+ # Get frequency components
178
+ max_position = int(positions.max()) + 1
179
+ cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype)
180
+
181
+ # Split features for vertical and horizontal processing
182
+ vertical_features, horizontal_features = tokens.chunk(2, dim=-1)
183
+
184
+ # Apply RoPE separately for each dimension
185
+ vertical_features = self._apply_1d_rope(vertical_features, positions[..., 0], cos_comp, sin_comp)
186
+ horizontal_features = self._apply_1d_rope(horizontal_features, positions[..., 1], cos_comp, sin_comp)
187
+
188
+ # Combine processed features
189
+ return torch.cat((vertical_features, horizontal_features), dim=-1)
vggt_layers_swiglu_ffn.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/swiglu_ffn.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ import os
8
+ from typing import Callable, Optional
9
+ import warnings
10
+
11
+ from torch import Tensor, nn
12
+ import torch.nn.functional as F
13
+
14
+
15
+ class SwiGLUFFN(nn.Module):
16
+ def __init__(
17
+ self,
18
+ in_features: int,
19
+ hidden_features: Optional[int] = None,
20
+ out_features: Optional[int] = None,
21
+ act_layer: Callable[..., nn.Module] = None,
22
+ drop: float = 0.0,
23
+ bias: bool = True,
24
+ ) -> None:
25
+ super().__init__()
26
+ out_features = out_features or in_features
27
+ hidden_features = hidden_features or in_features
28
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
29
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
30
+
31
+ def forward(self, x: Tensor) -> Tensor:
32
+ x12 = self.w12(x)
33
+ x1, x2 = x12.chunk(2, dim=-1)
34
+ hidden = F.silu(x1) * x2
35
+ return self.w3(hidden)
36
+
37
+
38
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
39
+ # try:
40
+ # if XFORMERS_ENABLED:
41
+ # from xformers.ops import SwiGLU
42
+
43
+ # XFORMERS_AVAILABLE = True
44
+ # warnings.warn("xFormers is available (SwiGLU)")
45
+ # else:
46
+ # warnings.warn("xFormers is disabled (SwiGLU)")
47
+ # raise ImportError
48
+ # except ImportError:
49
+ SwiGLU = SwiGLUFFN
50
+ XFORMERS_AVAILABLE = False
51
+
52
+ # warnings.warn("xFormers is not available (SwiGLU)")
53
+
54
+
55
+ class SwiGLUFFNFused(SwiGLU):
56
+ def __init__(
57
+ self,
58
+ in_features: int,
59
+ hidden_features: Optional[int] = None,
60
+ out_features: Optional[int] = None,
61
+ act_layer: Callable[..., nn.Module] = None,
62
+ drop: float = 0.0,
63
+ bias: bool = True,
64
+ ) -> None:
65
+ out_features = out_features or in_features
66
+ hidden_features = hidden_features or in_features
67
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
68
+ super().__init__(in_features=in_features, hidden_features=hidden_features, out_features=out_features, bias=bias)
vggt_layers_vision_transformer.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/layers/vision_transformer.py; only the imports are changed (flat module names).
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # This source code is licensed under the Apache License, Version 2.0
5
+ # found in the LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
10
+
11
+ from functools import partial
12
+ import math
13
+ import logging
14
+ from typing import Sequence, Tuple, Union, Callable
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ from torch.utils.checkpoint import checkpoint
19
+ from torch.nn.init import trunc_normal_
20
+ from .vggt_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
21
+
22
+ logger = logging.getLogger("dinov2")
23
+
24
+
25
+ def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
26
+ if not depth_first and include_root:
27
+ fn(module=module, name=name)
28
+ for child_name, child_module in module.named_children():
29
+ child_name = ".".join((name, child_name)) if name else child_name
30
+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
31
+ if depth_first and include_root:
32
+ fn(module=module, name=name)
33
+ return module
34
+
35
+
36
+ class BlockChunk(nn.ModuleList):
37
+ def forward(self, x):
38
+ for b in self:
39
+ x = b(x)
40
+ return x
41
+
42
+
43
+ class DinoVisionTransformer(nn.Module):
44
+ def __init__(
45
+ self,
46
+ img_size=224,
47
+ patch_size=16,
48
+ in_chans=3,
49
+ embed_dim=768,
50
+ depth=12,
51
+ num_heads=12,
52
+ mlp_ratio=4.0,
53
+ qkv_bias=True,
54
+ ffn_bias=True,
55
+ proj_bias=True,
56
+ drop_path_rate=0.0,
57
+ drop_path_uniform=False,
58
+ init_values=None, # for layerscale: None or 0 => no layerscale
59
+ embed_layer=PatchEmbed,
60
+ act_layer=nn.GELU,
61
+ block_fn=Block,
62
+ ffn_layer="mlp",
63
+ block_chunks=1,
64
+ num_register_tokens=0,
65
+ interpolate_antialias=False,
66
+ interpolate_offset=0.1,
67
+ qk_norm=False,
68
+ ):
69
+ """
70
+ Args:
71
+ img_size (int, tuple): input image size
72
+ patch_size (int, tuple): patch size
73
+ in_chans (int): number of input channels
74
+ embed_dim (int): embedding dimension
75
+ depth (int): depth of transformer
76
+ num_heads (int): number of attention heads
77
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
78
+ qkv_bias (bool): enable bias for qkv if True
79
+ proj_bias (bool): enable bias for proj in attn if True
80
+ ffn_bias (bool): enable bias for ffn if True
81
+ drop_path_rate (float): stochastic depth rate
82
+ drop_path_uniform (bool): apply uniform drop rate across blocks
83
+ weight_init (str): weight init scheme
84
+ init_values (float): layer-scale init values
85
+ embed_layer (nn.Module): patch embedding layer
86
+ act_layer (nn.Module): MLP activation layer
87
+ block_fn (nn.Module): transformer block class
88
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
89
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
90
+ num_register_tokens: (int) number of extra cls tokens (so-called "registers")
91
+ interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
92
+ interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
93
+ """
94
+ super().__init__()
95
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
96
+
97
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
98
+ self.num_tokens = 1
99
+ self.n_blocks = depth
100
+ self.num_heads = num_heads
101
+ self.patch_size = patch_size
102
+ self.num_register_tokens = num_register_tokens
103
+ self.interpolate_antialias = interpolate_antialias
104
+ self.interpolate_offset = interpolate_offset
105
+ self.use_reentrant = False # hardcoded to False
106
+
107
+ self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
108
+ num_patches = self.patch_embed.num_patches
109
+
110
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
111
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
112
+ assert num_register_tokens >= 0
113
+ self.register_tokens = (
114
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
115
+ )
116
+
117
+ if drop_path_uniform is True:
118
+ dpr = [drop_path_rate] * depth
119
+ else:
120
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
121
+
122
+ if ffn_layer == "mlp":
123
+ logger.info("using MLP layer as FFN")
124
+ ffn_layer = Mlp
125
+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
126
+ logger.info("using SwiGLU layer as FFN")
127
+ ffn_layer = SwiGLUFFNFused
128
+ elif ffn_layer == "identity":
129
+ logger.info("using Identity layer as FFN")
130
+
131
+ def f(*args, **kwargs):
132
+ return nn.Identity()
133
+
134
+ ffn_layer = f
135
+ else:
136
+ raise NotImplementedError
137
+
138
+ blocks_list = [
139
+ block_fn(
140
+ dim=embed_dim,
141
+ num_heads=num_heads,
142
+ mlp_ratio=mlp_ratio,
143
+ qkv_bias=qkv_bias,
144
+ proj_bias=proj_bias,
145
+ ffn_bias=ffn_bias,
146
+ drop_path=dpr[i],
147
+ norm_layer=norm_layer,
148
+ act_layer=act_layer,
149
+ ffn_layer=ffn_layer,
150
+ init_values=init_values,
151
+ qk_norm=qk_norm,
152
+ )
153
+ for i in range(depth)
154
+ ]
155
+ if block_chunks > 0:
156
+ self.chunked_blocks = True
157
+ chunked_blocks = []
158
+ chunksize = depth // block_chunks
159
+ for i in range(0, depth, chunksize):
160
+ # this is to keep the block index consistent if we chunk the block list
161
+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
162
+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
163
+ else:
164
+ self.chunked_blocks = False
165
+ self.blocks = nn.ModuleList(blocks_list)
166
+
167
+ self.norm = norm_layer(embed_dim)
168
+ self.head = nn.Identity()
169
+
170
+ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
171
+
172
+ self.init_weights()
173
+
174
+ def init_weights(self):
175
+ trunc_normal_(self.pos_embed, std=0.02)
176
+ nn.init.normal_(self.cls_token, std=1e-6)
177
+ if self.register_tokens is not None:
178
+ nn.init.normal_(self.register_tokens, std=1e-6)
179
+ named_apply(init_weights_vit_timm, self)
180
+
181
+ def interpolate_pos_encoding(self, x, w, h):
182
+ previous_dtype = x.dtype
183
+ npatch = x.shape[1] - 1
184
+ N = self.pos_embed.shape[1] - 1
185
+ if npatch == N and w == h:
186
+ return self.pos_embed
187
+ pos_embed = self.pos_embed.float()
188
+ class_pos_embed = pos_embed[:, 0]
189
+ patch_pos_embed = pos_embed[:, 1:]
190
+ dim = x.shape[-1]
191
+ w0 = w // self.patch_size
192
+ h0 = h // self.patch_size
193
+ M = int(math.sqrt(N)) # Recover the number of patches in each dimension
194
+ assert N == M * M
195
+ kwargs = {}
196
+ if self.interpolate_offset:
197
+ # Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8
198
+ # Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors
199
+ sx = float(w0 + self.interpolate_offset) / M
200
+ sy = float(h0 + self.interpolate_offset) / M
201
+ kwargs["scale_factor"] = (sx, sy)
202
+ else:
203
+ # Simply specify an output size instead of a scale factor
204
+ kwargs["size"] = (w0, h0)
205
+ patch_pos_embed = nn.functional.interpolate(
206
+ patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2),
207
+ mode="bicubic",
208
+ antialias=self.interpolate_antialias,
209
+ **kwargs,
210
+ )
211
+ assert (w0, h0) == patch_pos_embed.shape[-2:]
212
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
213
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
214
+
215
+ def prepare_tokens_with_masks(self, x, masks=None):
216
+ B, nc, w, h = x.shape
217
+ x = self.patch_embed(x)
218
+ if masks is not None:
219
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
220
+
221
+ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
222
+ x = x + self.interpolate_pos_encoding(x, w, h)
223
+
224
+ if self.register_tokens is not None:
225
+ x = torch.cat((x[:, :1], self.register_tokens.expand(x.shape[0], -1, -1), x[:, 1:]), dim=1)
226
+
227
+ return x
228
+
229
+ def forward_features_list(self, x_list, masks_list):
230
+ x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
231
+
232
+ for blk in self.blocks:
233
+ if self.training:
234
+ x = checkpoint(blk, x, use_reentrant=self.use_reentrant)
235
+ else:
236
+ x = blk(x)
237
+
238
+ all_x = x
239
+ output = []
240
+ for x, masks in zip(all_x, masks_list):
241
+ x_norm = self.norm(x)
242
+ output.append(
243
+ {
244
+ "x_norm_clstoken": x_norm[:, 0],
245
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
246
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
247
+ "x_prenorm": x,
248
+ "masks": masks,
249
+ }
250
+ )
251
+ return output
252
+
253
+ def forward_features(self, x, masks=None):
254
+ if isinstance(x, list):
255
+ return self.forward_features_list(x, masks)
256
+
257
+ x = self.prepare_tokens_with_masks(x, masks)
258
+
259
+ for blk in self.blocks:
260
+ if self.training:
261
+ x = checkpoint(blk, x, use_reentrant=self.use_reentrant)
262
+ else:
263
+ x = blk(x)
264
+
265
+ x_norm = self.norm(x)
266
+ return {
267
+ "x_norm_clstoken": x_norm[:, 0],
268
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
269
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
270
+ "x_prenorm": x,
271
+ "masks": masks,
272
+ }
273
+
274
+ def _get_intermediate_layers_not_chunked(self, x, n=1):
275
+ x = self.prepare_tokens_with_masks(x)
276
+ # If n is an int, take the n last blocks. If it's a list, take them
277
+ output, total_block_len = [], len(self.blocks)
278
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
279
+ for i, blk in enumerate(self.blocks):
280
+ x = blk(x)
281
+ if i in blocks_to_take:
282
+ output.append(x)
283
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
284
+ return output
285
+
286
+ def _get_intermediate_layers_chunked(self, x, n=1):
287
+ x = self.prepare_tokens_with_masks(x)
288
+ output, i, total_block_len = [], 0, len(self.blocks[-1])
289
+ # If n is an int, take the n last blocks. If it's a list, take them
290
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
291
+ for block_chunk in self.blocks:
292
+ for blk in block_chunk[i:]: # Passing the nn.Identity()
293
+ x = blk(x)
294
+ if i in blocks_to_take:
295
+ output.append(x)
296
+ i += 1
297
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
298
+ return output
299
+
300
+ def get_intermediate_layers(
301
+ self,
302
+ x: torch.Tensor,
303
+ n: Union[int, Sequence] = 1, # Layers or n last layers to take
304
+ reshape: bool = False,
305
+ return_class_token: bool = False,
306
+ norm=True,
307
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
308
+ if self.chunked_blocks:
309
+ outputs = self._get_intermediate_layers_chunked(x, n)
310
+ else:
311
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
312
+ if norm:
313
+ outputs = [self.norm(out) for out in outputs]
314
+ class_tokens = [out[:, 0] for out in outputs]
315
+ outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs]
316
+ if reshape:
317
+ B, _, w, h = x.shape
318
+ outputs = [
319
+ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
320
+ for out in outputs
321
+ ]
322
+ if return_class_token:
323
+ return tuple(zip(outputs, class_tokens))
324
+ return tuple(outputs)
325
+
326
+ def forward(self, *args, is_training=True, **kwargs):
327
+ ret = self.forward_features(*args, **kwargs)
328
+ if is_training:
329
+ return ret
330
+ else:
331
+ return self.head(ret["x_norm_clstoken"])
332
+
333
+
334
+ def init_weights_vit_timm(module: nn.Module, name: str = ""):
335
+ """ViT weight initialization, original timm impl (for reproducibility)"""
336
+ if isinstance(module, nn.Linear):
337
+ trunc_normal_(module.weight, std=0.02)
338
+ if module.bias is not None:
339
+ nn.init.zeros_(module.bias)
340
+
341
+
342
+ def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
343
+ model = DinoVisionTransformer(
344
+ patch_size=patch_size,
345
+ embed_dim=384,
346
+ depth=12,
347
+ num_heads=6,
348
+ mlp_ratio=4,
349
+ block_fn=partial(Block, attn_class=MemEffAttention),
350
+ num_register_tokens=num_register_tokens,
351
+ **kwargs,
352
+ )
353
+ return model
354
+
355
+
356
+ def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
357
+ model = DinoVisionTransformer(
358
+ patch_size=patch_size,
359
+ embed_dim=768,
360
+ depth=12,
361
+ num_heads=12,
362
+ mlp_ratio=4,
363
+ block_fn=partial(Block, attn_class=MemEffAttention),
364
+ num_register_tokens=num_register_tokens,
365
+ **kwargs,
366
+ )
367
+ return model
368
+
369
+
370
+ def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
371
+ model = DinoVisionTransformer(
372
+ patch_size=patch_size,
373
+ embed_dim=1024,
374
+ depth=24,
375
+ num_heads=16,
376
+ mlp_ratio=4,
377
+ block_fn=partial(Block, attn_class=MemEffAttention),
378
+ num_register_tokens=num_register_tokens,
379
+ **kwargs,
380
+ )
381
+ return model
382
+
383
+
384
+ def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
385
+ """
386
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
387
+ """
388
+ model = DinoVisionTransformer(
389
+ patch_size=patch_size,
390
+ embed_dim=1536,
391
+ depth=40,
392
+ num_heads=24,
393
+ mlp_ratio=4,
394
+ block_fn=partial(Block, attn_class=MemEffAttention),
395
+ num_register_tokens=num_register_tokens,
396
+ **kwargs,
397
+ )
398
+ return model
vggt_models_aggregator.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from facebookresearch/vggt, vggt/models/aggregator.py; only the imports are changed (flat module names).
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 file in the root directory of this source tree.
7
+
8
+ import logging
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torch.utils.checkpoint import checkpoint
13
+ from typing import Optional, Tuple, Union, List, Dict, Any
14
+
15
+ from .vggt_layers import PatchEmbed
16
+ from .vggt_layers_block import Block
17
+ from .vggt_layers_rope import RotaryPositionEmbedding2D, PositionGetter
18
+ from .vggt_layers_vision_transformer import vit_small, vit_base, vit_large, vit_giant2
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _RESNET_MEAN = [0.485, 0.456, 0.406]
23
+ _RESNET_STD = [0.229, 0.224, 0.225]
24
+
25
+
26
+ class Aggregator(nn.Module):
27
+ """
28
+ The Aggregator applies alternating-attention over input frames,
29
+ as described in VGGT: Visual Geometry Grounded Transformer.
30
+
31
+ Remember to set model.train() to enable gradient checkpointing to reduce memory usage.
32
+
33
+ Args:
34
+ img_size (int): Image size in pixels.
35
+ patch_size (int): Size of each patch for PatchEmbed.
36
+ embed_dim (int): Dimension of the token embeddings.
37
+ depth (int): Number of blocks.
38
+ num_heads (int): Number of attention heads.
39
+ mlp_ratio (float): Ratio of MLP hidden dim to embedding dim.
40
+ num_register_tokens (int): Number of register tokens.
41
+ block_fn (nn.Module): The block type used for attention (Block by default).
42
+ qkv_bias (bool): Whether to include bias in QKV projections.
43
+ proj_bias (bool): Whether to include bias in the output projection.
44
+ ffn_bias (bool): Whether to include bias in MLP layers.
45
+ patch_embed (str): Type of patch embed. e.g., "conv" or "dinov2_vitl14_reg".
46
+ aa_order (list[str]): The order of alternating attention, e.g. ["frame", "global"].
47
+ aa_block_size (int): How many blocks to group under each attention type before switching. If not necessary, set to 1.
48
+ qk_norm (bool): Whether to apply QK normalization.
49
+ rope_freq (int): Base frequency for rotary embedding. -1 to disable.
50
+ init_values (float): Init scale for layer scale.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ img_size=518,
56
+ patch_size=14,
57
+ embed_dim=1024,
58
+ depth=24,
59
+ num_heads=16,
60
+ mlp_ratio=4.0,
61
+ num_register_tokens=4,
62
+ block_fn=Block,
63
+ qkv_bias=True,
64
+ proj_bias=True,
65
+ ffn_bias=True,
66
+ patch_embed="dinov2_vitl14_reg",
67
+ aa_order=["frame", "global"],
68
+ aa_block_size=1,
69
+ qk_norm=True,
70
+ rope_freq=100,
71
+ init_values=0.01,
72
+ cached_layer_indices: Tuple[int, ...] = (4, 11, 17, 23),
73
+ ):
74
+ super().__init__()
75
+
76
+ self.__build_patch_embed__(patch_embed, img_size, patch_size, num_register_tokens, embed_dim=embed_dim)
77
+
78
+ # Initialize rotary position embedding if frequency > 0
79
+ self.rope = RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None
80
+ self.position_getter = PositionGetter() if self.rope is not None else None
81
+
82
+ self.frame_blocks = nn.ModuleList(
83
+ [
84
+ block_fn(
85
+ dim=embed_dim,
86
+ num_heads=num_heads,
87
+ mlp_ratio=mlp_ratio,
88
+ qkv_bias=qkv_bias,
89
+ proj_bias=proj_bias,
90
+ ffn_bias=ffn_bias,
91
+ init_values=init_values,
92
+ qk_norm=qk_norm,
93
+ rope=self.rope,
94
+ )
95
+ for _ in range(depth)
96
+ ]
97
+ )
98
+
99
+ self.global_blocks = nn.ModuleList(
100
+ [
101
+ block_fn(
102
+ dim=embed_dim,
103
+ num_heads=num_heads,
104
+ mlp_ratio=mlp_ratio,
105
+ qkv_bias=qkv_bias,
106
+ proj_bias=proj_bias,
107
+ ffn_bias=ffn_bias,
108
+ init_values=init_values,
109
+ qk_norm=qk_norm,
110
+ rope=self.rope,
111
+ )
112
+ for _ in range(depth)
113
+ ]
114
+ )
115
+
116
+ self.depth = depth
117
+ self.aa_order = aa_order
118
+ self.patch_size = patch_size
119
+ self.aa_block_size = aa_block_size
120
+ self.cached_layer_indices = set(cached_layer_indices)
121
+ self.cached_layer_indices.add(depth - 1)
122
+
123
+ # Validate that depth is divisible by aa_block_size
124
+ if self.depth % self.aa_block_size != 0:
125
+ raise ValueError(f"depth ({depth}) must be divisible by aa_block_size ({aa_block_size})")
126
+
127
+ self.aa_block_num = self.depth // self.aa_block_size
128
+
129
+ # Note: We have two camera tokens, one for the first frame and one for the rest
130
+ # The same applies for register tokens
131
+ self.camera_token = nn.Parameter(torch.randn(1, 2, 1, embed_dim))
132
+ self.register_token = nn.Parameter(torch.randn(1, 2, num_register_tokens, embed_dim))
133
+
134
+ # The patch tokens start after the camera and register tokens
135
+ self.patch_start_idx = 1 + num_register_tokens
136
+
137
+ # Initialize parameters with small values
138
+ nn.init.normal_(self.camera_token, std=1e-6)
139
+ nn.init.normal_(self.register_token, std=1e-6)
140
+
141
+ # Register normalization constants as buffers
142
+ for name, value in (("_resnet_mean", _RESNET_MEAN), ("_resnet_std", _RESNET_STD)):
143
+ self.register_buffer(name, torch.FloatTensor(value).view(1, 1, 3, 1, 1), persistent=False)
144
+
145
+ self.use_reentrant = False # hardcoded to False
146
+
147
+ def __build_patch_embed__(
148
+ self,
149
+ patch_embed,
150
+ img_size,
151
+ patch_size,
152
+ num_register_tokens,
153
+ interpolate_antialias=True,
154
+ interpolate_offset=0.0,
155
+ block_chunks=0,
156
+ init_values=1.0,
157
+ embed_dim=1024,
158
+ ):
159
+ """
160
+ Build the patch embed layer. If 'conv', we use a
161
+ simple PatchEmbed conv layer. Otherwise, we use a vision transformer.
162
+ """
163
+
164
+ if "conv" in patch_embed:
165
+ self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=3, embed_dim=embed_dim)
166
+ else:
167
+ vit_models = {
168
+ "dinov2_vitl14_reg": vit_large,
169
+ "dinov2_vitb14_reg": vit_base,
170
+ "dinov2_vits14_reg": vit_small,
171
+ "dinov2_vitg2_reg": vit_giant2,
172
+ }
173
+
174
+ self.patch_embed = vit_models[patch_embed](
175
+ img_size=img_size,
176
+ patch_size=patch_size,
177
+ num_register_tokens=num_register_tokens,
178
+ interpolate_antialias=interpolate_antialias,
179
+ interpolate_offset=interpolate_offset,
180
+ block_chunks=block_chunks,
181
+ init_values=init_values,
182
+ )
183
+
184
+ # Disable gradient updates for mask token
185
+ if hasattr(self.patch_embed, "mask_token"):
186
+ self.patch_embed.mask_token.requires_grad_(False)
187
+
188
+ def forward(self, images: torch.Tensor) -> Tuple[List[Optional[torch.Tensor]], int]:
189
+ """
190
+ Args:
191
+ images (torch.Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1].
192
+ B: batch size, S: sequence length, 3: RGB channels, H: height, W: width
193
+
194
+ Returns:
195
+ (list[torch.Tensor | None], int):
196
+ The list of cached outputs from the attention blocks. Entries for
197
+ uncached layers are None so layer indices remain stable.
198
+ and the patch_start_idx indicating where patch tokens begin.
199
+ """
200
+ B, S, C_in, H, W = images.shape
201
+
202
+ if C_in != 3:
203
+ raise ValueError(f"Expected 3 input channels, got {C_in}")
204
+
205
+ # Normalize images and reshape for patch embed
206
+ images = (images - self._resnet_mean) / self._resnet_std
207
+
208
+ # Reshape to [B*S, C, H, W] for patch embedding
209
+ images = images.view(B * S, C_in, H, W)
210
+ patch_tokens = self.patch_embed(images)
211
+
212
+ if isinstance(patch_tokens, dict):
213
+ patch_tokens = patch_tokens["x_norm_patchtokens"]
214
+
215
+ _, P, C = patch_tokens.shape
216
+
217
+ # Expand camera and register tokens to match batch size and sequence length
218
+ camera_token = slice_expand_and_flatten(self.camera_token, B, S)
219
+ register_token = slice_expand_and_flatten(self.register_token, B, S)
220
+
221
+ # Concatenate special tokens with patch tokens
222
+ tokens = torch.cat([camera_token, register_token, patch_tokens], dim=1)
223
+
224
+ pos = None
225
+ if self.rope is not None:
226
+ pos = self.position_getter(B * S, H // self.patch_size, W // self.patch_size, device=images.device)
227
+
228
+ if self.patch_start_idx > 0:
229
+ # do not use position embedding for special tokens (camera and register tokens)
230
+ # so set pos to 0 for the special tokens
231
+ pos = pos + 1
232
+ pos_special = torch.zeros(B * S, self.patch_start_idx, 2).to(images.device).to(pos.dtype)
233
+ pos = torch.cat([pos_special, pos], dim=1)
234
+
235
+ # update P because we added special tokens
236
+ _, P, C = tokens.shape
237
+
238
+ frame_idx = 0
239
+ global_idx = 0
240
+ output_list = []
241
+
242
+ for _ in range(self.aa_block_num):
243
+ for attn_type in self.aa_order:
244
+ if attn_type == "frame":
245
+ tokens, frame_idx, frame_intermediates = self._process_frame_attention(
246
+ tokens, B, S, P, C, frame_idx, pos=pos
247
+ )
248
+ elif attn_type == "global":
249
+ tokens, global_idx, global_intermediates = self._process_global_attention(
250
+ tokens, B, S, P, C, global_idx, pos=pos
251
+ )
252
+ else:
253
+ raise ValueError(f"Unknown attention type: {attn_type}")
254
+
255
+ for i in range(len(frame_intermediates)):
256
+ layer_idx = len(output_list)
257
+ if layer_idx in self.cached_layer_indices:
258
+ # concat frame and global intermediates, [B x S x P x 2C]
259
+ concat_inter = torch.cat([frame_intermediates[i], global_intermediates[i]], dim=-1)
260
+ output_list.append(concat_inter)
261
+ else:
262
+ output_list.append(None)
263
+
264
+ del frame_intermediates
265
+ del global_intermediates
266
+ return output_list, self.patch_start_idx
267
+
268
+ def _process_frame_attention(self, tokens, B, S, P, C, frame_idx, pos=None):
269
+ """
270
+ Process frame attention blocks. We keep tokens in shape (B*S, P, C).
271
+ """
272
+ # If needed, reshape tokens or positions:
273
+ if tokens.shape != (B * S, P, C):
274
+ tokens = tokens.view(B, S, P, C).view(B * S, P, C)
275
+
276
+ if pos is not None and pos.shape != (B * S, P, 2):
277
+ pos = pos.view(B, S, P, 2).view(B * S, P, 2)
278
+
279
+ intermediates = []
280
+
281
+ # by default, self.aa_block_size=1, which processes one block at a time
282
+ for _ in range(self.aa_block_size):
283
+ if self.training:
284
+ tokens = checkpoint(self.frame_blocks[frame_idx], tokens, pos, use_reentrant=self.use_reentrant)
285
+ else:
286
+ tokens = self.frame_blocks[frame_idx](tokens, pos=pos)
287
+ frame_idx += 1
288
+ intermediates.append(tokens.view(B, S, P, C))
289
+
290
+ return tokens, frame_idx, intermediates
291
+
292
+ def _process_global_attention(self, tokens, B, S, P, C, global_idx, pos=None):
293
+ """
294
+ Process global attention blocks. We keep tokens in shape (B, S*P, C).
295
+ """
296
+ if tokens.shape != (B, S * P, C):
297
+ tokens = tokens.view(B, S, P, C).view(B, S * P, C)
298
+
299
+ if pos is not None and pos.shape != (B, S * P, 2):
300
+ pos = pos.view(B, S, P, 2).view(B, S * P, 2)
301
+
302
+ intermediates = []
303
+
304
+ # by default, self.aa_block_size=1, which processes one block at a time
305
+ for _ in range(self.aa_block_size):
306
+ if self.training:
307
+ tokens = checkpoint(self.global_blocks[global_idx], tokens, pos, use_reentrant=self.use_reentrant)
308
+ else:
309
+ tokens = self.global_blocks[global_idx](tokens, pos=pos)
310
+ global_idx += 1
311
+ intermediates.append(tokens.view(B, S, P, C))
312
+
313
+ return tokens, global_idx, intermediates
314
+
315
+
316
+ def slice_expand_and_flatten(token_tensor, B, S):
317
+ """
318
+ Processes specialized tokens with shape (1, 2, X, C) for multi-frame processing:
319
+ 1) Uses the first position (index=0) for the first frame only
320
+ 2) Uses the second position (index=1) for all remaining frames (S-1 frames)
321
+ 3) Expands both to match batch size B
322
+ 4) Concatenates to form (B, S, X, C) where each sequence has 1 first-position token
323
+ followed by (S-1) second-position tokens
324
+ 5) Flattens to (B*S, X, C) for processing
325
+
326
+ Returns:
327
+ torch.Tensor: Processed tokens with shape (B*S, X, C)
328
+ """
329
+
330
+ # Slice out the "query" tokens => shape (1, 1, ...)
331
+ query = token_tensor[:, 0:1, ...].expand(B, 1, *token_tensor.shape[2:])
332
+ # Slice out the "other" tokens => shape (1, S-1, ...)
333
+ others = token_tensor[:, 1:, ...].expand(B, S - 1, *token_tensor.shape[2:])
334
+ # Concatenate => shape (B, S, ...)
335
+ combined = torch.cat([query, others], dim=1)
336
+
337
+ # Finally flatten => shape (B*S, ...)
338
+ combined = combined.view(B * S, *combined.shape[2:])
339
+ return combined