rishitdagli commited on
Commit
46ff99b
·
0 Parent(s):

push a demo

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. .gitignore +1 -0
  3. README.md +12 -0
  4. app.py +112 -0
  5. config.yaml +21 -0
  6. configs/model/audioldm.yaml +24 -0
  7. configs/model/clap.yaml +10 -0
  8. configs/model/clip.yaml +22 -0
  9. configs/model/codi.yaml +22 -0
  10. configs/model/openai_unet.yaml +85 -0
  11. configs/model/optimus.yaml +102 -0
  12. configs/model/sd.yaml +20 -0
  13. configs/vocab/bert-base-cased-vocab.txt +0 -0
  14. configs/vocab/bert_vocab_download_info.json +15 -0
  15. configs/vocab/gpt2-merges.txt +0 -0
  16. configs/vocab/gpt2-vocab.json +0 -0
  17. configs/vocab/gpt2_vocab_merge_download_info.json +4 -0
  18. examples/1.png +3 -0
  19. examples/2.png +3 -0
  20. examples/3.png +3 -0
  21. examples/4.png +3 -0
  22. examples/5.png +3 -0
  23. examples/6.png +3 -0
  24. examples/7.png +3 -0
  25. examples/8.png +3 -0
  26. examples/9.png +3 -0
  27. requirements.txt +30 -0
  28. torchhub/README.md +3 -0
  29. torchhub/facebookresearch_dinov2_main/CODE_OF_CONDUCT.md +80 -0
  30. torchhub/facebookresearch_dinov2_main/CONTRIBUTING.md +31 -0
  31. torchhub/facebookresearch_dinov2_main/LICENSE +400 -0
  32. torchhub/facebookresearch_dinov2_main/MODEL_CARD.md +201 -0
  33. torchhub/facebookresearch_dinov2_main/README.md +277 -0
  34. torchhub/facebookresearch_dinov2_main/conda.yaml +22 -0
  35. torchhub/facebookresearch_dinov2_main/dinov2/__init__.py +7 -0
  36. torchhub/facebookresearch_dinov2_main/dinov2/configs/__init__.py +23 -0
  37. torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitb14_pretrain.yaml +6 -0
  38. torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitg14_pretrain.yaml +7 -0
  39. torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitl14_pretrain.yaml +6 -0
  40. torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vits14_pretrain.yaml +6 -0
  41. torchhub/facebookresearch_dinov2_main/dinov2/configs/ssl_default_config.yaml +115 -0
  42. torchhub/facebookresearch_dinov2_main/dinov2/configs/train/vitg14.yaml +26 -0
  43. torchhub/facebookresearch_dinov2_main/dinov2/configs/train/vitl14.yaml +26 -0
  44. torchhub/facebookresearch_dinov2_main/dinov2/configs/train/vitl16_short.yaml +6 -0
  45. torchhub/facebookresearch_dinov2_main/dinov2/data/__init__.py +11 -0
  46. torchhub/facebookresearch_dinov2_main/dinov2/data/adapters.py +29 -0
  47. torchhub/facebookresearch_dinov2_main/dinov2/data/augmentations.py +130 -0
  48. torchhub/facebookresearch_dinov2_main/dinov2/data/collate.py +72 -0
  49. torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/__init__.py +8 -0
  50. torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/decoders.py +32 -0
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ checkpoints/* filter=lfs diff=lfs merge=lfs -text
37
+ examples/* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ checkpoints.sh
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: SEE-2-SOUND
3
+ emoji: 👀
4
+ colorFrom: pink
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 4.36.1
8
+ app_file: app.py
9
+ pinned: true
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union
2
+
3
+ import gradio as gr
4
+ import numpy as np
5
+ import see2sound
6
+ import spaces
7
+ import torch
8
+ import yaml
9
+ from huggingface_hub import snapshot_download
10
+
11
+ model_id = "rishitdagli/see-2-sound"
12
+ base_path = snapshot_download(repo_id=model_id)
13
+
14
+ with open("config.yaml", "r") as file:
15
+ data = yaml.safe_load(file)
16
+ data_str = yaml.dump(data)
17
+ updated_data_str = data_str.replace("checkpoints", base_path)
18
+ updated_data = yaml.safe_load(updated_data_str)
19
+ with open("config.yaml", "w") as file:
20
+ yaml.safe_dump(updated_data, file)
21
+
22
+ model = see2sound.See2Sound(config_path="config.yaml")
23
+ model.setup()
24
+
25
+
26
+ @spaces.GPU(duration=250)
27
+ @torch.no_grad()
28
+ def process_image(
29
+ image: str, num_audios: int, prompt: Union[str, None], steps: Union[int, None]
30
+ ) -> Tuple[str, str]:
31
+ model.run(
32
+ path=image,
33
+ output_path="audio.wav",
34
+ num_audios=num_audios,
35
+ prompt=prompt,
36
+ steps=steps,
37
+ )
38
+ return image, "audio.wav"
39
+
40
+
41
+ description_text = """# SEE-2-SOUND 🔊 Demo
42
+
43
+ Official demo for **SEE-2-SOUND 🔊: Zero-Shot Spatial Environment-to-Spatial Sound**.
44
+ Please refer to our [paper](https://arxiv.org/abs/2406.06612), [project page](https://see2sound.github.io/), or [github](https://github.com/see2sound/see2sound) for more details.
45
+ > Note: You should make sure that your hardware supports spatial audio.
46
+
47
+ [![arXiv](https://img.shields.io/badge/arXiv-2406.06612-b31b1b.svg)](https://arxiv.org/abs/2406.06612)
48
+ ![GitHub Repo stars](https://img.shields.io/github/stars/see2sound/see2sound)
49
+ """
50
+
51
+ css = """
52
+ h1 {
53
+ text-align: center;
54
+ }
55
+ """
56
+
57
+ with gr.Blocks(css=css) as demo:
58
+ gr.Markdown(description_text)
59
+
60
+ with gr.Row():
61
+ with gr.Column():
62
+ image = gr.Image(
63
+ label="Select an image", sources=["upload", "webcam"], type="filepath"
64
+ )
65
+
66
+ with gr.Accordion("Advanced Settings", open=False):
67
+ steps = gr.Slider(
68
+ label="Diffusion Steps", minimum=1, maximum=1000, step=1, value=500
69
+ )
70
+ prompt = gr.Text(
71
+ label="Prompt",
72
+ show_label=True,
73
+ max_lines=1,
74
+ placeholder="Enter your prompt",
75
+ container=True,
76
+ )
77
+ num_audios = gr.Slider(
78
+ label="Number of Audios", minimum=1, maximum=10, step=1, value=3
79
+ )
80
+
81
+ submit_button = gr.Button("Submit")
82
+
83
+ with gr.Column():
84
+ processed_image = gr.Image(label="Processed Image")
85
+ generated_audio = gr.Audio(
86
+ label="Generated Audio",
87
+ show_download_button=True,
88
+ show_share_button=True,
89
+ waveform_options=gr.WaveformOptions(
90
+ waveform_color="#01C6FF",
91
+ waveform_progress_color="#0066B4",
92
+ show_controls=True,
93
+ ),
94
+ )
95
+
96
+ gr.Examples(
97
+ examples=[[f"examples/{i}.png"] for i in range(1, 10)],
98
+ inputs=[image],
99
+ outputs=[processed_image, generated_audio],
100
+ # cache_examples=True,
101
+ # fn=process_image,
102
+ )
103
+
104
+ gr.on(
105
+ triggers=[submit_button.click],
106
+ fn=process_image,
107
+ inputs=[image, num_audios, prompt, steps],
108
+ outputs=[processed_image, generated_audio],
109
+ )
110
+
111
+ if __name__ == "__main__":
112
+ demo.launch()
config.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ codi_encoder: 'checkpoints/codi/codi_encoder.pth'
2
+ codi_text: 'checkpoints/codi/codi_text.pth'
3
+ codi_audio: 'checkpoints/codi/codi_audio.pth'
4
+ codi_video: 'checkpoints/codi/codi_video.pth'
5
+
6
+ sam: 'checkpoints/sam/sam.pth'
7
+ # H, L or B in decreasing performance
8
+ sam_size: 'H'
9
+
10
+ depth: 'checkpoints/depth/depth.pth'
11
+ # L, B, or S in decreasing performance
12
+ depth_size: 'L'
13
+
14
+ download: False
15
+ low_mem: False
16
+ fp16: False
17
+ gpu: True
18
+ steps: 500
19
+ num_audios: 3
20
+ prompt: ''
21
+ verbose: True
configs/model/audioldm.yaml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ########################
2
+ # audioldm autoencoder #
3
+ ########################
4
+
5
+
6
+ audioldm_autoencoder:
7
+ type: audioldm_autoencoder
8
+ args:
9
+ embed_dim: 8
10
+ monitor: val/rec_loss
11
+ ddconfig:
12
+ double_z: True
13
+ z_channels: 8
14
+ resolution: 256
15
+ downsample_time: False
16
+ in_channels: 1
17
+ out_ch: 1
18
+ ch: 128
19
+ ch_mult: [1, 2, 4]
20
+ num_res_blocks: 2
21
+ attn_resolutions: []
22
+ dropout: 0.0
23
+ lossconfig:
24
+ target: torch.nn.Identity
configs/model/clap.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################
2
+ # clap audio encoder #
3
+ ######################
4
+
5
+
6
+ clap_audio:
7
+ type: clap_audio
8
+ args:
9
+ amodel: "HTSAT-large"
10
+ joint_embed_shape: 768
configs/model/clip.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##############################
2
+ # clip vision & text encoder #
3
+ ##############################
4
+
5
+ clip:
6
+ symbol: clip
7
+ args: {}
8
+
9
+ clip_frozen:
10
+ super_cfg: clip
11
+ type: clip_frozen
12
+ args: {}
13
+
14
+ clip_text:
15
+ super_cfg: clip
16
+ type: clip_text
17
+ args: {}
18
+
19
+ clip_vision:
20
+ super_cfg: clip
21
+ type: clip_vision
22
+ args: {}
configs/model/codi.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ########
2
+ # CoDi #
3
+ ########
4
+
5
+ codi:
6
+ type: codi
7
+ symbol: codi
8
+ find_unused_parameters: true
9
+ args:
10
+ audioldm_cfg: MODEL(audioldm_autoencoder)
11
+ autokl_cfg: MODEL(sd_autoencoder)
12
+ optimus_cfg: MODEL(optimus_vae)
13
+ clip_cfg: MODEL(clip_frozen)
14
+ clap_cfg: MODEL(clap_audio)
15
+ unet_config: MODEL(openai_unet_codi)
16
+ beta_linear_start: 0.00085
17
+ beta_linear_end: 0.012
18
+ timesteps: 1000
19
+ vision_scale_factor: 0.18215
20
+ text_scale_factor: 4.3108
21
+ audio_scale_factor: 0.9228
22
+ use_ema: false
configs/model/openai_unet.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ openai_unet_sd:
2
+ type: openai_unet
3
+ args:
4
+ image_size: null # no use
5
+ in_channels: 4
6
+ out_channels: 4
7
+ model_channels: 320
8
+ attention_resolutions: [ 4, 2, 1 ]
9
+ num_res_blocks: [ 2, 2, 2, 2 ]
10
+ channel_mult: [ 1, 2, 4, 4 ]
11
+ num_heads: 8
12
+ use_spatial_transformer: True
13
+ transformer_depth: 1
14
+ context_dim: 768
15
+ use_checkpoint: True
16
+ legacy: False
17
+
18
+ openai_unet_dual_context:
19
+ super_cfg: openai_unet_sd
20
+ type: openai_unet_dual_context
21
+
22
+ ########################
23
+ # Code cleaned version #
24
+ ########################
25
+
26
+ openai_unet_2d_audio:
27
+ type: openai_unet_2d
28
+ args:
29
+ input_channels: 8
30
+ model_channels: 192
31
+ output_channels: 8
32
+ num_noattn_blocks: [ 2, 2, 2, 2 ]
33
+ channel_mult: [ 1, 2, 4, 4 ]
34
+ with_attn: [true, true, true, false]
35
+ channel_mult_connector: [1, 2, 4]
36
+ num_noattn_blocks_connector: [1, 1, 1]
37
+ with_connector: [True, True, True, False]
38
+ connector_output_channel: 1280
39
+ num_heads: 8
40
+ context_dim: 768
41
+ use_checkpoint: False
42
+
43
+ openai_unet_2d:
44
+ type: openai_unet_2d
45
+ args:
46
+ input_channels: 4
47
+ model_channels: 320
48
+ output_channels: 4
49
+ num_noattn_blocks: [ 2, 2, 2, 2 ]
50
+ channel_mult: [ 1, 2, 4, 4 ]
51
+ with_attn: [true, true, true, false]
52
+ channel_mult_connector: [1, 2, 4]
53
+ num_noattn_blocks_connector: [1, 1, 1]
54
+ with_connector: [True, True, True, False]
55
+ connector_output_channel: 1280
56
+ num_heads: 8
57
+ context_dim: 768
58
+ use_checkpoint: True
59
+ use_video_architecture: True
60
+
61
+ openai_unet_0dmd:
62
+ type: openai_unet_0dmd
63
+ args:
64
+ input_channels: 768
65
+ model_channels: 320
66
+ output_channels: 768
67
+ num_noattn_blocks: [ 2, 2, 2, 2 ]
68
+ channel_mult: [ 1, 2, 4, 4 ]
69
+ second_dim: [ 4, 4, 4, 4 ]
70
+ with_attn: [true, true, true, false]
71
+ num_noattn_blocks_connector: [1, 1, 1]
72
+ second_dim_connector: [4, 4, 4]
73
+ with_connector: [True, True, True, False]
74
+ connector_output_channel: 1280
75
+ num_heads: 8
76
+ context_dim: 768
77
+ use_checkpoint: True
78
+
79
+ openai_unet_codi:
80
+ type: openai_unet_codi
81
+ args:
82
+ unet_image_cfg: MODEL(openai_unet_2d)
83
+ unet_text_cfg: MODEL(openai_unet_0dmd)
84
+ unet_audio_cfg: MODEL(openai_unet_2d_audio)
85
+ model_type: ['video', 'image', 'text', 'audio']
configs/model/optimus.yaml ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ optimus:
3
+ symbol: optimus
4
+ find_unused_parameters: false
5
+ args: {}
6
+
7
+ optimus_bert_encoder:
8
+ super_cfg: optimus
9
+ type: optimus_bert_connector
10
+ # pth: pretrained/optimus_bert_encoder.pth
11
+ args:
12
+ config:
13
+ architectures:
14
+ - BertForMaskedLM
15
+ attention_probs_dropout_prob: 0.1
16
+ finetuning_task: null
17
+ hidden_act: gelu
18
+ hidden_dropout_prob: 0.1
19
+ hidden_size: 768
20
+ initializer_range: 0.02
21
+ intermediate_size: 3072
22
+ layer_norm_eps: 1.e-12
23
+ max_position_embeddings: 512
24
+ num_attention_heads: 12
25
+ num_hidden_layers: 12
26
+ num_labels: 2
27
+ output_attentions: false
28
+ output_hidden_states: false
29
+ pruned_heads: {}
30
+ torchscript: false
31
+ type_vocab_size: 2
32
+ vocab_size: 28996
33
+ latent_size: 768
34
+
35
+ optimus_bert_tokenizer:
36
+ super_cfg: optimus
37
+ type: optimus_bert_tokenizer
38
+ args:
39
+ do_lower_case: false
40
+ max_len: 512
41
+ vocab_file: configs/vocab/bert-base-cased-vocab.txt
42
+
43
+ optimus_gpt2_decoder:
44
+ super_cfg: optimus
45
+ type: optimus_gpt2_connector
46
+ # pth: pretrained/optimus_gpt2_decoder.pth
47
+ args:
48
+ config:
49
+ architectures:
50
+ - GPT2LMHeadModel
51
+ attn_pdrop: 0.1
52
+ embd_pdrop: 0.1
53
+ finetuning_task: null
54
+ hidden_size: 768
55
+ initializer_range: 0.02
56
+ latent_size: 768
57
+ layer_norm_epsilon: 1.e-05
58
+ max_position_embeddings: 1024
59
+ n_ctx: 1024
60
+ n_embd: 768
61
+ n_head: 12
62
+ n_layer: 12
63
+ n_positions: 1024
64
+ num_attention_heads: 12
65
+ num_hidden_layers: 12
66
+ num_labels: 1
67
+ output_attentions: false
68
+ output_hidden_states: false
69
+ pretrained_config_archive_map:
70
+ gpt2 : https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json
71
+ gpt2-medium : https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-config.json
72
+ gpt2-large : https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-config.json
73
+ pruned_heads: {}
74
+ resid_pdrop: 0.1
75
+ summary_activation: null
76
+ summary_first_dropout: 0.1
77
+ summary_proj_to_labels: true
78
+ summary_type: cls_index
79
+ summary_use_proj: true
80
+ torchscript: false
81
+ vocab_size: 50260
82
+
83
+ optimus_gpt2_tokenizer:
84
+ super_cfg: optimus
85
+ type: optimus_gpt2_tokenizer
86
+ args:
87
+ do_lower_case: false
88
+ max_len: 1024
89
+ vocab_file: configs/vocab/gpt2-vocab.json
90
+ merges_file: configs/vocab/gpt2-merges.txt
91
+
92
+ optimus_vae:
93
+ super_cfg: optimus
94
+ type: optimus_vae
95
+ pth: pretrained/optimus-vae.pth
96
+ args:
97
+ encoder: MODEL(optimus_bert_encoder)
98
+ decoder: MODEL(optimus_gpt2_decoder)
99
+ tokenizer_encoder: MODEL(optimus_bert_tokenizer)
100
+ tokenizer_decoder: MODEL(optimus_gpt2_tokenizer)
101
+ args:
102
+ latent_size: 768
configs/model/sd.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sd_autoencoder:
2
+ type: autoencoderkl
3
+ args:
4
+ embed_dim: 4
5
+ monitor: val/rec_loss
6
+ ddconfig:
7
+ double_z: true
8
+ z_channels: 4
9
+ resolution: 256
10
+ in_channels: 3
11
+ out_ch: 3
12
+ ch: 128
13
+ ch_mult: [1, 2, 4, 4]
14
+ num_res_blocks: 2
15
+ attn_resolutions: []
16
+ dropout: 0.0
17
+ # use_video_arch: true
18
+ lossconfig:
19
+ target: torch.nn.Identity
20
+ pth: pretrained/kl-f8.pth
configs/vocab/bert-base-cased-vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
configs/vocab/bert_vocab_download_info.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bert-base-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
3
+ "bert-large-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
4
+ "bert-base-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt",
5
+ "bert-large-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt",
6
+ "bert-base-multilingual-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt",
7
+ "bert-base-multilingual-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt",
8
+ "bert-base-chinese": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt",
9
+ "bert-base-german-cased": "https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt",
10
+ "bert-large-uncased-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt",
11
+ "bert-large-cased-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt",
12
+ "bert-large-uncased-whole-word-masking-finetuned-squad": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt",
13
+ "bert-large-cased-whole-word-masking-finetuned-squad": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt",
14
+ "bert-base-cased-finetuned-mrpc": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt"
15
+ }
configs/vocab/gpt2-merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
configs/vocab/gpt2-vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
configs/vocab/gpt2_vocab_merge_download_info.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "vocab_file": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json",
3
+ "merges_file": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt",
4
+ }
examples/1.png ADDED

Git LFS Details

  • SHA256: 3127b5e5979af264a30310b24c05efada006b0a1ee7e8ce6cb7bc5547cfc4f0c
  • Pointer size: 131 Bytes
  • Size of remote file: 506 kB
examples/2.png ADDED

Git LFS Details

  • SHA256: 1395b9e17f0a39c4dd6aba768771a43dca6f1de53c7703a8cc1c3022741b5cce
  • Pointer size: 131 Bytes
  • Size of remote file: 101 kB
examples/3.png ADDED

Git LFS Details

  • SHA256: 4fdc865770afcc98599490408ae3a3277d0497f09072b643315e48fcda326b96
  • Pointer size: 130 Bytes
  • Size of remote file: 63.5 kB
examples/4.png ADDED

Git LFS Details

  • SHA256: 6d15b083001c86f43bfba434087a3228f2263106e13565bc8a562d3debfd501d
  • Pointer size: 132 Bytes
  • Size of remote file: 3.61 MB
examples/5.png ADDED

Git LFS Details

  • SHA256: c8090079a16b9d6e527a0b0b102ef068890a31d93dc2364d47be143b25cd803d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.15 MB
examples/6.png ADDED

Git LFS Details

  • SHA256: fac97ff6081d608ff43bf137d0e7fc1b9cbe08473828b9e2efbeed87a5f2687d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.19 MB
examples/7.png ADDED

Git LFS Details

  • SHA256: 8e8bea0013b062cc3d2df8f53f076f3c932f53ad78a99c24fdb8f739d063d9fe
  • Pointer size: 130 Bytes
  • Size of remote file: 94.9 kB
examples/8.png ADDED

Git LFS Details

  • SHA256: ee1718571153427f87677a41494c9e32f7f590bb1633f2cca11b9b6bba5a8fe3
  • Pointer size: 131 Bytes
  • Size of remote file: 193 kB
examples/9.png ADDED

Git LFS Details

  • SHA256: 48ff91ff8f7a7cb1b4eb89930a886336ef28beddfa25756b6aa7cbbc3307342e
  • Pointer size: 131 Bytes
  • Size of remote file: 339 kB
requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ -e git+https://github.com/see2sound/see2sound.git#egg=see2sound
3
+ opencv-python-headless
4
+ matplotlib
5
+ # don't install torch or numpy explicitly in hf spaces which has some environment issues
6
+ # numpy==1.26.4
7
+ # torch
8
+ torchvision
9
+ torchaudio
10
+ segment_anything @ git+https://github.com/facebookresearch/segment-anything
11
+ scipy
12
+ pyroomacoustics
13
+ diffusers
14
+ transformers==4.26.0
15
+ contourpy
16
+ huggingface-hub
17
+ librosa
18
+ lightning-utilities
19
+ numba
20
+ pytorch-lightning
21
+ torchlibrosa
22
+ torchmetrics
23
+ einops
24
+ wget
25
+ decord
26
+ ftfy
27
+ easydict
28
+ six
29
+ timm
30
+ pyyaml
torchhub/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Local PyTorch Hub
2
+
3
+ This directory is for loading the DINOv2 encoder locally in case of no Internet connection.
torchhub/facebookresearch_dinov2_main/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <[email protected]>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
torchhub/facebookresearch_dinov2_main/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to DINOv2
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Ensure the test suite passes.
12
+ 5. Make sure your code lints.
13
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
14
+
15
+ ## Contributor License Agreement ("CLA")
16
+ In order to accept your pull request, we need you to submit a CLA. You only need
17
+ to do this once to work on any of Meta's open source projects.
18
+
19
+ Complete your CLA here: <https://code.facebook.com/cla>
20
+
21
+ ## Issues
22
+ We use GitHub issues to track public bugs. Please ensure your description is
23
+ clear and has sufficient instructions to be able to reproduce the issue.
24
+
25
+ Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
26
+ disclosure of security bugs. In those cases, please go through the process
27
+ outlined on that page and do not file a public issue.
28
+
29
+ ## License
30
+ By contributing to DINOv2, you agree that your contributions will be licensed
31
+ under the LICENSE file in the root directory of this source tree.
torchhub/facebookresearch_dinov2_main/LICENSE ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Attribution-NonCommercial 4.0 International
3
+
4
+ =======================================================================
5
+
6
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
7
+ does not provide legal services or legal advice. Distribution of
8
+ Creative Commons public licenses does not create a lawyer-client or
9
+ other relationship. Creative Commons makes its licenses and related
10
+ information available on an "as-is" basis. Creative Commons gives no
11
+ warranties regarding its licenses, any material licensed under their
12
+ terms and conditions, or any related information. Creative Commons
13
+ disclaims all liability for damages resulting from their use to the
14
+ fullest extent possible.
15
+
16
+ Using Creative Commons Public Licenses
17
+
18
+ Creative Commons public licenses provide a standard set of terms and
19
+ conditions that creators and other rights holders may use to share
20
+ original works of authorship and other material subject to copyright
21
+ and certain other rights specified in the public license below. The
22
+ following considerations are for informational purposes only, are not
23
+ exhaustive, and do not form part of our licenses.
24
+
25
+ Considerations for licensors: Our public licenses are
26
+ intended for use by those authorized to give the public
27
+ permission to use material in ways otherwise restricted by
28
+ copyright and certain other rights. Our licenses are
29
+ irrevocable. Licensors should read and understand the terms
30
+ and conditions of the license they choose before applying it.
31
+ Licensors should also secure all rights necessary before
32
+ applying our licenses so that the public can reuse the
33
+ material as expected. Licensors should clearly mark any
34
+ material not subject to the license. This includes other CC-
35
+ licensed material, or material used under an exception or
36
+ limitation to copyright. More considerations for licensors:
37
+ wiki.creativecommons.org/Considerations_for_licensors
38
+
39
+ Considerations for the public: By using one of our public
40
+ licenses, a licensor grants the public permission to use the
41
+ licensed material under specified terms and conditions. If
42
+ the licensor's permission is not necessary for any reason--for
43
+ example, because of any applicable exception or limitation to
44
+ copyright--then that use is not regulated by the license. Our
45
+ licenses grant only permissions under copyright and certain
46
+ other rights that a licensor has authority to grant. Use of
47
+ the licensed material may still be restricted for other
48
+ reasons, including because others have copyright or other
49
+ rights in the material. A licensor may make special requests,
50
+ such as asking that all changes be marked or described.
51
+ Although not required by our licenses, you are encouraged to
52
+ respect those requests where reasonable. More_considerations
53
+ for the public:
54
+ wiki.creativecommons.org/Considerations_for_licensees
55
+
56
+ =======================================================================
57
+
58
+ Creative Commons Attribution-NonCommercial 4.0 International Public
59
+ License
60
+
61
+ By exercising the Licensed Rights (defined below), You accept and agree
62
+ to be bound by the terms and conditions of this Creative Commons
63
+ Attribution-NonCommercial 4.0 International Public License ("Public
64
+ License"). To the extent this Public License may be interpreted as a
65
+ contract, You are granted the Licensed Rights in consideration of Your
66
+ acceptance of these terms and conditions, and the Licensor grants You
67
+ such rights in consideration of benefits the Licensor receives from
68
+ making the Licensed Material available under these terms and
69
+ conditions.
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+ Section 2 -- Scope.
142
+
143
+ a. License grant.
144
+
145
+ 1. Subject to the terms and conditions of this Public License,
146
+ the Licensor hereby grants You a worldwide, royalty-free,
147
+ non-sublicensable, non-exclusive, irrevocable license to
148
+ exercise the Licensed Rights in the Licensed Material to:
149
+
150
+ a. reproduce and Share the Licensed Material, in whole or
151
+ in part, for NonCommercial purposes only; and
152
+
153
+ b. produce, reproduce, and Share Adapted Material for
154
+ NonCommercial purposes only.
155
+
156
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
157
+ Exceptions and Limitations apply to Your use, this Public
158
+ License does not apply, and You do not need to comply with
159
+ its terms and conditions.
160
+
161
+ 3. Term. The term of this Public License is specified in Section
162
+ 6(a).
163
+
164
+ 4. Media and formats; technical modifications allowed. The
165
+ Licensor authorizes You to exercise the Licensed Rights in
166
+ all media and formats whether now known or hereafter created,
167
+ and to make technical modifications necessary to do so. The
168
+ Licensor waives and/or agrees not to assert any right or
169
+ authority to forbid You from making technical modifications
170
+ necessary to exercise the Licensed Rights, including
171
+ technical modifications necessary to circumvent Effective
172
+ Technological Measures. For purposes of this Public License,
173
+ simply making modifications authorized by this Section 2(a)
174
+ (4) never produces Adapted Material.
175
+
176
+ 5. Downstream recipients.
177
+
178
+ a. Offer from the Licensor -- Licensed Material. Every
179
+ recipient of the Licensed Material automatically
180
+ receives an offer from the Licensor to exercise the
181
+ Licensed Rights under the terms and conditions of this
182
+ Public License.
183
+
184
+ b. No downstream restrictions. You may not offer or impose
185
+ any additional or different terms or conditions on, or
186
+ apply any Effective Technological Measures to, the
187
+ Licensed Material if doing so restricts exercise of the
188
+ Licensed Rights by any recipient of the Licensed
189
+ Material.
190
+
191
+ 6. No endorsement. Nothing in this Public License constitutes or
192
+ may be construed as permission to assert or imply that You
193
+ are, or that Your use of the Licensed Material is, connected
194
+ with, or sponsored, endorsed, or granted official status by,
195
+ the Licensor or others designated to receive attribution as
196
+ provided in Section 3(a)(1)(A)(i).
197
+
198
+ b. Other rights.
199
+
200
+ 1. Moral rights, such as the right of integrity, are not
201
+ licensed under this Public License, nor are publicity,
202
+ privacy, and/or other similar personality rights; however, to
203
+ the extent possible, the Licensor waives and/or agrees not to
204
+ assert any such rights held by the Licensor to the limited
205
+ extent necessary to allow You to exercise the Licensed
206
+ Rights, but not otherwise.
207
+
208
+ 2. Patent and trademark rights are not licensed under this
209
+ Public License.
210
+
211
+ 3. To the extent possible, the Licensor waives any right to
212
+ collect royalties from You for the exercise of the Licensed
213
+ Rights, whether directly or through a collecting society
214
+ under any voluntary or waivable statutory or compulsory
215
+ licensing scheme. In all other cases the Licensor expressly
216
+ reserves any right to collect such royalties, including when
217
+ the Licensed Material is used other than for NonCommercial
218
+ purposes.
219
+
220
+ Section 3 -- License Conditions.
221
+
222
+ Your exercise of the Licensed Rights is expressly made subject to the
223
+ following conditions.
224
+
225
+ a. Attribution.
226
+
227
+ 1. If You Share the Licensed Material (including in modified
228
+ form), You must:
229
+
230
+ a. retain the following if it is supplied by the Licensor
231
+ with the Licensed Material:
232
+
233
+ i. identification of the creator(s) of the Licensed
234
+ Material and any others designated to receive
235
+ attribution, in any reasonable manner requested by
236
+ the Licensor (including by pseudonym if
237
+ designated);
238
+
239
+ ii. a copyright notice;
240
+
241
+ iii. a notice that refers to this Public License;
242
+
243
+ iv. a notice that refers to the disclaimer of
244
+ warranties;
245
+
246
+ v. a URI or hyperlink to the Licensed Material to the
247
+ extent reasonably practicable;
248
+
249
+ b. indicate if You modified the Licensed Material and
250
+ retain an indication of any previous modifications; and
251
+
252
+ c. indicate the Licensed Material is licensed under this
253
+ Public License, and include the text of, or the URI or
254
+ hyperlink to, this Public License.
255
+
256
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
257
+ reasonable manner based on the medium, means, and context in
258
+ which You Share the Licensed Material. For example, it may be
259
+ reasonable to satisfy the conditions by providing a URI or
260
+ hyperlink to a resource that includes the required
261
+ information.
262
+
263
+ 3. If requested by the Licensor, You must remove any of the
264
+ information required by Section 3(a)(1)(A) to the extent
265
+ reasonably practicable.
266
+
267
+ 4. If You Share Adapted Material You produce, the Adapter's
268
+ License You apply must not prevent recipients of the Adapted
269
+ Material from complying with this Public License.
270
+
271
+ Section 4 -- Sui Generis Database Rights.
272
+
273
+ Where the Licensed Rights include Sui Generis Database Rights that
274
+ apply to Your use of the Licensed Material:
275
+
276
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
277
+ to extract, reuse, reproduce, and Share all or a substantial
278
+ portion of the contents of the database for NonCommercial purposes
279
+ only;
280
+
281
+ b. if You include all or a substantial portion of the database
282
+ contents in a database in which You have Sui Generis Database
283
+ Rights, then the database in which You have Sui Generis Database
284
+ Rights (but not its individual contents) is Adapted Material; and
285
+
286
+ c. You must comply with the conditions in Section 3(a) if You Share
287
+ all or a substantial portion of the contents of the database.
288
+
289
+ For the avoidance of doubt, this Section 4 supplements and does not
290
+ replace Your obligations under this Public License where the Licensed
291
+ Rights include other Copyright and Similar Rights.
292
+
293
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
294
+
295
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
296
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
297
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
298
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
299
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
300
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
301
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
302
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
303
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
304
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
305
+
306
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
307
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
308
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
309
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
310
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
311
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
312
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
313
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
314
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
315
+
316
+ c. The disclaimer of warranties and limitation of liability provided
317
+ above shall be interpreted in a manner that, to the extent
318
+ possible, most closely approximates an absolute disclaimer and
319
+ waiver of all liability.
320
+
321
+ Section 6 -- Term and Termination.
322
+
323
+ a. This Public License applies for the term of the Copyright and
324
+ Similar Rights licensed here. However, if You fail to comply with
325
+ this Public License, then Your rights under this Public License
326
+ terminate automatically.
327
+
328
+ b. Where Your right to use the Licensed Material has terminated under
329
+ Section 6(a), it reinstates:
330
+
331
+ 1. automatically as of the date the violation is cured, provided
332
+ it is cured within 30 days of Your discovery of the
333
+ violation; or
334
+
335
+ 2. upon express reinstatement by the Licensor.
336
+
337
+ For the avoidance of doubt, this Section 6(b) does not affect any
338
+ right the Licensor may have to seek remedies for Your violations
339
+ of this Public License.
340
+
341
+ c. For the avoidance of doubt, the Licensor may also offer the
342
+ Licensed Material under separate terms or conditions or stop
343
+ distributing the Licensed Material at any time; however, doing so
344
+ will not terminate this Public License.
345
+
346
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
347
+ License.
348
+
349
+ Section 7 -- Other Terms and Conditions.
350
+
351
+ a. The Licensor shall not be bound by any additional or different
352
+ terms or conditions communicated by You unless expressly agreed.
353
+
354
+ b. Any arrangements, understandings, or agreements regarding the
355
+ Licensed Material not stated herein are separate from and
356
+ independent of the terms and conditions of this Public License.
357
+
358
+ Section 8 -- Interpretation.
359
+
360
+ a. For the avoidance of doubt, this Public License does not, and
361
+ shall not be interpreted to, reduce, limit, restrict, or impose
362
+ conditions on any use of the Licensed Material that could lawfully
363
+ be made without permission under this Public License.
364
+
365
+ b. To the extent possible, if any provision of this Public License is
366
+ deemed unenforceable, it shall be automatically reformed to the
367
+ minimum extent necessary to make it enforceable. If the provision
368
+ cannot be reformed, it shall be severed from this Public License
369
+ without affecting the enforceability of the remaining terms and
370
+ conditions.
371
+
372
+ c. No term or condition of this Public License will be waived and no
373
+ failure to comply consented to unless expressly agreed to by the
374
+ Licensor.
375
+
376
+ d. Nothing in this Public License constitutes or may be interpreted
377
+ as a limitation upon, or waiver of, any privileges and immunities
378
+ that apply to the Licensor or You, including from the legal
379
+ processes of any jurisdiction or authority.
380
+
381
+ =======================================================================
382
+
383
+ Creative Commons is not a party to its public
384
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
385
+ its public licenses to material it publishes and in those instances
386
+ will be considered the “Licensor.” The text of the Creative Commons
387
+ public licenses is dedicated to the public domain under the CC0 Public
388
+ Domain Dedication. Except for the limited purpose of indicating that
389
+ material is shared under a Creative Commons public license or as
390
+ otherwise permitted by the Creative Commons policies published at
391
+ creativecommons.org/policies, Creative Commons does not authorize the
392
+ use of the trademark "Creative Commons" or any other trademark or logo
393
+ of Creative Commons without its prior written consent including,
394
+ without limitation, in connection with any unauthorized modifications
395
+ to any of its public licenses or any other arrangements,
396
+ understandings, or agreements concerning use of licensed material. For
397
+ the avoidance of doubt, this paragraph does not form part of the
398
+ public licenses.
399
+
400
+ Creative Commons may be contacted at creativecommons.org.
torchhub/facebookresearch_dinov2_main/MODEL_CARD.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Card for DINOv2-S/B/L/g
2
+
3
+ These are Vision Transformer models trained following the method described in the paper:
4
+ "DINOv2: Learning Robust Visual Features without Supervision"
5
+
6
+ We provide 4 models: 1 ViT-g trained from scratch, and 3 ViT-S/B/L models distilled from the ViT-g.
7
+
8
+ ## Model Details
9
+ The model takes an image as input and returns a class token and patch tokens.
10
+
11
+ The embedding dimension is:
12
+ - 384 for ViT-S.
13
+ - 768 for ViT-B.
14
+ - 1024 for ViT-L.
15
+ - 1536 for ViT-g.
16
+
17
+ The models follow a Transformer architecture, with a patch size of 14.
18
+
19
+ For a 224x224 image, this results in 1 class token + 256 patch tokens.
20
+
21
+ The models can accept larger images provided the image shapes are multiples of the patch size (14).
22
+ If this condition is not verified, the model will crop to the closest smaller multiple of the patch size.
23
+
24
+ ### Model Description
25
+
26
+ - **Developed by:** Meta AI
27
+ - **Model type:** Vision Transformer
28
+ - **License:** CC-BY-NC
29
+
30
+ - **Repository:** https://github.com/facebookresearch/dinov2
31
+ - **Paper:** https://arxiv.org/abs/2304.07193
32
+ - **Demo:** https://dinov2.metademolab.com/
33
+
34
+ ## Uses
35
+
36
+ The models are vision backbones providing multi-purpose features for downstream tasks.
37
+
38
+ ### Direct Use
39
+
40
+ The models can be used without fine-tuning, with downstream classifiers as simple as linear layers, to obtain competitive results:
41
+ - on depth estimation, semantic segmentation, using linear layers.
42
+ - on image classification, using k-NN classifiers on the class token.
43
+ - on image classification, with logistic regression classifiers applied on the class token.
44
+ - on image classification, with a linear layer applied on the class token and the average of the patch tokens.
45
+ - on image retrieval using nearest neighbors.
46
+
47
+ ### Downstream Use
48
+
49
+ It is technically possible to perform fine-tuning on the models, for small gains (we measured +2% on ImageNet-1k classification).
50
+ We recommend keeping this as a very last step and only when necessary, as the features already provide good performance out-of-the-box.
51
+
52
+ ## Bias, Risks, and Limitations
53
+
54
+ Despite improvements thanks to the training method not using annotations, we still observe significant biases in our models toward rich households from Western countries.
55
+
56
+ ### Recommendations
57
+
58
+ We expect fine-tuning will increase the biases in the features produced by the model as they will be tuned to the fine-tuning labels.
59
+
60
+ ## How to Get Started with the Model
61
+
62
+ Use the code below to get started with the model.
63
+
64
+ ```python
65
+ import torch
66
+ dinov2_vits14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')
67
+ dinov2_vitb14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')
68
+ dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')
69
+ dinov2_vitg14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitg14')
70
+ ```
71
+
72
+ ## Training Details
73
+
74
+ ### Training Data
75
+
76
+ - **Training data:** LVD-142M (see paper)
77
+ - **Training regime:** fp16 using PyTorch-FSDP mixed-precision.
78
+
79
+ ### Training Procedure
80
+
81
+ - **Training objective:**
82
+ - DINO self-distillation loss with multi-crop
83
+ - iBOT masked-image modeling loss
84
+ - KoLeo regularization on [CLS] tokens
85
+ - **Architectures:**
86
+ - ViT-S (21M params): Patch size 14, embedding dimension 384, 6 heads, MLP FFN
87
+ - ViT-B (86M params): Patch size 14, embedding dimension 768, 12 heads, MLP FFN
88
+ - ViT-L (0.3B params): Patch size 14, embedding dimension 1024, 16 heads, MLP FFN
89
+ - ViT-g (1.1B params): Patch size 14, embedding dimension 1536, 24 heads, SwiGLU FFN
90
+ - **Distillation:**
91
+ - Distillation follows the standard DINOv2 pretraining procedure, except the teacher is a pretrained ViT-g, frozen.
92
+
93
+ ## Evaluation
94
+
95
+ We refer users to the associated paper for the evaluation protocols.
96
+
97
+ <table>
98
+ <tr>
99
+ <th>model</th>
100
+ <th colspan="3">ImageNet-1k</th>
101
+ <th>NYU-Depth v2</th>
102
+ <th>SUN-RGBD</th>
103
+ <th>ADE20k</th>
104
+ <th>iNaturalist 2018</th>
105
+ <th>Oxford-H</th>
106
+ </tr>
107
+ <tr>
108
+ <th rowspan="2">task</th>
109
+ <th>classif. (acc)</th>
110
+ <th>classif. (acc)</th>
111
+ <th>classif. V2 (acc)</th>
112
+ <th>depth (RMSE)</th>
113
+ <th>depth (RMSE)</th>
114
+ <th>segm. (mAP)</th>
115
+ <th>classif. (acc)</th>
116
+ <th>retrieval (mAP)</th>
117
+ </tr>
118
+ <tr>
119
+ <!-- <th>^</th> -->
120
+ <th>k-NN</th>
121
+ <th>linear</th>
122
+ <th>linear</th>
123
+ <th>linear<br />4 layers</th>
124
+ <th>NYU-D transfer</th>
125
+ <th>multiscale</th>
126
+ <th>linear</th>
127
+ <th>nearest neighbor</th>
128
+ </tr>
129
+ <tr>
130
+ <td>ViT-S/14</td>
131
+ <td align="right">79.0%</td>
132
+ <td align="right">81.1%</td>
133
+ <td align="right">70.8%</td>
134
+ <td align="right">0.417</td>
135
+ <td align="right">0.431</td>
136
+ <td align="right">47.2</td>
137
+ <td align="right">69.5%</td>
138
+ <td align="right">43.2</td>
139
+ </tr>
140
+ <tr>
141
+ <td>ViT-B/14</td>
142
+ <td align="right">82.1%</td>
143
+ <td align="right">84.5%</td>
144
+ <td align="right">74.9%</td>
145
+ <td align="right">0.362</td>
146
+ <td align="right">0.400</td>
147
+ <td align="right">51.3</td>
148
+ <td align="right">76.3%</td>
149
+ <td align="right">49.5</td>
150
+ </tr>
151
+ <tr>
152
+ <td>ViT-L/14</td>
153
+ <td align="right">83.5%</td>
154
+ <td align="right">86.3%</td>
155
+ <td align="right">77.6%</td>
156
+ <td align="right">0.333</td>
157
+ <td align="right">0.396</td>
158
+ <td align="right">53.1</td>
159
+ <td align="right">79.8%</td>
160
+ <td align="right">54.0</td>
161
+ </tr>
162
+ <tr>
163
+ <td>ViT-g/14</td>
164
+ <td align="right">83.5%</td>
165
+ <td align="right">86.5%</td>
166
+ <td align="right">78.4%</td>
167
+ <td align="right">0.298</td>
168
+ <td align="right">0.362</td>
169
+ <td align="right">53.0</td>
170
+ <td align="right">81.6%</td>
171
+ <td align="right">52.3</td>
172
+ </tr>
173
+ </table>
174
+
175
+ ## Environmental Impact
176
+
177
+ - **Hardware Type:** Nvidia A100
178
+ - **Hours used:** 22,000 for ViT-g, 4,500 for ViT-S distillation, 5,300 for ViT-B distillation, 8,000 for ViT-L distillation
179
+ - **Cloud Provider:** Private infra
180
+ - **Compute Region:** USA
181
+ - **Carbon Emitted:** 7t CO2eq
182
+
183
+ #### Hardware
184
+
185
+ Nvidia A100 GPUs
186
+
187
+ #### Software
188
+
189
+ PyTorch 2.0,
190
+ xFormers 0.0.18
191
+
192
+ **BibTeX**
193
+
194
+ ```
195
+ @misc{oquab2023dinov2,
196
+ title={DINOv2: Learning Robust Visual Features without Supervision},
197
+ author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy and Szafraniec, Marc and Khalidov, Vasil and Fernandez, Pierre and Haziza, Daniel and Massa, Francisco and El-Nouby, Alaaeldin and Howes, Russell and Huang, Po-Yao and Xu, Hu and Sharma, Vasu and Li, Shang-Wen and Galuba, Wojciech and Rabbat, Mike and Assran, Mido and Ballas, Nicolas and Synnaeve, Gabriel and Misra, Ishan and Jegou, Herve and Mairal, Julien and Labatut, Patrick and Joulin, Armand and Bojanowski, Piotr},
198
+ journal={arXiv:2304.07193},
199
+ year={2023}
200
+ }
201
+ ```
torchhub/facebookresearch_dinov2_main/README.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DINOv2: Learning Robust Visual Features without Supervision
2
+
3
+ **[Meta AI Research, FAIR](https://ai.facebook.com/research/)**
4
+
5
+ Maxime Oquab,
6
+ Timothée Darcet,
7
+ Théo Moutakanni,
8
+ Huy V. Vo,
9
+ Marc Szafraniec,
10
+ Vasil Khalidov,
11
+ Patrick Labatut,
12
+ Armand Joulin,
13
+ Piotr Bojanowski
14
+
15
+ [[`Paper`](https://arxiv.org/abs/2304.07193)] [[`Blog`](https://ai.facebook.com/blog/dino-v2-computer-vision-self-supervised-learning/)] [[`Demo`](https://dinov2.metademolab.com)] [[`BibTeX`](#citing-dinov2)]
16
+
17
+ PyTorch implementation and pretrained models for DINOv2. For details, see the paper: **[DINOv2: Learning Robust Visual Features without Supervision](https://arxiv.org/abs/2304.07193)**.
18
+
19
+ DINOv2 models produce high-performance visual features that can be directly employed with classifiers as simple as linear layers on a variety of computer vision tasks; these visual features are robust and perform well across domains without any requirement for fine-tuning. The models were pretrained on a dataset of 142 M images without using any labels or annotations.
20
+
21
+ https://github.com/facebookresearch/dinov2/assets/60359573/f168823e-7922-415a-b429-578badf5c356
22
+
23
+ <div align="center">
24
+ Visualization of the three first principal components of the patch features of all frames, mapped to RGB values.
25
+ </div>
26
+
27
+ ## Pretrained models
28
+
29
+ <table style="margin: auto">
30
+ <tr>
31
+ <th>model</th>
32
+ <th># of<br />params</th>
33
+ <th>ImageNet<br />k-NN</th>
34
+ <th>ImageNet<br />linear</th>
35
+ <th>download</th>
36
+ </tr>
37
+ <tr>
38
+ <td>ViT-S/14 distilled</td>
39
+ <td align="right">21 M</td>
40
+ <td align="right">79.0%</td>
41
+ <td align="right">81.1%</td>
42
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_pretrain.pth">backbone only</a></td>
43
+ </tr>
44
+ <tr>
45
+ <td>ViT-B/14 distilled</td>
46
+ <td align="right">86 M</td>
47
+ <td align="right">82.1%</td>
48
+ <td align="right">84.5%</td>
49
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_pretrain.pth">backbone only</a></td>
50
+ </tr>
51
+ <tr>
52
+ <td>ViT-L/14 distilled</td>
53
+ <td align="right">300 M</td>
54
+ <td align="right">83.5%</td>
55
+ <td align="right">86.3%</td>
56
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth">backbone only</a></td>
57
+ </tr>
58
+ <tr>
59
+ <td>ViT-g/14</td>
60
+ <td align="right">1,100 M</td>
61
+ <td align="right">83.5%</td>
62
+ <td align="right">86.5%</td>
63
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth">backbone only</a></td>
64
+ </tr>
65
+ </table>
66
+
67
+ ### Pretrained models via PyTorch Hub
68
+
69
+ Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install PyTorch (the only required dependency for loading the model). Installing PyTorch with CUDA support is strongly recommended.
70
+
71
+ A corresponding [model card](MODEL_CARD.md) is included in the repository.
72
+
73
+ ```python
74
+ import torch
75
+
76
+ dinov2_vits14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')
77
+ dinov2_vitb14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')
78
+ dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')
79
+ dinov2_vitg14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitg14')
80
+ ```
81
+
82
+ ## Installation
83
+
84
+ The training and evaluation code requires PyTorch 2.0 and [xFormers](https://github.com/facebookresearch/xformers) 0.0.18 as well as a number of other 3rd party packages. Note that the code has only been tested with the specified versions and also expects a Linux environment. To setup all the required dependencies for training and evaluation, please follow the instructions below:
85
+
86
+ *[conda](https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html)* **(Recommended)** - Clone the repository and then create and activate a `dinov2` conda environment using the provided environment definition:
87
+
88
+ ```shell
89
+ conda env create -f conda.yaml
90
+ conda activate dinov2
91
+ ```
92
+
93
+ *[pip](https://pip.pypa.io/en/stable/getting-started/)* - Clone the repository and then use the provided `requirements.txt` to install the dependencies:
94
+
95
+ ```shell
96
+ pip install -r requirements.txt
97
+ ```
98
+
99
+ ## Data preparation
100
+
101
+ ### ImageNet-1k
102
+
103
+ The root directory of the dataset should hold the following contents:
104
+
105
+ - `<ROOT>/test/ILSVRC2012_test_00000001.JPEG`
106
+ - `<ROOT>/test/[..]`
107
+ - `<ROOT>/test/ILSVRC2012_test_00100000.JPEG`
108
+ - `<ROOT>/train/n01440764/n01440764_10026.JPEG`
109
+ - `<ROOT>/train/[...]`
110
+ - `<ROOT>/train/n15075141/n15075141_9993.JPEG`
111
+ - `<ROOT>/val/n01440764/ILSVRC2012_val_00000293.JPEG`
112
+ - `<ROOT>/val/[...]`
113
+ - `<ROOT>/val/n15075141/ILSVRC2012_val_00049174.JPEG`
114
+ - `<ROOT>/labels.txt`
115
+
116
+ The provided dataset implementation expects a few additional metadata files to be present under the extra directory:
117
+
118
+ - `<EXTRA>/class-ids-TRAIN.npy`
119
+ - `<EXTRA>/class-ids-VAL.npy`
120
+ - `<EXTRA>/class-names-TRAIN.npy`
121
+ - `<EXTRA>/class-names-VAL.npy`
122
+ - `<EXTRA>/entries-TEST.npy`
123
+ - `<EXTRA>/entries-TRAIN.npy`
124
+ - `<EXTRA>/entries-VAL.npy`
125
+
126
+ These metadata files can be generated (once) with the following lines of Python code:
127
+
128
+ ```python
129
+ from dinov2.data.datasets import ImageNet
130
+
131
+ for split in ImageNet.Split:
132
+ dataset = ImageNet(split=split, root="<ROOT>", extra="<EXTRA>")
133
+ dataset.dump_extra()
134
+ ```
135
+
136
+ Note that the root and extra directories do not have to be distinct directories.
137
+
138
+ ### ImageNet-22k
139
+
140
+ Please adapt the [dataset class](dinov2/data/datasets/image_net_22k.py) to match your local setup.
141
+
142
+ <br />
143
+
144
+ :warning: To execute the commands provided in the next sections for training and evaluation, the `dinov2` package should be included in the Python module search path, i.e. simply prefix the command to run with `PYTHONPATH=.`.
145
+
146
+ ## Training
147
+
148
+ ### Fast setup: training DINOv2 ViT-L/16 on ImageNet-1k
149
+
150
+ Run DINOv2 training on 4 A100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit:
151
+
152
+ ```shell
153
+ python dinov2/run/train/train.py \
154
+ --nodes 4 \
155
+ --config-file dinov2/configs/train/vitl16_short.yaml \
156
+ --output-dir <PATH/TO/OUTPUT/DIR> \
157
+ train.dataset_path=ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
158
+ ```
159
+
160
+ Training time is approximately 1 day and the resulting checkpoint should reach 81.6% on k-NN eval and 82.9% on linear eval.
161
+
162
+ The training code saves the weights of the teacher in the `eval` folder every 12500 iterations for evaluation.
163
+
164
+ ### Long setup: training DINOv2 ViT-L/14 on ImageNet-22k
165
+
166
+ Run DINOv2 training on 12 A100-80GB nodes (96 GPUs) in a SLURM cluster environment with submitit:
167
+
168
+ ```shell
169
+ python dinov2/run/train/train.py \
170
+ --nodes 12 \
171
+ --config-file dinov2/configs/train/vitl14.yaml \
172
+ --output-dir <PATH/TO/OUTPUT/DIR> \
173
+ train.dataset_path=ImageNet22k:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
174
+ ```
175
+
176
+ Training time is approximately 3.3 days and the resulting checkpoint should reach 82.0% on k-NN eval and 84.5% on linear eval.
177
+
178
+ The training code saves the weights of the teacher in the `eval` folder every 12500 iterations for evaluation.
179
+
180
+
181
+ ## Evaluation
182
+
183
+ The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node:
184
+
185
+ ### k-NN classification on ImageNet-1k
186
+
187
+ ```shell
188
+ python dinov2/run/eval/knn.py \
189
+ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \
190
+ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \
191
+ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/knn \
192
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
193
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
194
+ ```
195
+
196
+ ### Logistic regression classification on ImageNet-1k
197
+
198
+ ```shell
199
+ python dinov2/run/eval/log_regression.py \
200
+ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \
201
+ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \
202
+ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/logreg \
203
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
204
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
205
+ ```
206
+
207
+ ### Linear classification with data augmentation on ImageNet-1k
208
+
209
+ ```shell
210
+ python dinov2/run/eval/linear.py \
211
+ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \
212
+ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \
213
+ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/linear \
214
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
215
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
216
+ ```
217
+
218
+ We release the weights from evaluating the different models:
219
+
220
+ <table style="margin: auto">
221
+ <tr>
222
+ <th>model</th>
223
+ <th>ImageNet<br />top-1</th>
224
+ <th>linear evaluation</th>
225
+ </tr>
226
+ <tr>
227
+ <td>ViT-S/14 distilled</td>
228
+ <td align="right">81.1%</td>
229
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_linear_head.pth">linear head weights</a></td>
230
+ </tr>
231
+ <tr>
232
+ <td>ViT-B/14 distilled</td>
233
+ <td align="right">84.5%</td>
234
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_linear_head.pth">linear head weights</a></td>
235
+ </tr>
236
+ <tr>
237
+ <td>ViT-L/14 distilled</td>
238
+ <td align="right">86.3%</td>
239
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_linear_head.pth">linear head weights</a></td>
240
+ </tr>
241
+ <tr>
242
+ <td>ViT-g/14</td>
243
+ <td align="right">86.5%</td>
244
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_linear_head.pth">linear head weights</a></td>
245
+ </tr>
246
+ </table>
247
+
248
+ The performance of the provided pretrained model weights can be evaluated as follows on ImageNet-1k:
249
+
250
+ ```shell
251
+ python dinov2/run/eval/linear.py \
252
+ --config-file dinov2/configs/eval/vitg14_pretrain.yaml \
253
+ --pretrained-weights https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth \
254
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
255
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
256
+ ```
257
+
258
+ ## License
259
+
260
+ DINOv2 code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
261
+
262
+ ## Contributing
263
+
264
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
265
+
266
+ ## Citing DINOv2
267
+
268
+ If you find this repository useful, please consider giving a star :star: and citation :t-rex::
269
+
270
+ ```
271
+ @misc{oquab2023dinov2,
272
+ title={DINOv2: Learning Robust Visual Features without Supervision},
273
+ author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy V. and Szafraniec, Marc and Khalidov, Vasil and Fernandez, Pierre and Haziza, Daniel and Massa, Francisco and El-Nouby, Alaaeldin and Howes, Russell and Huang, Po-Yao and Xu, Hu and Sharma, Vasu and Li, Shang-Wen and Galuba, Wojciech and Rabbat, Mike and Assran, Mido and Ballas, Nicolas and Synnaeve, Gabriel and Misra, Ishan and Jegou, Herve and Mairal, Julien and Labatut, Patrick and Joulin, Armand and Bojanowski, Piotr},
274
+ journal={arXiv:2304.07193},
275
+ year={2023}
276
+ }
277
+ ```
torchhub/facebookresearch_dinov2_main/conda.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: dinov2
2
+ channels:
3
+ - defaults
4
+ - pytorch
5
+ - nvidia
6
+ - xformers
7
+ - conda-forge
8
+ dependencies:
9
+ - python=3.9
10
+ - pytorch::pytorch=2.0.0
11
+ - pytorch::pytorch-cuda=11.7.0
12
+ - pytorch::torchvision=0.15.0
13
+ - omegaconf
14
+ - torchmetrics=0.10.3
15
+ - fvcore
16
+ - iopath
17
+ - xformers::xformers=0.0.18
18
+ - pip
19
+ - pip:
20
+ - git+https://github.com/facebookincubator/submitit
21
+ - --extra-index-url https://pypi.nvidia.com
22
+ - cuml-cu11
torchhub/facebookresearch_dinov2_main/dinov2/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ __version__ = "0.0.1"
torchhub/facebookresearch_dinov2_main/dinov2/configs/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import pathlib
8
+
9
+ from omegaconf import OmegaConf
10
+
11
+
12
+ def load_config(config_name: str):
13
+ config_filename = config_name + ".yaml"
14
+ return OmegaConf.load(pathlib.Path(__file__).parent.resolve() / config_filename)
15
+
16
+
17
+ dinov2_default_config = load_config("ssl_default_config")
18
+
19
+
20
+ def load_and_merge_config(config_name: str):
21
+ default_config = OmegaConf.create(dinov2_default_config)
22
+ loaded_config = load_config(config_name)
23
+ return OmegaConf.merge(default_config, loaded_config)
torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitb14_pretrain.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_base
3
+ patch_size: 14
4
+ crops:
5
+ global_crops_size: 518 # this is to set up the position embeddings properly
6
+ local_crops_size: 98
torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitg14_pretrain.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_giant2
3
+ patch_size: 14
4
+ ffn_layer: swiglufused
5
+ crops:
6
+ global_crops_size: 518 # this is to set up the position embeddings properly
7
+ local_crops_size: 98
torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitl14_pretrain.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_large
3
+ patch_size: 14
4
+ crops:
5
+ global_crops_size: 518 # this is to set up the position embeddings properly
6
+ local_crops_size: 98
torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vits14_pretrain.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_small
3
+ patch_size: 14
4
+ crops:
5
+ global_crops_size: 518 # this is to set up the position embeddings properly
6
+ local_crops_size: 98
torchhub/facebookresearch_dinov2_main/dinov2/configs/ssl_default_config.yaml ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL:
2
+ WEIGHTS: ''
3
+ compute_precision:
4
+ grad_scaler: true
5
+ teacher:
6
+ backbone:
7
+ sharding_strategy: SHARD_GRAD_OP
8
+ mixed_precision:
9
+ param_dtype: fp16
10
+ reduce_dtype: fp16
11
+ buffer_dtype: fp32
12
+ dino_head:
13
+ sharding_strategy: SHARD_GRAD_OP
14
+ mixed_precision:
15
+ param_dtype: fp16
16
+ reduce_dtype: fp16
17
+ buffer_dtype: fp32
18
+ ibot_head:
19
+ sharding_strategy: SHARD_GRAD_OP
20
+ mixed_precision:
21
+ param_dtype: fp16
22
+ reduce_dtype: fp16
23
+ buffer_dtype: fp32
24
+ student:
25
+ backbone:
26
+ sharding_strategy: SHARD_GRAD_OP
27
+ mixed_precision:
28
+ param_dtype: fp16
29
+ reduce_dtype: fp16
30
+ buffer_dtype: fp32
31
+ dino_head:
32
+ sharding_strategy: SHARD_GRAD_OP
33
+ mixed_precision:
34
+ param_dtype: fp16
35
+ reduce_dtype: fp32
36
+ buffer_dtype: fp32
37
+ ibot_head:
38
+ sharding_strategy: SHARD_GRAD_OP
39
+ mixed_precision:
40
+ param_dtype: fp16
41
+ reduce_dtype: fp32
42
+ buffer_dtype: fp32
43
+ dino:
44
+ loss_weight: 1.0
45
+ head_n_prototypes: 65536
46
+ head_bottleneck_dim: 256
47
+ head_nlayers: 3
48
+ head_hidden_dim: 2048
49
+ koleo_loss_weight: 0.1
50
+ ibot:
51
+ loss_weight: 1.0
52
+ mask_sample_probability: 0.5
53
+ mask_ratio_min_max:
54
+ - 0.1
55
+ - 0.5
56
+ separate_head: false
57
+ head_n_prototypes: 65536
58
+ head_bottleneck_dim: 256
59
+ head_nlayers: 3
60
+ head_hidden_dim: 2048
61
+ train:
62
+ batch_size_per_gpu: 64
63
+ dataset_path: ImageNet:split=TRAIN
64
+ output_dir: .
65
+ saveckp_freq: 20
66
+ seed: 0
67
+ num_workers: 10
68
+ OFFICIAL_EPOCH_LENGTH: 1250
69
+ cache_dataset: true
70
+ centering: "centering" # or "sinkhorn_knopp"
71
+ student:
72
+ arch: vit_large
73
+ patch_size: 16
74
+ drop_path_rate: 0.3
75
+ layerscale: 1.0e-05
76
+ drop_path_uniform: true
77
+ pretrained_weights: ''
78
+ ffn_layer: "mlp"
79
+ block_chunks: 0
80
+ qkv_bias: true
81
+ proj_bias: true
82
+ ffn_bias: true
83
+ teacher:
84
+ momentum_teacher: 0.992
85
+ final_momentum_teacher: 1
86
+ warmup_teacher_temp: 0.04
87
+ teacher_temp: 0.07
88
+ warmup_teacher_temp_epochs: 30
89
+ optim:
90
+ epochs: 100
91
+ weight_decay: 0.04
92
+ weight_decay_end: 0.4
93
+ base_lr: 0.004 # learning rate for a batch size of 1024
94
+ lr: 0. # will be set after applying scaling rule
95
+ warmup_epochs: 10
96
+ min_lr: 1.0e-06
97
+ clip_grad: 3.0
98
+ freeze_last_layer_epochs: 1
99
+ scaling_rule: sqrt_wrt_1024
100
+ patch_embed_lr_mult: 0.2
101
+ layerwise_decay: 0.9
102
+ adamw_beta1: 0.9
103
+ adamw_beta2: 0.999
104
+ crops:
105
+ global_crops_scale:
106
+ - 0.32
107
+ - 1.0
108
+ local_crops_number: 8
109
+ local_crops_scale:
110
+ - 0.05
111
+ - 0.32
112
+ global_crops_size: 224
113
+ local_crops_size: 96
114
+ evaluation:
115
+ eval_period_iterations: 12500
torchhub/facebookresearch_dinov2_main/dinov2/configs/train/vitg14.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dino:
2
+ head_n_prototypes: 131072
3
+ head_bottleneck_dim: 384
4
+ ibot:
5
+ separate_head: true
6
+ head_n_prototypes: 131072
7
+ train:
8
+ batch_size_per_gpu: 12
9
+ dataset_path: ImageNet22k
10
+ centering: sinkhorn_knopp
11
+ student:
12
+ arch: vit_giant2
13
+ patch_size: 14
14
+ drop_path_rate: 0.4
15
+ ffn_layer: swiglufused
16
+ block_chunks: 4
17
+ teacher:
18
+ momentum_teacher: 0.994
19
+ optim:
20
+ epochs: 500
21
+ weight_decay_end: 0.2
22
+ base_lr: 2.0e-04 # learning rate for a batch size of 1024
23
+ warmup_epochs: 80
24
+ layerwise_decay: 1.0
25
+ crops:
26
+ local_crops_size: 98
torchhub/facebookresearch_dinov2_main/dinov2/configs/train/vitl14.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dino:
2
+ head_n_prototypes: 131072
3
+ head_bottleneck_dim: 384
4
+ ibot:
5
+ separate_head: true
6
+ head_n_prototypes: 131072
7
+ train:
8
+ batch_size_per_gpu: 32
9
+ dataset_path: ImageNet22k
10
+ centering: sinkhorn_knopp
11
+ student:
12
+ arch: vit_large
13
+ patch_size: 14
14
+ drop_path_rate: 0.4
15
+ ffn_layer: swiglufused
16
+ block_chunks: 4
17
+ teacher:
18
+ momentum_teacher: 0.994
19
+ optim:
20
+ epochs: 500
21
+ weight_decay_end: 0.2
22
+ base_lr: 2.0e-04 # learning rate for a batch size of 1024
23
+ warmup_epochs: 80
24
+ layerwise_decay: 1.0
25
+ crops:
26
+ local_crops_size: 98
torchhub/facebookresearch_dinov2_main/dinov2/configs/train/vitl16_short.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # this corresponds to the default config
2
+ train:
3
+ dataset_path: ImageNet:split=TRAIN
4
+ batch_size_per_gpu: 64
5
+ student:
6
+ block_chunks: 4
torchhub/facebookresearch_dinov2_main/dinov2/data/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .adapters import DatasetWithEnumeratedTargets
8
+ from .augmentations import DataAugmentationDINO
9
+ from .collate import collate_data_and_cast
10
+ from .loaders import SamplerType, make_data_loader, make_dataset
11
+ from .masking import MaskingGenerator
torchhub/facebookresearch_dinov2_main/dinov2/data/adapters.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Any, Tuple
8
+
9
+ from torch.utils.data import Dataset
10
+
11
+
12
+ class DatasetWithEnumeratedTargets(Dataset):
13
+ def __init__(self, dataset):
14
+ self._dataset = dataset
15
+
16
+ def get_image_data(self, index: int) -> bytes:
17
+ return self._dataset.get_image_data(index)
18
+
19
+ def get_target(self, index: int) -> Tuple[Any, int]:
20
+ target = self._dataset.get_target(index)
21
+ return (index, target)
22
+
23
+ def __getitem__(self, index: int) -> Tuple[Any, Tuple[Any, int]]:
24
+ image, target = self._dataset[index]
25
+ target = index if target is None else target
26
+ return image, (index, target)
27
+
28
+ def __len__(self) -> int:
29
+ return len(self._dataset)
torchhub/facebookresearch_dinov2_main/dinov2/data/augmentations.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+
9
+ from torchvision import transforms
10
+
11
+ from .transforms import GaussianBlur, make_normalize_transform
12
+
13
+ logger = logging.getLogger("dinov2")
14
+
15
+
16
+ class DataAugmentationDINO(object):
17
+ def __init__(
18
+ self,
19
+ global_crops_scale,
20
+ local_crops_scale,
21
+ local_crops_number,
22
+ global_crops_size=224,
23
+ local_crops_size=96,
24
+ ):
25
+ self.global_crops_scale = global_crops_scale
26
+ self.local_crops_scale = local_crops_scale
27
+ self.local_crops_number = local_crops_number
28
+ self.global_crops_size = global_crops_size
29
+ self.local_crops_size = local_crops_size
30
+
31
+ logger.info("###################################")
32
+ logger.info("Using data augmentation parameters:")
33
+ logger.info(f"global_crops_scale: {global_crops_scale}")
34
+ logger.info(f"local_crops_scale: {local_crops_scale}")
35
+ logger.info(f"local_crops_number: {local_crops_number}")
36
+ logger.info(f"global_crops_size: {global_crops_size}")
37
+ logger.info(f"local_crops_size: {local_crops_size}")
38
+ logger.info("###################################")
39
+
40
+ # random resized crop and flip
41
+ self.geometric_augmentation_global = transforms.Compose(
42
+ [
43
+ transforms.RandomResizedCrop(
44
+ global_crops_size,
45
+ scale=global_crops_scale,
46
+ interpolation=transforms.InterpolationMode.BICUBIC,
47
+ ),
48
+ transforms.RandomHorizontalFlip(p=0.5),
49
+ ]
50
+ )
51
+
52
+ self.geometric_augmentation_local = transforms.Compose(
53
+ [
54
+ transforms.RandomResizedCrop(
55
+ local_crops_size,
56
+ scale=local_crops_scale,
57
+ interpolation=transforms.InterpolationMode.BICUBIC,
58
+ ),
59
+ transforms.RandomHorizontalFlip(p=0.5),
60
+ ]
61
+ )
62
+
63
+ # color distorsions / blurring
64
+ color_jittering = transforms.Compose(
65
+ [
66
+ transforms.RandomApply(
67
+ [
68
+ transforms.ColorJitter(
69
+ brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1
70
+ )
71
+ ],
72
+ p=0.8,
73
+ ),
74
+ transforms.RandomGrayscale(p=0.2),
75
+ ]
76
+ )
77
+
78
+ global_transfo1_extra = GaussianBlur(p=1.0)
79
+
80
+ global_transfo2_extra = transforms.Compose(
81
+ [
82
+ GaussianBlur(p=0.1),
83
+ transforms.RandomSolarize(threshold=128, p=0.2),
84
+ ]
85
+ )
86
+
87
+ local_transfo_extra = GaussianBlur(p=0.5)
88
+
89
+ # normalization
90
+ self.normalize = transforms.Compose(
91
+ [
92
+ transforms.ToTensor(),
93
+ make_normalize_transform(),
94
+ ]
95
+ )
96
+
97
+ self.global_transfo1 = transforms.Compose(
98
+ [color_jittering, global_transfo1_extra, self.normalize]
99
+ )
100
+ self.global_transfo2 = transforms.Compose(
101
+ [color_jittering, global_transfo2_extra, self.normalize]
102
+ )
103
+ self.local_transfo = transforms.Compose(
104
+ [color_jittering, local_transfo_extra, self.normalize]
105
+ )
106
+
107
+ def __call__(self, image):
108
+ output = {}
109
+
110
+ # global crops:
111
+ im1_base = self.geometric_augmentation_global(image)
112
+ global_crop_1 = self.global_transfo1(im1_base)
113
+
114
+ im2_base = self.geometric_augmentation_global(image)
115
+ global_crop_2 = self.global_transfo2(im2_base)
116
+
117
+ output["global_crops"] = [global_crop_1, global_crop_2]
118
+
119
+ # global crops for teacher:
120
+ output["global_crops_teacher"] = [global_crop_1, global_crop_2]
121
+
122
+ # local crops:
123
+ local_crops = [
124
+ self.local_transfo(self.geometric_augmentation_local(image))
125
+ for _ in range(self.local_crops_number)
126
+ ]
127
+ output["local_crops"] = local_crops
128
+ output["offsets"] = ()
129
+
130
+ return output
torchhub/facebookresearch_dinov2_main/dinov2/data/collate.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import random
8
+
9
+ import torch
10
+
11
+
12
+ def collate_data_and_cast(
13
+ samples_list,
14
+ mask_ratio_tuple,
15
+ mask_probability,
16
+ dtype,
17
+ n_tokens=None,
18
+ mask_generator=None,
19
+ ):
20
+ # dtype = torch.half # TODO: Remove
21
+
22
+ n_global_crops = len(samples_list[0][0]["global_crops"])
23
+ n_local_crops = len(samples_list[0][0]["local_crops"])
24
+
25
+ collated_global_crops = torch.stack(
26
+ [s[0]["global_crops"][i] for i in range(n_global_crops) for s in samples_list]
27
+ )
28
+
29
+ collated_local_crops = torch.stack(
30
+ [s[0]["local_crops"][i] for i in range(n_local_crops) for s in samples_list]
31
+ )
32
+
33
+ B = len(collated_global_crops)
34
+ N = n_tokens
35
+ n_samples_masked = int(B * mask_probability)
36
+ probs = torch.linspace(*mask_ratio_tuple, n_samples_masked + 1)
37
+ upperbound = 0
38
+ masks_list = []
39
+ for i in range(0, n_samples_masked):
40
+ prob_min = probs[i]
41
+ prob_max = probs[i + 1]
42
+ masks_list.append(
43
+ torch.BoolTensor(
44
+ mask_generator(int(N * random.uniform(prob_min, prob_max)))
45
+ )
46
+ )
47
+ upperbound += int(N * prob_max)
48
+ for i in range(n_samples_masked, B):
49
+ masks_list.append(torch.BoolTensor(mask_generator(0)))
50
+
51
+ random.shuffle(masks_list)
52
+
53
+ collated_masks = torch.stack(masks_list).flatten(1)
54
+ mask_indices_list = collated_masks.flatten().nonzero().flatten()
55
+
56
+ masks_weight = (
57
+ (1 / collated_masks.sum(-1).clamp(min=1.0))
58
+ .unsqueeze(-1)
59
+ .expand_as(collated_masks)[collated_masks]
60
+ )
61
+
62
+ return {
63
+ "collated_global_crops": collated_global_crops.to(dtype),
64
+ "collated_local_crops": collated_local_crops.to(dtype),
65
+ "collated_masks": collated_masks,
66
+ "mask_indices_list": mask_indices_list,
67
+ "masks_weight": masks_weight,
68
+ "upperbound": upperbound,
69
+ "n_masked_patches": torch.full(
70
+ (1,), fill_value=mask_indices_list.shape[0], dtype=torch.long
71
+ ),
72
+ }
torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .image_net import ImageNet
8
+ from .image_net_22k import ImageNet22k
torchhub/facebookresearch_dinov2_main/dinov2/data/datasets/decoders.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from io import BytesIO
8
+ from typing import Any
9
+
10
+ from PIL import Image
11
+
12
+
13
+ class Decoder:
14
+ def decode(self) -> Any:
15
+ raise NotImplementedError
16
+
17
+
18
+ class ImageDataDecoder(Decoder):
19
+ def __init__(self, image_data: bytes) -> None:
20
+ self._image_data = image_data
21
+
22
+ def decode(self) -> Image:
23
+ f = BytesIO(self._image_data)
24
+ return Image.open(f).convert(mode="RGB")
25
+
26
+
27
+ class TargetDecoder(Decoder):
28
+ def __init__(self, target: Any):
29
+ self._target = target
30
+
31
+ def decode(self) -> Any:
32
+ return self._target