Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0003000.log +136 -0
- LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0006000.log +136 -0
- LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0009000.log +136 -0
- LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0010000.log +136 -0
- LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0012000.log +136 -0
- LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0013000.log +136 -0
- LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_bert_10/step_012500.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_bert_len1024_C1_to_1024_absrope_time4_d256_l3_h4_subset8192_8gpu_20260526_144131/step_012000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_bert_len1024_C1_to_1024_absrope_time4_d256_l3_h4_subset8192_8gpu_20260526_144131/step_019000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260526_171143/step_004000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260526_171143/step_011000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/focalnet/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/focalnet/configuration_focalnet.py +98 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/focalnet/modeling_focalnet.py +928 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/__init__.py +29 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/configuration_superglue.py +92 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/image_processing_pil_superglue.py +299 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/image_processing_superglue.py +325 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/modeling_superglue.py +758 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_full_rev8/audit.jsonl +3 -0
.gitattributes
CHANGED
|
@@ -96,3 +96,4 @@ LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articl
|
|
| 96 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_300k_snapshot_rev8_docs600000_shards32/part-018.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 97 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_300k_snapshot_rev8_docs600000_shards32/part-029.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 98 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_300k_snapshot_rev8_docs600000_shards32/part-019.jsonl filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 96 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_300k_snapshot_rev8_docs600000_shards32/part-018.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 97 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_300k_snapshot_rev8_docs600000_shards32/part-029.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 98 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_300k_snapshot_rev8_docs600000_shards32/part-019.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 99 |
+
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_full_rev8/audit.jsonl filter=lfs diff=lfs merge=lfs -text
|
LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0003000.log
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-gumbel] 2026-05-25_21:11:10 infer runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0003000.pt -> docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0003000
|
| 2 |
+
[load] runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0003000.pt
|
| 3 |
+
[ckpt] step=3000
|
| 4 |
+
[sde] generated 2/128
|
| 5 |
+
[sde] generated 4/128
|
| 6 |
+
[sde] generated 6/128
|
| 7 |
+
[sde] generated 8/128
|
| 8 |
+
[sde] generated 10/128
|
| 9 |
+
[sde] generated 12/128
|
| 10 |
+
[sde] generated 14/128
|
| 11 |
+
[sde] generated 16/128
|
| 12 |
+
[sde] generated 18/128
|
| 13 |
+
[sde] generated 20/128
|
| 14 |
+
[sde] generated 22/128
|
| 15 |
+
[sde] generated 24/128
|
| 16 |
+
[sde] generated 26/128
|
| 17 |
+
[sde] generated 28/128
|
| 18 |
+
[sde] generated 30/128
|
| 19 |
+
[sde] generated 32/128
|
| 20 |
+
[sde] generated 34/128
|
| 21 |
+
[sde] generated 36/128
|
| 22 |
+
[sde] generated 38/128
|
| 23 |
+
[sde] generated 40/128
|
| 24 |
+
[sde] generated 42/128
|
| 25 |
+
[sde] generated 44/128
|
| 26 |
+
[sde] generated 46/128
|
| 27 |
+
[sde] generated 48/128
|
| 28 |
+
[sde] generated 50/128
|
| 29 |
+
[sde] generated 52/128
|
| 30 |
+
[sde] generated 54/128
|
| 31 |
+
[sde] generated 56/128
|
| 32 |
+
[sde] generated 58/128
|
| 33 |
+
[sde] generated 60/128
|
| 34 |
+
[sde] generated 62/128
|
| 35 |
+
[sde] generated 64/128
|
| 36 |
+
[sde] generated 66/128
|
| 37 |
+
[sde] generated 68/128
|
| 38 |
+
[sde] generated 70/128
|
| 39 |
+
[sde] generated 72/128
|
| 40 |
+
[sde] generated 74/128
|
| 41 |
+
[sde] generated 76/128
|
| 42 |
+
[sde] generated 78/128
|
| 43 |
+
[sde] generated 80/128
|
| 44 |
+
[sde] generated 82/128
|
| 45 |
+
[sde] generated 84/128
|
| 46 |
+
[sde] generated 86/128
|
| 47 |
+
[sde] generated 88/128
|
| 48 |
+
[sde] generated 90/128
|
| 49 |
+
[sde] generated 92/128
|
| 50 |
+
[sde] generated 94/128
|
| 51 |
+
[sde] generated 96/128
|
| 52 |
+
[sde] generated 98/128
|
| 53 |
+
[sde] generated 100/128
|
| 54 |
+
[sde] generated 102/128
|
| 55 |
+
[sde] generated 104/128
|
| 56 |
+
[sde] generated 106/128
|
| 57 |
+
[sde] generated 108/128
|
| 58 |
+
[sde] generated 110/128
|
| 59 |
+
[sde] generated 112/128
|
| 60 |
+
[sde] generated 114/128
|
| 61 |
+
[sde] generated 116/128
|
| 62 |
+
[sde] generated 118/128
|
| 63 |
+
[sde] generated 120/128
|
| 64 |
+
[sde] generated 122/128
|
| 65 |
+
[sde] generated 124/128
|
| 66 |
+
[sde] generated 126/128
|
| 67 |
+
[sde] generated 128/128
|
| 68 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 69 |
+
[summary] {
|
| 70 |
+
"type": "summary",
|
| 71 |
+
"checkpoint": "runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0003000.pt",
|
| 72 |
+
"step": 3000,
|
| 73 |
+
"decode": {
|
| 74 |
+
"decode_rule": "dirichlet_resample_sde",
|
| 75 |
+
"steps": 128,
|
| 76 |
+
"model_t_mode": "support_t",
|
| 77 |
+
"mean_mode": "endpoint_only",
|
| 78 |
+
"anchor_gamma": 1.0,
|
| 79 |
+
"endpoint_floor": 0.0,
|
| 80 |
+
"concentration_min": 30522.0,
|
| 81 |
+
"concentration_max": 61044.0,
|
| 82 |
+
"endpoint_temp": 1.45,
|
| 83 |
+
"endpoint_temp_start": null,
|
| 84 |
+
"endpoint_temp_end": null,
|
| 85 |
+
"endpoint_projection": "gumbel_softmax",
|
| 86 |
+
"endpoint_top_k": 0,
|
| 87 |
+
"endpoint_top_p": 0.95,
|
| 88 |
+
"gumbel_tau_start": 1.0,
|
| 89 |
+
"gumbel_tau_end": 0.2,
|
| 90 |
+
"gumbel_noise_scale_start": 1.0,
|
| 91 |
+
"gumbel_noise_scale_end": 1.0,
|
| 92 |
+
"ban_special_tokens": false,
|
| 93 |
+
"banned_endpoint_ids": [],
|
| 94 |
+
"support_power": 1.0,
|
| 95 |
+
"semantic_power": 1.0,
|
| 96 |
+
"noise_init": "dirichlet",
|
| 97 |
+
"noise_sigma": -1.0,
|
| 98 |
+
"noise_dirichlet_concentration": 30522.0,
|
| 99 |
+
"sde_resample": "dirichlet",
|
| 100 |
+
"logistic_normal_sigma_min": 0.18,
|
| 101 |
+
"logistic_normal_sigma_max": 3.0,
|
| 102 |
+
"logistic_normal_tau_min": 0.65,
|
| 103 |
+
"logistic_normal_tau_max": 1.0,
|
| 104 |
+
"final_from": "blend_0.5",
|
| 105 |
+
"n_samples": 128,
|
| 106 |
+
"seed": 20260524
|
| 107 |
+
},
|
| 108 |
+
"raw_genppl": {
|
| 109 |
+
"ppl": 3.8147677280337264,
|
| 110 |
+
"nll_per_token": 1.3388797790123395,
|
| 111 |
+
"tokens": 125410,
|
| 112 |
+
"kept_samples": 128,
|
| 113 |
+
"total_samples": 128,
|
| 114 |
+
"empty_rate": 0.0,
|
| 115 |
+
"skipped_samples": 0
|
| 116 |
+
},
|
| 117 |
+
"stripped_genppl": {
|
| 118 |
+
"ppl": 3.7623815682257042,
|
| 119 |
+
"nll_per_token": 1.3250521526960528,
|
| 120 |
+
"tokens": 124984,
|
| 121 |
+
"kept_samples": 128,
|
| 122 |
+
"total_samples": 128,
|
| 123 |
+
"empty_rate": 0.0,
|
| 124 |
+
"skipped_samples": 0
|
| 125 |
+
},
|
| 126 |
+
"diversity": {
|
| 127 |
+
"sample_entropy": 1.1669265594308051,
|
| 128 |
+
"unique_tokens": 557,
|
| 129 |
+
"token_count": 131072,
|
| 130 |
+
"distinct_1": 0.00424957275390625,
|
| 131 |
+
"distinct_2": 0.02731702101661779,
|
| 132 |
+
"top_token_mass": 0.5301742553710938
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
[done] docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0003000/sde_steps128_samples128_scored.jsonl
|
| 136 |
+
[watch-gumbel] 2026-05-25_21:22:30 done step_0003000
|
LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0006000.log
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-gumbel] 2026-05-26_01:14:44 infer runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0006000.pt -> docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0006000
|
| 2 |
+
[load] runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0006000.pt
|
| 3 |
+
[ckpt] step=6000
|
| 4 |
+
[sde] generated 2/128
|
| 5 |
+
[sde] generated 4/128
|
| 6 |
+
[sde] generated 6/128
|
| 7 |
+
[sde] generated 8/128
|
| 8 |
+
[sde] generated 10/128
|
| 9 |
+
[sde] generated 12/128
|
| 10 |
+
[sde] generated 14/128
|
| 11 |
+
[sde] generated 16/128
|
| 12 |
+
[sde] generated 18/128
|
| 13 |
+
[sde] generated 20/128
|
| 14 |
+
[sde] generated 22/128
|
| 15 |
+
[sde] generated 24/128
|
| 16 |
+
[sde] generated 26/128
|
| 17 |
+
[sde] generated 28/128
|
| 18 |
+
[sde] generated 30/128
|
| 19 |
+
[sde] generated 32/128
|
| 20 |
+
[sde] generated 34/128
|
| 21 |
+
[sde] generated 36/128
|
| 22 |
+
[sde] generated 38/128
|
| 23 |
+
[sde] generated 40/128
|
| 24 |
+
[sde] generated 42/128
|
| 25 |
+
[sde] generated 44/128
|
| 26 |
+
[sde] generated 46/128
|
| 27 |
+
[sde] generated 48/128
|
| 28 |
+
[sde] generated 50/128
|
| 29 |
+
[sde] generated 52/128
|
| 30 |
+
[sde] generated 54/128
|
| 31 |
+
[sde] generated 56/128
|
| 32 |
+
[sde] generated 58/128
|
| 33 |
+
[sde] generated 60/128
|
| 34 |
+
[sde] generated 62/128
|
| 35 |
+
[sde] generated 64/128
|
| 36 |
+
[sde] generated 66/128
|
| 37 |
+
[sde] generated 68/128
|
| 38 |
+
[sde] generated 70/128
|
| 39 |
+
[sde] generated 72/128
|
| 40 |
+
[sde] generated 74/128
|
| 41 |
+
[sde] generated 76/128
|
| 42 |
+
[sde] generated 78/128
|
| 43 |
+
[sde] generated 80/128
|
| 44 |
+
[sde] generated 82/128
|
| 45 |
+
[sde] generated 84/128
|
| 46 |
+
[sde] generated 86/128
|
| 47 |
+
[sde] generated 88/128
|
| 48 |
+
[sde] generated 90/128
|
| 49 |
+
[sde] generated 92/128
|
| 50 |
+
[sde] generated 94/128
|
| 51 |
+
[sde] generated 96/128
|
| 52 |
+
[sde] generated 98/128
|
| 53 |
+
[sde] generated 100/128
|
| 54 |
+
[sde] generated 102/128
|
| 55 |
+
[sde] generated 104/128
|
| 56 |
+
[sde] generated 106/128
|
| 57 |
+
[sde] generated 108/128
|
| 58 |
+
[sde] generated 110/128
|
| 59 |
+
[sde] generated 112/128
|
| 60 |
+
[sde] generated 114/128
|
| 61 |
+
[sde] generated 116/128
|
| 62 |
+
[sde] generated 118/128
|
| 63 |
+
[sde] generated 120/128
|
| 64 |
+
[sde] generated 122/128
|
| 65 |
+
[sde] generated 124/128
|
| 66 |
+
[sde] generated 126/128
|
| 67 |
+
[sde] generated 128/128
|
| 68 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 69 |
+
[summary] {
|
| 70 |
+
"type": "summary",
|
| 71 |
+
"checkpoint": "runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0006000.pt",
|
| 72 |
+
"step": 6000,
|
| 73 |
+
"decode": {
|
| 74 |
+
"decode_rule": "dirichlet_resample_sde",
|
| 75 |
+
"steps": 128,
|
| 76 |
+
"model_t_mode": "support_t",
|
| 77 |
+
"mean_mode": "endpoint_only",
|
| 78 |
+
"anchor_gamma": 1.0,
|
| 79 |
+
"endpoint_floor": 0.0,
|
| 80 |
+
"concentration_min": 30522.0,
|
| 81 |
+
"concentration_max": 61044.0,
|
| 82 |
+
"endpoint_temp": 1.45,
|
| 83 |
+
"endpoint_temp_start": null,
|
| 84 |
+
"endpoint_temp_end": null,
|
| 85 |
+
"endpoint_projection": "gumbel_softmax",
|
| 86 |
+
"endpoint_top_k": 0,
|
| 87 |
+
"endpoint_top_p": 0.95,
|
| 88 |
+
"gumbel_tau_start": 1.0,
|
| 89 |
+
"gumbel_tau_end": 0.2,
|
| 90 |
+
"gumbel_noise_scale_start": 1.0,
|
| 91 |
+
"gumbel_noise_scale_end": 1.0,
|
| 92 |
+
"ban_special_tokens": false,
|
| 93 |
+
"banned_endpoint_ids": [],
|
| 94 |
+
"support_power": 1.0,
|
| 95 |
+
"semantic_power": 1.0,
|
| 96 |
+
"noise_init": "dirichlet",
|
| 97 |
+
"noise_sigma": -1.0,
|
| 98 |
+
"noise_dirichlet_concentration": 30522.0,
|
| 99 |
+
"sde_resample": "dirichlet",
|
| 100 |
+
"logistic_normal_sigma_min": 0.18,
|
| 101 |
+
"logistic_normal_sigma_max": 3.0,
|
| 102 |
+
"logistic_normal_tau_min": 0.65,
|
| 103 |
+
"logistic_normal_tau_max": 1.0,
|
| 104 |
+
"final_from": "blend_0.5",
|
| 105 |
+
"n_samples": 128,
|
| 106 |
+
"seed": 20260524
|
| 107 |
+
},
|
| 108 |
+
"raw_genppl": {
|
| 109 |
+
"ppl": 2.0555040043182493,
|
| 110 |
+
"nll_per_token": 0.7205210754532657,
|
| 111 |
+
"tokens": 128145,
|
| 112 |
+
"kept_samples": 128,
|
| 113 |
+
"total_samples": 128,
|
| 114 |
+
"empty_rate": 0.0,
|
| 115 |
+
"skipped_samples": 0
|
| 116 |
+
},
|
| 117 |
+
"stripped_genppl": {
|
| 118 |
+
"ppl": 2.0238469957582215,
|
| 119 |
+
"nll_per_token": 0.7050001535866586,
|
| 120 |
+
"tokens": 127950,
|
| 121 |
+
"kept_samples": 128,
|
| 122 |
+
"total_samples": 128,
|
| 123 |
+
"empty_rate": 0.0,
|
| 124 |
+
"skipped_samples": 0
|
| 125 |
+
},
|
| 126 |
+
"diversity": {
|
| 127 |
+
"sample_entropy": 1.2342076949480105,
|
| 128 |
+
"unique_tokens": 923,
|
| 129 |
+
"token_count": 131072,
|
| 130 |
+
"distinct_1": 0.00704193115234375,
|
| 131 |
+
"distinct_2": 0.037894061583577714,
|
| 132 |
+
"top_token_mass": 0.26293182373046875
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
[done] docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0006000/sde_steps128_samples128_scored.jsonl
|
| 136 |
+
[watch-gumbel] 2026-05-26_01:33:28 done step_0006000
|
LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0009000.log
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-gumbel] 2026-05-26_06:55:00 infer runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0009000.pt -> docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0009000
|
| 2 |
+
[load] runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0009000.pt
|
| 3 |
+
[ckpt] step=9000
|
| 4 |
+
[sde] generated 2/128
|
| 5 |
+
[sde] generated 4/128
|
| 6 |
+
[sde] generated 6/128
|
| 7 |
+
[sde] generated 8/128
|
| 8 |
+
[sde] generated 10/128
|
| 9 |
+
[sde] generated 12/128
|
| 10 |
+
[sde] generated 14/128
|
| 11 |
+
[sde] generated 16/128
|
| 12 |
+
[sde] generated 18/128
|
| 13 |
+
[sde] generated 20/128
|
| 14 |
+
[sde] generated 22/128
|
| 15 |
+
[sde] generated 24/128
|
| 16 |
+
[sde] generated 26/128
|
| 17 |
+
[sde] generated 28/128
|
| 18 |
+
[sde] generated 30/128
|
| 19 |
+
[sde] generated 32/128
|
| 20 |
+
[sde] generated 34/128
|
| 21 |
+
[sde] generated 36/128
|
| 22 |
+
[sde] generated 38/128
|
| 23 |
+
[sde] generated 40/128
|
| 24 |
+
[sde] generated 42/128
|
| 25 |
+
[sde] generated 44/128
|
| 26 |
+
[sde] generated 46/128
|
| 27 |
+
[sde] generated 48/128
|
| 28 |
+
[sde] generated 50/128
|
| 29 |
+
[sde] generated 52/128
|
| 30 |
+
[sde] generated 54/128
|
| 31 |
+
[sde] generated 56/128
|
| 32 |
+
[sde] generated 58/128
|
| 33 |
+
[sde] generated 60/128
|
| 34 |
+
[sde] generated 62/128
|
| 35 |
+
[sde] generated 64/128
|
| 36 |
+
[sde] generated 66/128
|
| 37 |
+
[sde] generated 68/128
|
| 38 |
+
[sde] generated 70/128
|
| 39 |
+
[sde] generated 72/128
|
| 40 |
+
[sde] generated 74/128
|
| 41 |
+
[sde] generated 76/128
|
| 42 |
+
[sde] generated 78/128
|
| 43 |
+
[sde] generated 80/128
|
| 44 |
+
[sde] generated 82/128
|
| 45 |
+
[sde] generated 84/128
|
| 46 |
+
[sde] generated 86/128
|
| 47 |
+
[sde] generated 88/128
|
| 48 |
+
[sde] generated 90/128
|
| 49 |
+
[sde] generated 92/128
|
| 50 |
+
[sde] generated 94/128
|
| 51 |
+
[sde] generated 96/128
|
| 52 |
+
[sde] generated 98/128
|
| 53 |
+
[sde] generated 100/128
|
| 54 |
+
[sde] generated 102/128
|
| 55 |
+
[sde] generated 104/128
|
| 56 |
+
[sde] generated 106/128
|
| 57 |
+
[sde] generated 108/128
|
| 58 |
+
[sde] generated 110/128
|
| 59 |
+
[sde] generated 112/128
|
| 60 |
+
[sde] generated 114/128
|
| 61 |
+
[sde] generated 116/128
|
| 62 |
+
[sde] generated 118/128
|
| 63 |
+
[sde] generated 120/128
|
| 64 |
+
[sde] generated 122/128
|
| 65 |
+
[sde] generated 124/128
|
| 66 |
+
[sde] generated 126/128
|
| 67 |
+
[sde] generated 128/128
|
| 68 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 69 |
+
[summary] {
|
| 70 |
+
"type": "summary",
|
| 71 |
+
"checkpoint": "runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0009000.pt",
|
| 72 |
+
"step": 9000,
|
| 73 |
+
"decode": {
|
| 74 |
+
"decode_rule": "dirichlet_resample_sde",
|
| 75 |
+
"steps": 128,
|
| 76 |
+
"model_t_mode": "support_t",
|
| 77 |
+
"mean_mode": "endpoint_only",
|
| 78 |
+
"anchor_gamma": 1.0,
|
| 79 |
+
"endpoint_floor": 0.0,
|
| 80 |
+
"concentration_min": 30522.0,
|
| 81 |
+
"concentration_max": 61044.0,
|
| 82 |
+
"endpoint_temp": 1.45,
|
| 83 |
+
"endpoint_temp_start": null,
|
| 84 |
+
"endpoint_temp_end": null,
|
| 85 |
+
"endpoint_projection": "gumbel_softmax",
|
| 86 |
+
"endpoint_top_k": 0,
|
| 87 |
+
"endpoint_top_p": 0.95,
|
| 88 |
+
"gumbel_tau_start": 1.0,
|
| 89 |
+
"gumbel_tau_end": 0.2,
|
| 90 |
+
"gumbel_noise_scale_start": 1.0,
|
| 91 |
+
"gumbel_noise_scale_end": 1.0,
|
| 92 |
+
"ban_special_tokens": false,
|
| 93 |
+
"banned_endpoint_ids": [],
|
| 94 |
+
"support_power": 1.0,
|
| 95 |
+
"semantic_power": 1.0,
|
| 96 |
+
"noise_init": "dirichlet",
|
| 97 |
+
"noise_sigma": -1.0,
|
| 98 |
+
"noise_dirichlet_concentration": 30522.0,
|
| 99 |
+
"sde_resample": "dirichlet",
|
| 100 |
+
"logistic_normal_sigma_min": 0.18,
|
| 101 |
+
"logistic_normal_sigma_max": 3.0,
|
| 102 |
+
"logistic_normal_tau_min": 0.65,
|
| 103 |
+
"logistic_normal_tau_max": 1.0,
|
| 104 |
+
"final_from": "blend_0.5",
|
| 105 |
+
"n_samples": 128,
|
| 106 |
+
"seed": 20260524
|
| 107 |
+
},
|
| 108 |
+
"raw_genppl": {
|
| 109 |
+
"ppl": 5.088105610903924,
|
| 110 |
+
"nll_per_token": 1.6269055826824483,
|
| 111 |
+
"tokens": 129820,
|
| 112 |
+
"kept_samples": 128,
|
| 113 |
+
"total_samples": 128,
|
| 114 |
+
"empty_rate": 0.0,
|
| 115 |
+
"skipped_samples": 0
|
| 116 |
+
},
|
| 117 |
+
"stripped_genppl": {
|
| 118 |
+
"ppl": 5.014868702762704,
|
| 119 |
+
"nll_per_token": 1.612407240166428,
|
| 120 |
+
"tokens": 129623,
|
| 121 |
+
"kept_samples": 128,
|
| 122 |
+
"total_samples": 128,
|
| 123 |
+
"empty_rate": 0.0,
|
| 124 |
+
"skipped_samples": 0
|
| 125 |
+
},
|
| 126 |
+
"diversity": {
|
| 127 |
+
"sample_entropy": 1.3782953161976421,
|
| 128 |
+
"unique_tokens": 1229,
|
| 129 |
+
"token_count": 131072,
|
| 130 |
+
"distinct_1": 0.00937652587890625,
|
| 131 |
+
"distinct_2": 0.0396963587487781,
|
| 132 |
+
"top_token_mass": 0.366668701171875
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
[done] docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0009000/sde_steps128_samples128_scored.jsonl
|
| 136 |
+
[watch-gumbel] 2026-05-26_07:13:03 done step_0009000
|
LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0010000.log
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-gumbel] 2026-05-26_08:47:07 infer runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0010000.pt -> docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0010000
|
| 2 |
+
[load] runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0010000.pt
|
| 3 |
+
[ckpt] step=10000
|
| 4 |
+
[sde] generated 2/128
|
| 5 |
+
[sde] generated 4/128
|
| 6 |
+
[sde] generated 6/128
|
| 7 |
+
[sde] generated 8/128
|
| 8 |
+
[sde] generated 10/128
|
| 9 |
+
[sde] generated 12/128
|
| 10 |
+
[sde] generated 14/128
|
| 11 |
+
[sde] generated 16/128
|
| 12 |
+
[sde] generated 18/128
|
| 13 |
+
[sde] generated 20/128
|
| 14 |
+
[sde] generated 22/128
|
| 15 |
+
[sde] generated 24/128
|
| 16 |
+
[sde] generated 26/128
|
| 17 |
+
[sde] generated 28/128
|
| 18 |
+
[sde] generated 30/128
|
| 19 |
+
[sde] generated 32/128
|
| 20 |
+
[sde] generated 34/128
|
| 21 |
+
[sde] generated 36/128
|
| 22 |
+
[sde] generated 38/128
|
| 23 |
+
[sde] generated 40/128
|
| 24 |
+
[sde] generated 42/128
|
| 25 |
+
[sde] generated 44/128
|
| 26 |
+
[sde] generated 46/128
|
| 27 |
+
[sde] generated 48/128
|
| 28 |
+
[sde] generated 50/128
|
| 29 |
+
[sde] generated 52/128
|
| 30 |
+
[sde] generated 54/128
|
| 31 |
+
[sde] generated 56/128
|
| 32 |
+
[sde] generated 58/128
|
| 33 |
+
[sde] generated 60/128
|
| 34 |
+
[sde] generated 62/128
|
| 35 |
+
[sde] generated 64/128
|
| 36 |
+
[sde] generated 66/128
|
| 37 |
+
[sde] generated 68/128
|
| 38 |
+
[sde] generated 70/128
|
| 39 |
+
[sde] generated 72/128
|
| 40 |
+
[sde] generated 74/128
|
| 41 |
+
[sde] generated 76/128
|
| 42 |
+
[sde] generated 78/128
|
| 43 |
+
[sde] generated 80/128
|
| 44 |
+
[sde] generated 82/128
|
| 45 |
+
[sde] generated 84/128
|
| 46 |
+
[sde] generated 86/128
|
| 47 |
+
[sde] generated 88/128
|
| 48 |
+
[sde] generated 90/128
|
| 49 |
+
[sde] generated 92/128
|
| 50 |
+
[sde] generated 94/128
|
| 51 |
+
[sde] generated 96/128
|
| 52 |
+
[sde] generated 98/128
|
| 53 |
+
[sde] generated 100/128
|
| 54 |
+
[sde] generated 102/128
|
| 55 |
+
[sde] generated 104/128
|
| 56 |
+
[sde] generated 106/128
|
| 57 |
+
[sde] generated 108/128
|
| 58 |
+
[sde] generated 110/128
|
| 59 |
+
[sde] generated 112/128
|
| 60 |
+
[sde] generated 114/128
|
| 61 |
+
[sde] generated 116/128
|
| 62 |
+
[sde] generated 118/128
|
| 63 |
+
[sde] generated 120/128
|
| 64 |
+
[sde] generated 122/128
|
| 65 |
+
[sde] generated 124/128
|
| 66 |
+
[sde] generated 126/128
|
| 67 |
+
[sde] generated 128/128
|
| 68 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 69 |
+
[summary] {
|
| 70 |
+
"type": "summary",
|
| 71 |
+
"checkpoint": "runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0010000.pt",
|
| 72 |
+
"step": 10000,
|
| 73 |
+
"decode": {
|
| 74 |
+
"decode_rule": "dirichlet_resample_sde",
|
| 75 |
+
"steps": 128,
|
| 76 |
+
"model_t_mode": "support_t",
|
| 77 |
+
"mean_mode": "endpoint_only",
|
| 78 |
+
"anchor_gamma": 1.0,
|
| 79 |
+
"endpoint_floor": 0.0,
|
| 80 |
+
"concentration_min": 30522.0,
|
| 81 |
+
"concentration_max": 61044.0,
|
| 82 |
+
"endpoint_temp": 1.45,
|
| 83 |
+
"endpoint_temp_start": null,
|
| 84 |
+
"endpoint_temp_end": null,
|
| 85 |
+
"endpoint_projection": "gumbel_softmax",
|
| 86 |
+
"endpoint_top_k": 0,
|
| 87 |
+
"endpoint_top_p": 0.95,
|
| 88 |
+
"gumbel_tau_start": 1.0,
|
| 89 |
+
"gumbel_tau_end": 0.2,
|
| 90 |
+
"gumbel_noise_scale_start": 1.0,
|
| 91 |
+
"gumbel_noise_scale_end": 1.0,
|
| 92 |
+
"ban_special_tokens": false,
|
| 93 |
+
"banned_endpoint_ids": [],
|
| 94 |
+
"support_power": 1.0,
|
| 95 |
+
"semantic_power": 1.0,
|
| 96 |
+
"noise_init": "dirichlet",
|
| 97 |
+
"noise_sigma": -1.0,
|
| 98 |
+
"noise_dirichlet_concentration": 30522.0,
|
| 99 |
+
"sde_resample": "dirichlet",
|
| 100 |
+
"logistic_normal_sigma_min": 0.18,
|
| 101 |
+
"logistic_normal_sigma_max": 3.0,
|
| 102 |
+
"logistic_normal_tau_min": 0.65,
|
| 103 |
+
"logistic_normal_tau_max": 1.0,
|
| 104 |
+
"final_from": "blend_0.5",
|
| 105 |
+
"n_samples": 128,
|
| 106 |
+
"seed": 20260524
|
| 107 |
+
},
|
| 108 |
+
"raw_genppl": {
|
| 109 |
+
"ppl": 7.382004975613158,
|
| 110 |
+
"nll_per_token": 1.9990452786272435,
|
| 111 |
+
"tokens": 108846,
|
| 112 |
+
"kept_samples": 128,
|
| 113 |
+
"total_samples": 128,
|
| 114 |
+
"empty_rate": 0.0,
|
| 115 |
+
"skipped_samples": 0
|
| 116 |
+
},
|
| 117 |
+
"stripped_genppl": {
|
| 118 |
+
"ppl": 7.193271401079397,
|
| 119 |
+
"nll_per_token": 1.9731460614509597,
|
| 120 |
+
"tokens": 108120,
|
| 121 |
+
"kept_samples": 128,
|
| 122 |
+
"total_samples": 128,
|
| 123 |
+
"empty_rate": 0.0,
|
| 124 |
+
"skipped_samples": 0
|
| 125 |
+
},
|
| 126 |
+
"diversity": {
|
| 127 |
+
"sample_entropy": 1.9640364761127493,
|
| 128 |
+
"unique_tokens": 1041,
|
| 129 |
+
"token_count": 131072,
|
| 130 |
+
"distinct_1": 0.00794219970703125,
|
| 131 |
+
"distinct_2": 0.05942234848484849,
|
| 132 |
+
"top_token_mass": 0.31719970703125
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
[done] docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0010000/sde_steps128_samples128_scored.jsonl
|
| 136 |
+
[watch-gumbel] 2026-05-26_09:06:14 done step_0010000
|
LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0012000.log
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-gumbel] 2026-05-26_12:52:47 infer runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0012000.pt -> docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0012000
|
| 2 |
+
[load] runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0012000.pt
|
| 3 |
+
[ckpt] step=12000
|
| 4 |
+
[sde] generated 2/128
|
| 5 |
+
[sde] generated 4/128
|
| 6 |
+
[sde] generated 6/128
|
| 7 |
+
[sde] generated 8/128
|
| 8 |
+
[sde] generated 10/128
|
| 9 |
+
[sde] generated 12/128
|
| 10 |
+
[sde] generated 14/128
|
| 11 |
+
[sde] generated 16/128
|
| 12 |
+
[sde] generated 18/128
|
| 13 |
+
[sde] generated 20/128
|
| 14 |
+
[sde] generated 22/128
|
| 15 |
+
[sde] generated 24/128
|
| 16 |
+
[sde] generated 26/128
|
| 17 |
+
[sde] generated 28/128
|
| 18 |
+
[sde] generated 30/128
|
| 19 |
+
[sde] generated 32/128
|
| 20 |
+
[sde] generated 34/128
|
| 21 |
+
[sde] generated 36/128
|
| 22 |
+
[sde] generated 38/128
|
| 23 |
+
[sde] generated 40/128
|
| 24 |
+
[sde] generated 42/128
|
| 25 |
+
[sde] generated 44/128
|
| 26 |
+
[sde] generated 46/128
|
| 27 |
+
[sde] generated 48/128
|
| 28 |
+
[sde] generated 50/128
|
| 29 |
+
[sde] generated 52/128
|
| 30 |
+
[sde] generated 54/128
|
| 31 |
+
[sde] generated 56/128
|
| 32 |
+
[sde] generated 58/128
|
| 33 |
+
[sde] generated 60/128
|
| 34 |
+
[sde] generated 62/128
|
| 35 |
+
[sde] generated 64/128
|
| 36 |
+
[sde] generated 66/128
|
| 37 |
+
[sde] generated 68/128
|
| 38 |
+
[sde] generated 70/128
|
| 39 |
+
[sde] generated 72/128
|
| 40 |
+
[sde] generated 74/128
|
| 41 |
+
[sde] generated 76/128
|
| 42 |
+
[sde] generated 78/128
|
| 43 |
+
[sde] generated 80/128
|
| 44 |
+
[sde] generated 82/128
|
| 45 |
+
[sde] generated 84/128
|
| 46 |
+
[sde] generated 86/128
|
| 47 |
+
[sde] generated 88/128
|
| 48 |
+
[sde] generated 90/128
|
| 49 |
+
[sde] generated 92/128
|
| 50 |
+
[sde] generated 94/128
|
| 51 |
+
[sde] generated 96/128
|
| 52 |
+
[sde] generated 98/128
|
| 53 |
+
[sde] generated 100/128
|
| 54 |
+
[sde] generated 102/128
|
| 55 |
+
[sde] generated 104/128
|
| 56 |
+
[sde] generated 106/128
|
| 57 |
+
[sde] generated 108/128
|
| 58 |
+
[sde] generated 110/128
|
| 59 |
+
[sde] generated 112/128
|
| 60 |
+
[sde] generated 114/128
|
| 61 |
+
[sde] generated 116/128
|
| 62 |
+
[sde] generated 118/128
|
| 63 |
+
[sde] generated 120/128
|
| 64 |
+
[sde] generated 122/128
|
| 65 |
+
[sde] generated 124/128
|
| 66 |
+
[sde] generated 126/128
|
| 67 |
+
[sde] generated 128/128
|
| 68 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 69 |
+
[summary] {
|
| 70 |
+
"type": "summary",
|
| 71 |
+
"checkpoint": "runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0012000.pt",
|
| 72 |
+
"step": 12000,
|
| 73 |
+
"decode": {
|
| 74 |
+
"decode_rule": "dirichlet_resample_sde",
|
| 75 |
+
"steps": 128,
|
| 76 |
+
"model_t_mode": "support_t",
|
| 77 |
+
"mean_mode": "endpoint_only",
|
| 78 |
+
"anchor_gamma": 1.0,
|
| 79 |
+
"endpoint_floor": 0.0,
|
| 80 |
+
"concentration_min": 30522.0,
|
| 81 |
+
"concentration_max": 61044.0,
|
| 82 |
+
"endpoint_temp": 1.45,
|
| 83 |
+
"endpoint_temp_start": null,
|
| 84 |
+
"endpoint_temp_end": null,
|
| 85 |
+
"endpoint_projection": "gumbel_softmax",
|
| 86 |
+
"endpoint_top_k": 0,
|
| 87 |
+
"endpoint_top_p": 0.95,
|
| 88 |
+
"gumbel_tau_start": 1.0,
|
| 89 |
+
"gumbel_tau_end": 0.2,
|
| 90 |
+
"gumbel_noise_scale_start": 1.0,
|
| 91 |
+
"gumbel_noise_scale_end": 1.0,
|
| 92 |
+
"ban_special_tokens": false,
|
| 93 |
+
"banned_endpoint_ids": [],
|
| 94 |
+
"support_power": 1.0,
|
| 95 |
+
"semantic_power": 1.0,
|
| 96 |
+
"noise_init": "dirichlet",
|
| 97 |
+
"noise_sigma": -1.0,
|
| 98 |
+
"noise_dirichlet_concentration": 30522.0,
|
| 99 |
+
"sde_resample": "dirichlet",
|
| 100 |
+
"logistic_normal_sigma_min": 0.18,
|
| 101 |
+
"logistic_normal_sigma_max": 3.0,
|
| 102 |
+
"logistic_normal_tau_min": 0.65,
|
| 103 |
+
"logistic_normal_tau_max": 1.0,
|
| 104 |
+
"final_from": "blend_0.5",
|
| 105 |
+
"n_samples": 128,
|
| 106 |
+
"seed": 20260524
|
| 107 |
+
},
|
| 108 |
+
"raw_genppl": {
|
| 109 |
+
"ppl": 9.787557925258849,
|
| 110 |
+
"nll_per_token": 2.281111979588946,
|
| 111 |
+
"tokens": 121050,
|
| 112 |
+
"kept_samples": 128,
|
| 113 |
+
"total_samples": 128,
|
| 114 |
+
"empty_rate": 0.0,
|
| 115 |
+
"skipped_samples": 0
|
| 116 |
+
},
|
| 117 |
+
"stripped_genppl": {
|
| 118 |
+
"ppl": 9.575427309198085,
|
| 119 |
+
"nll_per_token": 2.2592001616634176,
|
| 120 |
+
"tokens": 120277,
|
| 121 |
+
"kept_samples": 128,
|
| 122 |
+
"total_samples": 128,
|
| 123 |
+
"empty_rate": 0.0,
|
| 124 |
+
"skipped_samples": 0
|
| 125 |
+
},
|
| 126 |
+
"diversity": {
|
| 127 |
+
"sample_entropy": 2.3105578319413413,
|
| 128 |
+
"unique_tokens": 1540,
|
| 129 |
+
"token_count": 131072,
|
| 130 |
+
"distinct_1": 0.011749267578125,
|
| 131 |
+
"distinct_2": 0.08389082355816227,
|
| 132 |
+
"top_token_mass": 0.17154693603515625
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
[done] docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0012000/sde_steps128_samples128_scored.jsonl
|
| 136 |
+
[watch-gumbel] 2026-05-26_13:16:51 done step_0012000
|
LTA_openwebtext_dualt/logs/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_gumbel_sde_watch/infer_lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525_step_0013000.log
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-gumbel] 2026-05-26_15:32:28 infer runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0013000.pt -> docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0013000
|
| 2 |
+
[load] runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0013000.pt
|
| 3 |
+
[ckpt] step=13000
|
| 4 |
+
[sde] generated 2/128
|
| 5 |
+
[sde] generated 4/128
|
| 6 |
+
[sde] generated 6/128
|
| 7 |
+
[sde] generated 8/128
|
| 8 |
+
[sde] generated 10/128
|
| 9 |
+
[sde] generated 12/128
|
| 10 |
+
[sde] generated 14/128
|
| 11 |
+
[sde] generated 16/128
|
| 12 |
+
[sde] generated 18/128
|
| 13 |
+
[sde] generated 20/128
|
| 14 |
+
[sde] generated 22/128
|
| 15 |
+
[sde] generated 24/128
|
| 16 |
+
[sde] generated 26/128
|
| 17 |
+
[sde] generated 28/128
|
| 18 |
+
[sde] generated 30/128
|
| 19 |
+
[sde] generated 32/128
|
| 20 |
+
[sde] generated 34/128
|
| 21 |
+
[sde] generated 36/128
|
| 22 |
+
[sde] generated 38/128
|
| 23 |
+
[sde] generated 40/128
|
| 24 |
+
[sde] generated 42/128
|
| 25 |
+
[sde] generated 44/128
|
| 26 |
+
[sde] generated 46/128
|
| 27 |
+
[sde] generated 48/128
|
| 28 |
+
[sde] generated 50/128
|
| 29 |
+
[sde] generated 52/128
|
| 30 |
+
[sde] generated 54/128
|
| 31 |
+
[sde] generated 56/128
|
| 32 |
+
[sde] generated 58/128
|
| 33 |
+
[sde] generated 60/128
|
| 34 |
+
[sde] generated 62/128
|
| 35 |
+
[sde] generated 64/128
|
| 36 |
+
[sde] generated 66/128
|
| 37 |
+
[sde] generated 68/128
|
| 38 |
+
[sde] generated 70/128
|
| 39 |
+
[sde] generated 72/128
|
| 40 |
+
[sde] generated 74/128
|
| 41 |
+
[sde] generated 76/128
|
| 42 |
+
[sde] generated 78/128
|
| 43 |
+
[sde] generated 80/128
|
| 44 |
+
[sde] generated 82/128
|
| 45 |
+
[sde] generated 84/128
|
| 46 |
+
[sde] generated 86/128
|
| 47 |
+
[sde] generated 88/128
|
| 48 |
+
[sde] generated 90/128
|
| 49 |
+
[sde] generated 92/128
|
| 50 |
+
[sde] generated 94/128
|
| 51 |
+
[sde] generated 96/128
|
| 52 |
+
[sde] generated 98/128
|
| 53 |
+
[sde] generated 100/128
|
| 54 |
+
[sde] generated 102/128
|
| 55 |
+
[sde] generated 104/128
|
| 56 |
+
[sde] generated 106/128
|
| 57 |
+
[sde] generated 108/128
|
| 58 |
+
[sde] generated 110/128
|
| 59 |
+
[sde] generated 112/128
|
| 60 |
+
[sde] generated 114/128
|
| 61 |
+
[sde] generated 116/128
|
| 62 |
+
[sde] generated 118/128
|
| 63 |
+
[sde] generated 120/128
|
| 64 |
+
[sde] generated 122/128
|
| 65 |
+
[sde] generated 124/128
|
| 66 |
+
[sde] generated 126/128
|
| 67 |
+
[sde] generated 128/128
|
| 68 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 69 |
+
[summary] {
|
| 70 |
+
"type": "summary",
|
| 71 |
+
"checkpoint": "runs/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0013000.pt",
|
| 72 |
+
"step": 13000,
|
| 73 |
+
"decode": {
|
| 74 |
+
"decode_rule": "dirichlet_resample_sde",
|
| 75 |
+
"steps": 128,
|
| 76 |
+
"model_t_mode": "support_t",
|
| 77 |
+
"mean_mode": "endpoint_only",
|
| 78 |
+
"anchor_gamma": 1.0,
|
| 79 |
+
"endpoint_floor": 0.0,
|
| 80 |
+
"concentration_min": 30522.0,
|
| 81 |
+
"concentration_max": 61044.0,
|
| 82 |
+
"endpoint_temp": 1.45,
|
| 83 |
+
"endpoint_temp_start": null,
|
| 84 |
+
"endpoint_temp_end": null,
|
| 85 |
+
"endpoint_projection": "gumbel_softmax",
|
| 86 |
+
"endpoint_top_k": 0,
|
| 87 |
+
"endpoint_top_p": 0.95,
|
| 88 |
+
"gumbel_tau_start": 1.0,
|
| 89 |
+
"gumbel_tau_end": 0.2,
|
| 90 |
+
"gumbel_noise_scale_start": 1.0,
|
| 91 |
+
"gumbel_noise_scale_end": 1.0,
|
| 92 |
+
"ban_special_tokens": false,
|
| 93 |
+
"banned_endpoint_ids": [],
|
| 94 |
+
"support_power": 1.0,
|
| 95 |
+
"semantic_power": 1.0,
|
| 96 |
+
"noise_init": "dirichlet",
|
| 97 |
+
"noise_sigma": -1.0,
|
| 98 |
+
"noise_dirichlet_concentration": 30522.0,
|
| 99 |
+
"sde_resample": "dirichlet",
|
| 100 |
+
"logistic_normal_sigma_min": 0.18,
|
| 101 |
+
"logistic_normal_sigma_max": 3.0,
|
| 102 |
+
"logistic_normal_tau_min": 0.65,
|
| 103 |
+
"logistic_normal_tau_max": 1.0,
|
| 104 |
+
"final_from": "blend_0.5",
|
| 105 |
+
"n_samples": 128,
|
| 106 |
+
"seed": 20260524
|
| 107 |
+
},
|
| 108 |
+
"raw_genppl": {
|
| 109 |
+
"ppl": 11.019391485874875,
|
| 110 |
+
"nll_per_token": 2.399656583132524,
|
| 111 |
+
"tokens": 130289,
|
| 112 |
+
"kept_samples": 128,
|
| 113 |
+
"total_samples": 128,
|
| 114 |
+
"empty_rate": 0.0,
|
| 115 |
+
"skipped_samples": 0
|
| 116 |
+
},
|
| 117 |
+
"stripped_genppl": {
|
| 118 |
+
"ppl": 10.84729878838137,
|
| 119 |
+
"nll_per_token": 2.3839160893946967,
|
| 120 |
+
"tokens": 129965,
|
| 121 |
+
"kept_samples": 128,
|
| 122 |
+
"total_samples": 128,
|
| 123 |
+
"empty_rate": 0.0,
|
| 124 |
+
"skipped_samples": 0
|
| 125 |
+
},
|
| 126 |
+
"diversity": {
|
| 127 |
+
"sample_entropy": 2.991297718897202,
|
| 128 |
+
"unique_tokens": 1773,
|
| 129 |
+
"token_count": 131072,
|
| 130 |
+
"distinct_1": 0.01352691650390625,
|
| 131 |
+
"distinct_2": 0.11194098240469208,
|
| 132 |
+
"top_token_mass": 0.14432525634765625
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
[done] docs/lta_samples/metrics_20260525/owt_bert_absrope_adaln_Cv_to_2v_mask1_sameT_every1k_sde_gumbel_topp0p95_tau1p0_to_0p2_blend_c30522_61044_n128/lta_owt_bert_absrope_adaln_dirichlet_len1024_Cv_to_2v_mask1_sameT_gbs512_b4x4_1m_save1k_watch_20260525/step_0013000/sde_steps128_samples128_scored.jsonl
|
| 136 |
+
[watch-gumbel] 2026-05-26_15:50:49 done step_0013000
|
LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_bert_10/step_012500.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9b7366cc71d0cff71249d34125e85054c58c1fe18feda5e7ffac8283b0afb9a3
|
| 3 |
+
size 73308686
|
LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_bert_len1024_C1_to_1024_absrope_time4_d256_l3_h4_subset8192_8gpu_20260526_144131/step_012000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:397ae1f3c0db55dc87f897d235996c36cb99e0f0c9716f269754985794bc61f1
|
| 3 |
+
size 73308750
|
LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_bert_len1024_C1_to_1024_absrope_time4_d256_l3_h4_subset8192_8gpu_20260526_144131/step_019000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25fcdea6805c097703a1b13763da1b9fb7ef1f8d99e1618c2754a4a11c4d249b
|
| 3 |
+
size 73308750
|
LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260526_171143/step_004000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9b55d4a7cc02543d0e2df27836592056f908a3dac5d28044523c83d12d824faf
|
| 3 |
+
size 542871814
|
LTA_openwebtext_dualt/mini_owt_fit/runs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260526_171143/step_011000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fd951d671bb4e9bf33270259cc8b6d08c6acce0c6604277601af3e5cde428dff
|
| 3 |
+
size 542871814
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/focalnet/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_focalnet import *
|
| 22 |
+
from .modeling_focalnet import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/focalnet/configuration_focalnet.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""FocalNet model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...backbone_utils import BackboneConfigMixin
|
| 19 |
+
from ...configuration_utils import PreTrainedConfig
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@auto_docstring(checkpoint="microsoft/focalnet-tiny")
|
| 24 |
+
@strict
|
| 25 |
+
class FocalNetConfig(BackboneConfigMixin, PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
use_conv_embed (`bool`, *optional*, defaults to `False`):
|
| 28 |
+
Whether to use convolutional embedding. The authors noted that using convolutional embedding usually
|
| 29 |
+
improve the performance, but it's not used by default.
|
| 30 |
+
focal_levels (`list(int)`, *optional*, defaults to `[2, 2, 2, 2]`):
|
| 31 |
+
Number of focal levels in each layer of the respective stages in the encoder.
|
| 32 |
+
focal_windows (`list(int)`, *optional*, defaults to `[3, 3, 3, 3]`):
|
| 33 |
+
Focal window size in each layer of the respective stages in the encoder.
|
| 34 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 35 |
+
The dropout probability for all fully connected layers in the embeddings and encoder.
|
| 36 |
+
use_layerscale (`bool`, *optional*, defaults to `False`):
|
| 37 |
+
Whether to use layer scale in the encoder.
|
| 38 |
+
layerscale_value (`float`, *optional*, defaults to 0.0001):
|
| 39 |
+
The initial value of the layer scale.
|
| 40 |
+
use_post_layernorm (`bool`, *optional*, defaults to `False`):
|
| 41 |
+
Whether to use post layer normalization in the encoder.
|
| 42 |
+
use_post_layernorm_in_modulation (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether to use post layer normalization in the modulation layer.
|
| 44 |
+
normalize_modulator (`bool`, *optional*, defaults to `False`):
|
| 45 |
+
Whether to normalize the modulator.
|
| 46 |
+
encoder_stride (`int`, *optional*, defaults to 32):
|
| 47 |
+
Factor to increase the spatial resolution by in the decoder head for masked image modeling.
|
| 48 |
+
|
| 49 |
+
Example:
|
| 50 |
+
|
| 51 |
+
```python
|
| 52 |
+
>>> from transformers import FocalNetConfig, FocalNetModel
|
| 53 |
+
|
| 54 |
+
>>> # Initializing a FocalNet microsoft/focalnet-tiny style configuration
|
| 55 |
+
>>> configuration = FocalNetConfig()
|
| 56 |
+
|
| 57 |
+
>>> # Initializing a model (with random weights) from the microsoft/focalnet-tiny style configuration
|
| 58 |
+
>>> model = FocalNetModel(configuration)
|
| 59 |
+
|
| 60 |
+
>>> # Accessing the model configuration
|
| 61 |
+
>>> configuration = model.config
|
| 62 |
+
```"""
|
| 63 |
+
|
| 64 |
+
model_type = "focalnet"
|
| 65 |
+
|
| 66 |
+
image_size: int | list[int] | tuple[int, int] = 224
|
| 67 |
+
patch_size: int | list[int] | tuple[int, int] = 4
|
| 68 |
+
num_channels: int = 3
|
| 69 |
+
embed_dim: int = 96
|
| 70 |
+
use_conv_embed: bool = False
|
| 71 |
+
hidden_sizes: list[int] | tuple[int, ...] = (192, 384, 768, 768)
|
| 72 |
+
depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)
|
| 73 |
+
focal_levels: list[int] | tuple[int, ...] = (2, 2, 2, 2)
|
| 74 |
+
focal_windows: list[int] | tuple[int, ...] = (3, 3, 3, 3)
|
| 75 |
+
hidden_act: str = "gelu"
|
| 76 |
+
mlp_ratio: float = 4.0
|
| 77 |
+
hidden_dropout_prob: float | int = 0.0
|
| 78 |
+
drop_path_rate: float | int = 0.1
|
| 79 |
+
use_layerscale: bool = False
|
| 80 |
+
layerscale_value: float = 1e-4
|
| 81 |
+
use_post_layernorm: bool = False
|
| 82 |
+
use_post_layernorm_in_modulation: bool = False
|
| 83 |
+
normalize_modulator: bool = False
|
| 84 |
+
initializer_range: float = 0.02
|
| 85 |
+
layer_norm_eps: float = 1e-5
|
| 86 |
+
encoder_stride: int = 32
|
| 87 |
+
_out_features: list[str] | None = None
|
| 88 |
+
_out_indices: list[int] | None = None
|
| 89 |
+
|
| 90 |
+
def __post_init__(self, **kwargs):
|
| 91 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
|
| 92 |
+
self.set_output_features_output_indices(
|
| 93 |
+
out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
|
| 94 |
+
)
|
| 95 |
+
super().__post_init__(**kwargs)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
__all__ = ["FocalNetConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/focalnet/modeling_focalnet.py
ADDED
|
@@ -0,0 +1,928 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch FocalNet model."""
|
| 15 |
+
|
| 16 |
+
import collections.abc
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...backbone_utils import BackboneMixin, filter_output_hidden_states
|
| 26 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
from ...modeling_outputs import BackboneOutput
|
| 28 |
+
from ...modeling_utils import PreTrainedModel
|
| 29 |
+
from ...utils import ModelOutput, auto_docstring, logging
|
| 30 |
+
from ...utils.generic import can_return_tuple
|
| 31 |
+
from .configuration_focalnet import FocalNetConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@auto_docstring(
|
| 38 |
+
custom_intro="""
|
| 39 |
+
FocalNet encoder's outputs, with potential hidden states.
|
| 40 |
+
"""
|
| 41 |
+
)
|
| 42 |
+
@dataclass
|
| 43 |
+
class FocalNetEncoderOutput(ModelOutput):
|
| 44 |
+
r"""
|
| 45 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 46 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 47 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 48 |
+
|
| 49 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 50 |
+
include the spatial dimensions.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 54 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 55 |
+
reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@auto_docstring(
|
| 59 |
+
custom_intro="""
|
| 60 |
+
FocalNet model's outputs that also contains a pooling of the last hidden states.
|
| 61 |
+
"""
|
| 62 |
+
)
|
| 63 |
+
@dataclass
|
| 64 |
+
class FocalNetModelOutput(ModelOutput):
|
| 65 |
+
r"""
|
| 66 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
|
| 67 |
+
Average pooling of the last layer hidden-state.
|
| 68 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 69 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 70 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 71 |
+
|
| 72 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 73 |
+
include the spatial dimensions.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 77 |
+
pooler_output: torch.FloatTensor | None = None
|
| 78 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 79 |
+
reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@auto_docstring(
|
| 83 |
+
custom_intro="""
|
| 84 |
+
FocalNet masked image model outputs.
|
| 85 |
+
"""
|
| 86 |
+
)
|
| 87 |
+
@dataclass
|
| 88 |
+
class FocalNetMaskedImageModelingOutput(ModelOutput):
|
| 89 |
+
r"""
|
| 90 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
|
| 91 |
+
Masked image modeling (MLM) loss.
|
| 92 |
+
reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 93 |
+
Reconstructed pixel values.
|
| 94 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 95 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 96 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 97 |
+
|
| 98 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 99 |
+
include the spatial dimensions.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
loss: torch.FloatTensor | None = None
|
| 103 |
+
reconstruction: torch.FloatTensor | None = None
|
| 104 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 105 |
+
reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@auto_docstring(
|
| 109 |
+
custom_intro="""
|
| 110 |
+
FocalNet outputs for image classification.
|
| 111 |
+
"""
|
| 112 |
+
)
|
| 113 |
+
@dataclass
|
| 114 |
+
class FocalNetImageClassifierOutput(ModelOutput):
|
| 115 |
+
r"""
|
| 116 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 117 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 118 |
+
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 119 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 120 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 121 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 122 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 123 |
+
|
| 124 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 125 |
+
include the spatial dimensions.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
loss: torch.FloatTensor | None = None
|
| 129 |
+
logits: torch.FloatTensor | None = None
|
| 130 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 131 |
+
reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class FocalNetEmbeddings(nn.Module):
|
| 135 |
+
"""
|
| 136 |
+
Construct the patch embeddings and layernorm. Optionally, also the mask token.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def __init__(self, config, use_mask_token=False):
|
| 140 |
+
super().__init__()
|
| 141 |
+
|
| 142 |
+
self.patch_embeddings = FocalNetPatchEmbeddings(
|
| 143 |
+
config=config,
|
| 144 |
+
image_size=config.image_size,
|
| 145 |
+
patch_size=config.patch_size,
|
| 146 |
+
num_channels=config.num_channels,
|
| 147 |
+
embed_dim=config.embed_dim,
|
| 148 |
+
use_conv_embed=config.use_conv_embed,
|
| 149 |
+
is_stem=True,
|
| 150 |
+
)
|
| 151 |
+
self.patch_grid = self.patch_embeddings.grid_size
|
| 152 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
|
| 153 |
+
|
| 154 |
+
self.norm = nn.LayerNorm(config.embed_dim, eps=config.layer_norm_eps)
|
| 155 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self, pixel_values: torch.FloatTensor | None, bool_masked_pos: torch.BoolTensor | None = None
|
| 159 |
+
) -> tuple[torch.Tensor]:
|
| 160 |
+
embeddings, output_dimensions = self.patch_embeddings(pixel_values)
|
| 161 |
+
embeddings = self.norm(embeddings)
|
| 162 |
+
batch_size, seq_len, _ = embeddings.size()
|
| 163 |
+
|
| 164 |
+
if bool_masked_pos is not None:
|
| 165 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
|
| 166 |
+
# replace the masked visual tokens by mask_tokens
|
| 167 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 168 |
+
embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
|
| 169 |
+
|
| 170 |
+
embeddings = self.dropout(embeddings)
|
| 171 |
+
return embeddings, output_dimensions
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class FocalNetPatchEmbeddings(nn.Module):
|
| 175 |
+
def __init__(
|
| 176 |
+
self,
|
| 177 |
+
config,
|
| 178 |
+
image_size,
|
| 179 |
+
patch_size,
|
| 180 |
+
num_channels,
|
| 181 |
+
embed_dim,
|
| 182 |
+
add_norm=False,
|
| 183 |
+
use_conv_embed=False,
|
| 184 |
+
is_stem=False,
|
| 185 |
+
):
|
| 186 |
+
super().__init__()
|
| 187 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 188 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 189 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 190 |
+
self.image_size = image_size
|
| 191 |
+
self.patch_size = patch_size
|
| 192 |
+
self.num_channels = num_channels
|
| 193 |
+
self.num_patches = num_patches
|
| 194 |
+
self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
|
| 195 |
+
|
| 196 |
+
if use_conv_embed:
|
| 197 |
+
# if we choose to use conv embedding, then we treat the stem and non-stem differently
|
| 198 |
+
if is_stem:
|
| 199 |
+
kernel_size = 7
|
| 200 |
+
padding = 2
|
| 201 |
+
stride = 4
|
| 202 |
+
else:
|
| 203 |
+
kernel_size = 3
|
| 204 |
+
padding = 1
|
| 205 |
+
stride = 2
|
| 206 |
+
self.projection = nn.Conv2d(
|
| 207 |
+
num_channels, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
|
| 211 |
+
|
| 212 |
+
if add_norm:
|
| 213 |
+
self.norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 214 |
+
else:
|
| 215 |
+
self.norm = None
|
| 216 |
+
|
| 217 |
+
def maybe_pad(self, pixel_values, height, width):
|
| 218 |
+
if width % self.patch_size[1] != 0:
|
| 219 |
+
pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
|
| 220 |
+
pixel_values = nn.functional.pad(pixel_values, pad_values)
|
| 221 |
+
if height % self.patch_size[0] != 0:
|
| 222 |
+
pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
|
| 223 |
+
pixel_values = nn.functional.pad(pixel_values, pad_values)
|
| 224 |
+
return pixel_values
|
| 225 |
+
|
| 226 |
+
def forward(self, pixel_values: torch.FloatTensor | None) -> tuple[torch.Tensor, tuple[int]]:
|
| 227 |
+
_, num_channels, height, width = pixel_values.shape
|
| 228 |
+
if num_channels != self.num_channels:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 231 |
+
)
|
| 232 |
+
# pad the input to be divisible by self.patch_size, if needed
|
| 233 |
+
pixel_values = self.maybe_pad(pixel_values, height, width)
|
| 234 |
+
embeddings = self.projection(pixel_values)
|
| 235 |
+
_, _, height, width = embeddings.shape
|
| 236 |
+
output_dimensions = (height, width)
|
| 237 |
+
embeddings = embeddings.flatten(2).transpose(1, 2)
|
| 238 |
+
|
| 239 |
+
if self.norm is not None:
|
| 240 |
+
embeddings = self.norm(embeddings)
|
| 241 |
+
|
| 242 |
+
return embeddings, output_dimensions
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class FocalNetModulation(nn.Module):
|
| 246 |
+
def __init__(self, config, index, dim, focal_factor=2, bias=True, projection_dropout=0.0):
|
| 247 |
+
super().__init__()
|
| 248 |
+
|
| 249 |
+
self.dim = dim
|
| 250 |
+
self.focal_window = config.focal_windows[index]
|
| 251 |
+
self.focal_level = config.focal_levels[index]
|
| 252 |
+
self.focal_factor = focal_factor
|
| 253 |
+
self.use_post_layernorm_in_modulation = config.use_post_layernorm_in_modulation
|
| 254 |
+
self.normalize_modulator = config.normalize_modulator
|
| 255 |
+
|
| 256 |
+
self.projection_in = nn.Linear(dim, 2 * dim + (self.focal_level + 1), bias=bias)
|
| 257 |
+
self.projection_context = nn.Conv2d(dim, dim, kernel_size=1, stride=1, bias=bias)
|
| 258 |
+
|
| 259 |
+
self.activation = nn.GELU()
|
| 260 |
+
self.projection_out = nn.Linear(dim, dim)
|
| 261 |
+
self.projection_dropout = nn.Dropout(projection_dropout)
|
| 262 |
+
self.focal_layers = nn.ModuleList()
|
| 263 |
+
|
| 264 |
+
self.kernel_sizes = []
|
| 265 |
+
for k in range(self.focal_level):
|
| 266 |
+
kernel_size = self.focal_factor * k + self.focal_window
|
| 267 |
+
self.focal_layers.append(
|
| 268 |
+
nn.Sequential(
|
| 269 |
+
nn.Conv2d(
|
| 270 |
+
dim, dim, kernel_size=kernel_size, stride=1, groups=dim, padding=kernel_size // 2, bias=False
|
| 271 |
+
),
|
| 272 |
+
nn.GELU(),
|
| 273 |
+
)
|
| 274 |
+
)
|
| 275 |
+
self.kernel_sizes.append(kernel_size)
|
| 276 |
+
if self.use_post_layernorm_in_modulation:
|
| 277 |
+
self.layernorm = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 278 |
+
|
| 279 |
+
def forward(self, hidden_state):
|
| 280 |
+
"""
|
| 281 |
+
Args:
|
| 282 |
+
hidden_state:
|
| 283 |
+
Input features with shape of (batch_size, height, width, num_channels)
|
| 284 |
+
"""
|
| 285 |
+
num_channels = hidden_state.shape[-1]
|
| 286 |
+
|
| 287 |
+
# pre linear projection
|
| 288 |
+
x = self.projection_in(hidden_state).permute(0, 3, 1, 2).contiguous()
|
| 289 |
+
q, ctx, gates = torch.split(x, (num_channels, num_channels, self.focal_level + 1), 1)
|
| 290 |
+
|
| 291 |
+
# context aggregation
|
| 292 |
+
ctx_all = 0
|
| 293 |
+
for level in range(self.focal_level):
|
| 294 |
+
ctx = self.focal_layers[level](ctx)
|
| 295 |
+
ctx_all = ctx_all + ctx * gates[:, level : level + 1]
|
| 296 |
+
ctx_global = self.activation(ctx.mean(2, keepdim=True).mean(3, keepdim=True))
|
| 297 |
+
ctx_all = ctx_all + ctx_global * gates[:, self.focal_level :]
|
| 298 |
+
|
| 299 |
+
# normalize context
|
| 300 |
+
if self.normalize_modulator:
|
| 301 |
+
ctx_all = ctx_all / (self.focal_level + 1)
|
| 302 |
+
|
| 303 |
+
# focal modulation
|
| 304 |
+
modulator = self.projection_context(ctx_all)
|
| 305 |
+
x_out = q * modulator
|
| 306 |
+
x_out = x_out.permute(0, 2, 3, 1).contiguous()
|
| 307 |
+
if self.use_post_layernorm_in_modulation:
|
| 308 |
+
x_out = self.layernorm(x_out)
|
| 309 |
+
|
| 310 |
+
# post linear projection
|
| 311 |
+
x_out = self.projection_out(x_out)
|
| 312 |
+
x_out = self.projection_dropout(x_out)
|
| 313 |
+
return x_out
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class FocalNetMlp(nn.Module):
|
| 317 |
+
def __init__(self, config, in_features, hidden_features=None, out_features=None, drop=0.0):
|
| 318 |
+
super().__init__()
|
| 319 |
+
out_features = out_features or in_features
|
| 320 |
+
hidden_features = hidden_features or in_features
|
| 321 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 322 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 323 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
| 324 |
+
self.drop = nn.Dropout(drop)
|
| 325 |
+
|
| 326 |
+
def forward(self, hidden_state):
|
| 327 |
+
hidden_state = self.fc1(hidden_state)
|
| 328 |
+
hidden_state = self.activation(hidden_state)
|
| 329 |
+
hidden_state = self.drop(hidden_state)
|
| 330 |
+
hidden_state = self.fc2(hidden_state)
|
| 331 |
+
hidden_state = self.drop(hidden_state)
|
| 332 |
+
return hidden_state
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->FocalNetDropPath
|
| 336 |
+
class FocalNetDropPath(nn.Module):
|
| 337 |
+
"""Stochastic depth (DropPath) per sample, for residual blocks.
|
| 338 |
+
|
| 339 |
+
Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
|
| 340 |
+
<https://arxiv.org/abs/1603.09382>`_.
|
| 341 |
+
"""
|
| 342 |
+
|
| 343 |
+
def __init__(self, drop_prob: float = 0.0) -> None:
|
| 344 |
+
super().__init__()
|
| 345 |
+
self.drop_prob = drop_prob
|
| 346 |
+
|
| 347 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 348 |
+
if self.drop_prob == 0.0 or not self.training:
|
| 349 |
+
return hidden_states
|
| 350 |
+
keep_prob = 1 - self.drop_prob
|
| 351 |
+
shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
|
| 352 |
+
random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 353 |
+
random_tensor = torch.floor(random_tensor + keep_prob)
|
| 354 |
+
return hidden_states.div(keep_prob) * random_tensor
|
| 355 |
+
|
| 356 |
+
def extra_repr(self) -> str:
|
| 357 |
+
return f"p={self.drop_prob}"
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class FocalNetLayer(nn.Module):
|
| 361 |
+
r"""Focal Modulation Network layer (block).
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
config (`FocalNetConfig`):
|
| 365 |
+
Model config.
|
| 366 |
+
index (`int`):
|
| 367 |
+
Layer index.
|
| 368 |
+
dim (`int`):
|
| 369 |
+
Number of input channels.
|
| 370 |
+
input_resolution (`tuple[int]`):
|
| 371 |
+
Input resolution.
|
| 372 |
+
drop_path (`float`, *optional*, defaults to 0.0):
|
| 373 |
+
Stochastic depth rate.
|
| 374 |
+
"""
|
| 375 |
+
|
| 376 |
+
def __init__(self, config, index, dim, input_resolution, drop_path=0.0):
|
| 377 |
+
super().__init__()
|
| 378 |
+
|
| 379 |
+
self.config = config
|
| 380 |
+
|
| 381 |
+
# layer-specific attributes
|
| 382 |
+
self.dim = dim
|
| 383 |
+
self.input_resolution = input_resolution
|
| 384 |
+
|
| 385 |
+
# general attributes
|
| 386 |
+
self.drop = config.hidden_dropout_prob
|
| 387 |
+
self.use_post_layernorm = config.use_post_layernorm
|
| 388 |
+
|
| 389 |
+
self.norm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 390 |
+
self.modulation = FocalNetModulation(
|
| 391 |
+
config=config,
|
| 392 |
+
index=index,
|
| 393 |
+
dim=dim,
|
| 394 |
+
projection_dropout=self.drop,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
self.drop_path = FocalNetDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 398 |
+
self.norm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 399 |
+
mlp_hidden_dim = int(dim * config.mlp_ratio)
|
| 400 |
+
self.mlp = FocalNetMlp(config=config, in_features=dim, hidden_features=mlp_hidden_dim, drop=self.drop)
|
| 401 |
+
|
| 402 |
+
self.gamma_1 = 1.0
|
| 403 |
+
self.gamma_2 = 1.0
|
| 404 |
+
if config.use_layerscale:
|
| 405 |
+
self.gamma_1 = nn.Parameter(config.layerscale_value * torch.ones(dim), requires_grad=True)
|
| 406 |
+
self.gamma_2 = nn.Parameter(config.layerscale_value * torch.ones(dim), requires_grad=True)
|
| 407 |
+
|
| 408 |
+
def forward(self, hidden_state, input_dimensions):
|
| 409 |
+
height, width = input_dimensions
|
| 410 |
+
batch_size, _, num_channels = hidden_state.shape
|
| 411 |
+
shortcut = hidden_state
|
| 412 |
+
|
| 413 |
+
# Focal Modulation
|
| 414 |
+
hidden_state = hidden_state if self.use_post_layernorm else self.norm1(hidden_state)
|
| 415 |
+
hidden_state = hidden_state.view(batch_size, height, width, num_channels)
|
| 416 |
+
hidden_state = self.modulation(hidden_state).view(batch_size, height * width, num_channels)
|
| 417 |
+
hidden_state = hidden_state if not self.use_post_layernorm else self.norm1(hidden_state)
|
| 418 |
+
|
| 419 |
+
# FFN
|
| 420 |
+
hidden_state = shortcut + self.drop_path(self.gamma_1 * hidden_state)
|
| 421 |
+
hidden_state = hidden_state + self.drop_path(
|
| 422 |
+
self.gamma_2
|
| 423 |
+
* (self.norm2(self.mlp(hidden_state)) if self.use_post_layernorm else self.mlp(self.norm2(hidden_state)))
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
return hidden_state
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
class FocalNetStage(GradientCheckpointingLayer):
|
| 430 |
+
def __init__(self, config, index, input_resolution):
|
| 431 |
+
super().__init__()
|
| 432 |
+
|
| 433 |
+
self.config = config
|
| 434 |
+
self.num_stages = len(config.depths)
|
| 435 |
+
|
| 436 |
+
embed_dim = [config.embed_dim * (2**i) for i in range(self.num_stages)]
|
| 437 |
+
dim = embed_dim[index]
|
| 438 |
+
out_dim = embed_dim[index + 1] if (index < self.num_stages - 1) else None
|
| 439 |
+
downsample = FocalNetPatchEmbeddings if (index < self.num_stages - 1) else None
|
| 440 |
+
|
| 441 |
+
# stochastic depth decay rule
|
| 442 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
|
| 443 |
+
drop_path = dpr[sum(config.depths[:index]) : sum(config.depths[: index + 1])]
|
| 444 |
+
|
| 445 |
+
self.layers = nn.ModuleList(
|
| 446 |
+
[
|
| 447 |
+
FocalNetLayer(
|
| 448 |
+
config=config,
|
| 449 |
+
index=index,
|
| 450 |
+
dim=dim,
|
| 451 |
+
input_resolution=input_resolution,
|
| 452 |
+
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
| 453 |
+
)
|
| 454 |
+
for i in range(config.depths[index])
|
| 455 |
+
]
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
if downsample is not None:
|
| 459 |
+
self.downsample = downsample(
|
| 460 |
+
config=config,
|
| 461 |
+
image_size=input_resolution,
|
| 462 |
+
patch_size=2,
|
| 463 |
+
num_channels=dim,
|
| 464 |
+
embed_dim=out_dim,
|
| 465 |
+
add_norm=True,
|
| 466 |
+
use_conv_embed=config.use_conv_embed,
|
| 467 |
+
is_stem=False,
|
| 468 |
+
)
|
| 469 |
+
else:
|
| 470 |
+
self.downsample = None
|
| 471 |
+
|
| 472 |
+
self.pointing = False
|
| 473 |
+
|
| 474 |
+
def forward(self, hidden_states: torch.Tensor, input_dimensions: tuple[int, int]) -> tuple[torch.Tensor]:
|
| 475 |
+
height, width = input_dimensions
|
| 476 |
+
for layer_module in self.layers:
|
| 477 |
+
hidden_states = layer_module(hidden_states, input_dimensions)
|
| 478 |
+
|
| 479 |
+
hidden_states_before_downsampling = hidden_states
|
| 480 |
+
if self.downsample is not None:
|
| 481 |
+
height, width = input_dimensions
|
| 482 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(
|
| 483 |
+
hidden_states_before_downsampling.shape[0], -1, height, width
|
| 484 |
+
)
|
| 485 |
+
hidden_states, output_dimensions = self.downsample(hidden_states)
|
| 486 |
+
|
| 487 |
+
else:
|
| 488 |
+
output_dimensions = (height, width, height, width)
|
| 489 |
+
|
| 490 |
+
stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
|
| 491 |
+
|
| 492 |
+
return stage_outputs
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class FocalNetEncoder(nn.Module):
|
| 496 |
+
def __init__(self, config, grid_size):
|
| 497 |
+
super().__init__()
|
| 498 |
+
self.num_stages = len(config.depths)
|
| 499 |
+
self.config = config
|
| 500 |
+
|
| 501 |
+
self.stages = nn.ModuleList(
|
| 502 |
+
[
|
| 503 |
+
FocalNetStage(
|
| 504 |
+
config=config,
|
| 505 |
+
index=i_layer,
|
| 506 |
+
input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
|
| 507 |
+
)
|
| 508 |
+
for i_layer in range(self.num_stages)
|
| 509 |
+
]
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
self.gradient_checkpointing = False
|
| 513 |
+
|
| 514 |
+
def forward(
|
| 515 |
+
self,
|
| 516 |
+
hidden_states: torch.Tensor,
|
| 517 |
+
input_dimensions: tuple[int, int],
|
| 518 |
+
output_hidden_states: bool | None = False,
|
| 519 |
+
output_hidden_states_before_downsampling: bool | None = False,
|
| 520 |
+
return_dict: bool | None = True,
|
| 521 |
+
) -> tuple | FocalNetEncoderOutput:
|
| 522 |
+
all_hidden_states = () if output_hidden_states else None
|
| 523 |
+
all_reshaped_hidden_states = () if output_hidden_states else None
|
| 524 |
+
|
| 525 |
+
if output_hidden_states:
|
| 526 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 527 |
+
# rearrange b (h w) c -> b c h w
|
| 528 |
+
reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
|
| 529 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 530 |
+
all_hidden_states += (hidden_states,)
|
| 531 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 532 |
+
|
| 533 |
+
for i, stage_module in enumerate(self.stages):
|
| 534 |
+
stage_outputs = stage_module(hidden_states, input_dimensions)
|
| 535 |
+
|
| 536 |
+
hidden_states = stage_outputs[0]
|
| 537 |
+
hidden_states_before_downsampling = stage_outputs[1]
|
| 538 |
+
output_dimensions = stage_outputs[2]
|
| 539 |
+
|
| 540 |
+
input_dimensions = (output_dimensions[-2], output_dimensions[-1])
|
| 541 |
+
|
| 542 |
+
if output_hidden_states and output_hidden_states_before_downsampling:
|
| 543 |
+
batch_size, _, hidden_size = hidden_states_before_downsampling.shape
|
| 544 |
+
# rearrange b (h w) c -> b c h w
|
| 545 |
+
# here we use the original (not downsampled) height and width
|
| 546 |
+
reshaped_hidden_state = hidden_states_before_downsampling.view(
|
| 547 |
+
batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
|
| 548 |
+
)
|
| 549 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 550 |
+
all_hidden_states += (hidden_states_before_downsampling,)
|
| 551 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 552 |
+
elif output_hidden_states and not output_hidden_states_before_downsampling:
|
| 553 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 554 |
+
# rearrange b (h w) c -> b c h w
|
| 555 |
+
reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
|
| 556 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 557 |
+
all_hidden_states += (hidden_states,)
|
| 558 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 559 |
+
|
| 560 |
+
if not return_dict:
|
| 561 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 562 |
+
|
| 563 |
+
return FocalNetEncoderOutput(
|
| 564 |
+
last_hidden_state=hidden_states,
|
| 565 |
+
hidden_states=all_hidden_states,
|
| 566 |
+
reshaped_hidden_states=all_reshaped_hidden_states,
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
@auto_docstring
|
| 571 |
+
class FocalNetPreTrainedModel(PreTrainedModel):
|
| 572 |
+
config: FocalNetConfig
|
| 573 |
+
base_model_prefix = "focalnet"
|
| 574 |
+
main_input_name = "pixel_values"
|
| 575 |
+
supports_gradient_checkpointing = True
|
| 576 |
+
_no_split_modules = ["FocalNetStage"]
|
| 577 |
+
|
| 578 |
+
@torch.no_grad()
|
| 579 |
+
def _init_weights(self, module):
|
| 580 |
+
"""Initialize the weights"""
|
| 581 |
+
super()._init_weights(module)
|
| 582 |
+
if isinstance(module, FocalNetEmbeddings):
|
| 583 |
+
if module.mask_token is not None:
|
| 584 |
+
init.zeros_(module.mask_token)
|
| 585 |
+
elif isinstance(module, FocalNetLayer):
|
| 586 |
+
if self.config.use_layerscale:
|
| 587 |
+
init.constant_(module.gamma_1, self.config.layerscale_value)
|
| 588 |
+
init.constant_(module.gamma_2, self.config.layerscale_value)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
@auto_docstring
|
| 592 |
+
class FocalNetModel(FocalNetPreTrainedModel):
|
| 593 |
+
def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
|
| 594 |
+
r"""
|
| 595 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 596 |
+
Whether to add a pooling layer
|
| 597 |
+
use_mask_token (`bool`, *optional*, defaults to `False`):
|
| 598 |
+
Whether to use a mask token for masked image modeling.
|
| 599 |
+
"""
|
| 600 |
+
super().__init__(config)
|
| 601 |
+
self.config = config
|
| 602 |
+
self.num_stages = len(config.depths)
|
| 603 |
+
self.num_features = int(config.embed_dim * 2 ** (self.num_stages - 1))
|
| 604 |
+
|
| 605 |
+
self.embeddings = FocalNetEmbeddings(config, use_mask_token=use_mask_token)
|
| 606 |
+
self.encoder = FocalNetEncoder(config, self.embeddings.patch_grid)
|
| 607 |
+
|
| 608 |
+
self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
|
| 609 |
+
self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
|
| 610 |
+
|
| 611 |
+
# Initialize weights and apply final processing
|
| 612 |
+
self.post_init()
|
| 613 |
+
|
| 614 |
+
def get_input_embeddings(self):
|
| 615 |
+
return self.embeddings.patch_embeddings
|
| 616 |
+
|
| 617 |
+
@auto_docstring
|
| 618 |
+
def forward(
|
| 619 |
+
self,
|
| 620 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 621 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 622 |
+
output_hidden_states: bool | None = None,
|
| 623 |
+
return_dict: bool | None = None,
|
| 624 |
+
**kwargs,
|
| 625 |
+
) -> tuple | FocalNetModelOutput:
|
| 626 |
+
r"""
|
| 627 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 628 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 629 |
+
"""
|
| 630 |
+
output_hidden_states = (
|
| 631 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 632 |
+
)
|
| 633 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 634 |
+
|
| 635 |
+
if pixel_values is None:
|
| 636 |
+
raise ValueError("You have to specify pixel_values")
|
| 637 |
+
|
| 638 |
+
embedding_output, input_dimensions = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 639 |
+
|
| 640 |
+
encoder_outputs = self.encoder(
|
| 641 |
+
embedding_output,
|
| 642 |
+
input_dimensions,
|
| 643 |
+
output_hidden_states=output_hidden_states,
|
| 644 |
+
return_dict=return_dict,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
sequence_output = encoder_outputs[0]
|
| 648 |
+
sequence_output = self.layernorm(sequence_output)
|
| 649 |
+
|
| 650 |
+
pooled_output = None
|
| 651 |
+
if self.pooler is not None:
|
| 652 |
+
pooled_output = self.pooler(sequence_output.transpose(1, 2))
|
| 653 |
+
pooled_output = torch.flatten(pooled_output, 1)
|
| 654 |
+
|
| 655 |
+
if not return_dict:
|
| 656 |
+
output = (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 657 |
+
|
| 658 |
+
return output
|
| 659 |
+
|
| 660 |
+
return FocalNetModelOutput(
|
| 661 |
+
last_hidden_state=sequence_output,
|
| 662 |
+
pooler_output=pooled_output,
|
| 663 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 664 |
+
reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
@auto_docstring(
|
| 669 |
+
custom_intro="""
|
| 670 |
+
FocalNet Model with a decoder on top for masked image modeling.
|
| 671 |
+
|
| 672 |
+
This follows the same implementation as in [SimMIM](https://huggingface.co/papers/2111.09886).
|
| 673 |
+
|
| 674 |
+
<Tip>
|
| 675 |
+
|
| 676 |
+
Note that we provide a script to pre-train this model on custom data in our [examples
|
| 677 |
+
directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
|
| 678 |
+
|
| 679 |
+
</Tip>
|
| 680 |
+
"""
|
| 681 |
+
)
|
| 682 |
+
class FocalNetForMaskedImageModeling(FocalNetPreTrainedModel):
|
| 683 |
+
def __init__(self, config):
|
| 684 |
+
super().__init__(config)
|
| 685 |
+
|
| 686 |
+
self.focalnet = FocalNetModel(config, add_pooling_layer=False, use_mask_token=True)
|
| 687 |
+
|
| 688 |
+
self.num_stages = len(config.depths)
|
| 689 |
+
num_features = int(config.embed_dim * 2 ** (self.num_stages - 1))
|
| 690 |
+
self.decoder = nn.Sequential(
|
| 691 |
+
nn.Conv2d(
|
| 692 |
+
in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
|
| 693 |
+
),
|
| 694 |
+
nn.PixelShuffle(config.encoder_stride),
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
# Initialize weights and apply final processing
|
| 698 |
+
self.post_init()
|
| 699 |
+
|
| 700 |
+
@auto_docstring
|
| 701 |
+
def forward(
|
| 702 |
+
self,
|
| 703 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 704 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 705 |
+
output_hidden_states: bool | None = None,
|
| 706 |
+
return_dict: bool | None = None,
|
| 707 |
+
**kwargs,
|
| 708 |
+
) -> tuple | FocalNetMaskedImageModelingOutput:
|
| 709 |
+
r"""
|
| 710 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 711 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 712 |
+
|
| 713 |
+
Examples:
|
| 714 |
+
```python
|
| 715 |
+
>>> from transformers import AutoImageProcessor, FocalNetConfig, FocalNetForMaskedImageModeling
|
| 716 |
+
>>> import torch
|
| 717 |
+
>>> from PIL import Image
|
| 718 |
+
>>> import httpx
|
| 719 |
+
>>> from io import BytesIO
|
| 720 |
+
|
| 721 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 722 |
+
>>> with httpx.stream("GET", url) as response:
|
| 723 |
+
... image = Image.open(BytesIO(response.read()))
|
| 724 |
+
|
| 725 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-base-simmim-window6-192")
|
| 726 |
+
>>> config = FocalNetConfig()
|
| 727 |
+
>>> model = FocalNetForMaskedImageModeling(config)
|
| 728 |
+
|
| 729 |
+
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
|
| 730 |
+
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
|
| 731 |
+
>>> # create random boolean mask of shape (batch_size, num_patches)
|
| 732 |
+
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
|
| 733 |
+
|
| 734 |
+
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 735 |
+
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.logits
|
| 736 |
+
>>> list(reconstructed_pixel_values.shape)
|
| 737 |
+
[1, 3, 192, 192]
|
| 738 |
+
```"""
|
| 739 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 740 |
+
|
| 741 |
+
outputs = self.focalnet(
|
| 742 |
+
pixel_values,
|
| 743 |
+
bool_masked_pos=bool_masked_pos,
|
| 744 |
+
output_hidden_states=output_hidden_states,
|
| 745 |
+
return_dict=return_dict,
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
sequence_output = outputs[0]
|
| 749 |
+
# Reshape to (batch_size, num_channels, height, width)
|
| 750 |
+
sequence_output = sequence_output.transpose(1, 2)
|
| 751 |
+
batch_size, num_channels, sequence_length = sequence_output.shape
|
| 752 |
+
height = width = math.floor(sequence_length**0.5)
|
| 753 |
+
sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
|
| 754 |
+
|
| 755 |
+
# Reconstruct pixel values
|
| 756 |
+
reconstructed_pixel_values = self.decoder(sequence_output)
|
| 757 |
+
|
| 758 |
+
masked_im_loss = None
|
| 759 |
+
if bool_masked_pos is not None:
|
| 760 |
+
size = self.config.image_size // self.config.patch_size
|
| 761 |
+
bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
|
| 762 |
+
mask = (
|
| 763 |
+
bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
|
| 764 |
+
.repeat_interleave(self.config.patch_size, 2)
|
| 765 |
+
.unsqueeze(1)
|
| 766 |
+
.contiguous()
|
| 767 |
+
)
|
| 768 |
+
reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
|
| 769 |
+
masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
|
| 770 |
+
|
| 771 |
+
if not return_dict:
|
| 772 |
+
output = (reconstructed_pixel_values,) + outputs[2:]
|
| 773 |
+
return ((masked_im_loss,) + output) if masked_im_loss is not None else output
|
| 774 |
+
|
| 775 |
+
return FocalNetMaskedImageModelingOutput(
|
| 776 |
+
loss=masked_im_loss,
|
| 777 |
+
reconstruction=reconstructed_pixel_values,
|
| 778 |
+
hidden_states=outputs.hidden_states,
|
| 779 |
+
reshaped_hidden_states=outputs.reshaped_hidden_states,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
@auto_docstring(
|
| 784 |
+
custom_intro="""
|
| 785 |
+
FocalNet Model with an image classification head on top (a linear layer on top of the pooled output) e.g. for
|
| 786 |
+
ImageNet.
|
| 787 |
+
"""
|
| 788 |
+
)
|
| 789 |
+
class FocalNetForImageClassification(FocalNetPreTrainedModel):
|
| 790 |
+
# Copied from transformers.models.swin.modeling_swin.SwinForImageClassification.__init__ with Swin->FocalNet, swin->focalnet
|
| 791 |
+
def __init__(self, config):
|
| 792 |
+
super().__init__(config)
|
| 793 |
+
|
| 794 |
+
self.num_labels = config.num_labels
|
| 795 |
+
self.focalnet = FocalNetModel(config)
|
| 796 |
+
|
| 797 |
+
# Classifier head
|
| 798 |
+
self.classifier = (
|
| 799 |
+
nn.Linear(self.focalnet.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
# Initialize weights and apply final processing
|
| 803 |
+
self.post_init()
|
| 804 |
+
|
| 805 |
+
@auto_docstring
|
| 806 |
+
def forward(
|
| 807 |
+
self,
|
| 808 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 809 |
+
labels: torch.LongTensor | None = None,
|
| 810 |
+
output_hidden_states: bool | None = None,
|
| 811 |
+
return_dict: bool | None = None,
|
| 812 |
+
**kwargs,
|
| 813 |
+
) -> tuple | FocalNetImageClassifierOutput:
|
| 814 |
+
r"""
|
| 815 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 816 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 817 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 818 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 819 |
+
"""
|
| 820 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 821 |
+
|
| 822 |
+
outputs = self.focalnet(
|
| 823 |
+
pixel_values,
|
| 824 |
+
output_hidden_states=output_hidden_states,
|
| 825 |
+
return_dict=return_dict,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
pooled_output = outputs[1]
|
| 829 |
+
|
| 830 |
+
logits = self.classifier(pooled_output)
|
| 831 |
+
|
| 832 |
+
loss = None
|
| 833 |
+
if labels is not None:
|
| 834 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 835 |
+
|
| 836 |
+
if not return_dict:
|
| 837 |
+
output = (logits,) + outputs[2:]
|
| 838 |
+
return ((loss,) + output) if loss is not None else output
|
| 839 |
+
|
| 840 |
+
return FocalNetImageClassifierOutput(
|
| 841 |
+
loss=loss,
|
| 842 |
+
logits=logits,
|
| 843 |
+
hidden_states=outputs.hidden_states,
|
| 844 |
+
reshaped_hidden_states=outputs.reshaped_hidden_states,
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
@auto_docstring(
|
| 849 |
+
custom_intro="""
|
| 850 |
+
FocalNet backbone, to be used with frameworks like X-Decoder.
|
| 851 |
+
"""
|
| 852 |
+
)
|
| 853 |
+
class FocalNetBackbone(BackboneMixin, FocalNetPreTrainedModel):
|
| 854 |
+
has_attentions = False
|
| 855 |
+
|
| 856 |
+
def __init__(self, config: FocalNetConfig):
|
| 857 |
+
super().__init__(config)
|
| 858 |
+
|
| 859 |
+
self.num_features = [config.embed_dim] + config.hidden_sizes
|
| 860 |
+
self.focalnet = FocalNetModel(config)
|
| 861 |
+
|
| 862 |
+
# initialize weights and apply final processing
|
| 863 |
+
self.post_init()
|
| 864 |
+
|
| 865 |
+
@can_return_tuple
|
| 866 |
+
@filter_output_hidden_states
|
| 867 |
+
@auto_docstring
|
| 868 |
+
def forward(
|
| 869 |
+
self,
|
| 870 |
+
pixel_values: torch.Tensor,
|
| 871 |
+
output_hidden_states: bool | None = None,
|
| 872 |
+
return_dict: bool | None = None,
|
| 873 |
+
**kwargs,
|
| 874 |
+
) -> BackboneOutput:
|
| 875 |
+
r"""
|
| 876 |
+
Examples:
|
| 877 |
+
|
| 878 |
+
```python
|
| 879 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 880 |
+
>>> import torch
|
| 881 |
+
>>> from PIL import Image
|
| 882 |
+
>>> import httpx
|
| 883 |
+
>>> from io import BytesIO
|
| 884 |
+
|
| 885 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 886 |
+
>>> with httpx.stream("GET", url) as response:
|
| 887 |
+
... image = Image.open(BytesIO(response.read()))
|
| 888 |
+
|
| 889 |
+
>>> processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny-lrf")
|
| 890 |
+
>>> model = AutoBackbone.from_pretrained("microsoft/focalnet-tiny-lrf")
|
| 891 |
+
|
| 892 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 893 |
+
>>> outputs = model(**inputs)
|
| 894 |
+
```"""
|
| 895 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 896 |
+
output_hidden_states = (
|
| 897 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
outputs = self.focalnet(pixel_values, output_hidden_states=True, return_dict=True)
|
| 901 |
+
|
| 902 |
+
hidden_states = outputs.reshaped_hidden_states
|
| 903 |
+
|
| 904 |
+
feature_maps = ()
|
| 905 |
+
for idx, stage in enumerate(self.stage_names):
|
| 906 |
+
if stage in self.out_features:
|
| 907 |
+
feature_maps += (hidden_states[idx],)
|
| 908 |
+
|
| 909 |
+
if not return_dict:
|
| 910 |
+
output = (feature_maps,)
|
| 911 |
+
if output_hidden_states:
|
| 912 |
+
output += (outputs.hidden_states,)
|
| 913 |
+
return output
|
| 914 |
+
|
| 915 |
+
return BackboneOutput(
|
| 916 |
+
feature_maps=feature_maps,
|
| 917 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 918 |
+
attentions=None,
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
__all__ = [
|
| 923 |
+
"FocalNetForImageClassification",
|
| 924 |
+
"FocalNetForMaskedImageModeling",
|
| 925 |
+
"FocalNetBackbone",
|
| 926 |
+
"FocalNetModel",
|
| 927 |
+
"FocalNetPreTrainedModel",
|
| 928 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_superglue import *
|
| 22 |
+
from .image_processing_pil_superglue import *
|
| 23 |
+
from .image_processing_superglue import *
|
| 24 |
+
from .modeling_superglue import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/configuration_superglue.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from huggingface_hub.dataclasses import strict
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PreTrainedConfig
|
| 18 |
+
from ...utils import auto_docstring
|
| 19 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="magic-leap-community/superglue_indoor")
|
| 23 |
+
@strict
|
| 24 |
+
class SuperGlueConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
keypoint_detector_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SuperPointConfig`):
|
| 27 |
+
The config object or dictionary of the keypoint detector.
|
| 28 |
+
keypoint_encoder_sizes (`list[int]`, *optional*, defaults to `[32, 64, 128, 256]`):
|
| 29 |
+
The sizes of the keypoint encoder layers.
|
| 30 |
+
gnn_layers_types (`list[str]`, *optional*, defaults to `['self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross']`):
|
| 31 |
+
The types of the GNN layers. Must be either 'self' or 'cross'.
|
| 32 |
+
sinkhorn_iterations (`int`, *optional*, defaults to 100):
|
| 33 |
+
The number of Sinkhorn iterations.
|
| 34 |
+
matching_threshold (`float`, *optional*, defaults to 0.0):
|
| 35 |
+
The matching threshold.
|
| 36 |
+
|
| 37 |
+
Examples:
|
| 38 |
+
```python
|
| 39 |
+
>>> from transformers import SuperGlueConfig, SuperGlueModel
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a SuperGlue superglue style configuration
|
| 42 |
+
>>> configuration = SuperGlueConfig()
|
| 43 |
+
|
| 44 |
+
>>> # Initializing a model from the superglue style configuration
|
| 45 |
+
>>> model = SuperGlueModel(configuration)
|
| 46 |
+
|
| 47 |
+
>>> # Accessing the model configuration
|
| 48 |
+
>>> configuration = model.config
|
| 49 |
+
```
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
model_type = "superglue"
|
| 53 |
+
sub_configs = {"keypoint_detector_config": AutoConfig}
|
| 54 |
+
|
| 55 |
+
keypoint_detector_config: dict | PreTrainedConfig | None = None
|
| 56 |
+
hidden_size: int = 256
|
| 57 |
+
keypoint_encoder_sizes: list[int] | None = None
|
| 58 |
+
gnn_layers_types: list[str] | None = None
|
| 59 |
+
num_attention_heads: int = 4
|
| 60 |
+
sinkhorn_iterations: int = 100
|
| 61 |
+
matching_threshold: float = 0.0
|
| 62 |
+
initializer_range: float = 0.02
|
| 63 |
+
is_decoder: bool = False
|
| 64 |
+
attention_probs_dropout_prob: int | float = 0.0
|
| 65 |
+
|
| 66 |
+
def __post_init__(self, **kwargs):
|
| 67 |
+
self.gnn_layers_types = self.gnn_layers_types if self.gnn_layers_types is not None else ["self", "cross"] * 9
|
| 68 |
+
self.keypoint_encoder_sizes = (
|
| 69 |
+
self.keypoint_encoder_sizes if self.keypoint_encoder_sizes is not None else [32, 64, 128, 256]
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if isinstance(self.keypoint_detector_config, dict):
|
| 73 |
+
self.keypoint_detector_config["model_type"] = self.keypoint_detector_config.get("model_type", "superpoint")
|
| 74 |
+
self.keypoint_detector_config = CONFIG_MAPPING[self.keypoint_detector_config["model_type"]](
|
| 75 |
+
**self.keypoint_detector_config
|
| 76 |
+
)
|
| 77 |
+
elif self.keypoint_detector_config is None:
|
| 78 |
+
self.keypoint_detector_config = CONFIG_MAPPING["superpoint"]()
|
| 79 |
+
|
| 80 |
+
super().__post_init__(**kwargs)
|
| 81 |
+
|
| 82 |
+
def validate_architecture(self):
|
| 83 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 84 |
+
# Check whether all gnn_layers_types are either 'self' or 'cross'
|
| 85 |
+
if not all(layer_type in ["self", "cross"] for layer_type in self.gnn_layers_types):
|
| 86 |
+
raise ValueError("All gnn_layers_types must be either 'self' or 'cross'")
|
| 87 |
+
|
| 88 |
+
if self.hidden_size % self.num_attention_heads != 0:
|
| 89 |
+
raise ValueError("hidden_size % num_attention_heads is different from zero")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
__all__ = ["SuperGlueConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/image_processing_pil_superglue.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Image processor class for SuperGlue."""
|
| 15 |
+
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
from PIL import Image, ImageDraw
|
| 20 |
+
|
| 21 |
+
from ...image_processing_backends import PilBackend
|
| 22 |
+
from ...image_processing_utils import BatchFeature
|
| 23 |
+
from ...image_utils import (
|
| 24 |
+
ImageInput,
|
| 25 |
+
ImageType,
|
| 26 |
+
PILImageResampling,
|
| 27 |
+
SizeDict,
|
| 28 |
+
get_image_type,
|
| 29 |
+
is_pil_image,
|
| 30 |
+
is_valid_image,
|
| 31 |
+
to_numpy_array,
|
| 32 |
+
)
|
| 33 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 34 |
+
from ...utils import TensorType, auto_docstring
|
| 35 |
+
from ...utils.import_utils import requires
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if TYPE_CHECKING:
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
from .modeling_superglue import SuperGlueKeypointMatchingOutput
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_grayscale(image: np.ndarray):
|
| 45 |
+
if image.shape[0] == 1:
|
| 46 |
+
return True
|
| 47 |
+
return np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...])
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def convert_to_grayscale(image: ImageInput) -> ImageInput:
|
| 51 |
+
"""
|
| 52 |
+
Converts an image to grayscale format using the NTSC formula. Only support numpy and PIL Image.
|
| 53 |
+
|
| 54 |
+
This function is supposed to return a 1-channel image, but it returns a 3-channel image with the same value in each
|
| 55 |
+
channel, because of an issue that is discussed in :
|
| 56 |
+
https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
image (Image):
|
| 60 |
+
The image to convert.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
if isinstance(image, np.ndarray):
|
| 64 |
+
if is_grayscale(image):
|
| 65 |
+
return image
|
| 66 |
+
|
| 67 |
+
gray_image = image[0, ...] * 0.2989 + image[1, ...] * 0.5870 + image[2, ...] * 0.1140
|
| 68 |
+
gray_image = np.stack([gray_image] * 3, axis=0)
|
| 69 |
+
return gray_image
|
| 70 |
+
|
| 71 |
+
if not isinstance(image, Image.Image):
|
| 72 |
+
return image
|
| 73 |
+
|
| 74 |
+
image = image.convert("L")
|
| 75 |
+
return image
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Adapted from transformers.models.superglue.image_processing_superglue.validate_and_format_image_pairs
|
| 79 |
+
def validate_and_format_image_pairs(images: ImageInput):
|
| 80 |
+
error_message = (
|
| 81 |
+
"Input images must be a one of the following :",
|
| 82 |
+
" - A pair of PIL images.",
|
| 83 |
+
" - A pair of 3D arrays.",
|
| 84 |
+
" - A list of pairs of PIL images.",
|
| 85 |
+
" - A list of pairs of 3D arrays.",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def _is_valid_image(image):
|
| 89 |
+
"""images is a PIL Image or a 3D array."""
|
| 90 |
+
return is_pil_image(image) or (
|
| 91 |
+
is_valid_image(image) and get_image_type(image) != ImageType.PIL and len(image.shape) == 3
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
if isinstance(images, list):
|
| 95 |
+
if len(images) == 2 and all((_is_valid_image(image)) for image in images):
|
| 96 |
+
return images
|
| 97 |
+
if all(
|
| 98 |
+
isinstance(image_pair, list)
|
| 99 |
+
and len(image_pair) == 2
|
| 100 |
+
and all(_is_valid_image(image) for image in image_pair)
|
| 101 |
+
for image_pair in images
|
| 102 |
+
):
|
| 103 |
+
return [image for image_pair in images for image in image_pair]
|
| 104 |
+
raise ValueError(error_message)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class SuperGlueImageProcessorKwargs(ImagesKwargs, total=False):
|
| 108 |
+
r"""
|
| 109 |
+
do_grayscale (`bool`, *optional*, defaults to `self.do_grayscale`):
|
| 110 |
+
Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
do_grayscale: bool
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@auto_docstring
|
| 117 |
+
class SuperGlueImageProcessorPil(PilBackend):
|
| 118 |
+
valid_kwargs = SuperGlueImageProcessorKwargs
|
| 119 |
+
resample = PILImageResampling.BILINEAR
|
| 120 |
+
size = {"height": 480, "width": 640}
|
| 121 |
+
default_to_square = False
|
| 122 |
+
do_resize = True
|
| 123 |
+
do_rescale = True
|
| 124 |
+
rescale_factor = 1 / 255
|
| 125 |
+
do_normalize = None
|
| 126 |
+
do_grayscale = True
|
| 127 |
+
|
| 128 |
+
def __init__(self, **kwargs: Unpack[SuperGlueImageProcessorKwargs]):
|
| 129 |
+
super().__init__(**kwargs)
|
| 130 |
+
|
| 131 |
+
@auto_docstring
|
| 132 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[SuperGlueImageProcessorKwargs]) -> BatchFeature:
|
| 133 |
+
return super().preprocess(images, **kwargs)
|
| 134 |
+
|
| 135 |
+
def _prepare_images_structure(self, images: ImageInput, **kwargs) -> ImageInput:
|
| 136 |
+
# we need to handle image pairs validation and flattening
|
| 137 |
+
images = self.fetch_images(images)
|
| 138 |
+
return validate_and_format_image_pairs(images)
|
| 139 |
+
|
| 140 |
+
def _preprocess(
|
| 141 |
+
self,
|
| 142 |
+
images: list[np.ndarray],
|
| 143 |
+
do_resize: bool,
|
| 144 |
+
size: SizeDict,
|
| 145 |
+
resample: PILImageResampling | None,
|
| 146 |
+
do_rescale: bool,
|
| 147 |
+
rescale_factor: float,
|
| 148 |
+
return_tensors: str | TensorType | None,
|
| 149 |
+
do_grayscale: bool = True,
|
| 150 |
+
**kwargs,
|
| 151 |
+
) -> BatchFeature:
|
| 152 |
+
all_images = []
|
| 153 |
+
for image in images:
|
| 154 |
+
if do_resize:
|
| 155 |
+
image = self.resize(image=image, size=size, resample=resample)
|
| 156 |
+
|
| 157 |
+
if do_rescale:
|
| 158 |
+
image = self.rescale(image=image, scale=rescale_factor)
|
| 159 |
+
|
| 160 |
+
if do_grayscale:
|
| 161 |
+
image = convert_to_grayscale(image)
|
| 162 |
+
|
| 163 |
+
all_images.append(image)
|
| 164 |
+
|
| 165 |
+
# Convert back the flattened list of images into a list of pairs of images.
|
| 166 |
+
image_pairs = [all_images[i : i + 2] for i in range(0, len(all_images), 2)]
|
| 167 |
+
|
| 168 |
+
data = {"pixel_values": image_pairs}
|
| 169 |
+
|
| 170 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 171 |
+
|
| 172 |
+
@requires(backends=("torch",))
|
| 173 |
+
def post_process_keypoint_matching(
|
| 174 |
+
self,
|
| 175 |
+
outputs: "SuperGlueKeypointMatchingOutput",
|
| 176 |
+
target_sizes: TensorType | list[tuple],
|
| 177 |
+
threshold: float = 0.0,
|
| 178 |
+
) -> list[dict[str, "torch.Tensor"]]:
|
| 179 |
+
"""
|
| 180 |
+
Converts the raw output of [`SuperGlueKeypointMatchingOutput`] into lists of keypoints, scores and descriptors
|
| 181 |
+
with coordinates absolute to the original image sizes.
|
| 182 |
+
Args:
|
| 183 |
+
outputs ([`SuperGlueKeypointMatchingOutput`]):
|
| 184 |
+
Raw outputs of the model.
|
| 185 |
+
target_sizes (`torch.Tensor` or `list[tuple[tuple[int, int]]]`, *optional*):
|
| 186 |
+
Tensor of shape `(batch_size, 2, 2)` or list of tuples of tuples (`tuple[int, int]`) containing the
|
| 187 |
+
target size `(height, width)` of each image in the batch. This must be the original image size (before
|
| 188 |
+
any processing).
|
| 189 |
+
threshold (`float`, *optional*, defaults to `0.0`):
|
| 190 |
+
Threshold to filter out the matches with low scores.
|
| 191 |
+
Returns:
|
| 192 |
+
`list[Dict]`: A list of dictionaries, each dictionary containing the keypoints in the first and second image
|
| 193 |
+
of the pair, the matching scores and the matching indices.
|
| 194 |
+
"""
|
| 195 |
+
import torch
|
| 196 |
+
|
| 197 |
+
if outputs.mask.shape[0] != len(target_sizes):
|
| 198 |
+
raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the mask")
|
| 199 |
+
if not all(len(target_size) == 2 for target_size in target_sizes):
|
| 200 |
+
raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
|
| 201 |
+
|
| 202 |
+
if isinstance(target_sizes, list):
|
| 203 |
+
image_pair_sizes = torch.tensor(target_sizes, device=outputs.mask.device)
|
| 204 |
+
else:
|
| 205 |
+
if target_sizes.shape[1] != 2 or target_sizes.shape[2] != 2:
|
| 206 |
+
raise ValueError(
|
| 207 |
+
"Each element of target_sizes must contain the size (h, w) of each image of the batch"
|
| 208 |
+
)
|
| 209 |
+
image_pair_sizes = target_sizes
|
| 210 |
+
|
| 211 |
+
keypoints = outputs.keypoints.clone()
|
| 212 |
+
keypoints = keypoints * image_pair_sizes.flip(-1).reshape(-1, 2, 1, 2)
|
| 213 |
+
keypoints = keypoints.to(torch.int32)
|
| 214 |
+
|
| 215 |
+
results = []
|
| 216 |
+
for mask_pair, keypoints_pair, matches, scores in zip(
|
| 217 |
+
outputs.mask, keypoints, outputs.matches[:, 0], outputs.matching_scores[:, 0]
|
| 218 |
+
):
|
| 219 |
+
mask0 = mask_pair[0] > 0
|
| 220 |
+
mask1 = mask_pair[1] > 0
|
| 221 |
+
keypoints0 = keypoints_pair[0][mask0]
|
| 222 |
+
keypoints1 = keypoints_pair[1][mask1]
|
| 223 |
+
matches0 = matches[mask0]
|
| 224 |
+
scores0 = scores[mask0]
|
| 225 |
+
|
| 226 |
+
# Filter out matches with low scores, invalid matches, and out-of-bounds indices
|
| 227 |
+
valid_matches = (scores0 > threshold) & (matches0 > -1) & (matches0 < keypoints1.shape[0])
|
| 228 |
+
|
| 229 |
+
matched_keypoints0 = keypoints0[valid_matches]
|
| 230 |
+
matched_keypoints1 = keypoints1[matches0[valid_matches]]
|
| 231 |
+
matching_scores = scores0[valid_matches]
|
| 232 |
+
|
| 233 |
+
results.append(
|
| 234 |
+
{
|
| 235 |
+
"keypoints0": matched_keypoints0,
|
| 236 |
+
"keypoints1": matched_keypoints1,
|
| 237 |
+
"matching_scores": matching_scores,
|
| 238 |
+
}
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
return results
|
| 242 |
+
|
| 243 |
+
def visualize_keypoint_matching(
|
| 244 |
+
self, images: ImageInput, keypoint_matching_output: list[dict[str, "torch.Tensor"]]
|
| 245 |
+
) -> list["Image.Image"]:
|
| 246 |
+
"""
|
| 247 |
+
Plots the image pairs side by side with the detected keypoints as well as the matching between them.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
images (`ImageInput`):
|
| 251 |
+
Image pairs to plot. Same as `SuperGlueImageProcessor.preprocess`. Expects either a list of 2
|
| 252 |
+
images or a list of list of 2 images list with pixel values ranging from 0 to 255.
|
| 253 |
+
keypoint_matching_output (List[Dict[str, torch.Tensor]]]):
|
| 254 |
+
A post processed keypoint matching output
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
`List[PIL.Image.Image]`: A list of PIL images, each containing the image pairs side by side with the detected
|
| 258 |
+
keypoints as well as the matching between them.
|
| 259 |
+
"""
|
| 260 |
+
images = validate_and_format_image_pairs(images)
|
| 261 |
+
images = [to_numpy_array(image) for image in images]
|
| 262 |
+
image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)]
|
| 263 |
+
|
| 264 |
+
results = []
|
| 265 |
+
for image_pair, pair_output in zip(image_pairs, keypoint_matching_output):
|
| 266 |
+
height0, width0 = image_pair[0].shape[:2]
|
| 267 |
+
height1, width1 = image_pair[1].shape[:2]
|
| 268 |
+
plot_image = np.zeros((max(height0, height1), width0 + width1, 3), dtype=np.uint8)
|
| 269 |
+
plot_image[:height0, :width0] = image_pair[0]
|
| 270 |
+
plot_image[:height1, width0:] = image_pair[1]
|
| 271 |
+
|
| 272 |
+
plot_image_pil = Image.fromarray(plot_image)
|
| 273 |
+
draw = ImageDraw.Draw(plot_image_pil)
|
| 274 |
+
|
| 275 |
+
keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1)
|
| 276 |
+
keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1)
|
| 277 |
+
for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip(
|
| 278 |
+
keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"]
|
| 279 |
+
):
|
| 280 |
+
color = self._get_color(matching_score)
|
| 281 |
+
draw.line((keypoint0_x, keypoint0_y, keypoint1_x + width0, keypoint1_y), fill=color, width=3)
|
| 282 |
+
draw.ellipse((keypoint0_x - 2, keypoint0_y - 2, keypoint0_x + 2, keypoint0_y + 2), fill="black")
|
| 283 |
+
draw.ellipse(
|
| 284 |
+
(keypoint1_x + width0 - 2, keypoint1_y - 2, keypoint1_x + width0 + 2, keypoint1_y + 2),
|
| 285 |
+
fill="black",
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
results.append(plot_image_pil)
|
| 289 |
+
return results
|
| 290 |
+
|
| 291 |
+
def _get_color(self, score):
|
| 292 |
+
"""Maps a score to a color."""
|
| 293 |
+
r = int(255 * (1 - score))
|
| 294 |
+
g = int(255 * score)
|
| 295 |
+
b = 0
|
| 296 |
+
return (r, g, b)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
__all__ = ["SuperGlueImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/image_processing_superglue.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Image processor class for SuperGlue."""
|
| 15 |
+
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 21 |
+
from ...image_processing_utils import BatchFeature
|
| 22 |
+
from ...image_transforms import group_images_by_shape, reorder_images
|
| 23 |
+
from ...image_utils import (
|
| 24 |
+
ImageInput,
|
| 25 |
+
ImageType,
|
| 26 |
+
PILImageResampling,
|
| 27 |
+
SizeDict,
|
| 28 |
+
get_image_type,
|
| 29 |
+
is_pil_image,
|
| 30 |
+
is_valid_image,
|
| 31 |
+
to_numpy_array,
|
| 32 |
+
)
|
| 33 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 34 |
+
from ...utils import (
|
| 35 |
+
TensorType,
|
| 36 |
+
auto_docstring,
|
| 37 |
+
is_vision_available,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if TYPE_CHECKING:
|
| 42 |
+
from .modeling_superglue import SuperGlueKeypointMatchingOutput
|
| 43 |
+
|
| 44 |
+
if is_vision_available():
|
| 45 |
+
from PIL import Image, ImageDraw
|
| 46 |
+
|
| 47 |
+
from torchvision.transforms.v2 import functional as tvF
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _is_valid_image(image):
|
| 51 |
+
return is_pil_image(image) or (
|
| 52 |
+
is_valid_image(image) and get_image_type(image) != ImageType.PIL and len(image.shape) == 3
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def validate_and_format_image_pairs(images: ImageInput):
|
| 57 |
+
error_message = (
|
| 58 |
+
"Input images must be a one of the following :",
|
| 59 |
+
" - A pair of PIL images.",
|
| 60 |
+
" - A pair of 3D arrays.",
|
| 61 |
+
" - A list of pairs of PIL images.",
|
| 62 |
+
" - A list of pairs of 3D arrays.",
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def _is_valid_image(image):
|
| 66 |
+
"""images is a PIL Image or a 3D array."""
|
| 67 |
+
return is_pil_image(image) or (
|
| 68 |
+
is_valid_image(image) and get_image_type(image) != ImageType.PIL and len(image.shape) == 3
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
if isinstance(images, list):
|
| 72 |
+
if len(images) == 2 and all((_is_valid_image(image)) for image in images):
|
| 73 |
+
return images
|
| 74 |
+
if all(
|
| 75 |
+
isinstance(image_pair, list)
|
| 76 |
+
and len(image_pair) == 2
|
| 77 |
+
and all(_is_valid_image(image) for image in image_pair)
|
| 78 |
+
for image_pair in images
|
| 79 |
+
):
|
| 80 |
+
return [image for image_pair in images for image in image_pair]
|
| 81 |
+
raise ValueError(error_message)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def is_grayscale(
|
| 85 |
+
image: "torch.Tensor",
|
| 86 |
+
):
|
| 87 |
+
"""Checks if an image is grayscale (all RGB channels are identical)."""
|
| 88 |
+
if image.ndim < 3 or image.shape[0 if image.ndim == 3 else 1] == 1:
|
| 89 |
+
return True
|
| 90 |
+
return torch.all(image[..., 0, :, :] == image[..., 1, :, :]) and torch.all(
|
| 91 |
+
image[..., 1, :, :] == image[..., 2, :, :]
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def convert_to_grayscale(
|
| 96 |
+
image: "torch.Tensor",
|
| 97 |
+
) -> "torch.Tensor":
|
| 98 |
+
"""
|
| 99 |
+
Converts an image to grayscale format using the NTSC formula. Only support torch.Tensor.
|
| 100 |
+
|
| 101 |
+
This function is supposed to return a 1-channel image, but it returns a 3-channel image with the same value in each
|
| 102 |
+
channel, because of an issue that is discussed in :
|
| 103 |
+
https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
image (torch.Tensor):
|
| 107 |
+
The image to convert.
|
| 108 |
+
"""
|
| 109 |
+
if is_grayscale(image):
|
| 110 |
+
return image
|
| 111 |
+
return tvF.rgb_to_grayscale(image, num_output_channels=3)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class SuperGlueImageProcessorKwargs(ImagesKwargs, total=False):
|
| 115 |
+
r"""
|
| 116 |
+
do_grayscale (`bool`, *optional*, defaults to `self.do_grayscale`):
|
| 117 |
+
Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
do_grayscale: bool
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@auto_docstring
|
| 124 |
+
class SuperGlueImageProcessor(TorchvisionBackend):
|
| 125 |
+
valid_kwargs = SuperGlueImageProcessorKwargs
|
| 126 |
+
resample = PILImageResampling.BILINEAR
|
| 127 |
+
size = {"height": 480, "width": 640}
|
| 128 |
+
default_to_square = False
|
| 129 |
+
do_resize = True
|
| 130 |
+
do_rescale = True
|
| 131 |
+
rescale_factor = 1 / 255
|
| 132 |
+
do_normalize = None
|
| 133 |
+
do_grayscale = True
|
| 134 |
+
|
| 135 |
+
def __init__(self, **kwargs: Unpack[SuperGlueImageProcessorKwargs]):
|
| 136 |
+
super().__init__(**kwargs)
|
| 137 |
+
|
| 138 |
+
@auto_docstring
|
| 139 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[SuperGlueImageProcessorKwargs]) -> BatchFeature:
|
| 140 |
+
return super().preprocess(images, **kwargs)
|
| 141 |
+
|
| 142 |
+
def _prepare_images_structure(
|
| 143 |
+
self,
|
| 144 |
+
images: ImageInput,
|
| 145 |
+
**kwargs,
|
| 146 |
+
) -> ImageInput:
|
| 147 |
+
# we need to handle image pairs validation and flattening
|
| 148 |
+
images = self.fetch_images(images)
|
| 149 |
+
return validate_and_format_image_pairs(images)
|
| 150 |
+
|
| 151 |
+
def _preprocess(
|
| 152 |
+
self,
|
| 153 |
+
images: list["torch.Tensor"],
|
| 154 |
+
do_resize: bool,
|
| 155 |
+
size: SizeDict,
|
| 156 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 157 |
+
do_rescale: bool,
|
| 158 |
+
rescale_factor: float,
|
| 159 |
+
disable_grouping: bool | None,
|
| 160 |
+
return_tensors: str | TensorType | None,
|
| 161 |
+
do_grayscale: bool = True,
|
| 162 |
+
**kwargs,
|
| 163 |
+
) -> BatchFeature:
|
| 164 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 165 |
+
processed_images_grouped = {}
|
| 166 |
+
|
| 167 |
+
for shape, stacked_images in grouped_images.items():
|
| 168 |
+
if do_resize:
|
| 169 |
+
stacked_images = self.resize(stacked_images, size=size, resample=resample)
|
| 170 |
+
processed_images_grouped[shape] = stacked_images
|
| 171 |
+
resized_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 172 |
+
|
| 173 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 174 |
+
processed_images_grouped = {}
|
| 175 |
+
for shape, stacked_images in grouped_images.items():
|
| 176 |
+
if do_rescale:
|
| 177 |
+
stacked_images = self.rescale(stacked_images, rescale_factor)
|
| 178 |
+
if do_grayscale:
|
| 179 |
+
stacked_images = convert_to_grayscale(stacked_images)
|
| 180 |
+
processed_images_grouped[shape] = stacked_images
|
| 181 |
+
|
| 182 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 183 |
+
|
| 184 |
+
# Convert back to pairs format
|
| 185 |
+
image_pairs = [processed_images[i : i + 2] for i in range(0, len(processed_images), 2)]
|
| 186 |
+
|
| 187 |
+
# Stack each pair into a single tensor to match slow processor format
|
| 188 |
+
stacked_pairs = [torch.stack(pair, dim=0) for pair in image_pairs]
|
| 189 |
+
|
| 190 |
+
# Return in same format as slow processor
|
| 191 |
+
|
| 192 |
+
return BatchFeature(data={"pixel_values": stacked_pairs}, tensor_type=return_tensors)
|
| 193 |
+
|
| 194 |
+
def post_process_keypoint_matching(
|
| 195 |
+
self,
|
| 196 |
+
outputs: "SuperGlueKeypointMatchingOutput",
|
| 197 |
+
target_sizes: TensorType | list[tuple],
|
| 198 |
+
threshold: float = 0.0,
|
| 199 |
+
) -> list[dict[str, torch.Tensor]]:
|
| 200 |
+
"""
|
| 201 |
+
Converts the raw output of [`SuperGlueKeypointMatchingOutput`] into lists of keypoints, scores and descriptors
|
| 202 |
+
with coordinates absolute to the original image sizes.
|
| 203 |
+
Args:
|
| 204 |
+
outputs ([`SuperGlueKeypointMatchingOutput`]):
|
| 205 |
+
Raw outputs of the model.
|
| 206 |
+
target_sizes (`torch.Tensor` or `list[tuple[tuple[int, int]]]`, *optional*):
|
| 207 |
+
Tensor of shape `(batch_size, 2, 2)` or list of tuples of tuples (`tuple[int, int]`) containing the
|
| 208 |
+
target size `(height, width)` of each image in the batch. This must be the original image size (before
|
| 209 |
+
any processing).
|
| 210 |
+
threshold (`float`, *optional*, defaults to `0.0`):
|
| 211 |
+
Threshold to filter out the matches with low scores.
|
| 212 |
+
Returns:
|
| 213 |
+
`list[Dict]`: A list of dictionaries, each dictionary containing the keypoints in the first and second image
|
| 214 |
+
of the pair, the matching scores and the matching indices.
|
| 215 |
+
"""
|
| 216 |
+
if outputs.mask.shape[0] != len(target_sizes):
|
| 217 |
+
raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the mask")
|
| 218 |
+
if not all(len(target_size) == 2 for target_size in target_sizes):
|
| 219 |
+
raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
|
| 220 |
+
|
| 221 |
+
if isinstance(target_sizes, list):
|
| 222 |
+
image_pair_sizes = torch.tensor(target_sizes, device=outputs.mask.device)
|
| 223 |
+
else:
|
| 224 |
+
if target_sizes.shape[1] != 2 or target_sizes.shape[2] != 2:
|
| 225 |
+
raise ValueError(
|
| 226 |
+
"Each element of target_sizes must contain the size (h, w) of each image of the batch"
|
| 227 |
+
)
|
| 228 |
+
image_pair_sizes = target_sizes
|
| 229 |
+
|
| 230 |
+
keypoints = outputs.keypoints.clone()
|
| 231 |
+
keypoints = keypoints * image_pair_sizes.flip(-1).reshape(-1, 2, 1, 2)
|
| 232 |
+
keypoints = keypoints.to(torch.int32)
|
| 233 |
+
|
| 234 |
+
results = []
|
| 235 |
+
for mask_pair, keypoints_pair, matches, scores in zip(
|
| 236 |
+
outputs.mask, keypoints, outputs.matches[:, 0], outputs.matching_scores[:, 0]
|
| 237 |
+
):
|
| 238 |
+
mask0 = mask_pair[0] > 0
|
| 239 |
+
mask1 = mask_pair[1] > 0
|
| 240 |
+
keypoints0 = keypoints_pair[0][mask0]
|
| 241 |
+
keypoints1 = keypoints_pair[1][mask1]
|
| 242 |
+
matches0 = matches[mask0]
|
| 243 |
+
scores0 = scores[mask0]
|
| 244 |
+
|
| 245 |
+
# Filter out matches with low scores, invalid matches, and out-of-bounds indices
|
| 246 |
+
valid_matches = (scores0 > threshold) & (matches0 > -1) & (matches0 < keypoints1.shape[0])
|
| 247 |
+
|
| 248 |
+
matched_keypoints0 = keypoints0[valid_matches]
|
| 249 |
+
matched_keypoints1 = keypoints1[matches0[valid_matches]]
|
| 250 |
+
matching_scores = scores0[valid_matches]
|
| 251 |
+
|
| 252 |
+
results.append(
|
| 253 |
+
{
|
| 254 |
+
"keypoints0": matched_keypoints0,
|
| 255 |
+
"keypoints1": matched_keypoints1,
|
| 256 |
+
"matching_scores": matching_scores,
|
| 257 |
+
}
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
return results
|
| 261 |
+
|
| 262 |
+
def visualize_keypoint_matching(
|
| 263 |
+
self,
|
| 264 |
+
images,
|
| 265 |
+
keypoint_matching_output: list[dict[str, torch.Tensor]],
|
| 266 |
+
) -> list["Image.Image"]:
|
| 267 |
+
"""
|
| 268 |
+
Plots the image pairs side by side with the detected keypoints as well as the matching between them.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
images:
|
| 272 |
+
Image pairs to plot. Same as `EfficientLoFTRImageProcessor.preprocess`. Expects either a list of 2
|
| 273 |
+
images or a list of list of 2 images list with pixel values ranging from 0 to 255.
|
| 274 |
+
keypoint_matching_output (List[Dict[str, torch.Tensor]]]):
|
| 275 |
+
A post processed keypoint matching output
|
| 276 |
+
|
| 277 |
+
Returns:
|
| 278 |
+
`List[PIL.Image.Image]`: A list of PIL images, each containing the image pairs side by side with the detected
|
| 279 |
+
keypoints as well as the matching between them.
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
images = validate_and_format_image_pairs(images)
|
| 283 |
+
images = [to_numpy_array(image) for image in images]
|
| 284 |
+
image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)]
|
| 285 |
+
|
| 286 |
+
results = []
|
| 287 |
+
for image_pair, pair_output in zip(image_pairs, keypoint_matching_output):
|
| 288 |
+
height0, width0 = image_pair[0].shape[:2]
|
| 289 |
+
height1, width1 = image_pair[1].shape[:2]
|
| 290 |
+
plot_image = torch.zeros((max(height0, height1), width0 + width1, 3), dtype=torch.uint8)
|
| 291 |
+
plot_image[:height0, :width0] = torch.from_numpy(image_pair[0])
|
| 292 |
+
plot_image[:height1, width0:] = torch.from_numpy(image_pair[1])
|
| 293 |
+
|
| 294 |
+
plot_image_pil = Image.fromarray(plot_image.numpy())
|
| 295 |
+
draw = ImageDraw.Draw(plot_image_pil)
|
| 296 |
+
|
| 297 |
+
keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1)
|
| 298 |
+
keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1)
|
| 299 |
+
for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip(
|
| 300 |
+
keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"]
|
| 301 |
+
):
|
| 302 |
+
color = self._get_color(matching_score)
|
| 303 |
+
draw.line(
|
| 304 |
+
(keypoint0_x, keypoint0_y, keypoint1_x + width0, keypoint1_y),
|
| 305 |
+
fill=color,
|
| 306 |
+
width=3,
|
| 307 |
+
)
|
| 308 |
+
draw.ellipse((keypoint0_x - 2, keypoint0_y - 2, keypoint0_x + 2, keypoint0_y + 2), fill="black")
|
| 309 |
+
draw.ellipse(
|
| 310 |
+
(keypoint1_x + width0 - 2, keypoint1_y - 2, keypoint1_x + width0 + 2, keypoint1_y + 2),
|
| 311 |
+
fill="black",
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
results.append(plot_image_pil)
|
| 315 |
+
return results
|
| 316 |
+
|
| 317 |
+
def _get_color(self, score):
|
| 318 |
+
"""Maps a score to a color."""
|
| 319 |
+
r = int(255 * (1 - score))
|
| 320 |
+
g = int(255 * score)
|
| 321 |
+
b = 0
|
| 322 |
+
return r, g, b
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
__all__ = ["SuperGlueImageProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/superglue/modeling_superglue.py
ADDED
|
@@ -0,0 +1,758 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch SuperGlue model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
|
| 22 |
+
from transformers import PreTrainedModel
|
| 23 |
+
from transformers.models.superglue.configuration_superglue import SuperGlueConfig
|
| 24 |
+
|
| 25 |
+
from ... import initialization as init
|
| 26 |
+
from ...masking_utils import create_bidirectional_mask
|
| 27 |
+
from ...utils import ModelOutput, auto_docstring, logging
|
| 28 |
+
from ..auto import AutoModelForKeypointDetection
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def concat_pairs(tensor_tuple0: tuple[torch.Tensor], tensor_tuple1: tuple[torch.Tensor]) -> tuple[torch.Tensor]:
|
| 35 |
+
"""
|
| 36 |
+
Concatenate two tuples of tensors pairwise
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
tensor_tuple0 (`tuple[torch.Tensor]`):
|
| 40 |
+
Tuple of tensors.
|
| 41 |
+
tensor_tuple1 (`tuple[torch.Tensor]`):
|
| 42 |
+
Tuple of tensors.
|
| 43 |
+
|
| 44 |
+
Returns:
|
| 45 |
+
(`tuple[torch.Tensor]`): Tuple of concatenated tensors.
|
| 46 |
+
"""
|
| 47 |
+
return tuple(torch.cat([tensor0, tensor1]) for tensor0, tensor1 in zip(tensor_tuple0, tensor_tuple1))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def normalize_keypoints(keypoints: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 51 |
+
"""
|
| 52 |
+
Normalize keypoints locations based on image image_shape
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
keypoints (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`):
|
| 56 |
+
Keypoints locations in (x, y) format.
|
| 57 |
+
height (`int`):
|
| 58 |
+
Image height.
|
| 59 |
+
width (`int`):
|
| 60 |
+
Image width.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
Normalized keypoints locations of shape (`torch.Tensor` of shape `(batch_size, num_keypoints, 2)`).
|
| 64 |
+
"""
|
| 65 |
+
size = torch.tensor([width, height], device=keypoints.device, dtype=keypoints.dtype)[None]
|
| 66 |
+
center = size / 2
|
| 67 |
+
scaling = size.max(1, keepdim=True).values * 0.7
|
| 68 |
+
return (keypoints - center[:, None, :]) / scaling[:, None, :]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def log_sinkhorn_iterations(
|
| 72 |
+
log_cost_matrix: torch.Tensor,
|
| 73 |
+
log_source_distribution: torch.Tensor,
|
| 74 |
+
log_target_distribution: torch.Tensor,
|
| 75 |
+
num_iterations: int,
|
| 76 |
+
) -> torch.Tensor:
|
| 77 |
+
"""
|
| 78 |
+
Perform Sinkhorn Normalization in Log-space for stability
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
log_cost_matrix (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`):
|
| 82 |
+
Logarithm of the cost matrix.
|
| 83 |
+
log_source_distribution (`torch.Tensor` of shape `(batch_size, num_rows)`):
|
| 84 |
+
Logarithm of the source distribution.
|
| 85 |
+
log_target_distribution (`torch.Tensor` of shape `(batch_size, num_columns)`):
|
| 86 |
+
Logarithm of the target distribution.
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
log_cost_matrix (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`): Logarithm of the optimal
|
| 90 |
+
transport matrix.
|
| 91 |
+
"""
|
| 92 |
+
log_u_scaling = torch.zeros_like(log_source_distribution)
|
| 93 |
+
log_v_scaling = torch.zeros_like(log_target_distribution)
|
| 94 |
+
for _ in range(num_iterations):
|
| 95 |
+
log_u_scaling = log_source_distribution - torch.logsumexp(log_cost_matrix + log_v_scaling.unsqueeze(1), dim=2)
|
| 96 |
+
log_v_scaling = log_target_distribution - torch.logsumexp(log_cost_matrix + log_u_scaling.unsqueeze(2), dim=1)
|
| 97 |
+
return log_cost_matrix + log_u_scaling.unsqueeze(2) + log_v_scaling.unsqueeze(1)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def log_optimal_transport(scores: torch.Tensor, reg_param: torch.Tensor, iterations: int) -> torch.Tensor:
|
| 101 |
+
"""
|
| 102 |
+
Perform Differentiable Optimal Transport in Log-space for stability
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
scores: (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`):
|
| 106 |
+
Cost matrix.
|
| 107 |
+
reg_param: (`torch.Tensor` of shape `(batch_size, 1, 1)`):
|
| 108 |
+
Regularization parameter.
|
| 109 |
+
iterations: (`int`):
|
| 110 |
+
Number of Sinkhorn iterations.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
log_optimal_transport_matrix: (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`): Logarithm of the
|
| 114 |
+
optimal transport matrix.
|
| 115 |
+
"""
|
| 116 |
+
batch_size, num_rows, num_columns = scores.shape
|
| 117 |
+
one_tensor = scores.new_tensor(1)
|
| 118 |
+
num_rows_tensor, num_columns_tensor = (num_rows * one_tensor).to(scores), (num_columns * one_tensor).to(scores)
|
| 119 |
+
|
| 120 |
+
source_reg_param = reg_param.expand(batch_size, num_rows, 1)
|
| 121 |
+
target_reg_param = reg_param.expand(batch_size, 1, num_columns)
|
| 122 |
+
reg_param = reg_param.expand(batch_size, 1, 1)
|
| 123 |
+
|
| 124 |
+
couplings = torch.cat([torch.cat([scores, source_reg_param], -1), torch.cat([target_reg_param, reg_param], -1)], 1)
|
| 125 |
+
|
| 126 |
+
log_normalization = -(num_rows_tensor + num_columns_tensor).log()
|
| 127 |
+
log_source_distribution = torch.cat(
|
| 128 |
+
[log_normalization.expand(num_rows), num_columns_tensor.log()[None] + log_normalization]
|
| 129 |
+
)
|
| 130 |
+
log_target_distribution = torch.cat(
|
| 131 |
+
[log_normalization.expand(num_columns), num_rows_tensor.log()[None] + log_normalization]
|
| 132 |
+
)
|
| 133 |
+
log_source_distribution, log_target_distribution = (
|
| 134 |
+
log_source_distribution[None].expand(batch_size, -1),
|
| 135 |
+
log_target_distribution[None].expand(batch_size, -1),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
log_optimal_transport_matrix = log_sinkhorn_iterations(
|
| 139 |
+
couplings, log_source_distribution, log_target_distribution, num_iterations=iterations
|
| 140 |
+
)
|
| 141 |
+
log_optimal_transport_matrix = log_optimal_transport_matrix - log_normalization # multiply probabilities by M+N
|
| 142 |
+
return log_optimal_transport_matrix
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def arange_like(x, dim: int) -> torch.Tensor:
|
| 146 |
+
return x.new_ones(x.shape[dim]).cumsum(0) - 1
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@auto_docstring(
|
| 150 |
+
custom_intro="""
|
| 151 |
+
Base class for outputs of SuperGlue keypoint matching models. Due to the nature of keypoint detection and matching, the number
|
| 152 |
+
of keypoints is not fixed and can vary from image to image, which makes batching non-trivial. In the batch of
|
| 153 |
+
images, the maximum number of matches is set as the dimension of the matches and matching scores. The mask tensor is
|
| 154 |
+
used to indicate which values in the keypoints, matches and matching_scores tensors are keypoint matching
|
| 155 |
+
information.
|
| 156 |
+
"""
|
| 157 |
+
)
|
| 158 |
+
@dataclass
|
| 159 |
+
class SuperGlueKeypointMatchingOutput(ModelOutput):
|
| 160 |
+
r"""
|
| 161 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
|
| 162 |
+
Loss computed during training.
|
| 163 |
+
matches (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
|
| 164 |
+
Index of keypoint matched in the other image.
|
| 165 |
+
matching_scores (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
|
| 166 |
+
Scores of predicted matches.
|
| 167 |
+
keypoints (`torch.FloatTensor` of shape `(batch_size, num_keypoints, 2)`):
|
| 168 |
+
Absolute (x, y) coordinates of predicted keypoints in a given image.
|
| 169 |
+
mask (`torch.IntTensor` of shape `(batch_size, num_keypoints)`):
|
| 170 |
+
Mask indicating which values in matches and matching_scores are keypoint matching information.
|
| 171 |
+
hidden_states (`tuple[torch.FloatTensor, ...]`, *optional*):
|
| 172 |
+
Tuple of `torch.FloatTensor` (one for the output of each stage) of shape `(batch_size, 2, num_channels,
|
| 173 |
+
num_keypoints)`, returned when `output_hidden_states=True` is passed or when
|
| 174 |
+
`config.output_hidden_states=True`)
|
| 175 |
+
attentions (`tuple[torch.FloatTensor, ...]`, *optional*):
|
| 176 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, 2, num_heads, num_keypoints,
|
| 177 |
+
num_keypoints)`, returned when `output_attentions=True` is passed or when `config.output_attentions=True`)
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
loss: torch.FloatTensor | None = None
|
| 181 |
+
matches: torch.FloatTensor | None = None
|
| 182 |
+
matching_scores: torch.FloatTensor | None = None
|
| 183 |
+
keypoints: torch.FloatTensor | None = None
|
| 184 |
+
mask: torch.IntTensor | None = None
|
| 185 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 186 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class SuperGlueMultiLayerPerceptron(nn.Module):
|
| 190 |
+
def __init__(self, config: SuperGlueConfig, in_channels: int, out_channels: int) -> None:
|
| 191 |
+
super().__init__()
|
| 192 |
+
self.linear = nn.Linear(in_channels, out_channels)
|
| 193 |
+
self.batch_norm = nn.BatchNorm1d(out_channels)
|
| 194 |
+
self.activation = nn.ReLU()
|
| 195 |
+
|
| 196 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 197 |
+
hidden_state = self.linear(hidden_state)
|
| 198 |
+
hidden_state = hidden_state.transpose(-1, -2)
|
| 199 |
+
hidden_state = self.batch_norm(hidden_state)
|
| 200 |
+
hidden_state = hidden_state.transpose(-1, -2)
|
| 201 |
+
hidden_state = self.activation(hidden_state)
|
| 202 |
+
return hidden_state
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class SuperGlueKeypointEncoder(nn.Module):
|
| 206 |
+
def __init__(self, config: SuperGlueConfig) -> None:
|
| 207 |
+
super().__init__()
|
| 208 |
+
layer_sizes = config.keypoint_encoder_sizes
|
| 209 |
+
hidden_size = config.hidden_size
|
| 210 |
+
# 3 here consists of 2 for the (x, y) coordinates and 1 for the score of the keypoint
|
| 211 |
+
encoder_channels = [3] + layer_sizes + [hidden_size]
|
| 212 |
+
|
| 213 |
+
layers = [
|
| 214 |
+
SuperGlueMultiLayerPerceptron(config, encoder_channels[i - 1], encoder_channels[i])
|
| 215 |
+
for i in range(1, len(encoder_channels) - 1)
|
| 216 |
+
]
|
| 217 |
+
layers.append(nn.Linear(encoder_channels[-2], encoder_channels[-1]))
|
| 218 |
+
self.encoder = nn.ModuleList(layers)
|
| 219 |
+
|
| 220 |
+
def forward(
|
| 221 |
+
self,
|
| 222 |
+
keypoints: torch.Tensor,
|
| 223 |
+
scores: torch.Tensor,
|
| 224 |
+
output_hidden_states: bool | None = False,
|
| 225 |
+
) -> tuple[torch.Tensor, tuple[torch.Tensor] | None]:
|
| 226 |
+
scores = scores.unsqueeze(2)
|
| 227 |
+
hidden_state = torch.cat([keypoints, scores], dim=2)
|
| 228 |
+
all_hidden_states = () if output_hidden_states else None
|
| 229 |
+
for layer in self.encoder:
|
| 230 |
+
hidden_state = layer(hidden_state)
|
| 231 |
+
if output_hidden_states:
|
| 232 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 233 |
+
return hidden_state, all_hidden_states
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class SuperGlueSelfAttention(nn.Module):
|
| 237 |
+
def __init__(self, config):
|
| 238 |
+
super().__init__()
|
| 239 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 240 |
+
raise ValueError(
|
| 241 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 242 |
+
f"heads ({config.num_attention_heads})"
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
self.num_attention_heads = config.num_attention_heads
|
| 246 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 247 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 248 |
+
|
| 249 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 250 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 251 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 252 |
+
|
| 253 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 254 |
+
|
| 255 |
+
self.is_decoder = config.is_decoder
|
| 256 |
+
|
| 257 |
+
def forward(
|
| 258 |
+
self,
|
| 259 |
+
hidden_states: torch.Tensor,
|
| 260 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 261 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 262 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 263 |
+
output_attentions: bool | None = False,
|
| 264 |
+
) -> tuple[torch.Tensor]:
|
| 265 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 266 |
+
# and values come from an encoder; the attention mask needs to be
|
| 267 |
+
# such that the encoder's padding tokens are not attended to.
|
| 268 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 269 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 270 |
+
attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
|
| 271 |
+
|
| 272 |
+
batch_size = hidden_states.shape[0]
|
| 273 |
+
key_layer = (
|
| 274 |
+
self.key(current_states)
|
| 275 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 276 |
+
.transpose(1, 2)
|
| 277 |
+
)
|
| 278 |
+
value_layer = (
|
| 279 |
+
self.value(current_states)
|
| 280 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 281 |
+
.transpose(1, 2)
|
| 282 |
+
)
|
| 283 |
+
query_layer = (
|
| 284 |
+
self.query(hidden_states)
|
| 285 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 286 |
+
.transpose(1, 2)
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 290 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 291 |
+
|
| 292 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 293 |
+
if attention_mask is not None:
|
| 294 |
+
# Apply the attention mask is (precomputed for all layers in SuperGlueModel forward() function)
|
| 295 |
+
attention_scores = attention_scores + attention_mask
|
| 296 |
+
|
| 297 |
+
# Normalize the attention scores to probabilities.
|
| 298 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 299 |
+
|
| 300 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 301 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 302 |
+
attention_probs = self.dropout(attention_probs)
|
| 303 |
+
|
| 304 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 305 |
+
|
| 306 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 307 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 308 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 309 |
+
|
| 310 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 311 |
+
|
| 312 |
+
if self.is_decoder:
|
| 313 |
+
outputs = outputs + (None,)
|
| 314 |
+
return outputs
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class SuperGlueSelfOutput(nn.Module):
|
| 318 |
+
def __init__(self, config: SuperGlueConfig):
|
| 319 |
+
super().__init__()
|
| 320 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 321 |
+
|
| 322 |
+
def forward(self, hidden_states: torch.Tensor, *args) -> torch.Tensor:
|
| 323 |
+
hidden_states = self.dense(hidden_states)
|
| 324 |
+
return hidden_states
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
SUPERGLUE_SELF_ATTENTION_CLASSES = {
|
| 328 |
+
"eager": SuperGlueSelfAttention,
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class SuperGlueAttention(nn.Module):
|
| 333 |
+
def __init__(self, config):
|
| 334 |
+
super().__init__()
|
| 335 |
+
self.self = SUPERGLUE_SELF_ATTENTION_CLASSES[config._attn_implementation](config)
|
| 336 |
+
self.output = SuperGlueSelfOutput(config)
|
| 337 |
+
|
| 338 |
+
def forward(
|
| 339 |
+
self,
|
| 340 |
+
hidden_states: torch.Tensor,
|
| 341 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 342 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 343 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 344 |
+
output_attentions: bool | None = False,
|
| 345 |
+
) -> tuple[torch.Tensor]:
|
| 346 |
+
self_outputs = self.self(
|
| 347 |
+
hidden_states,
|
| 348 |
+
attention_mask=attention_mask,
|
| 349 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 350 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 351 |
+
output_attentions=output_attentions,
|
| 352 |
+
)
|
| 353 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 354 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 355 |
+
return outputs
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class SuperGlueAttentionalPropagation(nn.Module):
|
| 359 |
+
def __init__(self, config: SuperGlueConfig) -> None:
|
| 360 |
+
super().__init__()
|
| 361 |
+
hidden_size = config.hidden_size
|
| 362 |
+
self.attention = SuperGlueAttention(config)
|
| 363 |
+
mlp_channels = [hidden_size * 2, hidden_size * 2, hidden_size]
|
| 364 |
+
layers = [
|
| 365 |
+
SuperGlueMultiLayerPerceptron(config, mlp_channels[i - 1], mlp_channels[i])
|
| 366 |
+
for i in range(1, len(mlp_channels) - 1)
|
| 367 |
+
]
|
| 368 |
+
layers.append(nn.Linear(mlp_channels[-2], mlp_channels[-1]))
|
| 369 |
+
self.mlp = nn.ModuleList(layers)
|
| 370 |
+
|
| 371 |
+
def forward(
|
| 372 |
+
self,
|
| 373 |
+
descriptors: torch.Tensor,
|
| 374 |
+
attention_mask: torch.Tensor | None = None,
|
| 375 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 376 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 377 |
+
output_attentions: bool = False,
|
| 378 |
+
output_hidden_states: bool = False,
|
| 379 |
+
) -> tuple[torch.Tensor, tuple[torch.Tensor] | None, tuple[torch.Tensor] | None]:
|
| 380 |
+
attention_outputs = self.attention(
|
| 381 |
+
descriptors,
|
| 382 |
+
attention_mask=attention_mask,
|
| 383 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 384 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 385 |
+
output_attentions=output_attentions,
|
| 386 |
+
)
|
| 387 |
+
output = attention_outputs[0]
|
| 388 |
+
attention = attention_outputs[1:]
|
| 389 |
+
|
| 390 |
+
hidden_state = torch.cat([descriptors, output], dim=2)
|
| 391 |
+
|
| 392 |
+
all_hidden_states = () if output_hidden_states else None
|
| 393 |
+
for layer in self.mlp:
|
| 394 |
+
hidden_state = layer(hidden_state)
|
| 395 |
+
if output_hidden_states:
|
| 396 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 397 |
+
|
| 398 |
+
return hidden_state, all_hidden_states, attention
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
class SuperGlueAttentionalGNN(nn.Module):
|
| 402 |
+
def __init__(self, config: SuperGlueConfig) -> None:
|
| 403 |
+
super().__init__()
|
| 404 |
+
self.hidden_size = config.hidden_size
|
| 405 |
+
self.layers_types = config.gnn_layers_types
|
| 406 |
+
self.layers = nn.ModuleList([SuperGlueAttentionalPropagation(config) for _ in range(len(self.layers_types))])
|
| 407 |
+
|
| 408 |
+
def forward(
|
| 409 |
+
self,
|
| 410 |
+
descriptors: torch.Tensor,
|
| 411 |
+
mask: torch.Tensor | None = None,
|
| 412 |
+
output_attentions: bool = False,
|
| 413 |
+
output_hidden_states: bool | None = False,
|
| 414 |
+
) -> tuple[torch.Tensor, tuple | None, tuple | None]:
|
| 415 |
+
all_hidden_states = () if output_hidden_states else None
|
| 416 |
+
all_attentions = () if output_attentions else None
|
| 417 |
+
|
| 418 |
+
batch_size, num_keypoints, _ = descriptors.shape
|
| 419 |
+
if output_hidden_states:
|
| 420 |
+
all_hidden_states = all_hidden_states + (descriptors,)
|
| 421 |
+
|
| 422 |
+
for gnn_layer, layer_type in zip(self.layers, self.layers_types):
|
| 423 |
+
encoder_hidden_states = None
|
| 424 |
+
encoder_attention_mask = None
|
| 425 |
+
if layer_type == "cross":
|
| 426 |
+
encoder_hidden_states = (
|
| 427 |
+
descriptors.reshape(-1, 2, num_keypoints, self.hidden_size)
|
| 428 |
+
.flip(1)
|
| 429 |
+
.reshape(batch_size, num_keypoints, self.hidden_size)
|
| 430 |
+
)
|
| 431 |
+
encoder_attention_mask = (
|
| 432 |
+
mask.reshape(-1, 2, 1, 1, num_keypoints).flip(1).reshape(batch_size, 1, 1, num_keypoints)
|
| 433 |
+
if mask is not None
|
| 434 |
+
else None
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
gnn_outputs = gnn_layer(
|
| 438 |
+
descriptors,
|
| 439 |
+
attention_mask=mask,
|
| 440 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 441 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 442 |
+
output_hidden_states=output_hidden_states,
|
| 443 |
+
output_attentions=output_attentions,
|
| 444 |
+
)
|
| 445 |
+
delta = gnn_outputs[0]
|
| 446 |
+
|
| 447 |
+
if output_hidden_states:
|
| 448 |
+
all_hidden_states = all_hidden_states + gnn_outputs[1]
|
| 449 |
+
if output_attentions:
|
| 450 |
+
all_attentions = all_attentions + gnn_outputs[2]
|
| 451 |
+
|
| 452 |
+
descriptors = descriptors + delta
|
| 453 |
+
return descriptors, all_hidden_states, all_attentions
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class SuperGlueFinalProjection(nn.Module):
|
| 457 |
+
def __init__(self, config: SuperGlueConfig) -> None:
|
| 458 |
+
super().__init__()
|
| 459 |
+
hidden_size = config.hidden_size
|
| 460 |
+
self.final_proj = nn.Linear(hidden_size, hidden_size, bias=True)
|
| 461 |
+
|
| 462 |
+
def forward(self, descriptors: torch.Tensor) -> torch.Tensor:
|
| 463 |
+
return self.final_proj(descriptors)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
@auto_docstring
|
| 467 |
+
class SuperGluePreTrainedModel(PreTrainedModel):
|
| 468 |
+
config: SuperGlueConfig
|
| 469 |
+
base_model_prefix = "superglue"
|
| 470 |
+
main_input_name = "pixel_values"
|
| 471 |
+
input_modalities = ("image",)
|
| 472 |
+
|
| 473 |
+
@torch.no_grad()
|
| 474 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 475 |
+
"""Initialize the weights"""
|
| 476 |
+
super()._init_weights(module)
|
| 477 |
+
if hasattr(module, "bin_score"):
|
| 478 |
+
init.ones_(module.bin_score)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
@auto_docstring(
|
| 482 |
+
custom_intro="""
|
| 483 |
+
SuperGlue model taking images as inputs and outputting the matching of them.
|
| 484 |
+
"""
|
| 485 |
+
)
|
| 486 |
+
class SuperGlueForKeypointMatching(SuperGluePreTrainedModel):
|
| 487 |
+
"""SuperGlue feature matching middle-end
|
| 488 |
+
|
| 489 |
+
Given two sets of keypoints and locations, we determine the
|
| 490 |
+
correspondences by:
|
| 491 |
+
1. Keypoint Encoding (normalization + visual feature and location fusion)
|
| 492 |
+
2. Graph Neural Network with multiple self and cross-attention layers
|
| 493 |
+
3. Final projection layer
|
| 494 |
+
4. Optimal Transport Layer (a differentiable Hungarian matching algorithm)
|
| 495 |
+
5. Thresholding matrix based on mutual exclusivity and a match_threshold
|
| 496 |
+
|
| 497 |
+
The correspondence ids use -1 to indicate non-matching points.
|
| 498 |
+
|
| 499 |
+
Paul-Edouard Sarlin, Daniel DeTone, Tomasz Malisiewicz, and Andrew
|
| 500 |
+
Rabinovich. SuperGlue: Learning Feature Matching with Graph Neural
|
| 501 |
+
Networks. In CVPR, 2020. https://huggingface.co/papers/1911.11763
|
| 502 |
+
"""
|
| 503 |
+
|
| 504 |
+
def __init__(self, config: SuperGlueConfig) -> None:
|
| 505 |
+
super().__init__(config)
|
| 506 |
+
|
| 507 |
+
self.keypoint_detector = AutoModelForKeypointDetection.from_config(config.keypoint_detector_config)
|
| 508 |
+
|
| 509 |
+
self.keypoint_encoder = SuperGlueKeypointEncoder(config)
|
| 510 |
+
self.gnn = SuperGlueAttentionalGNN(config)
|
| 511 |
+
self.final_projection = SuperGlueFinalProjection(config)
|
| 512 |
+
|
| 513 |
+
bin_score = torch.nn.Parameter(torch.tensor(1.0))
|
| 514 |
+
self.register_parameter("bin_score", bin_score)
|
| 515 |
+
|
| 516 |
+
self.post_init()
|
| 517 |
+
|
| 518 |
+
def _match_image_pair(
|
| 519 |
+
self,
|
| 520 |
+
keypoints: torch.Tensor,
|
| 521 |
+
descriptors: torch.Tensor,
|
| 522 |
+
scores: torch.Tensor,
|
| 523 |
+
height: int,
|
| 524 |
+
width: int,
|
| 525 |
+
mask: torch.Tensor | None = None,
|
| 526 |
+
output_attentions: bool | None = None,
|
| 527 |
+
output_hidden_states: bool | None = None,
|
| 528 |
+
) -> tuple[torch.Tensor, torch.Tensor, tuple, tuple]:
|
| 529 |
+
"""
|
| 530 |
+
Perform keypoint matching between two images.
|
| 531 |
+
|
| 532 |
+
Args:
|
| 533 |
+
keypoints (`torch.Tensor` of shape `(batch_size, 2, num_keypoints, 2)`):
|
| 534 |
+
Keypoints detected in the pair of image.
|
| 535 |
+
descriptors (`torch.Tensor` of shape `(batch_size, 2, descriptor_dim, num_keypoints)`):
|
| 536 |
+
Descriptors of the keypoints detected in the image pair.
|
| 537 |
+
scores (`torch.Tensor` of shape `(batch_size, 2, num_keypoints)`):
|
| 538 |
+
Confidence scores of the keypoints detected in the image pair.
|
| 539 |
+
height (`int`): Image height.
|
| 540 |
+
width (`int`): Image width.
|
| 541 |
+
mask (`torch.Tensor` of shape `(batch_size, 2, num_keypoints)`, *optional*):
|
| 542 |
+
Mask indicating which values in the keypoints, matches and matching_scores tensors are keypoint matching
|
| 543 |
+
information.
|
| 544 |
+
output_attentions (`bool`, *optional*):
|
| 545 |
+
Whether or not to return the attentions tensors. Default to `config.output_attentions`.
|
| 546 |
+
output_hidden_states (`bool`, *optional*):
|
| 547 |
+
Whether or not to return the hidden states of all layers. Default to `config.output_hidden_states`.
|
| 548 |
+
|
| 549 |
+
Returns:
|
| 550 |
+
matches (`torch.Tensor` of shape `(batch_size, 2, num_keypoints)`):
|
| 551 |
+
For each image pair, for each keypoint in image0, the index of the keypoint in image1 that was matched
|
| 552 |
+
with. And for each keypoint in image1, the index of the keypoint in image0 that was matched with.
|
| 553 |
+
matching_scores (`torch.Tensor` of shape `(batch_size, 2, num_keypoints)`):
|
| 554 |
+
Scores of predicted matches for each image pair
|
| 555 |
+
all_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 556 |
+
Tuple of `torch.FloatTensor` (one for the output of each stage) of shape `(1, 2, num_keypoints,
|
| 557 |
+
num_channels)`.
|
| 558 |
+
all_attentions (`tuple(torch.FloatTensor)`, *optional*):
|
| 559 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(1, 2, num_heads, num_keypoints,
|
| 560 |
+
num_keypoints)`.
|
| 561 |
+
"""
|
| 562 |
+
all_hidden_states = () if output_hidden_states else None
|
| 563 |
+
all_attentions = () if output_attentions else None
|
| 564 |
+
|
| 565 |
+
if keypoints.shape[2] == 0: # no keypoints
|
| 566 |
+
shape = keypoints.shape[:-1]
|
| 567 |
+
return (
|
| 568 |
+
keypoints.new_full(shape, -1, dtype=torch.int),
|
| 569 |
+
keypoints.new_zeros(shape),
|
| 570 |
+
all_hidden_states,
|
| 571 |
+
all_attentions,
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
batch_size, _, num_keypoints, _ = keypoints.shape
|
| 575 |
+
# (batch_size, 2, num_keypoints, 2) -> (batch_size * 2, num_keypoints, 2)
|
| 576 |
+
keypoints = keypoints.reshape(batch_size * 2, num_keypoints, 2)
|
| 577 |
+
descriptors = descriptors.reshape(batch_size * 2, num_keypoints, self.config.hidden_size)
|
| 578 |
+
scores = scores.reshape(batch_size * 2, num_keypoints)
|
| 579 |
+
mask = mask.reshape(batch_size * 2, num_keypoints) if mask is not None else None
|
| 580 |
+
|
| 581 |
+
# Keypoint normalization
|
| 582 |
+
keypoints = normalize_keypoints(keypoints, height, width)
|
| 583 |
+
|
| 584 |
+
encoded_keypoints = self.keypoint_encoder(keypoints, scores, output_hidden_states=output_hidden_states)
|
| 585 |
+
|
| 586 |
+
last_hidden_state = encoded_keypoints[0]
|
| 587 |
+
|
| 588 |
+
# Keypoint MLP encoder.
|
| 589 |
+
descriptors = descriptors + last_hidden_state
|
| 590 |
+
|
| 591 |
+
extended_attention_mask = create_bidirectional_mask(
|
| 592 |
+
config=self.config,
|
| 593 |
+
inputs_embeds=descriptors[:, 0:1, :], # force q_len == 1
|
| 594 |
+
attention_mask=mask,
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
# Multi-layer Transformer network.
|
| 598 |
+
gnn_outputs = self.gnn(
|
| 599 |
+
descriptors,
|
| 600 |
+
mask=extended_attention_mask,
|
| 601 |
+
output_hidden_states=output_hidden_states,
|
| 602 |
+
output_attentions=output_attentions,
|
| 603 |
+
)
|
| 604 |
+
descriptors = gnn_outputs[0]
|
| 605 |
+
|
| 606 |
+
# Final MLP projection.
|
| 607 |
+
projected_descriptors = self.final_projection(descriptors)
|
| 608 |
+
|
| 609 |
+
# (batch_size * 2, num_keypoints, descriptor_dim) -> (batch_size, 2, num_keypoints, descriptor_dim)
|
| 610 |
+
final_descriptors = projected_descriptors.reshape(batch_size, 2, num_keypoints, self.config.hidden_size)
|
| 611 |
+
final_descriptors0 = final_descriptors[:, 0]
|
| 612 |
+
final_descriptors1 = final_descriptors[:, 1]
|
| 613 |
+
|
| 614 |
+
# Compute matching descriptor distance.
|
| 615 |
+
scores = final_descriptors0 @ final_descriptors1.transpose(1, 2)
|
| 616 |
+
scores = scores / self.config.hidden_size**0.5
|
| 617 |
+
|
| 618 |
+
if mask is not None:
|
| 619 |
+
mask = mask.reshape(batch_size, 2, num_keypoints)
|
| 620 |
+
mask0 = mask[:, 0].unsqueeze(2)
|
| 621 |
+
mask1 = mask[:, 1].unsqueeze(1)
|
| 622 |
+
mask = torch.logical_and(mask0, mask1)
|
| 623 |
+
scores = scores.masked_fill(mask == 0, torch.finfo(scores.dtype).min)
|
| 624 |
+
|
| 625 |
+
# Run the optimal transport.
|
| 626 |
+
scores = log_optimal_transport(scores, self.bin_score, iterations=self.config.sinkhorn_iterations)
|
| 627 |
+
|
| 628 |
+
# Get the matches with score above "match_threshold".
|
| 629 |
+
max0 = scores[:, :-1, :-1].max(2)
|
| 630 |
+
max1 = scores[:, :-1, :-1].max(1)
|
| 631 |
+
indices0 = max0.indices
|
| 632 |
+
indices1 = max1.indices
|
| 633 |
+
mutual0 = arange_like(indices0, 1)[None] == indices1.gather(1, indices0)
|
| 634 |
+
mutual1 = arange_like(indices1, 1)[None] == indices0.gather(1, indices1)
|
| 635 |
+
zero = scores.new_tensor(0)
|
| 636 |
+
matching_scores0 = torch.where(mutual0, max0.values.exp(), zero)
|
| 637 |
+
matching_scores0 = torch.where(matching_scores0 > self.config.matching_threshold, matching_scores0, zero)
|
| 638 |
+
matching_scores1 = torch.where(mutual1, matching_scores0.gather(1, indices1), zero)
|
| 639 |
+
valid0 = mutual0 & (matching_scores0 > zero)
|
| 640 |
+
valid1 = mutual1 & valid0.gather(1, indices1)
|
| 641 |
+
matches0 = torch.where(valid0, indices0, indices0.new_tensor(-1))
|
| 642 |
+
matches1 = torch.where(valid1, indices1, indices1.new_tensor(-1))
|
| 643 |
+
|
| 644 |
+
matches = torch.cat([matches0, matches1], dim=1).reshape(batch_size, 2, -1)
|
| 645 |
+
matching_scores = torch.cat([matching_scores0, matching_scores1], dim=1).reshape(batch_size, 2, -1)
|
| 646 |
+
|
| 647 |
+
if output_hidden_states:
|
| 648 |
+
all_hidden_states = all_hidden_states + encoded_keypoints[1]
|
| 649 |
+
all_hidden_states = all_hidden_states + gnn_outputs[1]
|
| 650 |
+
all_hidden_states = all_hidden_states + (projected_descriptors,)
|
| 651 |
+
all_hidden_states = tuple(
|
| 652 |
+
x.reshape(batch_size, 2, num_keypoints, -1).transpose(-1, -2) for x in all_hidden_states
|
| 653 |
+
)
|
| 654 |
+
if output_attentions:
|
| 655 |
+
all_attentions = all_attentions + gnn_outputs[2]
|
| 656 |
+
all_attentions = tuple(x.reshape(batch_size, 2, -1, num_keypoints, num_keypoints) for x in all_attentions)
|
| 657 |
+
|
| 658 |
+
return (
|
| 659 |
+
matches,
|
| 660 |
+
matching_scores,
|
| 661 |
+
all_hidden_states,
|
| 662 |
+
all_attentions,
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
@auto_docstring
|
| 666 |
+
def forward(
|
| 667 |
+
self,
|
| 668 |
+
pixel_values: torch.FloatTensor,
|
| 669 |
+
labels: torch.LongTensor | None = None,
|
| 670 |
+
output_attentions: bool | None = None,
|
| 671 |
+
output_hidden_states: bool | None = None,
|
| 672 |
+
return_dict: bool | None = None,
|
| 673 |
+
**kwargs,
|
| 674 |
+
) -> tuple | SuperGlueKeypointMatchingOutput:
|
| 675 |
+
r"""
|
| 676 |
+
Examples:
|
| 677 |
+
|
| 678 |
+
```python
|
| 679 |
+
>>> from transformers import AutoImageProcessor, AutoModel
|
| 680 |
+
>>> import torch
|
| 681 |
+
>>> from PIL import Image
|
| 682 |
+
>>> import httpx
|
| 683 |
+
>>> from io import BytesIO
|
| 684 |
+
|
| 685 |
+
>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_78916675_4568141288.jpg?raw=true"
|
| 686 |
+
>>> with httpx.stream("GET", url) as response:
|
| 687 |
+
... image_1 = Image.open(BytesIO(response.read()))
|
| 688 |
+
|
| 689 |
+
>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_19481797_2295892421.jpg?raw=true"
|
| 690 |
+
>>> with httpx.stream("GET", url) as response:
|
| 691 |
+
... image_2 = Image.open(BytesIO(response.read()))
|
| 692 |
+
|
| 693 |
+
>>> images = [image_1, image_2]
|
| 694 |
+
|
| 695 |
+
>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superglue_outdoor")
|
| 696 |
+
>>> model = AutoModel.from_pretrained("magic-leap-community/superglue_outdoor")
|
| 697 |
+
|
| 698 |
+
>>> with torch.no_grad():
|
| 699 |
+
>>> inputs = processor(images, return_tensors="pt")
|
| 700 |
+
>>> outputs = model(**inputs)
|
| 701 |
+
```"""
|
| 702 |
+
loss = None
|
| 703 |
+
if labels is not None:
|
| 704 |
+
raise ValueError("SuperGlue is not trainable, no labels should be provided.")
|
| 705 |
+
|
| 706 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 707 |
+
output_hidden_states = (
|
| 708 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 709 |
+
)
|
| 710 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 711 |
+
|
| 712 |
+
if pixel_values.ndim != 5 or pixel_values.size(1) != 2:
|
| 713 |
+
raise ValueError("Input must be a 5D tensor of shape (batch_size, 2, num_channels, height, width)")
|
| 714 |
+
|
| 715 |
+
batch_size, _, channels, height, width = pixel_values.shape
|
| 716 |
+
pixel_values = pixel_values.reshape(batch_size * 2, channels, height, width)
|
| 717 |
+
keypoint_detections = self.keypoint_detector(pixel_values)
|
| 718 |
+
|
| 719 |
+
keypoints, scores, descriptors, mask = keypoint_detections[:4]
|
| 720 |
+
keypoints = keypoints.reshape(batch_size, 2, -1, 2).to(pixel_values)
|
| 721 |
+
scores = scores.reshape(batch_size, 2, -1).to(pixel_values)
|
| 722 |
+
descriptors = descriptors.reshape(batch_size, 2, -1, self.config.hidden_size).to(pixel_values)
|
| 723 |
+
mask = mask.reshape(batch_size, 2, -1)
|
| 724 |
+
|
| 725 |
+
absolute_keypoints = keypoints.clone()
|
| 726 |
+
absolute_keypoints[:, :, :, 0] = absolute_keypoints[:, :, :, 0] * width
|
| 727 |
+
absolute_keypoints[:, :, :, 1] = absolute_keypoints[:, :, :, 1] * height
|
| 728 |
+
|
| 729 |
+
matches, matching_scores, hidden_states, attentions = self._match_image_pair(
|
| 730 |
+
absolute_keypoints,
|
| 731 |
+
descriptors,
|
| 732 |
+
scores,
|
| 733 |
+
height,
|
| 734 |
+
width,
|
| 735 |
+
mask=mask,
|
| 736 |
+
output_attentions=output_attentions,
|
| 737 |
+
output_hidden_states=output_hidden_states,
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
if not return_dict:
|
| 741 |
+
return tuple(
|
| 742 |
+
v
|
| 743 |
+
for v in [loss, matches, matching_scores, keypoints, mask, hidden_states, attentions]
|
| 744 |
+
if v is not None
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
return SuperGlueKeypointMatchingOutput(
|
| 748 |
+
loss=loss,
|
| 749 |
+
matches=matches,
|
| 750 |
+
matching_scores=matching_scores,
|
| 751 |
+
keypoints=keypoints,
|
| 752 |
+
mask=mask,
|
| 753 |
+
hidden_states=hidden_states,
|
| 754 |
+
attentions=attentions,
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
__all__ = ["SuperGluePreTrainedModel", "SuperGlueForKeypointMatching"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_full_rev8/audit.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:44edb65e0b1d02ea878c58bdc1eb75f7fca0a6dc544304bbdb28b28e942c334f
|
| 3 |
+
size 4846312223
|