``` ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── demo_webdino.py ├── demo_webdino_local.py ├── demo_webmae.py ├── demo_webmae_local.py ├── dinov2/ ├── layers/ ├── __init__.py ├── attention.py ├── block.py ├── dino_head.py ├── drop_path.py ├── layer_scale.py ├── mlp.py ├── patch_embed.py ├── swiglu_ffn.py ├── vision_transformer.py ├── mae/ ├── mae.py ├── sample_images/ ├── bird.JPEG ├── test_processor.py ``` ## /.gitignore ```gitignore path="/.gitignore" *.egg-info/ *.pyc __pycache__/ ``` ## /CODE_OF_CONDUCT.md # Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. This Code of Conduct also applies outside the project spaces when there is a reasonable belief that an individual's behavior may have a negative impact on the project or its community. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq ## /CONTRIBUTING.md # Contributing to metamorph We want to make contributing to this project as easy and transparent as possible. ## Pull Requests We actively welcome your pull requests. 1. Fork the repo and create your branch from `main`. 2. If you've added code that should be tested, add tests. 3. If you've changed APIs, update the documentation. 4. Ensure the test suite passes. 5. Make sure your code lints. 6. If you haven't already, complete the Contributor License Agreement ("CLA"). ## Contributor License Agreement ("CLA") In order to accept your pull request, we need you to submit a CLA. You only need to do this once to work on any of Facebook's open source projects. Complete your CLA here: ## Issues We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. In those cases, please go through the process outlined on that page and do not file a public issue. ## License By contributing to metamorph, you agree that your contributions will be licensed under the LICENSE file in the root directory of this source tree. ## /LICENSE ``` path="/LICENSE" Attribution-NonCommercial 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-NonCommercial 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ``` ## /README.md # Web-SSL: Scaling Language-Free Visual Representation Learning Official inference code for the **Web-SSL** model family introduced in: [Scaling Language-Free Visual Representation Learning](https://arxiv.org/abs/2504.01017). [David Fan](https://davidfan.io)\*, [Shengbang Tong](https://tsb0601.github.io/)\*, [Jiachen Zhu](https://jiachenzhu.github.io), [Koustuv Sinha](https://koustuvsinha.com/), [Zhuang Liu](https://liuzhuang13.github.io), [Xinlei Chen](https://xinleic.xyz/), [Michael Rabbat](https://scholar.google.com/citations?user=cMPKe9UAAAAJ), [Nicolas Ballas](https://scholar.google.com/citations?user=euUV4iUAAAAJ), [Yann LeCun](http://yann.lecun.com), [Amir Bar](https://www.amirbar.net/)†, [Saining Xie](https://www.sainingxie.com/)† FAIR Meta, New York University, Princeton University \*equal contribution, †equal advising [](https://arxiv.org/abs/2504.01017) [](https://davidfan.io/webssl/) [](https://huggingface.co/collections/facebook/web-ssl-68094132c15fbd7808d1e9bb)

## Overview Web-SSL explores the scaling potential of visual self-supervised learning (SSL) on web-scale data. By scaling model size and training data, we show that vision-only models can match and even surpass language-supervised methods like CLIP, challenging the prevailing assumption that language supervision is necessary to learn strong visual representations for multimodal modeling. We present Web-SSL: a family of vision-only models, ranging from 0.3B to 7B parameters, that offers a strong alternative to CLIP for both multimodal modeling and classic vision tasks. Key findings: - 📈 SSL improves continuously with both model capacity and data. - 🔍 Web-SSL matches or exceeds language-supervised methods on a wide range of VQA tasks—even on language-related tasks like OCR & Chart understanding, which were traditionally dominated by CLIP. - 🖼️ Our models maintain competitive performance on classic vision tasks like classification and segmentation while excelling at multimodal tasks. - 📊 Visual SSL methods are sensitive to data distribution! Training on filtered datasets with a higher concentration of text-rich images substantially improves OCR & Chart understanding. ## Our Models We provide our model weights in both HuggingFace and native PyTorch format. Please see the [Usage](#usage) section for sample model loading and inference code. ### Web-DINO Models #### Standard Models Web-DINO is a family of DINOv2 models ranging from 0.3B to 7B parameters trained on larger scale web images. Web-DINO models especially excel at multimodal tasks such as VQA, without sacrificing performance in classic vision tasks such as image classification. Please see our paper for full details. | Model | Patch Size | Resolution | Data | HuggingFace | Weights | |-------|------------|------------|------|-------------|---------| | webssl-dino300m-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino300m-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino300m_full2b_224.pth) | | webssl-dino1b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino1b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino1b_full2b_224.pth) | | webssl-dino2b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino2b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino2b_full2b_224.pth) | | webssl-dino3b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino3b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino3b_full2b_224.pth) | | webssl-dino5b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino5b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino5b_full2b_224.pth) | | **webssl-dino7b-full8b-224** ⭐ | 14x14 | 224x224 | 8B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino7b-full8b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino7b_full8b_224.pth) | | **webssl-dino7b-full8b-378** ⭐ | 14x14 | 378x378 | 8B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino7b-full8b-378) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino7b_full8b_378.pth) | | **webssl-dino7b-full8b-518** ⭐ | 14x14 | 518x518 | 8B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-dino7b-full8b-518) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino7b_full8b_518.pth) | **Model Notes:** - **webssl-dino7b-full8b-224** ⭐: Best 224x224 resolution model - **webssl-dino7b-full8b-378** ⭐: Better performance with 384x384 resolution - **webssl-dino7b-full8b-518** ⭐: Best overall performance with 518x518 resolution #### Filtered Data Models These models were trained on filtered subsets of MC-2B images with a higher concentration of text (e.g. signs, charts, tables, annotations, etc). This enhances OCR & Chart understanding capabilities without a notable performance drop in other VQA categories, relative to same-size models trained on the full data. | Model | Patch Size | Resolution | Data | HuggingFace | Weights | |-------|------------|------------|------|-------------|---------| | webssl-dino2b-light2b-224 | 14x14 | 224x224 | 2B (MC-2B light) | [Link](https://huggingface.co/facebook/webssl-dino2b-light2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino2b_light2b_224.pth) | | webssl-dino2b-heavy2b-224 | 14x14 | 224x224 | 2B (MC-2B heavy) | [Link](https://huggingface.co/facebook/webssl-dino2b-heavy2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino2b_heavy2b_224.pth) | | webssl-dino3b-light2b-224 | 14x14 | 224x224 | 2B (MC-2B light) | [Link](https://huggingface.co/facebook/webssl-dino3b-light2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino3b_light2b_224.pth) | | webssl-dino3b-heavy2b-224 | 14x14 | 224x224 | 2B (MC-2B heavy) | [Link](https://huggingface.co/facebook/webssl-dino3b-heavy2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_dino3b_heavy2b_224.pth) | **Data Notes:** - **MC-2B light**: 50.3% subset of MC-2B images that contain text - **MC-2B heavy**: 1.3% subset of MC-2B images that contain charts/documents ### Web-MAE Models Web-MAE is a family of MAE models ranging from 0.3B to 3B parameters, trained on larger scale web images. We release only the encoder for feature extraction. | Model | Patch Size | Resolution | Data | HuggingFace | Weights | |-------|------------|------------|------|-------------|---------| | webssl-mae300m-full2b-224 | 16x16 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-mae300m-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_mae300m_full2b_224.pth) | | webssl-mae700m-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-mae700m-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_mae700m_full2b_224.pth) | | webssl-mae1b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-mae1b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_mae1b_full2b_224.pth) | | webssl-mae2b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-mae2b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_mae2b_full2b_224.pth) | | webssl-mae3b-full2b-224 | 14x14 | 224x224 | 2B (MC-2B) | [Link](https://huggingface.co/facebook/webssl-mae3b-full2b-224) | [Link](https://dl.fbaipublicfiles.com/webssl/webssl_mae3b_full2b_224.pth) | ## Installation It is possible that older or newer versions will work. However, we haven't tested them for this inference code. ``` conda create -n webssl python=3.11 conda activate webssl pip install torch==2.5.1 torchvision==0.20.1 xformers --index-url https://download.pytorch.org/whl/cu124 pip install transformers==4.48.0 huggingface-hub==0.27.1 timm==1.0.15 ``` ## Usage We provide two examples to use our models with both HuggingFace and native PyTorch. Note that you are not limited to using the pretraining resolution for inference, however, you will probably get the best results by inferencing with the same resolution. ### 1. Using HuggingFace Transformers You may choose to download the model weights locally first using [huggingface-cli](https://huggingface.co/docs/huggingface_hub/main/en/guides/cli). This is convenient when you don't have a large cache or when the network is slow. E.g. `huggingface-cli download facebook/webssl-dino7b-full8b-518 --local-dir YOUR_PATH`, then supply `YOUR_PATH` to `from_pretrained()`. ```python from transformers import AutoImageProcessor, Dinov2Model # Load a Web-DINO model model_name = "facebook/webssl-dino1b-full2b-224" processor = AutoImageProcessor.from_pretrained(model_name) model = Dinov2Model.from_pretrained(model_name, attn_implementation='sdpa') # 'eager' attention also supported model.cuda().eval() # Process an image from PIL import Image image = Image.open("sample_images/bird.JPEG") with torch.no_grad(): inputs = processor(images=image, return_tensors="pt").to('cuda') outputs = model(**inputs) last_hidden_states = outputs.last_hidden_state ``` ### 2. Using PyTorch with original weights ```python from dinov2.vision_transformer import webssl_dino1b_full2b_224 import torch from PIL import Image from torchvision import transforms # Define image transformation transform = transforms.Compose([ transforms.Resize(256, interpolation=transforms.InterpolationMode.BICUBIC), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) ]) # Load model model = webssl_dino1b_full2b_224() # Load weights checkpoint_path = "path/to/downloaded/weights.pth" state_dict = torch.load(checkpoint_path, map_location="cpu") msg = model.load_state_dict(state_dict, strict=False) print(f"Loaded weights: {msg}") model.cuda().eval() # Process an image image = Image.open("sample_images/bird.JPEG") x = transform(image).unsqueeze(0).cuda() with torch.no_grad(): features = model.forward_features(x) patch_features = features['x_norm_patchtokens'] ``` See [demo_webdino.py](demo_webdino.py) and [demo_webmae.py](demo_webmae.py) for a complete example comparing HuggingFace and PyTorch implementations. ## Citation If you find this repository useful for your research, please consider citing: ```bibtex @article{fan2025scaling, title={Scaling Language-Free Visual Representation Learning}, author={Fan, David and Tong, Shengbang and Zhu, Jiachen and Sinha, Koustuv and Liu, Zhuang and Chen, Xinlei and Rabbat, Michael and Ballas, Nicolas and LeCun, Yann and Bar, Amir and others}, journal={arXiv preprint arXiv:2504.01017}, year={2025} } ``` ## License The majority of Web-SSL is licensed under CC-BY-NC, however portions of the project are available under separate license terms: DINOv2 is licensed under the Apache 2.0 license. ## Acknowledgements We thank the [DINOv2](https://github.com/facebookresearch/dinov2) and [MAE](https://github.com/facebookresearch/mae) teams for their excellent codebases, and the [MetaCLIP](https://github.com/facebookresearch/MetaCLIP) team for the wonderful MetaCLIP dataset and codebase. We thank the [Cambrian](https://github.com/cambrian-mllm/cambrian) team for their insightful study into the role of vision encoders in MLLMs and their evaluation suite. Lastly, we thank our amazing collaborators in FAIR and the Meta Open-Source team for making this possible. ## /demo_webdino.py ```py path="/demo_webdino.py" # 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 dinov2.vision_transformer import ( webssl_dino300m_full2b_224, webssl_dino1b_full2b_224, webssl_dino2b_full2b_224, webssl_dino2b_light2b_224, webssl_dino2b_heavy2b_224, webssl_dino3b_light2b_224, webssl_dino3b_heavy2b_224, webssl_dino3b_full2b_224, webssl_dino5b_full2b_224, webssl_dino7b_full8b_224, webssl_dino7b_full8b_378, webssl_dino7b_full8b_518 ) import os from PIL import Image import torch from torchvision import transforms from transformers import AutoImageProcessor, Dinov2Model, ViTModel # Load weights of the DINO teacher encoder # The PyTorch state_dict is already preprocessed to have the right key names def load_pretrained_dino_weights(model, pretrained_weights): state_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu") msg = model.load_state_dict(state_dict, strict=False) print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) # Adjust to your liking - e.g. the input resolution, and whether to crop / what crop resolution. def build_pt_transform(img_size): IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) # For this tutorial, we will omit center crop and resize directly to a square image. You may find what works best for you eval_transform = transforms.Compose([ transforms.Resize((img_size, img_size), interpolation=transforms.InterpolationMode.BICUBIC), # resize shortest side to img_size transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD) ]) return eval_transform def forward_dino(model_hf, model_pt): # Run a sample inference with DINO with torch.no_grad(): # Read and pre-process the image im = Image.open('sample_images/bird.JPEG') x_pt = pt_transform(im).cuda().unsqueeze(0) x_hf = hf_transform(im, return_tensors="pt").to("cuda") # Extract the patch-wise features from the last layer out_patch_features_pt = model_pt.forward_features(x_pt)['x_norm_patchtokens'] # x_norm_clstoken is the cls token out_patch_features_hf = model_hf(**x_hf).last_hidden_state[:, 1:] # index 0 is the cls token return out_patch_features_hf, out_patch_features_pt if __name__ == '__main__': model_name = 'webssl-dino1b-full2b-224' # Replace with your favored model, e.g. webssl-dino1b-full2b-224 or webssl-dino7b-full8b-518 model_name_with_underscore = model_name.replace('-', '_') # HuggingFace model repo name hf_model_name = f'facebook/{model_name}' # Path to local PyTorch weights pt_model_path = f'YOUR_PATH_TO_TORCH_WEIGHTS.pth' # Initialize the HuggingFace model, load pretrained weights model_hf = Dinov2Model.from_pretrained(hf_model_name, attn_implementation='sdpa') # 'eager' mode also supported model_hf.cuda().eval() # Build HuggingFace preprocessing transform # For this tutorial, we will omit center crop and resize directly to a square image. You may find what works best for your use-case hf_transform = AutoImageProcessor.from_pretrained(hf_model_name, use_fast=False) hf_transform.do_center_crop = False hf_transform.size = { 'height': hf_transform.size['shortest_edge'], 'width': hf_transform.size['shortest_edge'] } # Initialize the PyTorch model, load pretrained weights model_pt = globals()[model_name_with_underscore]() # fancy way to call a method given the name, e.g. webssl_dino7b_full8b_518() model_pt.cuda().eval() load_pretrained_dino_weights(model_pt, pt_model_path) # we won't load the dino_head and ibot_head from SSL # Build PyTorch preprocessing transform pt_transform = build_pt_transform(img_size = hf_transform.crop_size['height']) # Inference out_patch_features_hf, out_patch_features_pt = forward_dino(model_hf, model_pt) print(out_patch_features_hf.shape, out_patch_features_pt.shape, torch.abs(out_patch_features_pt - out_patch_features_hf).sum(), torch.allclose(out_patch_features_pt, out_patch_features_hf, atol=1e-3, rtol=1e-3)) ``` ## /demo_webdino_local.py ```py path="/demo_webdino_local.py" # 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 dinov2.vision_transformer import ( webssl_dino300m_full2b_224, webssl_dino1b_full2b_224, webssl_dino2b_full2b_224, webssl_dino2b_light2b_224, webssl_dino2b_heavy2b_224, webssl_dino3b_light2b_224, webssl_dino3b_heavy2b_224, webssl_dino3b_full2b_224, webssl_dino5b_full2b_224, webssl_dino7b_full8b_224, webssl_dino7b_full8b_378, webssl_dino7b_full8b_518 ) import os from PIL import Image import torch from torchvision import transforms from transformers import AutoImageProcessor, Dinov2Model, ViTModel # Process the PyTorch state_dict to have the right key names before loading into the model # For the non-processed teacher model def load_pretrained_teacher_dino_weights(model, pretrained_weights, checkpoint_key): state_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu") if checkpoint_key is not None and checkpoint_key in state_dict: print(f"Take key {checkpoint_key} in provided checkpoint dict") state_dict = state_dict[checkpoint_key] # remove `module.` prefix state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} # remove `backbone.` prefix induced by multicrop wrapper state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} # Remove pretraining heads filtered_state_dict = {k: v for k, v in state_dict.items() if not k.startswith("dino_head") and not k.startswith("ibot_head")} msg = model.load_state_dict(filtered_state_dict, strict=False) print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) # Process the PyTorch state_dict to have the right key names before loading into the model def load_pretrained_dino_weights(model, pretrained_weights): state_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu") msg = model.load_state_dict(state_dict, strict=False) print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) # Adjust to your liking - e.g. the input resolution, and whether to crop / what crop resolution. def build_pt_transform(img_size): IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) eval_transform = transforms.Compose([ transforms.Resize((img_size, img_size), interpolation=transforms.InterpolationMode.BICUBIC), # resize shortest side to img_size transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD) ]) return eval_transform def forward_dino(model_hf, model_pt): # Run a sample inference with DINO with torch.no_grad(): # Read and pre-process the image im = Image.open('sample_images/bird.JPEG') x_pt = pt_transform(im).cuda().unsqueeze(0) x_hf = hf_transform(im, return_tensors="pt").to("cuda") # Extract the patch-wise features from the last layer out_patch_features_pt = model_pt.forward_features(x_pt)['x_norm_patchtokens'] # x_norm_clstoken is the cls token out_patch_features_hf = model_hf(**x_hf).last_hidden_state[:, 1:] # index 0 is the cls token return out_patch_features_hf, out_patch_features_pt if __name__ == '__main__': model_name = 'webssl-dino2b-full2b-224' # Replace with your favored model, e.g. webssl-dino1b-full2b-224 or webssl-dino7b-full8b-518 model_name_with_underscore = model_name.replace('-', '_') # HuggingFace model repo name hf_model_name = f'facebook/{model_name}' # Path to local PyTorch weights pt_model_path = f'/checkpoint/amaia/video/davidfan/shared_checkpoints/webssl/{model_name_with_underscore}/{model_name_with_underscore}.pth' # Initialize the HuggingFace model, load pretrained weights model_hf = Dinov2Model.from_pretrained(hf_model_name, attn_implementation='sdpa') # 'eager' mode also supported model_hf.cuda().eval() # Build HuggingFace preprocessing transform hf_transform = AutoImageProcessor.from_pretrained(hf_model_name, use_fast=False) hf_transform.do_center_crop = False hf_transform.size = { 'height': hf_transform.size['shortest_edge'], 'width': hf_transform.size['shortest_edge'] } # Initialize the PyTorch model, load pretrained weights model_pt = globals()[model_name_with_underscore]() # fancy way to call a method given the name, e.g. webssl_dino7b_full8b_518() model_pt.cuda().eval() load_pretrained_dino_weights(model_pt, pt_model_path) # we won't load the dino_head and ibot_head from SSL # Build PyTorch preprocessing transform pt_transform = build_pt_transform(img_size = hf_transform.crop_size['height']) # Inference out_patch_features_hf, out_patch_features_pt = forward_dino(model_hf, model_pt) print(out_patch_features_hf.shape, out_patch_features_pt.shape, torch.abs(out_patch_features_pt - out_patch_features_hf).sum(), torch.allclose(out_patch_features_pt, out_patch_features_hf, atol=1e-3, rtol=1e-3)) ``` ## /demo_webmae.py ```py path="/demo_webmae.py" # 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 mae.mae import ( webssl_mae300m_full2b_224, webssl_mae700m_full2b_224, webssl_mae1b_full2b_224, webssl_mae2b_full2b_224, webssl_mae3b_full2b_224, ) import os from PIL import Image import torch from torchvision import transforms from transformers import AutoImageProcessor, ViTModel # Load weights of the MAE encoder def load_pretrained_mae_weights(model, pretrained_weights): state_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu") msg = model.load_state_dict(state_dict) print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) # Adjust to your liking - e.g. the input resolution, and whether to crop / what crop resolution. def build_pt_transform(img_size): IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) # For this tutorial, we will omit center crop and resize directly to a square image. You may find what works best for you eval_transform = transforms.Compose([ transforms.Resize((img_size, img_size), interpolation=transforms.InterpolationMode.BICUBIC), # resize shortest side to img_size transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD) ]) return eval_transform def forward_mae(model_hf, model_pt): # Run a sample inference with MAE with torch.no_grad(): # Read and pre-process the image im = Image.open('sample_images/bird.JPEG') x_pt = pt_transform(im).cuda().unsqueeze(0) x_hf = hf_transform(im, return_tensors="pt").to("cuda") # Extract the patch-wise features from the last layer out_patch_features_pt = model_pt.forward_features(x_pt)[:, 1:, ] # index 0 is the cls_token out_patch_features_hf = model_hf(**x_hf).last_hidden_state[:, 1:, ] # index 0 is the cls_token return out_patch_features_hf, out_patch_features_pt if __name__ == '__main__': model_name = 'webssl-mae1b-full2b-224' # Replace with your favored model, e.g. webssl-mae1b-full2b-224 or webssl-mae3b-full2b-224 model_name_with_underscore = model_name.replace('-', '_') # HuggingFace model repo name hf_model_name = f'facebook/{model_name}' # Path to local PyTorch weights pt_model_path = f'YOUR_PATH_TO_TORCH_WEIGHTS.pth' # Initialize the HuggingFace model, load pretrained weights model_hf = ViTModel.from_pretrained(hf_model_name, attn_implementation='sdpa') # 'eager' mode also supported model_hf.cuda().eval() # Build HuggingFace preprocessing transform # For this tutorial, we will omit center crop and resize directly to a square image. You may find what works best for your use-case hf_transform = AutoImageProcessor.from_pretrained(hf_model_name, use_fast=False) hf_transform.do_center_crop = False hf_transform.size = { 'height': hf_transform.size['shortest_edge'], 'width': hf_transform.size['shortest_edge'] } # Initialize the PyTorch model, load pretrained weights model_pt = globals()[model_name_with_underscore]() # fancy way to call a method given the name, e.g. webssl_dino7b_full8b_518() model_pt.cuda().eval() load_pretrained_mae_weights(model_pt, pt_model_path) # Build PyTorch preprocessing transform pt_transform = build_pt_transform(img_size = hf_transform.crop_size['height']) # Inference out_patch_features_hf, out_patch_features_pt = forward_mae(model_hf, model_pt) print(out_patch_features_hf.shape, out_patch_features_pt.shape, torch.abs(out_patch_features_pt - out_patch_features_hf).sum(), torch.allclose(out_patch_features_pt, out_patch_features_hf, atol=1e-3, rtol=1e-3)) ``` ## /demo_webmae_local.py ```py path="/demo_webmae_local.py" # 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 mae.mae import ( webssl_mae300m_full2b_224, webssl_mae700m_full2b_224, webssl_mae1b_full2b_224, webssl_mae2b_full2b_224, webssl_mae3b_full2b_224, ) import os from PIL import Image import torch from torchvision import transforms from transformers import AutoImageProcessor, ViTModel def load_pretrained_mae_weights(model, pretrained_weights): state_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu") msg = model.load_state_dict(state_dict) print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) # Adjust to your liking - e.g. the input resolution, and whether to crop / what crop resolution. def build_pt_transform(img_size): IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) eval_transform = transforms.Compose([ transforms.Resize((img_size, img_size), interpolation=transforms.InterpolationMode.BICUBIC), # resize shortest side to img_size transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD) ]) return eval_transform def forward_mae(model_hf, model_pt): # Run a sample inference with MAE with torch.no_grad(): # Read and pre-process the image im = Image.open('sample_images/bird.JPEG') x_pt = pt_transform(im).cuda().unsqueeze(0) x_hf = hf_transform(im, return_tensors="pt").to("cuda") # Extract the patch-wise features from the last layer out_patch_features_pt = model_pt.forward_features(x_pt)[:, 1:, ] # index 0 is the cls_token out_patch_features_hf = model_hf(**x_hf).last_hidden_state[:, 1:, ] # index 0 is the cls_token return out_patch_features_hf, out_patch_features_pt if __name__ == '__main__': model_name = 'webssl-mae3b-full2b-224' # Replace with your favored model, e.g. webssl-mae1b-full2b-224 or webssl-mae3b-full2b-224 model_name_with_underscore = model_name.replace('-', '_') # HuggingFace model repo name hf_model_name = f'facebook/{model_name}' # Path to local PyTorch weights pt_model_path = f'/checkpoint/amaia/video/davidfan/shared_checkpoints/webssl/{model_name_with_underscore}/{model_name_with_underscore}.pth' # Initialize the HuggingFace model, load pretrained weights model_hf = ViTModel.from_pretrained(hf_model_name, attn_implementation='sdpa') # 'eager' mode also supported model_hf.cuda().eval() # Build HuggingFace preprocessing transform hf_transform = AutoImageProcessor.from_pretrained(hf_model_name, use_fast=False) hf_transform.do_center_crop = False hf_transform.size = { 'height': hf_transform.size['shortest_edge'], 'width': hf_transform.size['shortest_edge'] } # Initialize the PyTorch model, load pretrained weights model_pt = globals()[model_name_with_underscore]() # fancy way to call a method given the name, e.g. webssl_dino7b_full8b_518() model_pt.cuda().eval() load_pretrained_mae_weights(model_pt, pt_model_path) # Build PyTorch preprocessing transform pt_transform = build_pt_transform(img_size = hf_transform.crop_size['height']) # Inference out_patch_features_hf, out_patch_features_pt = forward_mae(model_hf, model_pt) print(out_patch_features_hf.shape, out_patch_features_pt.shape, torch.abs(out_patch_features_pt - out_patch_features_hf).sum(), torch.allclose(out_patch_features_pt, out_patch_features_hf, atol=1e-3, rtol=1e-3)) ``` ## /dinov2/layers/__init__.py ```py path="/dinov2/layers/__init__.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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. from .dino_head import DINOHead from .mlp import Mlp from .patch_embed import PatchEmbed from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused from .block import NestedTensorBlock from .attention import MemEffAttention ``` ## /dinov2/layers/attention.py ```py path="/dinov2/layers/attention.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 logging import os import warnings from torch import Tensor from torch import nn logger = logging.getLogger("dinov2") XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None try: if XFORMERS_ENABLED: from xformers.ops import memory_efficient_attention, unbind XFORMERS_AVAILABLE = True warnings.warn("xFormers is available (Attention)") else: warnings.warn("xFormers is disabled (Attention)") raise ImportError except ImportError: XFORMERS_AVAILABLE = False warnings.warn("xFormers is not available (Attention)") class Attention(nn.Module): def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, proj_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, ) -> None: super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim**-0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim, bias=proj_bias) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x: Tensor) -> Tensor: B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).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) -> Tensor: 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 x ``` ## /dinov2/layers/block.py ```py path="/dinov2/layers/block.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 logging import os from typing import Callable, List, Any, Tuple, Dict import warnings import torch from torch import nn, Tensor from .attention import Attention, MemEffAttention from .drop_path import DropPath from .layer_scale import LayerScale from .mlp import Mlp logger = logging.getLogger("dinov2") XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None try: if XFORMERS_ENABLED: from xformers.ops import fmha, scaled_index_add, index_select_cat XFORMERS_AVAILABLE = True warnings.warn("xFormers is available (Block)") else: warnings.warn("xFormers is disabled (Block)") raise ImportError except ImportError: XFORMERS_AVAILABLE = False warnings.warn("xFormers is not available (Block)") class Block(nn.Module): def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = False, 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, ) -> None: super().__init__() # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") 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, ) 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) -> Tensor: def attn_residual_func(x: Tensor) -> Tensor: return self.ls1(self.attn(self.norm1(x))) 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, 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)) x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 else: x = x + attn_residual_func(x) 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, ) -> 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 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 AssertionError ``` ## /dinov2/layers/dino_head.py ```py path="/dinov2/layers/dino_head.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 torch import torch.nn as nn from torch.nn.init import trunc_normal_ from torch.nn.utils import weight_norm class DINOHead(nn.Module): def __init__( self, in_dim, out_dim, use_bn=False, nlayers=3, hidden_dim=2048, bottleneck_dim=256, mlp_bias=True, ): super().__init__() nlayers = max(nlayers, 1) self.mlp = _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=hidden_dim, use_bn=use_bn, bias=mlp_bias) self.apply(self._init_weights) self.last_layer = weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False)) self.last_layer.weight_g.data.fill_(1) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) def forward(self, x): x = self.mlp(x) eps = 1e-6 if x.dtype == torch.float16 else 1e-12 x = nn.functional.normalize(x, dim=-1, p=2, eps=eps) x = self.last_layer(x) return x def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True): if nlayers == 1: return nn.Linear(in_dim, bottleneck_dim, bias=bias) else: layers = [nn.Linear(in_dim, hidden_dim, bias=bias)] if use_bn: layers.append(nn.BatchNorm1d(hidden_dim)) layers.append(nn.GELU()) for _ in range(nlayers - 2): layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias)) if use_bn: layers.append(nn.BatchNorm1d(hidden_dim)) layers.append(nn.GELU()) layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias)) return nn.Sequential(*layers) ``` ## /dinov2/layers/drop_path.py ```py path="/dinov2/layers/drop_path.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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) ``` ## /dinov2/layers/layer_scale.py ```py path="/dinov2/layers/layer_scale.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 torch from torch import Tensor from 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.gamma ``` ## /dinov2/layers/mlp.py ```py path="/dinov2/layers/mlp.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 x ``` ## /dinov2/layers/patch_embed.py ```py path="/dinov2/layers/patch_embed.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 Tensor import 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 flops ``` ## /dinov2/layers/swiglu_ffn.py ```py path="/dinov2/layers/swiglu_ffn.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # Borrowed from https://github.com/facebookresearch/dinov2 # # 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 os from typing import Callable, Optional import warnings from torch import Tensor, nn import 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 = SwiGLUFFN XFORMERS_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, ) ``` ## /dinov2/vision_transformer.py ```py path="/dinov2/vision_transformer.py" # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # Adapted from https://github.com/facebookresearch/dinov2/blob/main/dinov2/models/vision_transformer.py from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.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, ): """ 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.img_size = img_size self.patch_size = patch_size self.num_register_tokens = num_register_tokens self.interpolate_antialias = interpolate_antialias self.interpolate_offset = interpolate_offset 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, ) 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)) logger.info("Initializing weights") 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: 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: 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) try: num_blocks = len(self.blocks[-1]) except: num_blocks = len(self.blocks[-1].module) # num_blocks = len(self.blocks[-1].module) output, i, total_block_len = [], 0, num_blocks # 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_last_selfattention(self, x): x = self.prepare_tokens(x) for i, blk in enumerate(self.blocks): if i < len(self.blocks) - 1: x = blk(x) else: # return attention of the last block return blk(x, return_attention=True) 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=False, **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 webssl_dino300m_full2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """ Web-DINO ViT-300M DINOv2's "large" architecture / ViT-L """ model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino1b_full2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """ Web-DINO ViT-1B DINOv2's "giant2" architecture / ViT-little g Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 """ model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=1536, depth=40, num_heads=24, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino2b_full2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-2B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=2688, depth=24, num_heads=21, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino2b_light2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-2B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=2688, depth=24, num_heads=21, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino2b_heavy2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-2B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=2688, depth=24, num_heads=21, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino3b_full2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-3B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=3072, depth=26, num_heads=24, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino3b_light2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-3B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=3072, depth=26, num_heads=24, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino3b_heavy2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-3B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=3072, depth=26, num_heads=24, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino5b_full2b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-5B (LLM-inspired scaling)""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=3584, depth=32, num_heads=28, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino7b_full8b_224(img_size=224, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-7B (LLM-inspired scaling) pretrained with 224x224 resolution""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=4096, depth=32, num_heads=32, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino7b_full8b_378(img_size=378, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-7B (LLM-inspired scaling) pretrained with 378x378 resolution""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=4096, depth=32, num_heads=32, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model def webssl_dino7b_full8b_518(img_size=518, patch_size=14, num_register_tokens=0, **kwargs): """Web-DINO ViT-7B (LLM-inspired scaling) pretrained with 518x518 resolution""" model = DinoVisionTransformer( img_size=img_size, patch_size=patch_size, embed_dim=4096, depth=32, num_heads=32, mlp_ratio=4, ffn_layer='swiglu', init_values=1.0e-05, block_chunks=4, qkv_bias=True, proj_bias=True, ffn_bias=True, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model ``` ## /mae/mae.py ```py path="/mae/mae.py" # 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 timm.models.vision_transformer import _create_vision_transformer def webssl_mae300m_full2b_224(): """ Web-MAE ViT-300M ViT-L architecture """ model = _create_vision_transformer('vit_large_patch16_224.mae', patch_size=16, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4.0) return model def webssl_mae700m_full2b_224(): """ Web-MAE ViT-700M ViT-H architecture """ model = _create_vision_transformer('vit_large_patch16_224.mae', patch_size=14, embed_dim=1280, depth=32, num_heads=16, mlp_ratio=4.0) return model def webssl_mae1b_full2b_224(): """ Web-MAE ViT-1B DINOv2's "giant2" architecture / ViT-little g Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 """ model = _create_vision_transformer('vit_large_patch16_224.mae', patch_size=14, embed_dim=1536, depth=40, num_heads=24, mlp_ratio=4.0) return model def webssl_mae2b_full2b_224(): """Web-MAE ViT-2B (LLM-inspired scaling)""" model = _create_vision_transformer('vit_large_patch16_224.mae', patch_size=14, embed_dim=2688, depth=24, num_heads=21, mlp_ratio=4.0) return model def webssl_mae3b_full2b_224(): """Web-MAE ViT-3B (LLM-inspired scaling)""" model = _create_vision_transformer('vit_large_patch16_224.mae', patch_size=14, embed_dim=3072, depth=26, num_heads=24, mlp_ratio=4.0) return model ``` ## /sample_images/bird.JPEG Binary file available at https://raw.githubusercontent.com/facebookresearch/webssl/refs/heads/main/sample_images/bird.JPEG ## /test_processor.py ```py path="/test_processor.py" from transformers import AutoImageProcessor from torchvision import transforms import torch from PIL import Image def test_resolution(img_size): processor_hf = AutoImageProcessor.from_pretrained(f'facebook/webssl-dino7b-full8b-{img_size}') # processor_hf = AutoImageProcessor.from_pretrained('facebook/dinov2-giant', use_fast=True) processor_hf.crop_size = { 'height': img_size, 'width': img_size } processor_hf.size = { 'height': img_size, 'width': img_size } processor_hf.do_center_crop = False transform_pt = transforms.Compose([ transforms.Resize((img_size, img_size), interpolation=transforms.InterpolationMode.BICUBIC), # resize shortest side to img_size transforms.ToTensor(), transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) ]) im = Image.open('sample_images/bird.JPEG') out_im = processor_hf(im).pixel_values[0] out_pt = transform_pt(im) print(torch.abs(out_pt - out_im).sum()) test_resolution(224) test_resolution(378) test_resolution(518) ``` The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.