Video-Text-to-Text
Transformers
Safetensors
spacetimevlm
feature-extraction
spatial-reasoning
3d
video
multimodal
vggt
qwen3.5
custom_code
Run this model with HF Jobs
Run DarioVajda/SpaceTimeVLM-2B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/DarioVajda/SpaceTimeVLM-2B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/DarioVajda/SpaceTimeVLM-2B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use DarioVajda/SpaceTimeVLM-2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use DarioVajda/SpaceTimeVLM-2B with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("DarioVajda/SpaceTimeVLM-2B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add SpaceTimeVLM-2B
Browse filesFiles changed (30)
- .gitattributes+1
- LICENSEAdded+9
- LICENSE-QWENAdded+202
- LICENSE-VGGTAdded+115
- README.mdAdded+102
- chat_template.jinjaAdded+154
- config.jsonAdded+137
- configuration_spacetimevlm.pyAdded+44
- generation_config.jsonAdded+9
- model-00001-of-00002.safetensorsAdded+3
- model-00002-of-00002.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- modeling_spacetimevlm.pyAdded+456
- processor_config.jsonAdded+61
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+51
- vggt_heads_dpt_head.pyAdded+485
- vggt_heads_head_act.pyAdded+126
- vggt_heads_utils.pyAdded+110
- vggt_layers.pyAdded+12
- vggt_layers_attention.pyAdded+94
- vggt_layers_block.pyAdded+248
- vggt_layers_drop_path.pyAdded+35
- vggt_layers_layer_scale.pyAdded+23
- vggt_layers_mlp.pyAdded+41
- vggt_layers_patch_embed.pyAdded+86
- vggt_layers_rope.pyAdded+189
- vggt_layers_swiglu_ffn.pyAdded+68
- vggt_layers_vision_transformer.pyAdded+398
- vggt_models_aggregator.pyAdded+339
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789SpaceTimeVLM model weights and code
The model as a whole is licensed under the Creative Commons Attribution-NonCommercial 4.0 International license(CC BY-NC 4.0): https://creativecommons.org/licenses/by-nc/4.0/legalcode
It contains components under their own licenses: - Qwen3.5 (weights, tokenizer and processor files): Apache License 2.0, see LICENSE-QWEN. - VGGT (vggt_*.py, copied from https://github.com/facebookresearch/vggt with only their imports changed): VGGT License, see LICENSE-VGGT. The VGGT-1B weights are released by Meta for non-commercial use.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Alibaba Cloud
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115VGGT License
v1 Last Updated: July 29, 2025
“Acceptable Use Policy” means the Acceptable Use Policy, applicable to Research Materials, that is incorporated into this Agreement.
“Agreement” means the terms and conditions for use, reproduction, distribution and modification of the Research Materials set forth herein.
“Documentation” means the specifications, manuals and documentation accompanying Research Materials distributed by Meta.
“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.
“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).“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.
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.
1. License Rights and Redistribution.
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. b. Redistribution and Use.
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.
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.
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.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.
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. 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. 5. Intellectual Property.
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. 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. 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. 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.
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.
Acceptable Use Policy
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.
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.
Prohibited Uses
You agree you will not use, or allow others to use, Research Materials to:
Violate the law or others’ rights, including to:Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:Violence or terrorismExploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse MaterialHuman trafficking, exploitation, and sexual violenceThe 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.Sexual solicitationAny other criminal activity
Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
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
Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
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
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
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
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:
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
Guns and illegal weapons (including weapon development)
Illegal drugs and regulated/controlled substancesOperation of critical infrastructure, transportation technologies, or heavy machinery
Self-harm or harm to others, including suicide, cutting, and eating disordersAny content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
3. Intentionally deceive or mislead others, including use of Research Materials related to the following:
Generating, promoting, or furthering fraud or the creation or promotion of disinformation Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
Generating, promoting, or further distributing spam
Impersonating another individual without consent, authorization, or legal right
Representing that outputs of research materials or outputs from technology using Research Materials are human-generated
Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
4. Fail to appropriately disclose to end users any known dangers of your Research Materials.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102---license: cc-by-nc-4.0library_name: transformerspipeline_tag: video-text-to-textbase_model:- Qwen/Qwen3.5-2B- facebook/VGGT-1Btags:- spatial-reasoning- 3d- video- multimodal- vggt- qwen3.5---
# SpaceTimeVLM-2B
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)with the frozen geometry encoder of [VGGT-1B](https://huggingface.co/facebook/VGGT-1B) read through a 3D-awarecross-attention:
1. Qwen3.5's vision encoder turns each frame into visual tokens (one per 28 x 28 px cell).2. VGGT-1B runs on the same frames. Its point head gives a 3D point per pixel, which is averaged per cell, so every visual token gets a position in the scene.3. After decoder layers 0, 1 and 2, every visual token attends over the geometry tokens of all frames (VGGT layers 11, 17 and 23, one token per cell), with a rotary embedding on (frame, x, y, z) and a learned 3D-distance bias. The result is added to the visual token.
The language model was fine-tuned with LoRA (merged into the weights here); the mergers and the cross-attention weretrained from scratch; VGGT is unchanged. VSI-Bench: **69.22** (32 frames).
## Usage
```pythonfrom transformers import AutoModel
model = AutoModel.from_pretrained("DarioVajda/SpaceTimeVLM-2B", trust_remote_code=True, device_map="cuda")print(model.chat("room.mp4", "How many chairs are in this room?"))```
`chat` takes a video file, a directory of frames, or a list of images (paths or PIL images), and one question or alist of questions about the same video (answered in one batch). It samples 32 uniformly spaced frames by default(`num_frames=...`). Answers are greedy; `max_new_tokens` defaults to 256. For full control, `model.prepare(frames,questions)` builds the inputs and `model.answer(batch, **generate_kwargs)` decodes them.
The benchmark scores below use the lmms-eval prompts, for example for VSI-Bench:
```pythonq = "These are frames of a video.\nHow many chairs are in this room?\nPlease answer the question using a single word or phrase."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."```
**Requirements:** a CUDA GPU, `transformers==5.20.1` (the version it was tested with), `torch`, `torchvision`, and`decord` or `av` to read videos. Install `flash-linear-attention` and `causal-conv1d` for Qwen3.5's fast linear-attentionkernels; without them it falls back to a slow PyTorch path. Qwen3.5 runs in bfloat16; VGGT and the cross-attentionkeep float32 weights and run under bfloat16 autocast, as in training.
## Results
Results across six spatial benchmarks (%). Avg. is the mean of the six overall scores. Higher is better. **Bold** and<u>underlined</u> mark the best and second best results in each column.
| Model | Avg. | VSI-Bench | MMSI-Bench | MindCube | ViewSpatial | SITE | CV-Bench ||---|---:|---:|---:|---:|---:|---:|---:|| Qwen2.5-VL-7B | 40.31 | 29.30 | 26.80 | 36.00 | 36.80 | 37.60 | 75.40 || Qwen3-VL-8B | 47.73 | 57.90 | 28.80 | 29.80 | 39.00 | 45.80 | 85.10 || Qwen3.5-2B | 42.83 | 45.72 | 26.30 | 34.86 | 36.28 | 31.45 | 82.34 || Qwen3.5-4B | 50.36 | 53.00 | 31.80 | 44.67 | 40.22 | 45.36 | 87.11 || Qwen3.5-9B | 52.87 | 60.80 | 31.90 | 44.10 | 44.07 | 48.27 | 88.06 || Qwen3.5-35B-A3B | 55.18 | 63.79 | <u>34.60</u> | 39.81 | 47.79 | 56.09 | **89.01** || | | | | | | | || Cambrian-S-7B | 47.28 | 67.50 | 25.80 | 39.60 | 40.90 | 33.00 | 76.90 || VLM-3R-7B | 45.40 | 60.90 | 27.90 | 40.00 | 40.50 | 31.30 | 71.80 || VG-LLM-8B | 51.05 | 62.20 | 30.00 | 36.10 | 45.80 | 50.50 | 81.70 || GeoThinker-7B | 60.43 | 68.50 | 31.70 | 83.60 | 41.90 | 54.80 | 82.10 || GeoThinker-8B | 62.23 | 72.60 | 30.90 | 83.00 | 45.90 | 55.90 | 85.10 || DK-VLM-7B | 60.84 | 69.42 | 29.95 | 83.81 | 44.98 | <u>57.47</u> | 79.38 || DK-VLM-8B | 64.09 | **74.33** | 30.79 | 83.83 | <u>51.25</u> | **59.81** | 84.52 || | | | | | | | || ➡️ **SpaceTimeVLM-2B (this model)** | 57.85 | 69.22 | 27.40 | 90.95 | 46.44 | 34.40 | 78.67 || SpaceTimeVLM-4B | 61.94 | 71.97 | 30.60 | 92.57 | 47.23 | 44.74 | 84.54 || SpaceTimeVLM-9B | <u>64.50</u> | <u>73.29</u> | 32.20 | <u>94.19</u> | 49.66 | 50.56 | 87.08 || SpaceTimeVLM-35B-A3B | **66.95** | 73.22 | **35.90** | **94.95** | **53.77** | 55.54 | <u>88.31</u> |
## Training
- Base: Qwen/Qwen3.5-2B (revision `15852e8c1636`), VGGT-1B (revision `860abec7937d`, frozen).- LoRA rank 64, alpha 128 on all linear layers of the language model; the vision encoder is frozen.- 500k question-answer pairs over videos and image sets (spatial and general video understanding), with 8, 16 or 32 frames per sample (60 / 30 / 10 %); 17,201 steps (warmup-stable-decay schedule).
## License and credits
This model combines:- [Qwen3.5](https://huggingface.co/Qwen/Qwen3.5-2B) by the Qwen team (Apache 2.0, `LICENSE-QWEN`);- [VGGT](https://github.com/facebookresearch/vggt) by Meta (the code is under the VGGT License, `LICENSE-VGGT`; the VGGT-1B weights are released for non-commercial use). The VGGT modules in `vggt_*.py` are copied from the VGGT repository with only their imports changed.
Because of the VGGT weights, the model as a whole is released under[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/) (non-commercial use only).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- macro render_content(content, do_vision_count, is_system_content=false) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain images.') }} {%- endif %} {%- if do_vision_count %} {%- set image_count.value = image_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Picture ' ~ image_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|image_pad|><|vision_end|>' }} {%- elif 'video' in item or item.type == 'video' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain videos.') }} {%- endif %} {%- if do_vision_count %} {%- set video_count.value = video_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Video ' ~ video_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|video_pad|><|vision_end|>' }} {%- elif 'text' in item %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type.') }} {%- endif %}{%- endmacro %}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %} {{- '<|im_start|>system\n' }} {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>" }} {{- '\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>' }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- else %} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set content = render_content(message.content, false)|trim %} {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}{%- if ns.multi_step_tool %} {{- raise_exception('No user query found in messages.') }}{%- endif %}{%- for message in messages %} {%- set content = render_content(message.content, true)|trim %} {%- if message.role == "system" %} {%- if not loop.first %} {{- raise_exception('System message must be at the beginning.') }} {%- endif %} {%- elif message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- set reasoning_content = reasoning_content|trim %} {%- if loop.index0 > ns.last_query_index %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {%- if loop.first %} {%- if content|trim %} {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- else %} {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- else %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- if tool_call.arguments is defined %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- 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 %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- raise_exception('Unexpected message role.') }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is true %} {{- '<think>\n' }} {%- else %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{ "architectures": [ "SpaceTimeVLMForConditionalGeneration" ], "auto_map": { "AutoConfig": "configuration_spacetimevlm.SpaceTimeVLMConfig", "AutoModel": "modeling_spacetimevlm.SpaceTimeVLMForConditionalGeneration", "AutoModelForImageTextToText": "modeling_spacetimevlm.SpaceTimeVLMForConditionalGeneration" }, "dtype": "bfloat16", "geometry": { "bias_nu": [ 0.1, 6.0 ], "fusion_after": [ 0, 1, 2 ], "local_bias": true, "max_pixels": 1605632, "merger_hidden": 4096, "min_pixels": 200704, "num_frames": 32, "pe_dmax": 10.0, "rope3": true, "theta": 100.0, "train_frames": 8, "vggt_dim": 2048, "vggt_embed_dim": 1024, "vggt_img_size": 518, "vggt_layers": [ 11, 17, 23 ], "vggt_patch_size": 14 }, "image_token_id": 248056, "model_type": "spacetimevlm", "text_config": { "attention_bias": false, "attention_dropout": 0.0, "attn_output_gate": true, "bos_token_id": null, "dtype": "bfloat16", "eos_token_id": 248044, "full_attention_interval": 4, "head_dim": 256, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 6144, "layer_types": [ "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention" ], "linear_conv_kernel_dim": 4, "linear_key_head_dim": 128, "linear_num_key_heads": 16, "linear_num_value_heads": 16, "linear_value_head_dim": 128, "mamba_ssm_dtype": "float32", "max_position_embeddings": 262144, "mlp_only_layers": [], "model_type": "qwen3_5_text", "mtp_num_hidden_layers": 1, "mtp_use_dedicated_embeddings": false, "num_attention_heads": 8, "num_hidden_layers": 24, "num_key_value_heads": 2, "pad_token_id": null, "rms_norm_eps": 1e-06, "rope_parameters": { "mrope_interleaved": true, "mrope_section": [ 11, 11, 10 ], "partial_rotary_factor": 0.25, "rope_theta": 10000000, "rope_type": "default" }, "tie_word_embeddings": true, "use_cache": true, "vocab_size": 248320 }, "tie_word_embeddings": true, "transformers_version": "5.20.1", "video_token_id": 248057, "vision_config": { "deepstack_visual_indexes": [], "depth": 24, "hidden_act": "gelu_pytorch_tanh", "hidden_size": 1024, "in_channels": 3, "initializer_range": 0.02, "intermediate_size": 4096, "model_type": "qwen3_5_vision", "num_heads": 16, "num_position_embeddings": 2304, "out_hidden_size": 2048, "patch_size": 16, "rope_parameters": { "rope_theta": 10000.0, "rope_type": "axial" }, "spatial_merge_size": 2, "temporal_patch_size": 2 }, "vision_end_token_id": 248054, "vision_start_token_id": 248053}1234567891011121314151617181920212223242526272829303132333435363738394041424344"""SpaceTimeVLM configuration: a Qwen3.5 configuration plus the geometry branch (VGGT-1B and the 3D cross-attention).
The dense models (2B, 4B, 9B) extend Qwen3_5Config, the mixture-of-experts model (35B-A3B) Qwen3_5MoeConfig. Allgeometry settings are in one dict, `geometry`; the defaults below are the released models' settings."""from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Configfrom transformers.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeConfig
GEOMETRY_DEFAULTS = { "vggt_layers": [11, 17, 23], # VGGT aggregator layers read by the cross-attention, paired in order with "fusion_after": [0, 1, 2], # the decoder layers whose output receives them "vggt_img_size": 518, # VGGT-1B's aggregator settings "vggt_patch_size": 14, "vggt_embed_dim": 1024, "vggt_dim": 2048, # aggregator output width (frame + global attention, concatenated) "merger_hidden": 4096, # geometry merger: 2x2 VGGT patches -> hidden -> LLM width "rope3": True, # 3D RoPE on (frame, x, y, z) in the cross-attention "local_bias": True, # learned 3D-distance attention bias "bias_nu": [0.1, 6.0], # its initial slopes (log-spaced over the heads); the learned ones are in the weights "pe_dmax": 10.0, # distance clip, in merged-cell units "train_frames": 8, # frames per video in training: the frame axis of RoPE is rescaled to this range "theta": 100.0, # RoPE base of the frame axis "min_pixels": 256 * 28 * 28, # evaluation pixel limits per frame (Qwen image processor) "max_pixels": 1605632, "num_frames": 32, # frames sampled per video by default (the evaluation setting)}
class SpaceTimeVLMConfig(Qwen3_5Config): model_type = "spacetimevlm" geometry: dict | None = None
def __post_init__(self, **kwargs): self.geometry = {**GEOMETRY_DEFAULTS, **(self.geometry or {})} super().__post_init__(**kwargs)
class SpaceTimeVLMMoeConfig(Qwen3_5MoeConfig): model_type = "spacetimevlm_moe" geometry: dict | None = None
def __post_init__(self, **kwargs): self.geometry = {**GEOMETRY_DEFAULTS, **(self.geometry or {})} super().__post_init__(**kwargs)123456789{ "do_sample": false, "eos_token_id": [ 248046, 248044 ], "pad_token_id": 248044, "transformers_version": "5.20.1"}123version https://git-lfs.github.com/spec/v1oid sha256:6e23b1f9a68daacc71157a80a2215ba3ff57bfe541493626b1041de0f9bae76dsize 4989000144123version https://git-lfs.github.com/spec/v1oid sha256:d893b373639bf27d313aaac358cdcd174aadb36ffe0d423d7f637b9e37eca3a7size 3909621376123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456"""SpaceTimeVLM: Qwen3.5 with 3D geometry from VGGT-1B, read through cross-attention after the first decoder layers.
For one video (a list of frames): 1. Qwen3.5's vision encoder turns each frame into visual tokens (one per 28 x 28 px cell); 2. VGGT-1B's aggregator runs on the same frames (resized to the same cell grid); its point head gives a 3D point per pixel, averaged per cell and rescaled so that one unit is about one cell on a typical surface; 3. after decoder layers 0, 1 and 2, every visual token attends over geometry tokens of all frames (VGGT layers 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 the result is added to the visual token.
Usage: model = AutoModel.from_pretrained("DarioVajda/SpaceTimeVLM-2B", trust_remote_code=True, device_map="cuda") model.chat("room.mp4", "How many chairs are in the room?")
VGGT and the cross-attention run in float32 weights under bfloat16 autocast, as in training; Qwen3.5 runs in bfloat16."""import importlibimport mathimport osfrom dataclasses import dataclass
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom PIL import Imagefrom transformers import AutoProcessorfrom transformers.modeling_outputs import BaseModelOutputWithPoolingfrom transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForConditionalGenerationfrom transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeForConditionalGeneration
from .configuration_spacetimevlm import SpaceTimeVLMConfig, SpaceTimeVLMMoeConfigfrom .vggt_heads_dpt_head import DPTHeadfrom .vggt_models_aggregator import _RESNET_MEAN, _RESNET_STD, Aggregator
SYSTEM_PROMPT = "You are a helpful assistant."VGGT_PATCH = 14IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png")
# ---- frames ----def _indices(n, k): """k uniformly spaced indices of n (all of them if n <= k).""" return np.arange(n) if n <= k else np.linspace(0, n - 1, k).astype(int)
def load_frames(video, num_frames=32): """k uniformly spaced frames as RGB PIL images, from a video file (decord, or PyAV if decord is not installed or fails), a directory of frame images (sorted by name), a list of image paths or a list of PIL images.""" if isinstance(video, (list, tuple)): items = [v if isinstance(v, Image.Image) else Image.open(v) for v in (video[i] for i in _indices(len(video), num_frames))] return [im.convert("RGB") for im in items] video = str(video) if os.path.isdir(video): paths = sorted(os.path.join(video, p) for p in os.listdir(video) if p.lower().endswith(IMAGE_SUFFIXES)) assert paths, f"no images in {video}" return [Image.open(paths[i]).convert("RGB") for i in _indices(len(paths), num_frames)] # decord and PyAV are optional (imported by name, so that transformers does not require them for remote code) try: decord = importlib.import_module("decord") vr = decord.VideoReader(video, ctx=decord.cpu(0)) idx = _indices(len(vr), num_frames) return [Image.fromarray(f) for f in vr.get_batch(idx.tolist()).asnumpy()] except Exception: # decord missing, or its decoder fails on this file (some VP9 videos) av = importlib.import_module("av") with av.open(video) as c: n = sum(1 for _ in c.decode(video=0)) assert n, f"no frames in {video}" want, out = set(_indices(n, num_frames).tolist()), {} with av.open(video) as c: for i, f in enumerate(c.decode(video=0)): if i in want: out[i] = f.to_image().convert("RGB") return [out[i] for i in sorted(want)]
# ---- 3D points of the merged cells (VGGT point head) ----@dataclassclass ScenePoints: xyz: torch.Tensor # [N, 3] float32, cell units, first camera's frame low: torch.Tensor # [N] bool, low-confidence cells dist: torch.Tensor # [N, N] float32, clipped 3D distance between cells, low-confidence keys at d_max scale: float # VGGT units per cell
CONF_FLOOR = 1 + 1e-6 # cell confidence at or below this: every pixel of the cell at VGGT's confidence floor
def pairwise_dist(xyz, block=16384): """Exact Euclidean distances [N, N], in blocks (one cdist over more than 65,535 points exceeds a CUDA limit).""" return torch.cat([torch.cat([torch.cdist(xyz[i:i + block], xyz[j:j + block], compute_mode="donot_use_mm_for_euclid_dist") for j in range(0, len(xyz), block)], 1) for i in range(0, len(xyz), block)])
def cell_points(points, conf, grid, d_max=10.0, patch=14, merge=2, low_q=0.1): """points [T, H, W, 3], conf [T, H, W] of one video (VGGT point head); grid: image_grid_thw [T, 3] in patches. Per merged cell (2 x 2 patches, one visual token): the mean point, rescaled by the median distance between horizontally adjacent confident cells; cells at the confidence floor or below the 10th percentile are low.""" cell = patch * merge xyz, cconf, pairs = [], [], [] for t, (_, h, w) in enumerate(grid.tolist()): hc, wc = h // merge, w // merge p = points[t, :hc * cell, :wc * cell].float().reshape(hc, cell, wc, cell, 3).mean((1, 3)) c = conf[t, :hc * cell, :wc * cell].float().reshape(hc, cell, wc, cell).mean((1, 3)) xyz.append(p.reshape(-1, 3)) cconf.append(c.reshape(-1)) pairs.append((p, c)) xyz, cconf = torch.cat(xyz), torch.cat(cconf) floor = cconf <= CONF_FLOOR rest = cconf[~floor] thr = torch.quantile(rest, low_q) if len(rest) else cconf.new_tensor(float("inf")) low = floor | (cconf < thr) gaps = [] for p, c in pairs: good = (c > CONF_FLOOR) & (c >= thr) ok = good[:, :-1] & good[:, 1:] gaps.append((p[:, 1:] - p[:, :-1]).norm(dim=-1)[ok]) gaps = torch.cat(gaps) scale = (gaps.median() if len(gaps) else (xyz[1:] - xyz[:-1]).norm(dim=-1).median()).clamp_min(1e-6) xyz = xyz / scale dist = pairwise_dist(xyz).clamp_max(d_max) dist[:, low] = d_max dist.fill_diagonal_(0.0) return ScenePoints(xyz=xyz, low=low, dist=dist, scale=scale.item())
# ---- geometry modules ----class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x): x32 = x.float() return (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight
class GeometryMerger(nn.Module): """VGGT patch tokens of one frame [h, w, in_dim] -> one geometry token per 2x2 window [(h/2)*(w/2), out_dim], in the row-major order of Qwen's merged visual tokens: RMSNorm, 2x2 concat, MLP."""
def __init__(self, in_dim=2048, hidden=4096, out_dim=2048, merge=2): super().__init__() self.merge = merge self.ln = RMSNorm(in_dim) self.mlp = nn.Sequential(nn.Linear(in_dim * merge * merge, hidden), nn.GELU(), nn.Linear(hidden, out_dim))
def forward(self, grid): h, w, c = grid.shape m = self.merge 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))
def per_head(init, heads): if isinstance(init, (int, float)): return torch.full((heads,), float(init)) lo, hi = init return torch.logspace(math.log10(lo), math.log10(hi), heads)
class AlignedXAttn(nn.Module): """Visual tokens (queries) attend over the geometry tokens of the whole video (keys / values):
out = W_o softmax(Q K^T / sqrt(d) - nu_h * min(|xyz_i - xyz_j|, d_max)) V
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 any number of frames on the training range, x, y, z in cell units with wavelengths 1.5 to 100 cells. The update is added to the visual tokens only."""
AXES_3D = (8, 8, 8, 8) W3D = (1.5, 100.0) QUERY_CHUNK = 4096 # query rows per attention call on long videos
def __init__(self, dim, heads, rope=True, local_bias=True, train_frames=8, theta=100.0, nu=1.5): super().__init__() self.heads, self.head_dim = heads, dim // heads self.rope, self.local_bias, self.train_frames, self.theta = rope, local_bias, train_frames, theta self.norm_q, self.norm_kv = nn.LayerNorm(dim), nn.LayerNorm(dim) self.q, self.k, self.v, self.o = (nn.Linear(dim, dim, bias=False) for _ in range(4)) if local_bias: self.nu = nn.Parameter(per_head(nu, heads)) if rope: assert 2 * sum(self.AXES_3D) <= self.head_dim, (self.AXES_3D, self.head_dim) axis, freq = self.rope_tables() self.register_buffer("rope_axis", axis, persistent=False) self.register_buffer("rope_freq", freq, persistent=False)
def rope_tables(self, device=None): """(axis index, frequency) of each rotary pair. Constants: not in the weights, rebuilt on load.""" n_t, n_s = self.AXES_3D[0], self.AXES_3D[1] axis = torch.cat([torch.full((n,), a) for a, n in enumerate(self.AXES_3D)]) w = torch.logspace(math.log10(self.W3D[0]), math.log10(self.W3D[1]), n_s) freq = torch.cat([self.theta ** (-torch.arange(n_t, dtype=torch.float) / n_t)] + [2 * math.pi / w] * 3) return axis.to(device), freq.to(device)
@staticmethod def positions(grid, merge=2): """(t, r, c) of the merged visual tokens of one video, in token order: [N, 3].""" out = [] for t, (_, h, w) in enumerate(grid.tolist()): r, c = torch.meshgrid(torch.arange(h // merge), torch.arange(w // merge), indexing="ij") out.append(torch.stack([torch.full_like(r, t), r, c], -1).reshape(-1, 3)) return torch.cat(out).to(grid.device)
def rotary(self, pos, pts): T = int(pos[:, 0].max()) + 1 p = pos.float() p[:, 0] = p[:, 0] * (self.train_frames - 1) / max(T - 1, 1) p = torch.cat([p[:, :1], pts.xyz.float()], 1) ang = p[:, self.rope_axis] * self.rope_freq return ang.cos(), ang.sin()
@staticmethod def apply_rotary(x, cos, sin): n = cos.shape[-1] x1, x2, rest = x[..., :n], x[..., n:2 * n], x[..., 2 * n:] cos, sin = cos.to(x.dtype), sin.to(x.dtype) return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin, rest], -1)
def bias(self, dtype, pts, rows=slice(None)): return -(self.nu[:, None, None] * pts.dist[rows])[None].to(dtype)
def keys(self, g, pos, pts): """Rotated keys and values of the geometry tokens g [N, D]: [1, H, N, d] each.""" split = lambda t: t.view(1, len(g), self.heads, self.head_dim).transpose(1, 2) gn = self.norm_kv(g)[None] k, v = split(self.k(gn)), split(self.v(gn)) if self.rope: k = self.apply_rotary(k, *self.rotary(pos, pts)) return k, v
def forward(self, y, pos, pts, kv): # y [B, N, D] visual tokens of one video; kv = keys(...) B, N, D = y.shape k, v = kv q = self.q(self.norm_q(y)).view(B, N, self.heads, self.head_dim).transpose(1, 2) if self.rope: q = self.apply_rotary(q, *self.rotary(pos, pts)) k, v = k.expand(B, -1, -1, -1), v.expand(B, -1, -1, -1) 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 out = torch.cat([F.scaled_dot_product_attention(q[:, :, i:i + self.QUERY_CHUNK], k, v, attn_mask=self.bias(q.dtype, pts, slice(i, i + self.QUERY_CHUNK))) for i in range(0, N, self.QUERY_CHUNK)], 2) else: out = F.scaled_dot_product_attention(q, k, v, attn_mask=self.bias(q.dtype, pts) if self.local_bias else None) return self.o(out.transpose(1, 2).reshape(B, N, D))
class Geometry(nn.Module): """VGGT-1B's aggregator and point head (frozen, from facebook/VGGT-1B) and, per injection point, a merger and the cross-attention."""
def __init__(self, config): super().__init__() g, tc = config.geometry, config.text_config self.vggt = Aggregator(img_size=g["vggt_img_size"], patch_size=g["vggt_patch_size"], embed_dim=g["vggt_embed_dim"]) self.point_head = DPTHead(dim_in=2 * g["vggt_embed_dim"], output_dim=4, activation="inv_log", conf_activation="expp1") self.vggt.cached_layer_indices = set(g["vggt_layers"]) | set(self.point_head.intermediate_layer_idx) D = tc.hidden_size keys = [str(k) for k in g["fusion_after"]] self.mergers = nn.ModuleDict({k: GeometryMerger(g["vggt_dim"], g["merger_hidden"], D) for k in keys}) self.aligned = nn.ModuleDict({k: AlignedXAttn(D, D // 128, g["rope3"], g["local_bias"], g["train_frames"], g["theta"], g["bias_nu"]) for k in keys})
class SpaceTimeVLMMixin: """The geometry branch on top of a Qwen3.5 conditional-generation model (dense or MoE)."""
_keep_in_fp32_modules_strict = ["geometry"]
def _setup_geometry(self, config): g = config.geometry self.geometry = Geometry(config) self.pairs = dict(zip(g["fusion_after"], g["vggt_layers"])) self.pe_dmax = g["pe_dmax"] self.merge = config.vision_config.spatial_merge_size self._geo = self._pos = self._pts = self._visual_mask = None self._processor = None layers = self.model.language_model.layers for k in g["fusion_after"]: layers[k].register_forward_hook(self._make_hook(str(k))) self.model.register_forward_pre_hook(self._capture_ids, with_kwargs=True)
def _init_weights(self, module): # Non-persistent constants are not in the checkpoint: rebuild them (also for a freshly built model). if isinstance(module, Aggregator): dev = module.camera_token.device module._resnet_mean = torch.tensor(_RESNET_MEAN, device=dev).view(1, 1, 3, 1, 1) module._resnet_std = torch.tensor(_RESNET_STD, device=dev).view(1, 1, 3, 1, 1) elif isinstance(module, AlignedXAttn): if module.rope: module.rope_axis, module.rope_freq = module.rope_tables(module.q.weight.device) else: super()._init_weights(module)
# ---- inputs ---- @property def processor(self): if self._processor is None: g = self.config.geometry self._processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True, min_pixels=g["min_pixels"], max_pixels=g["max_pixels"]) self._processor.tokenizer.padding_side = "left" return self._processor
def visual_inputs(self, frames): """Qwen pixel values and grids of the frames, and VGGT's input [T, 3, H, W] in [0, 1]: each frame resized to Qwen's patch grid x 14 px, padded with 1.0 at the bottom / right if the frames differ in size.""" from torchvision.transforms import functional as TF out = self.processor.image_processor(images=frames, return_tensors="pt") grid = out["image_grid_thw"] vggt = [TF.to_tensor(f.convert("RGB").resize((int(w) * VGGT_PATCH, int(h) * VGGT_PATCH), Image.Resampling.BICUBIC)) for f, (_, h, w) in zip(frames, grid.tolist())] H, W = max(t.shape[1] for t in vggt), max(t.shape[2] for t in vggt) vggt = torch.stack([F.pad(t, (0, W - t.shape[2], 0, H - t.shape[1]), value=1.0) for t in vggt]) return {"pixel_values": out["pixel_values"], "image_grid_thw": grid, "vggt_images": vggt}
def prompt_text(self, question, n_images): """System prompt, the frames as images, then the question; thinking off. A question with one "<image>" placeholder per frame gets each frame at its placeholder instead.""" parts = question.split("<image>") if len(parts) == 1: content = [{"type": "image"} for _ in range(n_images)] + [{"type": "text", "text": question}] else: assert len(parts) == n_images + 1, (len(parts) - 1, n_images) content = [{"type": "text", "text": parts[0]}] if parts[0] else [] for p in parts[1:]: content += [{"type": "image"}] + ([{"type": "text", "text": p}] if p else []) msgs = [{"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}, {"role": "user", "content": content}] return self.processor.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
def text_inputs(self, questions, grid): """Left-padded token ids of B questions about the same frames.""" tok = self.processor.tokenizer image_token = self.processor.image_token n_tok = (grid.prod(-1) // self.merge ** 2).tolist() rows = [] for q in questions: parts = self.prompt_text(q, len(grid)).split(image_token) assert len(parts) == len(grid) + 1, (len(parts) - 1, len(grid)) text = parts[0] + "".join(image_token * n + p for n, p in zip(n_tok, parts[1:])) rows.append(tok(text, add_special_tokens=False).input_ids) L = max(map(len, rows)) ids = torch.full((len(rows), L), tok.pad_token_id, dtype=torch.long) mask = torch.zeros((len(rows), L), dtype=torch.long) for i, r in enumerate(rows): ids[i, L - len(r):] = torch.tensor(r) mask[i, L - len(r):] = 1 return {"input_ids": ids, "attention_mask": mask, "mm_token_type_ids": (ids == self.config.image_token_id).int()}
def prepare(self, frames, questions): """Model inputs for B questions (a list of strings) about one list of frames.""" vis = self.visual_inputs(frames) return {**vis, **self.text_inputs(questions, vis["image_grid_thw"])}
# ---- geometry ---- @torch.no_grad() def set_geometry(self, images, grid): """Runs VGGT on the frames [T, 3, H, W] and the mergers: the geometry tokens, positions and 3D points of one video, read by the hooks in the next forward passes.""" geo_mod = self.geometry with torch.autocast("cuda", dtype=torch.bfloat16): out, ps = geo_mod.vggt(images[None]) with torch.autocast("cuda", enabled=False): # VGGT runs its heads in float32 toks = [o.float() if o is not None else None for o in out] pts, conf = geo_mod.point_head(toks, images=images[None].float(), patch_start_idx=ps) self._pts = cell_points(pts[0], conf[0], grid, self.pe_dmax, merge=self.merge) Hp, Wp = images.shape[-2] // VGGT_PATCH, images.shape[-1] // VGGT_PATCH self._geo = {} with torch.autocast("cuda", dtype=torch.bfloat16): for k, L in self.pairs.items(): tok = out[L][0] # [T, 5 + P, 2048] patches = tok[:, ps:].reshape(len(tok), Hp, Wp, -1) self._geo[str(k)] = torch.cat([geo_mod.mergers[str(k)](patches[t, :h, :w]) for t, (_, h, w) in enumerate(grid.tolist())]) self._pos = AlignedXAttn.positions(grid, self.merge)
def clear_geometry(self): self._geo = self._pos = self._pts = None
def _capture_ids(self, module, args, kwargs): ids = kwargs.get("input_ids", args[0] if args else None) self._visual_mask = None if ids is None else ids == self.config.image_token_id
def _make_hook(self, key): def hook(module, args, out): """Decoder layer k: add the cross-attention update to the visual tokens of its output.""" h = out[0] if isinstance(out, tuple) else out m = self._visual_mask if self._geo is None or m is None or m.shape != h.shape[:2] or not m.any(): return None # no geometry set, or a decoding step (no visual tokens) geo = self._geo[key] n = int(m[0].sum()) assert n == len(geo) and bool((m.sum(1) == n).all()), "visual tokens != geometry tokens" att = self.geometry.aligned[key] with torch.autocast("cuda", dtype=torch.bfloat16): kv = att.keys(geo, self._pos, self._pts) delta = torch.zeros_like(h) delta[m] = att(h[m].view(h.shape[0], n, -1), self._pos, self._pts, kv).reshape(-1, h.shape[-1]).to(h.dtype) new = h + delta return (new, *out[1:]) if isinstance(out, tuple) else new return hook
# ---- generation ---- def _llm_inputs(self, batch): B = batch["input_ids"].shape[0] feats = self.model.get_image_features(batch["pixel_values"], batch["image_grid_thw"], return_dict=True) feats = tuple(feats.pooler_output) * B # the vision encoder runs once; its tokens are shared by the B questions return dict(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], mm_token_type_ids=batch["mm_token_type_ids"], image_grid_thw=batch["image_grid_thw"].repeat(B, 1), mm_encoder_outputs={"image": BaseModelOutputWithPooling(pooler_output=feats)})
@torch.no_grad() def answer(self, batch, max_new_tokens=256, return_outputs=False, **generate_kwargs): """Greedy answers to the questions of a prepare() batch. return_outputs: the generate() output instead.""" batch = {k: v.to(self.device) for k, v in batch.items()} tok = self.processor.tokenizer stop = [tok.convert_tokens_to_ids(t) for t in ("<|im_end|>", "<|endoftext|>")] self.set_geometry(batch["vggt_images"], batch["image_grid_thw"]) try: with torch.autocast("cuda", dtype=torch.bfloat16): out = self.generate(**self._llm_inputs(batch), max_new_tokens=max_new_tokens, do_sample=False, temperature=None, top_p=None, top_k=None, eos_token_id=stop, pad_token_id=tok.pad_token_id, **generate_kwargs) finally: self.clear_geometry() if return_outputs: return out seqs = out.sequences if hasattr(out, "sequences") else out return [s.strip() for s in tok.batch_decode(seqs[:, batch["input_ids"].shape[1]:], skip_special_tokens=True)]
def chat(self, video, question, num_frames=None, max_new_tokens=256, **generate_kwargs): """Answer one question (a string) or several (a list, batched) about a video: a video file, a directory of frames, or a list of images / image paths. num_frames uniformly spaced frames are used (32 by default).""" frames = load_frames(video, num_frames or self.config.geometry["num_frames"]) questions = [question] if isinstance(question, str) else list(question) answers = self.answer(self.prepare(frames, questions), max_new_tokens=max_new_tokens, **generate_kwargs) return answers[0] if isinstance(question, str) else answers
class SpaceTimeVLMForConditionalGeneration(SpaceTimeVLMMixin, Qwen3_5ForConditionalGeneration): config_class = SpaceTimeVLMConfig
def __init__(self, config): super().__init__(config) self._setup_geometry(config) self.post_init()
class SpaceTimeVLMMoeForConditionalGeneration(SpaceTimeVLMMixin, Qwen3_5MoeForConditionalGeneration): config_class = SpaceTimeVLMMoeConfig
def __init__(self, config): super().__init__(config) self._setup_geometry(config) self.post_init()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061{ "image_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "Qwen2VLImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "merge_size": 2, "patch_size": 16, "resample": 3, "rescale_factor": 0.00392156862745098, "size": { "longest_edge": 1605632, "shortest_edge": 200704 }, "temporal_patch_size": 2 }, "processor_class": "Qwen3VLProcessor", "video_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_sample_frames": true, "fps": 2, "image_mean": [ 0.5, 0.5, 0.5 ], "image_std": [ 0.5, 0.5, 0.5 ], "max_frames": 768, "max_video_tokens": 768, "merge_size": 2, "min_frames": 4, "patch_size": 16, "resample": 3, "rescale_factor": 0.00392156862745098, "return_metadata": false, "size": { "longest_edge": 25165824, "shortest_edge": 4096 }, "temporal_patch_size": 2, "video_processor_type": "Qwen3VLVideoProcessor" }}123version https://git-lfs.github.com/spec/v1oid sha256:a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941fsize 19989339123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "add_prefix_space": false, "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "backend": "tokenizers", "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "extra_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "image_token": "<|image_pad|>", "is_local": false, "local_files_only": true, "max_pixels": 1605632, "merges_file": null, "min_pixels": 200704, "model_max_length": 262144, "model_specific_special_tokens": { "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "image_token": "<|image_pad|>", "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>" }, "pad_token": "<|endoftext|>", "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+", "processor_class": "Qwen3VLProcessor", "split_special_tokens": false, "tokenizer_class": "Qwen3_5Tokenizer", "unk_token": null, "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485# Copied from facebookresearch/vggt, vggt/heads/dpt_head.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# Inspired by https://github.com/DepthAnything/Depth-Anything-V2
import osfrom typing import List, Dict, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom .vggt_heads_head_act import activate_headfrom .vggt_heads_utils import create_uv_grid, position_grid_to_embed
class DPTHead(nn.Module): """ DPT Head for dense prediction tasks.
This implementation follows the architecture described in "Vision Transformers for Dense Prediction" (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer backbone and produces dense predictions by fusing multi-scale features.
Args: dim_in (int): Input dimension (channels). patch_size (int, optional): Patch size. Default is 14. output_dim (int, optional): Number of output channels. Default is 4. activation (str, optional): Activation type. Default is "inv_log". conf_activation (str, optional): Confidence activation type. Default is "expp1". features (int, optional): Feature channels for intermediate representations. Default is 256. out_channels (List[int], optional): Output channels for each intermediate layer. intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT. pos_embed (bool, optional): Whether to use positional embedding. Default is True. feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False. down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1. """
def __init__( self, dim_in: int, patch_size: int = 14, output_dim: int = 4, activation: str = "inv_log", conf_activation: str = "expp1", features: int = 256, out_channels: List[int] = [256, 512, 1024, 1024], intermediate_layer_idx: List[int] = [4, 11, 17, 23], pos_embed: bool = True, feature_only: bool = False, down_ratio: int = 1, ) -> None: super(DPTHead, self).__init__() self.patch_size = patch_size self.activation = activation self.conf_activation = conf_activation self.pos_embed = pos_embed self.feature_only = feature_only self.down_ratio = down_ratio self.intermediate_layer_idx = intermediate_layer_idx
self.norm = nn.LayerNorm(dim_in)
# Projection layers for each output channel from tokens. self.projects = nn.ModuleList( [nn.Conv2d(in_channels=dim_in, out_channels=oc, kernel_size=1, stride=1, padding=0) for oc in out_channels] )
# Resize layers for upsampling feature maps. self.resize_layers = nn.ModuleList( [ nn.ConvTranspose2d( in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0 ), nn.ConvTranspose2d( in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0 ), nn.Identity(), nn.Conv2d( in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1 ), ] )
self.scratch = _make_scratch(out_channels, features, expand=False)
# Attach additional modules to scratch. self.scratch.stem_transpose = None self.scratch.refinenet1 = _make_fusion_block(features) self.scratch.refinenet2 = _make_fusion_block(features) self.scratch.refinenet3 = _make_fusion_block(features) self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False)
head_features_1 = features head_features_2 = 32
if feature_only: self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1) else: self.scratch.output_conv1 = nn.Conv2d( head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 ) conv2_in_channels = head_features_1 // 2
self.scratch.output_conv2 = nn.Sequential( nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), )
def forward( self, aggregated_tokens_list: List[torch.Tensor], images: torch.Tensor, patch_start_idx: int, frames_chunk_size: int = 8, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Forward pass through the DPT head, supports processing by chunking frames. Args: aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. patch_start_idx (int): Starting index for patch tokens in the token sequence. Used to separate patch tokens from other tokens (e.g., camera or register tokens). frames_chunk_size (int, optional): Number of frames to process in each chunk. If None or larger than S, all frames are processed at once. Default: 8.
Returns: Tensor or Tuple[Tensor, Tensor]: - If feature_only=True: Feature maps with shape [B, S, C, H, W] - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W] """ B, S, _, H, W = images.shape
# If frames_chunk_size is not specified or greater than S, process all frames at once if frames_chunk_size is None or frames_chunk_size >= S: return self._forward_impl(aggregated_tokens_list, images, patch_start_idx)
# Otherwise, process frames in chunks to manage memory usage assert frames_chunk_size > 0
# Process frames in batches all_preds = [] all_conf = []
for frames_start_idx in range(0, S, frames_chunk_size): frames_end_idx = min(frames_start_idx + frames_chunk_size, S)
# Process batch of frames if self.feature_only: chunk_output = self._forward_impl( aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx ) all_preds.append(chunk_output) else: chunk_preds, chunk_conf = self._forward_impl( aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx ) all_preds.append(chunk_preds) all_conf.append(chunk_conf)
# Concatenate results along the sequence dimension if self.feature_only: return torch.cat(all_preds, dim=1) else: return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1)
def _forward_impl( self, aggregated_tokens_list: List[torch.Tensor], images: torch.Tensor, patch_start_idx: int, frames_start_idx: int = None, frames_end_idx: int = None, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Implementation of the forward pass through the DPT head.
This method processes a specific chunk of frames from the sequence.
Args: aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. images (Tensor): Input images with shape [B, S, 3, H, W]. patch_start_idx (int): Starting index for patch tokens. frames_start_idx (int, optional): Starting index for frames to process. frames_end_idx (int, optional): Ending index for frames to process.
Returns: Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence). """ if frames_start_idx is not None and frames_end_idx is not None: images = images[:, frames_start_idx:frames_end_idx].contiguous()
B, S, _, H, W = images.shape
patch_h, patch_w = H // self.patch_size, W // self.patch_size
out = [] dpt_idx = 0
for layer_idx in self.intermediate_layer_idx: x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:]
# Select frames if processing a chunk if frames_start_idx is not None and frames_end_idx is not None: x = x[:, frames_start_idx:frames_end_idx]
x = x.reshape(B * S, -1, x.shape[-1])
x = self.norm(x)
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
x = self.projects[dpt_idx](x) if self.pos_embed: x = self._apply_pos_embed(x, W, H) x = self.resize_layers[dpt_idx](x)
out.append(x) dpt_idx += 1
# Fuse features from multiple layers. out = self.scratch_forward(out) # Interpolate fused output to match target image resolution. out = custom_interpolate( out, (int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)), mode="bilinear", align_corners=True, )
if self.pos_embed: out = self._apply_pos_embed(out, W, H)
if self.feature_only: return out.view(B, S, *out.shape[1:])
out = self.scratch.output_conv2(out) preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation)
preds = preds.view(B, S, *preds.shape[1:]) conf = conf.view(B, S, *conf.shape[1:]) return preds, conf
def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: """ Apply positional embedding to tensor x. """ patch_w = x.shape[-1] patch_h = x.shape[-2] pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device) pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) pos_embed = pos_embed * ratio pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) return x + pos_embed
def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor: """ Forward pass through the fusion blocks.
Args: features (List[Tensor]): List of feature maps from different layers.
Returns: Tensor: Fused feature map. """ layer_1, layer_2, layer_3, layer_4 = features
layer_1_rn = self.scratch.layer1_rn(layer_1) layer_2_rn = self.scratch.layer2_rn(layer_2) layer_3_rn = self.scratch.layer3_rn(layer_3) layer_4_rn = self.scratch.layer4_rn(layer_4)
out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) del layer_4_rn, layer_4
out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:]) del layer_3_rn, layer_3
out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:]) del layer_2_rn, layer_2
out = self.scratch.refinenet1(out, layer_1_rn) del layer_1_rn, layer_1
out = self.scratch.output_conv1(out) return out
################################################################################# Modules################################################################################
def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module: return FeatureFusionBlock( features, nn.ReLU(inplace=True), deconv=False, bn=False, expand=False, align_corners=True, size=size, has_residual=has_residual, groups=groups, )
def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module: scratch = nn.Module() out_shape1 = out_shape out_shape2 = out_shape out_shape3 = out_shape if len(in_shape) >= 4: out_shape4 = out_shape
if expand: out_shape1 = out_shape out_shape2 = out_shape * 2 out_shape3 = out_shape * 4 if len(in_shape) >= 4: out_shape4 = out_shape * 8
scratch.layer1_rn = nn.Conv2d( in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer2_rn = nn.Conv2d( in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer3_rn = nn.Conv2d( in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) if len(in_shape) >= 4: scratch.layer4_rn = nn.Conv2d( in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) return scratch
class ResidualConvUnit(nn.Module): """Residual convolution module."""
def __init__(self, features, activation, bn, groups=1): """Init.
Args: features (int): number of features """ super().__init__()
self.bn = bn self.groups = groups self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
self.norm1 = None self.norm2 = None
self.activation = activation self.skip_add = nn.quantized.FloatFunctional()
def forward(self, x): """Forward pass.
Args: x (tensor): input
Returns: tensor: output """
out = self.activation(x) out = self.conv1(out) if self.norm1 is not None: out = self.norm1(out)
out = self.activation(out) out = self.conv2(out) if self.norm2 is not None: out = self.norm2(out)
return self.skip_add.add(out, x)
class FeatureFusionBlock(nn.Module): """Feature fusion block."""
def __init__( self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None, has_residual=True, groups=1, ): """Init.
Args: features (int): number of features """ super(FeatureFusionBlock, self).__init__()
self.deconv = deconv self.align_corners = align_corners self.groups = groups self.expand = expand out_features = features if self.expand == True: out_features = features // 2
self.out_conv = nn.Conv2d( features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=self.groups )
if has_residual: self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups)
self.has_residual = has_residual self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups)
self.skip_add = nn.quantized.FloatFunctional() self.size = size
def forward(self, *xs, size=None): """Forward pass.
Returns: tensor: output """ output = xs[0]
if self.has_residual: res = self.resConfUnit1(xs[1]) output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None): modifier = {"scale_factor": 2} elif size is None: modifier = {"size": self.size} else: modifier = {"size": size}
output = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners) output = self.out_conv(output)
return output
def custom_interpolate( x: torch.Tensor, size: Tuple[int, int] = None, scale_factor: float = None, mode: str = "bilinear", align_corners: bool = True,) -> torch.Tensor: """ Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate. """ if size is None: size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor))
INT_MAX = 1610612736
input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
if input_elements > INT_MAX: chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0) interpolated_chunks = [ nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks ] x = torch.cat(interpolated_chunks, dim=0) return x.contiguous() else: return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# Copied from facebookresearch/vggt, vggt/heads/head_act.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import torchimport torch.nn.functional as F
def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"): """ Activate pose parameters with specified activation functions.
Args: pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length] trans_act: Activation type for translation component quat_act: Activation type for quaternion component fl_act: Activation type for focal length component
Returns: Activated pose parameters tensor """ T = pred_pose_enc[..., :3] quat = pred_pose_enc[..., 3:7] fl = pred_pose_enc[..., 7:] # or fov
T = base_pose_act(T, trans_act) quat = base_pose_act(quat, quat_act) fl = base_pose_act(fl, fl_act) # or fov
pred_pose_enc = torch.cat([T, quat, fl], dim=-1)
return pred_pose_enc
def base_pose_act(pose_enc, act_type="linear"): """ Apply basic activation function to pose parameters.
Args: pose_enc: Tensor containing encoded pose parameters act_type: Activation type ("linear", "inv_log", "exp", "relu")
Returns: Activated pose parameters """ if act_type == "linear": return pose_enc elif act_type == "inv_log": return inverse_log_transform(pose_enc) elif act_type == "exp": return torch.exp(pose_enc) elif act_type == "relu": return F.relu(pose_enc) else: raise ValueError(f"Unknown act_type: {act_type}")
def activate_head(out, activation="norm_exp", conf_activation="expp1"): """ Process network output to extract 3D points and confidence values.
Args: out: Network output tensor (B, C, H, W) activation: Activation type for 3D points conf_activation: Activation type for confidence values
Returns: Tuple of (3D points tensor, confidence tensor) """ # Move channels from last dim to the 4th dimension => (B, H, W, C) fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected
# Split into xyz (first C-1 channels) and confidence (last channel) xyz = fmap[:, :, :, :-1] conf = fmap[:, :, :, -1]
if activation == "norm_exp": d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8) xyz_normed = xyz / d pts3d = xyz_normed * torch.expm1(d) elif activation == "norm": pts3d = xyz / xyz.norm(dim=-1, keepdim=True) elif activation == "exp": pts3d = torch.exp(xyz) elif activation == "relu": pts3d = F.relu(xyz) elif activation == "inv_log": pts3d = inverse_log_transform(xyz) elif activation == "xy_inv_log": xy, z = xyz.split([2, 1], dim=-1) z = inverse_log_transform(z) pts3d = torch.cat([xy * z, z], dim=-1) elif activation == "sigmoid": pts3d = torch.sigmoid(xyz) elif activation == "linear": pts3d = xyz else: raise ValueError(f"Unknown activation: {activation}")
if conf_activation == "expp1": conf_out = 1 + conf.exp() elif conf_activation == "expp0": conf_out = conf.exp() elif conf_activation == "sigmoid": conf_out = torch.sigmoid(conf) else: raise ValueError(f"Unknown conf_activation: {conf_activation}")
return pts3d, conf_out
def inverse_log_transform(y): """ Apply inverse log transform: sign(y) * (exp(|y|) - 1)
Args: y: Input tensor
Returns: Transformed tensor """ return torch.sign(y) * (torch.expm1(torch.abs(y)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# Copied from facebookresearch/vggt, vggt/heads/utils.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import torchimport torch.nn as nn
def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor: """ Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC)
Args: pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates embed_dim: Output channel dimension for embeddings
Returns: Tensor of shape (H, W, embed_dim) with positional embeddings """ H, W, grid_dim = pos_grid.shape assert grid_dim == 2 pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2)
# Process x and y coordinates separately emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2] emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2]
# Combine and reshape emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D]
return emb.view(H, W, embed_dim) # [H, W, D]
def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor: """ This function generates a 1D positional embedding from a given grid using sine and cosine functions.
Args: - embed_dim: The embedding dimension. - pos: The position to generate the embedding from.
Returns: - emb: The generated 1D positional embedding. """ assert embed_dim % 2 == 0 device = pos.device omega = torch.arange(embed_dim // 2, dtype=torch.float32 if device.type == "mps" else torch.double, device=device) omega /= embed_dim / 2.0 omega = 1.0 / omega_0**omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
emb_sin = torch.sin(out) # (M, D/2) emb_cos = torch.cos(out) # (M, D/2)
emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) return emb.float()
# Inspired by https://github.com/microsoft/moge
def create_uv_grid( width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None) -> torch.Tensor: """ Create a normalized UV grid of shape (width, height, 2).
The grid spans horizontally and vertically according to an aspect ratio, ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right corner is at (x_span, y_span), normalized by the diagonal of the plane.
Args: width (int): Number of points horizontally. height (int): Number of points vertically. aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height. dtype (torch.dtype, optional): Data type of the resulting tensor. device (torch.device, optional): Device on which the tensor is created.
Returns: torch.Tensor: A (width, height, 2) tensor of UV coordinates. """ # Derive aspect ratio if not explicitly provided if aspect_ratio is None: aspect_ratio = float(width) / float(height)
# Compute normalized spans for X and Y diag_factor = (aspect_ratio**2 + 1.0) ** 0.5 span_x = aspect_ratio / diag_factor span_y = 1.0 / diag_factor
# Establish the linspace boundaries left_x = -span_x * (width - 1) / width right_x = span_x * (width - 1) / width top_y = -span_y * (height - 1) / height bottom_y = span_y * (height - 1) / height
# Generate 1D coordinates x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device) y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device)
# Create 2D meshgrid (width x height) and stack into UV uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy") uv_grid = torch.stack((uu, vv), dim=-1)
return uv_grid123456789101112# Copied from facebookresearch/vggt, vggt/layers/__init__.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from .vggt_layers_mlp import Mlpfrom .vggt_layers_patch_embed import PatchEmbedfrom .vggt_layers_swiglu_ffn import SwiGLUFFN, SwiGLUFFNFusedfrom .vggt_layers_block import NestedTensorBlockfrom .vggt_layers_attention import MemEffAttention12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Copied from facebookresearch/vggt, vggt/layers/attention.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
import loggingimport osimport warnings
from torch import Tensorfrom torch import nnimport torch.nn.functional as F
XFORMERS_AVAILABLE = False
class Attention(nn.Module): def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, proj_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, norm_layer: nn.Module = nn.LayerNorm, qk_norm: bool = False, fused_attn: bool = True, # use F.scaled_dot_product_attention or not rope=None, ) -> None: super().__init__() assert dim % num_heads == 0, "dim should be divisible by num_heads" self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim**-0.5 self.fused_attn = fused_attn
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim, bias=proj_bias) self.proj_drop = nn.Dropout(proj_drop) self.rope = rope
def forward(self, x: Tensor, pos=None) -> Tensor: B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) q, k = self.q_norm(q), self.k_norm(k)
if self.rope is not None: q = self.rope(q, pos) k = self.rope(k, pos)
if self.fused_attn: x = F.scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0) else: q = q * self.scale attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = attn @ v
x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class MemEffAttention(Attention): def forward(self, x: Tensor, attn_bias=None, pos=None) -> Tensor: assert pos is None if not XFORMERS_AVAILABLE: if attn_bias is not None: raise AssertionError("xFormers is required for using nested tensors") return super().forward(x)
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
q, k, v = unbind(qkv, 2)
x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) x = x.reshape([B, N, C])
x = self.proj(x) x = self.proj_drop(x) return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# Copied from facebookresearch/vggt, vggt/layers/block.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
import loggingimport osfrom typing import Callable, List, Any, Tuple, Dictimport warnings
import torchfrom torch import nn, Tensor
from .vggt_layers_attention import Attentionfrom .vggt_layers_drop_path import DropPathfrom .vggt_layers_layer_scale import LayerScalefrom .vggt_layers_mlp import Mlp
XFORMERS_AVAILABLE = False
class Block(nn.Module): def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, proj_bias: bool = True, ffn_bias: bool = True, drop: float = 0.0, attn_drop: float = 0.0, init_values=None, drop_path: float = 0.0, act_layer: Callable[..., nn.Module] = nn.GELU, norm_layer: Callable[..., nn.Module] = nn.LayerNorm, attn_class: Callable[..., nn.Module] = Attention, ffn_layer: Callable[..., nn.Module] = Mlp, qk_norm: bool = False, fused_attn: bool = True, # use F.scaled_dot_product_attention or not rope=None, ) -> None: super().__init__()
self.norm1 = norm_layer(dim)
self.attn = attn_class( dim, num_heads=num_heads, qkv_bias=qkv_bias, proj_bias=proj_bias, attn_drop=attn_drop, proj_drop=drop, qk_norm=qk_norm, fused_attn=fused_attn, rope=rope, )
self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = ffn_layer( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, bias=ffn_bias ) self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.sample_drop_ratio = drop_path
def forward(self, x: Tensor, pos=None) -> Tensor: def attn_residual_func(x: Tensor, pos=None) -> Tensor: return self.ls1(self.attn(self.norm1(x), pos=pos))
def ffn_residual_func(x: Tensor) -> Tensor: return self.ls2(self.mlp(self.norm2(x)))
if self.training and self.sample_drop_ratio > 0.1: # the overhead is compensated only for a drop path rate larger than 0.1 x = drop_add_residual_stochastic_depth( x, pos=pos, residual_func=attn_residual_func, sample_drop_ratio=self.sample_drop_ratio ) x = drop_add_residual_stochastic_depth( x, residual_func=ffn_residual_func, sample_drop_ratio=self.sample_drop_ratio ) elif self.training and self.sample_drop_ratio > 0.0: x = x + self.drop_path1(attn_residual_func(x, pos=pos)) x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 else: x = x + attn_residual_func(x, pos=pos) x = x + ffn_residual_func(x) return x
def drop_add_residual_stochastic_depth( x: Tensor, residual_func: Callable[[Tensor], Tensor], sample_drop_ratio: float = 0.0, pos=None) -> Tensor: # 1) extract subset using permutation b, n, d = x.shape sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) brange = (torch.randperm(b, device=x.device))[:sample_subset_size] x_subset = x[brange]
# 2) apply residual_func to get residual if pos is not None: # if necessary, apply rope to the subset pos = pos[brange] residual = residual_func(x_subset, pos=pos) else: residual = residual_func(x_subset)
x_flat = x.flatten(1) residual = residual.flatten(1)
residual_scale_factor = b / sample_subset_size
# 3) add the residual x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) return x_plus_residual.view_as(x)
def get_branges_scales(x, sample_drop_ratio=0.0): b, n, d = x.shape sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) brange = (torch.randperm(b, device=x.device))[:sample_subset_size] residual_scale_factor = b / sample_subset_size return brange, residual_scale_factor
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): if scaling_vector is None: x_flat = x.flatten(1) residual = residual.flatten(1) x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) else: x_plus_residual = scaled_index_add( x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor ) return x_plus_residual
attn_bias_cache: Dict[Tuple, Any] = {}
def get_attn_bias_and_cat(x_list, branges=None): """ this will perform the index select, cat the tensors, and provide the attn_bias from cache """ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) if all_shapes not in attn_bias_cache.keys(): seqlens = [] for b, x in zip(batch_sizes, x_list): for _ in range(b): seqlens.append(x.shape[1]) attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) attn_bias._batch_sizes = batch_sizes attn_bias_cache[all_shapes] = attn_bias
if branges is not None: cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1]) else: tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) cat_tensors = torch.cat(tensors_bs1, dim=1)
return attn_bias_cache[all_shapes], cat_tensors
def drop_add_residual_stochastic_depth_list( x_list: List[Tensor], residual_func: Callable[[Tensor, Any], Tensor], sample_drop_ratio: float = 0.0, scaling_vector=None,) -> Tensor: # 1) generate random set of indices for dropping samples in the batch branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list] branges = [s[0] for s in branges_scales] residual_scale_factors = [s[1] for s in branges_scales]
# 2) get attention bias and index+concat the tensors attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
# 3) apply residual_func to get residual, and split the result residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
outputs = [] for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors): outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x)) return outputs
class NestedTensorBlock(Block): def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: """ x_list contains a list of tensors to nest together and run """ assert isinstance(self.attn, MemEffAttention)
if self.training and self.sample_drop_ratio > 0.0:
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.attn(self.norm1(x), attn_bias=attn_bias)
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.mlp(self.norm2(x))
x_list = drop_add_residual_stochastic_depth_list( x_list, residual_func=attn_residual_func, sample_drop_ratio=self.sample_drop_ratio, scaling_vector=(self.ls1.gamma if isinstance(self.ls1, LayerScale) else None), ) x_list = drop_add_residual_stochastic_depth_list( x_list, residual_func=ffn_residual_func, sample_drop_ratio=self.sample_drop_ratio, scaling_vector=(self.ls2.gamma if isinstance(self.ls1, LayerScale) else None), ) return x_list else:
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.ls2(self.mlp(self.norm2(x)))
attn_bias, x = get_attn_bias_and_cat(x_list) x = x + attn_residual_func(x, attn_bias=attn_bias) x = x + ffn_residual_func(x) return attn_bias.split(x)
def forward(self, x_or_x_list): if isinstance(x_or_x_list, Tensor): return super().forward(x_or_x_list) elif isinstance(x_or_x_list, list): if not XFORMERS_AVAILABLE: raise AssertionError("xFormers is required for using nested tensors") return self.forward_nested(x_or_x_list) else: raise AssertionError1234567891011121314151617181920212223242526272829303132333435# Copied from facebookresearch/vggt, vggt/layers/drop_path.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
from torch import nn
def drop_path(x, drop_prob: float = 0.0, training: bool = False): if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = x.new_empty(shape).bernoulli_(keep_prob) if keep_prob > 0.0: random_tensor.div_(keep_prob) output = x * random_tensor return output
class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob
def forward(self, x): return drop_path(x, self.drop_prob, self.training)1234567891011121314151617181920212223# Copied from facebookresearch/vggt, vggt/layers/layer_scale.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
from typing import Union
import torchfrom torch import Tensorfrom torch import nn
class LayerScale(nn.Module): def __init__(self, dim: int, init_values: Union[float, Tensor] = 1e-5, inplace: bool = False) -> None: super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor: return x.mul_(self.gamma) if self.inplace else x * self.gamma1234567891011121314151617181920212223242526272829303132333435363738394041# Copied from facebookresearch/vggt, vggt/layers/mlp.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
from typing import Callable, Optional
from torch import Tensor, nn
class Mlp(nn.Module): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = nn.GELU, drop: float = 0.0, bias: bool = True, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) self.drop = nn.Dropout(drop)
def forward(self, x: Tensor) -> Tensor: x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copied from facebookresearch/vggt, vggt/layers/patch_embed.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
from typing import Callable, Optional, Tuple, Union
from torch import Tensorimport torch.nn as nn
def make_2tuple(x): if isinstance(x, tuple): assert len(x) == 2 return x
assert isinstance(x, int) return (x, x)
class PatchEmbed(nn.Module): """ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
Args: img_size: Image size. patch_size: Patch token size. in_chans: Number of input image channels. embed_dim: Number of linear projection output channels. norm_layer: Normalization layer. """
def __init__( self, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 16, in_chans: int = 3, embed_dim: int = 768, norm_layer: Optional[Callable] = None, flatten_embedding: bool = True, ) -> None: super().__init__()
image_HW = make_2tuple(img_size) patch_HW = make_2tuple(patch_size) patch_grid_size = (image_HW[0] // patch_HW[0], image_HW[1] // patch_HW[1])
self.img_size = image_HW self.patch_size = patch_HW self.patches_resolution = patch_grid_size self.num_patches = patch_grid_size[0] * patch_grid_size[1]
self.in_chans = in_chans self.embed_dim = embed_dim
self.flatten_embedding = flatten_embedding
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x: Tensor) -> Tensor: _, _, H, W = x.shape patch_H, patch_W = self.patch_size
assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}" assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
x = self.proj(x) # B C H W H, W = x.size(2), x.size(3) x = x.flatten(2).transpose(1, 2) # B HW C x = self.norm(x) if not self.flatten_embedding: x = x.reshape(-1, H, W, self.embed_dim) # B H W C return x
def flops(self) -> float: Ho, Wo = self.patches_resolution flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) if self.norm is not None: flops += Ho * Wo * self.embed_dim return flops123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# Copied from facebookresearch/vggt, vggt/layers/rope.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# Implementation of 2D Rotary Position Embeddings (RoPE).
# This module provides a clean implementation of 2D Rotary Position Embeddings,# which extends the original RoPE concept to handle 2D spatial positions.
# Inspired by:# https://github.com/meta-llama/codellama/blob/main/llama/model.py# https://github.com/naver-ai/rope-vit
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom typing import Dict, Tuple
class PositionGetter: """Generates and caches 2D spatial positions for patches in a grid.
This class efficiently manages the generation of spatial coordinates for patches in a 2D grid, caching results to avoid redundant computations.
Attributes: position_cache: Dictionary storing precomputed position tensors for different grid dimensions. """
def __init__(self): """Initializes the position generator with an empty cache.""" self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {}
def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor: """Generates spatial positions for a batch of patches.
Args: batch_size: Number of samples in the batch. height: Height of the grid in patches. width: Width of the grid in patches. device: Target device for the position tensor.
Returns: Tensor of shape (batch_size, height*width, 2) containing y,x coordinates for each position in the grid, repeated for each batch item. """ if (height, width) not in self.position_cache: y_coords = torch.arange(height, device=device) x_coords = torch.arange(width, device=device) positions = torch.cartesian_prod(y_coords, x_coords) self.position_cache[height, width] = positions
cached_positions = self.position_cache[height, width] return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone()
class RotaryPositionEmbedding2D(nn.Module): """2D Rotary Position Embedding implementation.
This module applies rotary position embeddings to input tokens based on their 2D spatial positions. It handles the position-dependent rotation of features separately for vertical and horizontal dimensions.
Args: frequency: Base frequency for the position embeddings. Default: 100.0 scaling_factor: Scaling factor for frequency computation. Default: 1.0
Attributes: base_frequency: Base frequency for computing position embeddings. scaling_factor: Factor to scale the computed frequencies. frequency_cache: Cache for storing precomputed frequency components. """
def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0): """Initializes the 2D RoPE module.""" super().__init__() self.base_frequency = frequency self.scaling_factor = scaling_factor self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {}
def _compute_frequency_components( self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype ) -> Tuple[torch.Tensor, torch.Tensor]: """Computes frequency components for rotary embeddings.
Args: dim: Feature dimension (must be even). seq_len: Maximum sequence length. device: Target device for computations. dtype: Data type for the computed tensors.
Returns: Tuple of (cosine, sine) tensors for frequency components. """ cache_key = (dim, seq_len, device, dtype) if cache_key not in self.frequency_cache: # Compute frequency bands exponents = torch.arange(0, dim, 2, device=device).float() / dim inv_freq = 1.0 / (self.base_frequency**exponents)
# Generate position-dependent frequencies positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) angles = torch.einsum("i,j->ij", positions, inv_freq)
# Compute and cache frequency components angles = angles.to(dtype) angles = torch.cat((angles, angles), dim=-1) cos_components = angles.cos().to(dtype) sin_components = angles.sin().to(dtype) self.frequency_cache[cache_key] = (cos_components, sin_components)
return self.frequency_cache[cache_key]
@staticmethod def _rotate_features(x: torch.Tensor) -> torch.Tensor: """Performs feature rotation by splitting and recombining feature dimensions.
Args: x: Input tensor to rotate.
Returns: Rotated feature tensor. """ feature_dim = x.shape[-1] x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :] return torch.cat((-x2, x1), dim=-1)
def _apply_1d_rope( self, tokens: torch.Tensor, positions: torch.Tensor, cos_comp: torch.Tensor, sin_comp: torch.Tensor ) -> torch.Tensor: """Applies 1D rotary position embeddings along one dimension.
Args: tokens: Input token features. positions: Position indices. cos_comp: Cosine components for rotation. sin_comp: Sine components for rotation.
Returns: Tokens with applied rotary position embeddings. """ # Embed positions with frequency components cos = F.embedding(positions, cos_comp)[:, None, :, :] sin = F.embedding(positions, sin_comp)[:, None, :, :]
# Apply rotation return (tokens * cos) + (self._rotate_features(tokens) * sin)
def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: """Applies 2D rotary position embeddings to input tokens.
Args: tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim). The feature dimension (dim) must be divisible by 4. positions: Position tensor of shape (batch_size, n_tokens, 2) containing the y and x coordinates for each token.
Returns: Tensor of same shape as input with applied 2D rotary position embeddings.
Raises: AssertionError: If input dimensions are invalid or positions are malformed. """ # Validate inputs assert tokens.size(-1) % 2 == 0, "Feature dimension must be even" assert positions.ndim == 3 and positions.shape[-1] == 2, "Positions must have shape (batch_size, n_tokens, 2)"
# Compute feature dimension for each spatial direction feature_dim = tokens.size(-1) // 2
# Get frequency components max_position = int(positions.max()) + 1 cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype)
# Split features for vertical and horizontal processing vertical_features, horizontal_features = tokens.chunk(2, dim=-1)
# Apply RoPE separately for each dimension vertical_features = self._apply_1d_rope(vertical_features, positions[..., 0], cos_comp, sin_comp) horizontal_features = self._apply_1d_rope(horizontal_features, positions[..., 1], cos_comp, sin_comp)
# Combine processed features return torch.cat((vertical_features, horizontal_features), dim=-1)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Copied from facebookresearch/vggt, vggt/layers/swiglu_ffn.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
import osfrom typing import Callable, Optionalimport warnings
from torch import Tensor, nnimport torch.nn.functional as F
class SwiGLUFFN(nn.Module): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = None, drop: float = 0.0, bias: bool = True, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
def forward(self, x: Tensor) -> Tensor: x12 = self.w12(x) x1, x2 = x12.chunk(2, dim=-1) hidden = F.silu(x1) * x2 return self.w3(hidden)
XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None# try:# if XFORMERS_ENABLED:# from xformers.ops import SwiGLU
# XFORMERS_AVAILABLE = True# warnings.warn("xFormers is available (SwiGLU)")# else:# warnings.warn("xFormers is disabled (SwiGLU)")# raise ImportError# except ImportError:SwiGLU = SwiGLUFFNXFORMERS_AVAILABLE = False
# warnings.warn("xFormers is not available (SwiGLU)")
class SwiGLUFFNFused(SwiGLU): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = None, drop: float = 0.0, bias: bool = True, ) -> None: out_features = out_features or in_features hidden_features = hidden_features or in_features hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 super().__init__(in_features=in_features, hidden_features=hidden_features, out_features=out_features, bias=bias)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398# Copied from facebookresearch/vggt, vggt/layers/vision_transformer.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
from functools import partialimport mathimport loggingfrom typing import Sequence, Tuple, Union, Callable
import torchimport torch.nn as nnfrom torch.utils.checkpoint import checkpointfrom torch.nn.init import trunc_normal_from .vggt_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
logger = logging.getLogger("dinov2")
def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module: if not depth_first and include_root: fn(module=module, name=name) for child_name, child_module in module.named_children(): child_name = ".".join((name, child_name)) if name else child_name named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True) if depth_first and include_root: fn(module=module, name=name) return module
class BlockChunk(nn.ModuleList): def forward(self, x): for b in self: x = b(x) return x
class DinoVisionTransformer(nn.Module): def __init__( self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, ffn_bias=True, proj_bias=True, drop_path_rate=0.0, drop_path_uniform=False, init_values=None, # for layerscale: None or 0 => no layerscale embed_layer=PatchEmbed, act_layer=nn.GELU, block_fn=Block, ffn_layer="mlp", block_chunks=1, num_register_tokens=0, interpolate_antialias=False, interpolate_offset=0.1, qk_norm=False, ): """ Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True proj_bias (bool): enable bias for proj in attn if True ffn_bias (bool): enable bias for ffn if True drop_path_rate (float): stochastic depth rate drop_path_uniform (bool): apply uniform drop rate across blocks weight_init (str): weight init scheme init_values (float): layer-scale init values embed_layer (nn.Module): patch embedding layer act_layer (nn.Module): MLP activation layer block_fn (nn.Module): transformer block class ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" block_chunks: (int) split block sequence into block_chunks units for FSDP wrap num_register_tokens: (int) number of extra cls tokens (so-called "registers") interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings """ super().__init__() norm_layer = partial(nn.LayerNorm, eps=1e-6)
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_tokens = 1 self.n_blocks = depth self.num_heads = num_heads self.patch_size = patch_size self.num_register_tokens = num_register_tokens self.interpolate_antialias = interpolate_antialias self.interpolate_offset = interpolate_offset self.use_reentrant = False # hardcoded to False
self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) assert num_register_tokens >= 0 self.register_tokens = ( nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None )
if drop_path_uniform is True: dpr = [drop_path_rate] * depth else: dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
if ffn_layer == "mlp": logger.info("using MLP layer as FFN") ffn_layer = Mlp elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": logger.info("using SwiGLU layer as FFN") ffn_layer = SwiGLUFFNFused elif ffn_layer == "identity": logger.info("using Identity layer as FFN")
def f(*args, **kwargs): return nn.Identity()
ffn_layer = f else: raise NotImplementedError
blocks_list = [ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, proj_bias=proj_bias, ffn_bias=ffn_bias, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, ffn_layer=ffn_layer, init_values=init_values, qk_norm=qk_norm, ) for i in range(depth) ] if block_chunks > 0: self.chunked_blocks = True chunked_blocks = [] chunksize = depth // block_chunks for i in range(0, depth, chunksize): # this is to keep the block index consistent if we chunk the block list chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize]) self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) else: self.chunked_blocks = False self.blocks = nn.ModuleList(blocks_list)
self.norm = norm_layer(embed_dim) self.head = nn.Identity()
self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
self.init_weights()
def init_weights(self): trunc_normal_(self.pos_embed, std=0.02) nn.init.normal_(self.cls_token, std=1e-6) if self.register_tokens is not None: nn.init.normal_(self.register_tokens, std=1e-6) named_apply(init_weights_vit_timm, self)
def interpolate_pos_encoding(self, x, w, h): previous_dtype = x.dtype npatch = x.shape[1] - 1 N = self.pos_embed.shape[1] - 1 if npatch == N and w == h: return self.pos_embed pos_embed = self.pos_embed.float() class_pos_embed = pos_embed[:, 0] patch_pos_embed = pos_embed[:, 1:] dim = x.shape[-1] w0 = w // self.patch_size h0 = h // self.patch_size M = int(math.sqrt(N)) # Recover the number of patches in each dimension assert N == M * M kwargs = {} if self.interpolate_offset: # Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8 # Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors sx = float(w0 + self.interpolate_offset) / M sy = float(h0 + self.interpolate_offset) / M kwargs["scale_factor"] = (sx, sy) else: # Simply specify an output size instead of a scale factor kwargs["size"] = (w0, h0) patch_pos_embed = nn.functional.interpolate( patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2), mode="bicubic", antialias=self.interpolate_antialias, **kwargs, ) assert (w0, h0) == patch_pos_embed.shape[-2:] patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
def prepare_tokens_with_masks(self, x, masks=None): B, nc, w, h = x.shape x = self.patch_embed(x) if masks is not None: x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) x = x + self.interpolate_pos_encoding(x, w, h)
if self.register_tokens is not None: x = torch.cat((x[:, :1], self.register_tokens.expand(x.shape[0], -1, -1), x[:, 1:]), dim=1)
return x
def forward_features_list(self, x_list, masks_list): x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
for blk in self.blocks: if self.training: x = checkpoint(blk, x, use_reentrant=self.use_reentrant) else: x = blk(x)
all_x = x output = [] for x, masks in zip(all_x, masks_list): x_norm = self.norm(x) output.append( { "x_norm_clstoken": x_norm[:, 0], "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], "x_prenorm": x, "masks": masks, } ) return output
def forward_features(self, x, masks=None): if isinstance(x, list): return self.forward_features_list(x, masks)
x = self.prepare_tokens_with_masks(x, masks)
for blk in self.blocks: if self.training: x = checkpoint(blk, x, use_reentrant=self.use_reentrant) else: x = blk(x)
x_norm = self.norm(x) return { "x_norm_clstoken": x_norm[:, 0], "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], "x_prenorm": x, "masks": masks, }
def _get_intermediate_layers_not_chunked(self, x, n=1): x = self.prepare_tokens_with_masks(x) # If n is an int, take the n last blocks. If it's a list, take them output, total_block_len = [], len(self.blocks) blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n for i, blk in enumerate(self.blocks): x = blk(x) if i in blocks_to_take: output.append(x) assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" return output
def _get_intermediate_layers_chunked(self, x, n=1): x = self.prepare_tokens_with_masks(x) output, i, total_block_len = [], 0, len(self.blocks[-1]) # If n is an int, take the n last blocks. If it's a list, take them blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n for block_chunk in self.blocks: for blk in block_chunk[i:]: # Passing the nn.Identity() x = blk(x) if i in blocks_to_take: output.append(x) i += 1 assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" return output
def get_intermediate_layers( self, x: torch.Tensor, n: Union[int, Sequence] = 1, # Layers or n last layers to take reshape: bool = False, return_class_token: bool = False, norm=True, ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: if self.chunked_blocks: outputs = self._get_intermediate_layers_chunked(x, n) else: outputs = self._get_intermediate_layers_not_chunked(x, n) if norm: outputs = [self.norm(out) for out in outputs] class_tokens = [out[:, 0] for out in outputs] outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs] if reshape: B, _, w, h = x.shape outputs = [ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous() for out in outputs ] if return_class_token: return tuple(zip(outputs, class_tokens)) return tuple(outputs)
def forward(self, *args, is_training=True, **kwargs): ret = self.forward_features(*args, **kwargs) if is_training: return ret else: return self.head(ret["x_norm_clstoken"])
def init_weights_vit_timm(module: nn.Module, name: str = ""): """ViT weight initialization, original timm impl (for reproducibility)""" if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias)
def vit_small(patch_size=16, num_register_tokens=0, **kwargs): model = DinoVisionTransformer( patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def vit_base(patch_size=16, num_register_tokens=0, **kwargs): model = DinoVisionTransformer( patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def vit_large(patch_size=16, num_register_tokens=0, **kwargs): model = DinoVisionTransformer( patch_size=patch_size, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs): """ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 """ model = DinoVisionTransformer( patch_size=patch_size, embed_dim=1536, depth=40, num_heads=24, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339# Copied from facebookresearch/vggt, vggt/models/aggregator.py; only the imports are changed (flat module names).# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import loggingimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.utils.checkpoint import checkpointfrom typing import Optional, Tuple, Union, List, Dict, Any
from .vggt_layers import PatchEmbedfrom .vggt_layers_block import Blockfrom .vggt_layers_rope import RotaryPositionEmbedding2D, PositionGetterfrom .vggt_layers_vision_transformer import vit_small, vit_base, vit_large, vit_giant2
logger = logging.getLogger(__name__)
_RESNET_MEAN = [0.485, 0.456, 0.406]_RESNET_STD = [0.229, 0.224, 0.225]
class Aggregator(nn.Module): """ The Aggregator applies alternating-attention over input frames, as described in VGGT: Visual Geometry Grounded Transformer.
Remember to set model.train() to enable gradient checkpointing to reduce memory usage.
Args: img_size (int): Image size in pixels. patch_size (int): Size of each patch for PatchEmbed. embed_dim (int): Dimension of the token embeddings. depth (int): Number of blocks. num_heads (int): Number of attention heads. mlp_ratio (float): Ratio of MLP hidden dim to embedding dim. num_register_tokens (int): Number of register tokens. block_fn (nn.Module): The block type used for attention (Block by default). qkv_bias (bool): Whether to include bias in QKV projections. proj_bias (bool): Whether to include bias in the output projection. ffn_bias (bool): Whether to include bias in MLP layers. patch_embed (str): Type of patch embed. e.g., "conv" or "dinov2_vitl14_reg". aa_order (list[str]): The order of alternating attention, e.g. ["frame", "global"]. aa_block_size (int): How many blocks to group under each attention type before switching. If not necessary, set to 1. qk_norm (bool): Whether to apply QK normalization. rope_freq (int): Base frequency for rotary embedding. -1 to disable. init_values (float): Init scale for layer scale. """
def __init__( self, img_size=518, patch_size=14, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4.0, num_register_tokens=4, block_fn=Block, qkv_bias=True, proj_bias=True, ffn_bias=True, patch_embed="dinov2_vitl14_reg", aa_order=["frame", "global"], aa_block_size=1, qk_norm=True, rope_freq=100, init_values=0.01, cached_layer_indices: Tuple[int, ...] = (4, 11, 17, 23), ): super().__init__()
self.__build_patch_embed__(patch_embed, img_size, patch_size, num_register_tokens, embed_dim=embed_dim)
# Initialize rotary position embedding if frequency > 0 self.rope = RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None self.position_getter = PositionGetter() if self.rope is not None else None
self.frame_blocks = nn.ModuleList( [ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, proj_bias=proj_bias, ffn_bias=ffn_bias, init_values=init_values, qk_norm=qk_norm, rope=self.rope, ) for _ in range(depth) ] )
self.global_blocks = nn.ModuleList( [ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, proj_bias=proj_bias, ffn_bias=ffn_bias, init_values=init_values, qk_norm=qk_norm, rope=self.rope, ) for _ in range(depth) ] )
self.depth = depth self.aa_order = aa_order self.patch_size = patch_size self.aa_block_size = aa_block_size self.cached_layer_indices = set(cached_layer_indices) self.cached_layer_indices.add(depth - 1)
# Validate that depth is divisible by aa_block_size if self.depth % self.aa_block_size != 0: raise ValueError(f"depth ({depth}) must be divisible by aa_block_size ({aa_block_size})")
self.aa_block_num = self.depth // self.aa_block_size
# Note: We have two camera tokens, one for the first frame and one for the rest # The same applies for register tokens self.camera_token = nn.Parameter(torch.randn(1, 2, 1, embed_dim)) self.register_token = nn.Parameter(torch.randn(1, 2, num_register_tokens, embed_dim))
# The patch tokens start after the camera and register tokens self.patch_start_idx = 1 + num_register_tokens
# Initialize parameters with small values nn.init.normal_(self.camera_token, std=1e-6) nn.init.normal_(self.register_token, std=1e-6)
# Register normalization constants as buffers for name, value in (("_resnet_mean", _RESNET_MEAN), ("_resnet_std", _RESNET_STD)): self.register_buffer(name, torch.FloatTensor(value).view(1, 1, 3, 1, 1), persistent=False)
self.use_reentrant = False # hardcoded to False
def __build_patch_embed__( self, patch_embed, img_size, patch_size, num_register_tokens, interpolate_antialias=True, interpolate_offset=0.0, block_chunks=0, init_values=1.0, embed_dim=1024, ): """ Build the patch embed layer. If 'conv', we use a simple PatchEmbed conv layer. Otherwise, we use a vision transformer. """
if "conv" in patch_embed: self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=3, embed_dim=embed_dim) else: vit_models = { "dinov2_vitl14_reg": vit_large, "dinov2_vitb14_reg": vit_base, "dinov2_vits14_reg": vit_small, "dinov2_vitg2_reg": vit_giant2, }
self.patch_embed = vit_models[patch_embed]( img_size=img_size, patch_size=patch_size, num_register_tokens=num_register_tokens, interpolate_antialias=interpolate_antialias, interpolate_offset=interpolate_offset, block_chunks=block_chunks, init_values=init_values, )
# Disable gradient updates for mask token if hasattr(self.patch_embed, "mask_token"): self.patch_embed.mask_token.requires_grad_(False)
def forward(self, images: torch.Tensor) -> Tuple[List[Optional[torch.Tensor]], int]: """ Args: images (torch.Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. B: batch size, S: sequence length, 3: RGB channels, H: height, W: width
Returns: (list[torch.Tensor | None], int): The list of cached outputs from the attention blocks. Entries for uncached layers are None so layer indices remain stable. and the patch_start_idx indicating where patch tokens begin. """ B, S, C_in, H, W = images.shape
if C_in != 3: raise ValueError(f"Expected 3 input channels, got {C_in}")
# Normalize images and reshape for patch embed images = (images - self._resnet_mean) / self._resnet_std
# Reshape to [B*S, C, H, W] for patch embedding images = images.view(B * S, C_in, H, W) patch_tokens = self.patch_embed(images)
if isinstance(patch_tokens, dict): patch_tokens = patch_tokens["x_norm_patchtokens"]
_, P, C = patch_tokens.shape
# Expand camera and register tokens to match batch size and sequence length camera_token = slice_expand_and_flatten(self.camera_token, B, S) register_token = slice_expand_and_flatten(self.register_token, B, S)
# Concatenate special tokens with patch tokens tokens = torch.cat([camera_token, register_token, patch_tokens], dim=1)
pos = None if self.rope is not None: pos = self.position_getter(B * S, H // self.patch_size, W // self.patch_size, device=images.device)
if self.patch_start_idx > 0: # do not use position embedding for special tokens (camera and register tokens) # so set pos to 0 for the special tokens pos = pos + 1 pos_special = torch.zeros(B * S, self.patch_start_idx, 2).to(images.device).to(pos.dtype) pos = torch.cat([pos_special, pos], dim=1)
# update P because we added special tokens _, P, C = tokens.shape
frame_idx = 0 global_idx = 0 output_list = []
for _ in range(self.aa_block_num): for attn_type in self.aa_order: if attn_type == "frame": tokens, frame_idx, frame_intermediates = self._process_frame_attention( tokens, B, S, P, C, frame_idx, pos=pos ) elif attn_type == "global": tokens, global_idx, global_intermediates = self._process_global_attention( tokens, B, S, P, C, global_idx, pos=pos ) else: raise ValueError(f"Unknown attention type: {attn_type}")
for i in range(len(frame_intermediates)): layer_idx = len(output_list) if layer_idx in self.cached_layer_indices: # concat frame and global intermediates, [B x S x P x 2C] concat_inter = torch.cat([frame_intermediates[i], global_intermediates[i]], dim=-1) output_list.append(concat_inter) else: output_list.append(None)
del frame_intermediates del global_intermediates return output_list, self.patch_start_idx
def _process_frame_attention(self, tokens, B, S, P, C, frame_idx, pos=None): """ Process frame attention blocks. We keep tokens in shape (B*S, P, C). """ # If needed, reshape tokens or positions: if tokens.shape != (B * S, P, C): tokens = tokens.view(B, S, P, C).view(B * S, P, C)
if pos is not None and pos.shape != (B * S, P, 2): pos = pos.view(B, S, P, 2).view(B * S, P, 2)
intermediates = []
# by default, self.aa_block_size=1, which processes one block at a time for _ in range(self.aa_block_size): if self.training: tokens = checkpoint(self.frame_blocks[frame_idx], tokens, pos, use_reentrant=self.use_reentrant) else: tokens = self.frame_blocks[frame_idx](tokens, pos=pos) frame_idx += 1 intermediates.append(tokens.view(B, S, P, C))
return tokens, frame_idx, intermediates
def _process_global_attention(self, tokens, B, S, P, C, global_idx, pos=None): """ Process global attention blocks. We keep tokens in shape (B, S*P, C). """ if tokens.shape != (B, S * P, C): tokens = tokens.view(B, S, P, C).view(B, S * P, C)
if pos is not None and pos.shape != (B, S * P, 2): pos = pos.view(B, S, P, 2).view(B, S * P, 2)
intermediates = []
# by default, self.aa_block_size=1, which processes one block at a time for _ in range(self.aa_block_size): if self.training: tokens = checkpoint(self.global_blocks[global_idx], tokens, pos, use_reentrant=self.use_reentrant) else: tokens = self.global_blocks[global_idx](tokens, pos=pos) global_idx += 1 intermediates.append(tokens.view(B, S, P, C))
return tokens, global_idx, intermediates
def slice_expand_and_flatten(token_tensor, B, S): """ Processes specialized tokens with shape (1, 2, X, C) for multi-frame processing: 1) Uses the first position (index=0) for the first frame only 2) Uses the second position (index=1) for all remaining frames (S-1 frames) 3) Expands both to match batch size B 4) Concatenates to form (B, S, X, C) where each sequence has 1 first-position token followed by (S-1) second-position tokens 5) Flattens to (B*S, X, C) for processing
Returns: torch.Tensor: Processed tokens with shape (B*S, X, C) """
# Slice out the "query" tokens => shape (1, 1, ...) query = token_tensor[:, 0:1, ...].expand(B, 1, *token_tensor.shape[2:]) # Slice out the "other" tokens => shape (1, S-1, ...) others = token_tensor[:, 1:, ...].expand(B, S - 1, *token_tensor.shape[2:]) # Concatenate => shape (B, S, ...) combined = torch.cat([query, others], dim=1)
# Finally flatten => shape (B*S, ...) combined = combined.view(B * S, *combined.shape[2:]) return combined.gitattributes+1
LICENSEAdded+9
LICENSE-QWENAdded+202
LICENSE-VGGTAdded+115
README.mdAdded+102
chat_template.jinjaAdded+154
config.jsonAdded+137
configuration_spacetimevlm.pyAdded+44
generation_config.jsonAdded+9
model-00001-of-00002.safetensorsAdded+3
model-00002-of-00002.safetensorsAdded+3
model.safetensors.index.jsonAdded
modeling_spacetimevlm.pyAdded+456
processor_config.jsonAdded+61
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+51
vggt_heads_dpt_head.pyAdded+485
vggt_heads_head_act.pyAdded+126
vggt_heads_utils.pyAdded+110
vggt_layers.pyAdded+12
vggt_layers_attention.pyAdded+94
vggt_layers_block.pyAdded+248
vggt_layers_drop_path.pyAdded+35
vggt_layers_layer_scale.pyAdded+23
vggt_layers_mlp.pyAdded+41
vggt_layers_patch_embed.pyAdded+86
vggt_layers_rope.pyAdded+189
vggt_layers_swiglu_ffn.pyAdded+68
vggt_layers_vision_transformer.pyAdded+398
vggt_models_aggregator.pyAdded+339