Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0022000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0082000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0116000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/__init__.py +29 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/configuration_deit.py +72 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/image_processing_deit.py +34 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/image_processing_pil_deit.py +34 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/modeling_deit.py +671 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/configuration_imagegpt.py +79 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/image_processing_imagegpt.py +192 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/image_processing_pil_imagegpt.py +155 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilenet_v1/image_processing_mobilenet_v1.py +40 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilenet_v1/image_processing_pil_mobilenet_v1.py +40 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/configuration_slanet.py +77 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/modeling_slanet.py +480 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/modular_slanet.py +372 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/videomt/configuration_videomt.py +101 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/videomt/modular_videomt.py +266 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/videomt/video_processing_videomt.py +364 -0
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0022000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_00:36:48 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0022000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0022000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0022000.pt
|
| 3 |
+
[ckpt] step=22000
|
| 4 |
+
[sde] generated 16/256
|
| 5 |
+
[sde] generated 32/256
|
| 6 |
+
[sde] generated 48/256
|
| 7 |
+
[sde] generated 64/256
|
| 8 |
+
[sde] generated 80/256
|
| 9 |
+
[sde] generated 96/256
|
| 10 |
+
[sde] generated 112/256
|
| 11 |
+
[sde] generated 128/256
|
| 12 |
+
[sde] generated 144/256
|
| 13 |
+
[sde] generated 160/256
|
| 14 |
+
[sde] generated 176/256
|
| 15 |
+
[sde] generated 192/256
|
| 16 |
+
[sde] generated 208/256
|
| 17 |
+
[sde] generated 224/256
|
| 18 |
+
[sde] generated 240/256
|
| 19 |
+
[sde] generated 256/256
|
| 20 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 21 |
+
[summary] {
|
| 22 |
+
"type": "summary",
|
| 23 |
+
"checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0022000.pt",
|
| 24 |
+
"step": 22000,
|
| 25 |
+
"decode": {
|
| 26 |
+
"decode_rule": "logistic_normal_resample_sde",
|
| 27 |
+
"steps": 128,
|
| 28 |
+
"model_t_mode": "const0.5",
|
| 29 |
+
"mean_mode": "anchor_semantic",
|
| 30 |
+
"endpoint_floor": 0.0,
|
| 31 |
+
"concentration_min": 1.0,
|
| 32 |
+
"concentration_max": 1024.0,
|
| 33 |
+
"endpoint_temp": 1.45,
|
| 34 |
+
"support_power": 1.0,
|
| 35 |
+
"semantic_power": 1.0,
|
| 36 |
+
"noise_init": "logistic_normal",
|
| 37 |
+
"noise_sigma": 3.0,
|
| 38 |
+
"noise_dirichlet_concentration": 1.0,
|
| 39 |
+
"sde_resample": "logistic_normal",
|
| 40 |
+
"logistic_normal_sigma_min": 0.18,
|
| 41 |
+
"logistic_normal_sigma_max": 3.0,
|
| 42 |
+
"logistic_normal_tau_min": 0.65,
|
| 43 |
+
"logistic_normal_tau_max": 1.0,
|
| 44 |
+
"final_from": "blend_0.5",
|
| 45 |
+
"n_samples": 256,
|
| 46 |
+
"seed": 20260522
|
| 47 |
+
},
|
| 48 |
+
"raw_genppl": {
|
| 49 |
+
"ppl": 36.203633463316066,
|
| 50 |
+
"nll_per_token": 3.5891594857096103,
|
| 51 |
+
"tokens": 37429,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 52.686914223709124,
|
| 59 |
+
"nll_per_token": 3.9643671177635507,
|
| 60 |
+
"tokens": 30976,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.8378421959993116,
|
| 68 |
+
"unique_tokens": 2685,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.081939697265625,
|
| 71 |
+
"distinct_2": 0.3808132381889764,
|
| 72 |
+
"top_token_mass": 0.087738037109375
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
[done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0022000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_00:38:17 done step_0022000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0082000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_06:11:48 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0082000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0082000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0082000.pt
|
| 3 |
+
[ckpt] step=82000
|
| 4 |
+
[sde] generated 16/256
|
| 5 |
+
[sde] generated 32/256
|
| 6 |
+
[sde] generated 48/256
|
| 7 |
+
[sde] generated 64/256
|
| 8 |
+
[sde] generated 80/256
|
| 9 |
+
[sde] generated 96/256
|
| 10 |
+
[sde] generated 112/256
|
| 11 |
+
[sde] generated 128/256
|
| 12 |
+
[sde] generated 144/256
|
| 13 |
+
[sde] generated 160/256
|
| 14 |
+
[sde] generated 176/256
|
| 15 |
+
[sde] generated 192/256
|
| 16 |
+
[sde] generated 208/256
|
| 17 |
+
[sde] generated 224/256
|
| 18 |
+
[sde] generated 240/256
|
| 19 |
+
[sde] generated 256/256
|
| 20 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 21 |
+
[summary] {
|
| 22 |
+
"type": "summary",
|
| 23 |
+
"checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0082000.pt",
|
| 24 |
+
"step": 82000,
|
| 25 |
+
"decode": {
|
| 26 |
+
"decode_rule": "logistic_normal_resample_sde",
|
| 27 |
+
"steps": 128,
|
| 28 |
+
"model_t_mode": "const0.5",
|
| 29 |
+
"mean_mode": "anchor_semantic",
|
| 30 |
+
"endpoint_floor": 0.0,
|
| 31 |
+
"concentration_min": 1.0,
|
| 32 |
+
"concentration_max": 1024.0,
|
| 33 |
+
"endpoint_temp": 1.45,
|
| 34 |
+
"support_power": 1.0,
|
| 35 |
+
"semantic_power": 1.0,
|
| 36 |
+
"noise_init": "logistic_normal",
|
| 37 |
+
"noise_sigma": 3.0,
|
| 38 |
+
"noise_dirichlet_concentration": 1.0,
|
| 39 |
+
"sde_resample": "logistic_normal",
|
| 40 |
+
"logistic_normal_sigma_min": 0.18,
|
| 41 |
+
"logistic_normal_sigma_max": 3.0,
|
| 42 |
+
"logistic_normal_tau_min": 0.65,
|
| 43 |
+
"logistic_normal_tau_max": 1.0,
|
| 44 |
+
"final_from": "blend_0.5",
|
| 45 |
+
"n_samples": 256,
|
| 46 |
+
"seed": 20260522
|
| 47 |
+
},
|
| 48 |
+
"raw_genppl": {
|
| 49 |
+
"ppl": 32.86963269699827,
|
| 50 |
+
"nll_per_token": 3.4925492131992817,
|
| 51 |
+
"tokens": 35961,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 41.948984818093216,
|
| 59 |
+
"nll_per_token": 3.7364542328133203,
|
| 60 |
+
"tokens": 30476,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.5578483548277156,
|
| 68 |
+
"unique_tokens": 2118,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.06463623046875,
|
| 71 |
+
"distinct_2": 0.33544537401574803,
|
| 72 |
+
"top_token_mass": 0.09210205078125
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
[done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0082000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_06:13:17 done step_0082000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0116000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_09:21:40 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0116000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0116000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0116000.pt
|
| 3 |
+
[ckpt] step=116000
|
| 4 |
+
[sde] generated 16/256
|
| 5 |
+
[sde] generated 32/256
|
| 6 |
+
[sde] generated 48/256
|
| 7 |
+
[sde] generated 64/256
|
| 8 |
+
[sde] generated 80/256
|
| 9 |
+
[sde] generated 96/256
|
| 10 |
+
[sde] generated 112/256
|
| 11 |
+
[sde] generated 128/256
|
| 12 |
+
[sde] generated 144/256
|
| 13 |
+
[sde] generated 160/256
|
| 14 |
+
[sde] generated 176/256
|
| 15 |
+
[sde] generated 192/256
|
| 16 |
+
[sde] generated 208/256
|
| 17 |
+
[sde] generated 224/256
|
| 18 |
+
[sde] generated 240/256
|
| 19 |
+
[sde] generated 256/256
|
| 20 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 21 |
+
[summary] {
|
| 22 |
+
"type": "summary",
|
| 23 |
+
"checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0116000.pt",
|
| 24 |
+
"step": 116000,
|
| 25 |
+
"decode": {
|
| 26 |
+
"decode_rule": "logistic_normal_resample_sde",
|
| 27 |
+
"steps": 128,
|
| 28 |
+
"model_t_mode": "const0.5",
|
| 29 |
+
"mean_mode": "anchor_semantic",
|
| 30 |
+
"endpoint_floor": 0.0,
|
| 31 |
+
"concentration_min": 1.0,
|
| 32 |
+
"concentration_max": 1024.0,
|
| 33 |
+
"endpoint_temp": 1.45,
|
| 34 |
+
"support_power": 1.0,
|
| 35 |
+
"semantic_power": 1.0,
|
| 36 |
+
"noise_init": "logistic_normal",
|
| 37 |
+
"noise_sigma": 3.0,
|
| 38 |
+
"noise_dirichlet_concentration": 1.0,
|
| 39 |
+
"sde_resample": "logistic_normal",
|
| 40 |
+
"logistic_normal_sigma_min": 0.18,
|
| 41 |
+
"logistic_normal_sigma_max": 3.0,
|
| 42 |
+
"logistic_normal_tau_min": 0.65,
|
| 43 |
+
"logistic_normal_tau_max": 1.0,
|
| 44 |
+
"final_from": "blend_0.5",
|
| 45 |
+
"n_samples": 256,
|
| 46 |
+
"seed": 20260522
|
| 47 |
+
},
|
| 48 |
+
"raw_genppl": {
|
| 49 |
+
"ppl": 33.84903888580392,
|
| 50 |
+
"nll_per_token": 3.5219106056259073,
|
| 51 |
+
"tokens": 33058,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 46.07219135564344,
|
| 59 |
+
"nll_per_token": 3.8302095436000574,
|
| 60 |
+
"tokens": 27448,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.3640971283558763,
|
| 68 |
+
"unique_tokens": 2189,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.066802978515625,
|
| 71 |
+
"distinct_2": 0.3188976377952756,
|
| 72 |
+
"top_token_mass": 0.18438720703125
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
[done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0116000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_09:23:07 done step_0116000
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/__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_deit import *
|
| 22 |
+
from .image_processing_deit import *
|
| 23 |
+
from .image_processing_pil_deit import *
|
| 24 |
+
from .modeling_deit 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/deit/configuration_deit.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 Facebook AI Research (FAIR) 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 |
+
"""DeiT model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="facebook/deit-base-distilled-patch16-224")
|
| 23 |
+
@strict
|
| 24 |
+
class DeiTConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
encoder_stride (`int`, *optional*, defaults to 16):
|
| 27 |
+
Factor to increase the spatial resolution by in the decoder head for masked image modeling.
|
| 28 |
+
pooler_output_size (`int`, *optional*):
|
| 29 |
+
Dimensionality of the pooler layer. If None, defaults to `hidden_size`.
|
| 30 |
+
pooler_act (`str`, *optional*, defaults to `"tanh"`):
|
| 31 |
+
The activation function to be used by the pooler.
|
| 32 |
+
|
| 33 |
+
Example:
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
>>> from transformers import DeiTConfig, DeiTModel
|
| 37 |
+
|
| 38 |
+
>>> # Initializing a DeiT deit-base-distilled-patch16-224 style configuration
|
| 39 |
+
>>> configuration = DeiTConfig()
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a model (with random weights) from the deit-base-distilled-patch16-224 style configuration
|
| 42 |
+
>>> model = DeiTModel(configuration)
|
| 43 |
+
|
| 44 |
+
>>> # Accessing the model configuration
|
| 45 |
+
>>> configuration = model.config
|
| 46 |
+
```"""
|
| 47 |
+
|
| 48 |
+
model_type = "deit"
|
| 49 |
+
|
| 50 |
+
hidden_size: int = 768
|
| 51 |
+
num_hidden_layers: int = 12
|
| 52 |
+
num_attention_heads: int = 12
|
| 53 |
+
intermediate_size: int = 3072
|
| 54 |
+
hidden_act: str = "gelu"
|
| 55 |
+
hidden_dropout_prob: float | int = 0.0
|
| 56 |
+
attention_probs_dropout_prob: float | int = 0.0
|
| 57 |
+
initializer_range: float = 0.02
|
| 58 |
+
layer_norm_eps: float = 1e-12
|
| 59 |
+
image_size: int | list[int] | tuple[int, int] = 224
|
| 60 |
+
patch_size: int | list[int] | tuple[int, int] = 16
|
| 61 |
+
num_channels: int = 3
|
| 62 |
+
qkv_bias: bool = True
|
| 63 |
+
encoder_stride: int = 16
|
| 64 |
+
pooler_output_size: int | None = None
|
| 65 |
+
pooler_act: str = "tanh"
|
| 66 |
+
|
| 67 |
+
def __post_init__(self, **kwargs):
|
| 68 |
+
self.pooler_output_size = self.pooler_output_size if self.pooler_output_size else self.hidden_size
|
| 69 |
+
super().__post_init__(**kwargs)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
__all__ = ["DeiTConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/image_processing_deit.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Image processor class for DeiT."""
|
| 15 |
+
|
| 16 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 17 |
+
from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling
|
| 18 |
+
from ...utils import auto_docstring
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@auto_docstring
|
| 22 |
+
class DeiTImageProcessor(TorchvisionBackend):
|
| 23 |
+
resample = PILImageResampling.BICUBIC
|
| 24 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 25 |
+
image_std = IMAGENET_STANDARD_STD
|
| 26 |
+
size = {"height": 256, "width": 256}
|
| 27 |
+
crop_size = {"height": 224, "width": 224}
|
| 28 |
+
do_resize = True
|
| 29 |
+
do_center_crop = True
|
| 30 |
+
do_rescale = True
|
| 31 |
+
do_normalize = True
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = ["DeiTImageProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/image_processing_pil_deit.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Image processor class for DeiT."""
|
| 15 |
+
|
| 16 |
+
from ...image_processing_backends import PilBackend
|
| 17 |
+
from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling
|
| 18 |
+
from ...utils import auto_docstring
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@auto_docstring
|
| 22 |
+
class DeiTImageProcessorPil(PilBackend):
|
| 23 |
+
resample = PILImageResampling.BICUBIC
|
| 24 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 25 |
+
image_std = IMAGENET_STANDARD_STD
|
| 26 |
+
size = {"height": 256, "width": 256}
|
| 27 |
+
crop_size = {"height": 224, "width": 224}
|
| 28 |
+
do_resize = True
|
| 29 |
+
do_center_crop = True
|
| 30 |
+
do_rescale = True
|
| 31 |
+
do_normalize = True
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = ["DeiTImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deit/modeling_deit.py
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/deit/modular_deit.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_deit.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2021 Facebook AI Research & The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable, Iterable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
from ... import initialization as init
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...masking_utils import create_bidirectional_mask
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, ImageClassifierOutput, MaskedImageModelingOutput
|
| 32 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 33 |
+
from ...processing_utils import Unpack
|
| 34 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_int
|
| 35 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 36 |
+
from ...utils.output_capturing import capture_outputs
|
| 37 |
+
from .configuration_deit import DeiTConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DeiTPatchEmbeddings(nn.Module):
|
| 41 |
+
"""
|
| 42 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 43 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 44 |
+
Transformer.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self, config: DeiTConfig):
|
| 48 |
+
super().__init__()
|
| 49 |
+
image_size = config.image_size
|
| 50 |
+
patch_size = config.patch_size
|
| 51 |
+
image_size = image_size if isinstance(image_size, Iterable) else (image_size, image_size)
|
| 52 |
+
patch_size = patch_size if isinstance(patch_size, Iterable) else (patch_size, patch_size)
|
| 53 |
+
|
| 54 |
+
self.num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 55 |
+
self.image_size = image_size
|
| 56 |
+
self.patch_size = patch_size
|
| 57 |
+
self.num_channels = config.num_channels
|
| 58 |
+
self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 59 |
+
|
| 60 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 61 |
+
num_channels = pixel_values.shape[1]
|
| 62 |
+
if num_channels != self.num_channels:
|
| 63 |
+
raise ValueError(
|
| 64 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 65 |
+
f" Expected {self.num_channels} but got {num_channels}."
|
| 66 |
+
)
|
| 67 |
+
return self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class DeiTEmbeddings(nn.Module):
|
| 71 |
+
"""
|
| 72 |
+
Construct the CLS token, distillation token, position and patch embeddings. Optionally, also the mask token.
|
| 73 |
+
|
| 74 |
+
Differences from ViTEmbeddings:
|
| 75 |
+
- Adds a distillation token (for distillation pre-training).
|
| 76 |
+
- Position embeddings include +2 slots (CLS + distillation) instead of +1.
|
| 77 |
+
- interpolate_pos_encoding handles 2 special tokens instead of 1.
|
| 78 |
+
- forward concatenates distillation token and handles position encoding for both.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(self, config: DeiTConfig, use_mask_token: bool = False) -> None:
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 84 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
|
| 85 |
+
self.patch_embeddings = DeiTPatchEmbeddings(config)
|
| 86 |
+
num_patches = self.patch_embeddings.num_patches
|
| 87 |
+
# +2: one slot for CLS, one for distillation token
|
| 88 |
+
self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 2, config.hidden_size))
|
| 89 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 90 |
+
self.patch_size = config.patch_size
|
| 91 |
+
self.image_size = self.patch_embeddings.image_size
|
| 92 |
+
self.distillation_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 93 |
+
|
| 94 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 95 |
+
"""
|
| 96 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 97 |
+
images. This method is also adapted to support torch.jit tracing and 2 class embeddings.
|
| 98 |
+
|
| 99 |
+
Adapted from:
|
| 100 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 101 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
num_patches = embeddings.shape[1] - 2
|
| 105 |
+
num_positions = self.position_embeddings.shape[1] - 2
|
| 106 |
+
|
| 107 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 108 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 109 |
+
return self.position_embeddings
|
| 110 |
+
|
| 111 |
+
class_and_dist_pos_embed = self.position_embeddings[:, :2]
|
| 112 |
+
patch_pos_embed = self.position_embeddings[:, 2:]
|
| 113 |
+
|
| 114 |
+
dim = embeddings.shape[-1]
|
| 115 |
+
|
| 116 |
+
new_height = height // self.patch_size
|
| 117 |
+
new_width = width // self.patch_size
|
| 118 |
+
|
| 119 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 120 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 121 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 122 |
+
|
| 123 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 124 |
+
patch_pos_embed,
|
| 125 |
+
size=(new_height, new_width),
|
| 126 |
+
mode="bicubic",
|
| 127 |
+
align_corners=False,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 131 |
+
|
| 132 |
+
return torch.cat((class_and_dist_pos_embed, patch_pos_embed), dim=1)
|
| 133 |
+
|
| 134 |
+
def forward(
|
| 135 |
+
self,
|
| 136 |
+
pixel_values: torch.Tensor,
|
| 137 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 138 |
+
interpolate_pos_encoding: bool = False,
|
| 139 |
+
) -> torch.Tensor:
|
| 140 |
+
_, _, height, width = pixel_values.shape
|
| 141 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 142 |
+
|
| 143 |
+
batch_size, seq_length, _ = embeddings.size()
|
| 144 |
+
|
| 145 |
+
if bool_masked_pos is not None:
|
| 146 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
|
| 147 |
+
# replace the masked visual tokens by mask_tokens
|
| 148 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 149 |
+
embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
|
| 150 |
+
|
| 151 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 152 |
+
distillation_tokens = self.distillation_token.expand(batch_size, -1, -1)
|
| 153 |
+
embeddings = torch.cat((cls_tokens, distillation_tokens, embeddings), dim=1)
|
| 154 |
+
|
| 155 |
+
if interpolate_pos_encoding:
|
| 156 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 157 |
+
else:
|
| 158 |
+
if height != self.image_size[0] or width != self.image_size[1]:
|
| 159 |
+
raise ValueError(
|
| 160 |
+
f"Input image size ({height}*{width}) doesn't match model"
|
| 161 |
+
f" ({self.image_size[0]}*{self.image_size[1]})."
|
| 162 |
+
)
|
| 163 |
+
embeddings = embeddings + self.position_embeddings
|
| 164 |
+
|
| 165 |
+
embeddings = self.dropout(embeddings)
|
| 166 |
+
return embeddings
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def eager_attention_forward(
|
| 170 |
+
module: nn.Module,
|
| 171 |
+
query: torch.Tensor,
|
| 172 |
+
key: torch.Tensor,
|
| 173 |
+
value: torch.Tensor,
|
| 174 |
+
attention_mask: torch.Tensor | None,
|
| 175 |
+
scaling: float | None = None,
|
| 176 |
+
dropout: float = 0.0,
|
| 177 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 178 |
+
):
|
| 179 |
+
if scaling is None:
|
| 180 |
+
scaling = query.size(-1) ** -0.5
|
| 181 |
+
|
| 182 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 183 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 184 |
+
|
| 185 |
+
if attention_mask is not None:
|
| 186 |
+
attn_weights = attn_weights + attention_mask
|
| 187 |
+
|
| 188 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 189 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 190 |
+
|
| 191 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 192 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 193 |
+
|
| 194 |
+
return attn_output, attn_weights
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class DeiTAttention(nn.Module):
|
| 198 |
+
def __init__(self, config: DeiTConfig):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.config = config
|
| 201 |
+
self.num_attention_heads = config.num_attention_heads
|
| 202 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 203 |
+
self.attention_dropout = config.attention_probs_dropout_prob
|
| 204 |
+
self.scaling = self.head_dim**-0.5
|
| 205 |
+
self.is_causal = False
|
| 206 |
+
|
| 207 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.qkv_bias)
|
| 208 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.qkv_bias)
|
| 209 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.qkv_bias)
|
| 210 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
|
| 211 |
+
|
| 212 |
+
def forward(
|
| 213 |
+
self,
|
| 214 |
+
hidden_states: torch.Tensor,
|
| 215 |
+
attention_mask: torch.Tensor | None = None,
|
| 216 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 217 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 218 |
+
input_shape = hidden_states.shape[:-1]
|
| 219 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 220 |
+
|
| 221 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 222 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 223 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 224 |
+
|
| 225 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 226 |
+
self.config._attn_implementation, eager_attention_forward
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
attn_output, attn_weights = attention_interface(
|
| 230 |
+
self,
|
| 231 |
+
query_states,
|
| 232 |
+
key_states,
|
| 233 |
+
value_states,
|
| 234 |
+
attention_mask,
|
| 235 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 236 |
+
scaling=self.scaling,
|
| 237 |
+
**kwargs,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 241 |
+
attn_output = self.o_proj(attn_output)
|
| 242 |
+
|
| 243 |
+
return attn_output, attn_weights
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class DeiTMLP(nn.Module):
|
| 247 |
+
def __init__(self, config: DeiTConfig):
|
| 248 |
+
super().__init__()
|
| 249 |
+
self.config = config
|
| 250 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 251 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 252 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 253 |
+
|
| 254 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 255 |
+
hidden_states = self.fc1(hidden_states)
|
| 256 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 257 |
+
hidden_states = self.fc2(hidden_states)
|
| 258 |
+
|
| 259 |
+
return hidden_states
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class DeiTLayer(GradientCheckpointingLayer):
|
| 263 |
+
def __init__(self, config: DeiTConfig):
|
| 264 |
+
super().__init__()
|
| 265 |
+
self.attention = DeiTAttention(config)
|
| 266 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 267 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 268 |
+
self.mlp = DeiTMLP(config)
|
| 269 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 270 |
+
|
| 271 |
+
def forward(
|
| 272 |
+
self,
|
| 273 |
+
hidden_states: torch.Tensor,
|
| 274 |
+
attention_mask: torch.Tensor | None = None,
|
| 275 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 276 |
+
) -> torch.Tensor:
|
| 277 |
+
# Self Attention
|
| 278 |
+
residual = hidden_states
|
| 279 |
+
hidden_states = self.layernorm_before(hidden_states)
|
| 280 |
+
hidden_states, _ = self.attention(hidden_states, attention_mask, **kwargs)
|
| 281 |
+
hidden_states = self.dropout(hidden_states)
|
| 282 |
+
hidden_states = hidden_states + residual
|
| 283 |
+
|
| 284 |
+
# Fully Connected
|
| 285 |
+
residual = hidden_states
|
| 286 |
+
hidden_states = self.layernorm_after(hidden_states)
|
| 287 |
+
hidden_states = self.mlp(hidden_states)
|
| 288 |
+
hidden_states = self.dropout(hidden_states)
|
| 289 |
+
hidden_states = hidden_states + residual
|
| 290 |
+
|
| 291 |
+
return hidden_states
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@auto_docstring
|
| 295 |
+
class DeiTPreTrainedModel(PreTrainedModel):
|
| 296 |
+
config: DeiTConfig
|
| 297 |
+
base_model_prefix = "deit"
|
| 298 |
+
main_input_name = "pixel_values"
|
| 299 |
+
input_modalities = ("image",)
|
| 300 |
+
supports_gradient_checkpointing = True
|
| 301 |
+
_no_split_modules = ["DeiTEmbeddings", "DeiTLayer"]
|
| 302 |
+
_supports_sdpa = True
|
| 303 |
+
_supports_flash_attn = True
|
| 304 |
+
_supports_flex_attn = True
|
| 305 |
+
_supports_attention_backend = True
|
| 306 |
+
_can_compile_fullgraph = True
|
| 307 |
+
_can_record_outputs = {
|
| 308 |
+
"hidden_states": DeiTLayer,
|
| 309 |
+
"attentions": DeiTAttention,
|
| 310 |
+
}
|
| 311 |
+
_input_embed_layer = "patch_embeddings"
|
| 312 |
+
|
| 313 |
+
@torch.no_grad()
|
| 314 |
+
def _init_weights(self, module: nn.Linear | nn.Conv2d | nn.LayerNorm) -> None:
|
| 315 |
+
"""Initialize the weights"""
|
| 316 |
+
super()._init_weights(module)
|
| 317 |
+
if isinstance(module, DeiTEmbeddings):
|
| 318 |
+
if module.position_embeddings is not None:
|
| 319 |
+
init.trunc_normal_(module.position_embeddings, mean=0.0, std=self.config.initializer_range)
|
| 320 |
+
init.trunc_normal_(module.cls_token, mean=0.0, std=self.config.initializer_range)
|
| 321 |
+
if module.mask_token is not None:
|
| 322 |
+
init.zeros_(module.mask_token)
|
| 323 |
+
if isinstance(module, DeiTEmbeddings):
|
| 324 |
+
init.zeros_(module.cls_token)
|
| 325 |
+
init.zeros_(module.position_embeddings)
|
| 326 |
+
init.zeros_(module.distillation_token)
|
| 327 |
+
if module.mask_token is not None:
|
| 328 |
+
init.zeros_(module.mask_token)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class DeiTPooler(nn.Module):
|
| 332 |
+
def __init__(self, config: DeiTConfig):
|
| 333 |
+
super().__init__()
|
| 334 |
+
self.dense = nn.Linear(config.hidden_size, config.pooler_output_size)
|
| 335 |
+
self.activation = ACT2FN[config.pooler_act]
|
| 336 |
+
|
| 337 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 338 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 339 |
+
# to the first token.
|
| 340 |
+
first_token_tensor = hidden_states[:, 0]
|
| 341 |
+
pooled_output = self.dense(first_token_tensor)
|
| 342 |
+
pooled_output = self.activation(pooled_output)
|
| 343 |
+
return pooled_output
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
@auto_docstring
|
| 347 |
+
class DeiTModel(DeiTPreTrainedModel):
|
| 348 |
+
def __init__(self, config: DeiTConfig, add_pooling_layer: bool = True, use_mask_token: bool = False):
|
| 349 |
+
r"""
|
| 350 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 351 |
+
Whether to add a pooling layer
|
| 352 |
+
use_mask_token (`bool`, *optional*, defaults to `False`):
|
| 353 |
+
Whether to use a mask token for masked image modeling.
|
| 354 |
+
"""
|
| 355 |
+
super().__init__(config)
|
| 356 |
+
self.config = config
|
| 357 |
+
self.embeddings = DeiTEmbeddings(config, use_mask_token=use_mask_token)
|
| 358 |
+
self.layers = nn.ModuleList([DeiTLayer(config) for _ in range(config.num_hidden_layers)])
|
| 359 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 360 |
+
self.pooler = DeiTPooler(config) if add_pooling_layer else None
|
| 361 |
+
# Initialize weights and apply final processing
|
| 362 |
+
self.post_init()
|
| 363 |
+
|
| 364 |
+
@merge_with_config_defaults
|
| 365 |
+
@capture_outputs(tie_last_hidden_states=False)
|
| 366 |
+
@auto_docstring
|
| 367 |
+
def forward(
|
| 368 |
+
self,
|
| 369 |
+
pixel_values: torch.Tensor | None = None,
|
| 370 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 371 |
+
interpolate_pos_encoding: bool | None = None,
|
| 372 |
+
attention_mask: torch.Tensor | None = None,
|
| 373 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 374 |
+
) -> BaseModelOutputWithPooling:
|
| 375 |
+
r"""
|
| 376 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
| 377 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 378 |
+
"""
|
| 379 |
+
# Kept for BC, but this should be handled by users on the processed inputs directly.
|
| 380 |
+
expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
|
| 381 |
+
if pixel_values.dtype != expected_dtype:
|
| 382 |
+
pixel_values = pixel_values.to(expected_dtype)
|
| 383 |
+
|
| 384 |
+
embedding_output = self.embeddings(
|
| 385 |
+
pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
|
| 386 |
+
)
|
| 387 |
+
attention_mask = create_bidirectional_mask(
|
| 388 |
+
config=self.config,
|
| 389 |
+
inputs_embeds=embedding_output,
|
| 390 |
+
attention_mask=attention_mask,
|
| 391 |
+
)
|
| 392 |
+
hidden_states = embedding_output
|
| 393 |
+
for layer in self.layers:
|
| 394 |
+
hidden_states = layer(hidden_states, attention_mask, **kwargs)
|
| 395 |
+
|
| 396 |
+
sequence_output = self.layernorm(hidden_states)
|
| 397 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 398 |
+
|
| 399 |
+
return BaseModelOutputWithPooling(last_hidden_state=sequence_output, pooler_output=pooled_output)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@auto_docstring(
|
| 403 |
+
custom_intro="""
|
| 404 |
+
DeiT Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886).
|
| 405 |
+
|
| 406 |
+
<Tip>
|
| 407 |
+
|
| 408 |
+
Note that we provide a script to pre-train this model on custom data in our [examples
|
| 409 |
+
directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
|
| 410 |
+
|
| 411 |
+
</Tip>
|
| 412 |
+
"""
|
| 413 |
+
)
|
| 414 |
+
class DeiTForMaskedImageModeling(DeiTPreTrainedModel):
|
| 415 |
+
def __init__(self, config: DeiTConfig):
|
| 416 |
+
super().__init__(config)
|
| 417 |
+
|
| 418 |
+
self.deit = DeiTModel(config, add_pooling_layer=False, use_mask_token=True)
|
| 419 |
+
|
| 420 |
+
self.decoder = nn.Sequential(
|
| 421 |
+
nn.Conv2d(
|
| 422 |
+
in_channels=config.hidden_size,
|
| 423 |
+
out_channels=config.encoder_stride**2 * config.num_channels,
|
| 424 |
+
kernel_size=1,
|
| 425 |
+
),
|
| 426 |
+
nn.PixelShuffle(config.encoder_stride),
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
# Initialize weights and apply final processing
|
| 430 |
+
self.post_init()
|
| 431 |
+
|
| 432 |
+
@can_return_tuple
|
| 433 |
+
@auto_docstring
|
| 434 |
+
def forward(
|
| 435 |
+
self,
|
| 436 |
+
pixel_values: torch.Tensor | None = None,
|
| 437 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 438 |
+
interpolate_pos_encoding: bool = False,
|
| 439 |
+
attention_mask: torch.Tensor | None = None,
|
| 440 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 441 |
+
) -> MaskedImageModelingOutput:
|
| 442 |
+
r"""
|
| 443 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 444 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 445 |
+
|
| 446 |
+
Examples:
|
| 447 |
+
```python
|
| 448 |
+
>>> from transformers import AutoImageProcessor, DeiTForMaskedImageModeling
|
| 449 |
+
>>> import torch
|
| 450 |
+
>>> from PIL import Image
|
| 451 |
+
>>> import requests
|
| 452 |
+
|
| 453 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 454 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 455 |
+
|
| 456 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
|
| 457 |
+
>>> model = DeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224")
|
| 458 |
+
|
| 459 |
+
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
|
| 460 |
+
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
|
| 461 |
+
>>> # create random boolean mask of shape (batch_size, num_patches)
|
| 462 |
+
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
|
| 463 |
+
|
| 464 |
+
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 465 |
+
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
|
| 466 |
+
>>> list(reconstructed_pixel_values.shape)
|
| 467 |
+
[1, 3, 224, 224]
|
| 468 |
+
```"""
|
| 469 |
+
|
| 470 |
+
outputs: BaseModelOutputWithPooling = self.deit(
|
| 471 |
+
pixel_values,
|
| 472 |
+
bool_masked_pos=bool_masked_pos,
|
| 473 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 474 |
+
attention_mask=attention_mask,
|
| 475 |
+
**kwargs,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
sequence_output = outputs.last_hidden_state
|
| 479 |
+
|
| 480 |
+
# Reshape to (batch_size, num_channels, height, width)
|
| 481 |
+
# Remove the [CLS] token (index 0) and distillation token (index 1), keep only patch embeddings
|
| 482 |
+
sequence_output = sequence_output[:, 2:]
|
| 483 |
+
batch_size, sequence_length, num_channels = sequence_output.shape
|
| 484 |
+
height = width = int(sequence_length**0.5)
|
| 485 |
+
sequence_output = sequence_output.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
|
| 486 |
+
|
| 487 |
+
# Reconstruct pixel values
|
| 488 |
+
reconstructed_pixel_values = self.decoder(sequence_output)
|
| 489 |
+
|
| 490 |
+
masked_im_loss = None
|
| 491 |
+
if bool_masked_pos is not None:
|
| 492 |
+
size = self.config.image_size // self.config.patch_size
|
| 493 |
+
bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
|
| 494 |
+
mask = (
|
| 495 |
+
bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
|
| 496 |
+
.repeat_interleave(self.config.patch_size, 2)
|
| 497 |
+
.unsqueeze(1)
|
| 498 |
+
.contiguous()
|
| 499 |
+
)
|
| 500 |
+
reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
|
| 501 |
+
masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
|
| 502 |
+
|
| 503 |
+
return MaskedImageModelingOutput(
|
| 504 |
+
loss=masked_im_loss,
|
| 505 |
+
reconstruction=reconstructed_pixel_values,
|
| 506 |
+
hidden_states=outputs.hidden_states,
|
| 507 |
+
attentions=outputs.attentions,
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@auto_docstring(
|
| 512 |
+
custom_intro="""
|
| 513 |
+
DeiT Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 514 |
+
the [CLS] token) e.g. for ImageNet.
|
| 515 |
+
|
| 516 |
+
<Tip>
|
| 517 |
+
|
| 518 |
+
Note that it's possible to fine-tune DeiT on higher resolution images than the ones it has been trained on, by
|
| 519 |
+
setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
|
| 520 |
+
position embeddings to the higher resolution.
|
| 521 |
+
|
| 522 |
+
</Tip>
|
| 523 |
+
"""
|
| 524 |
+
)
|
| 525 |
+
class DeiTForImageClassification(DeiTPreTrainedModel):
|
| 526 |
+
def __init__(self, config: DeiTConfig):
|
| 527 |
+
super().__init__(config)
|
| 528 |
+
|
| 529 |
+
self.num_labels = config.num_labels
|
| 530 |
+
self.deit = DeiTModel(config, add_pooling_layer=False)
|
| 531 |
+
|
| 532 |
+
# Classifier head
|
| 533 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 534 |
+
|
| 535 |
+
# Initialize weights and apply final processing
|
| 536 |
+
self.post_init()
|
| 537 |
+
|
| 538 |
+
@can_return_tuple
|
| 539 |
+
@auto_docstring
|
| 540 |
+
def forward(
|
| 541 |
+
self,
|
| 542 |
+
pixel_values: torch.Tensor | None = None,
|
| 543 |
+
labels: torch.Tensor | None = None,
|
| 544 |
+
interpolate_pos_encoding: bool | None = None,
|
| 545 |
+
attention_mask: torch.Tensor | None = None,
|
| 546 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 547 |
+
) -> ImageClassifierOutput:
|
| 548 |
+
r"""
|
| 549 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 550 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 551 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 552 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 553 |
+
"""
|
| 554 |
+
|
| 555 |
+
outputs: BaseModelOutputWithPooling = self.deit(
|
| 556 |
+
pixel_values,
|
| 557 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 558 |
+
attention_mask=attention_mask,
|
| 559 |
+
**kwargs,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
sequence_output = outputs.last_hidden_state
|
| 563 |
+
pooled_output = sequence_output[:, 0, :]
|
| 564 |
+
logits = self.classifier(pooled_output)
|
| 565 |
+
|
| 566 |
+
loss = None
|
| 567 |
+
if labels is not None:
|
| 568 |
+
loss = self.loss_function(labels, logits, self.config, **kwargs)
|
| 569 |
+
|
| 570 |
+
return ImageClassifierOutput(
|
| 571 |
+
loss=loss,
|
| 572 |
+
logits=logits,
|
| 573 |
+
hidden_states=outputs.hidden_states,
|
| 574 |
+
attentions=outputs.attentions,
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
@auto_docstring(
|
| 579 |
+
custom_intro="""
|
| 580 |
+
Output type of [`DeiTForImageClassificationWithTeacher`].
|
| 581 |
+
"""
|
| 582 |
+
)
|
| 583 |
+
@dataclass
|
| 584 |
+
class DeiTForImageClassificationWithTeacherOutput(ModelOutput):
|
| 585 |
+
r"""
|
| 586 |
+
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 587 |
+
Prediction scores as the average of the cls_logits and distillation logits.
|
| 588 |
+
cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 589 |
+
Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
|
| 590 |
+
class token).
|
| 591 |
+
distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 592 |
+
Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
|
| 593 |
+
distillation token).
|
| 594 |
+
"""
|
| 595 |
+
|
| 596 |
+
logits: torch.FloatTensor | None = None
|
| 597 |
+
cls_logits: torch.FloatTensor | None = None
|
| 598 |
+
distillation_logits: torch.FloatTensor | None = None
|
| 599 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 600 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
@auto_docstring(
|
| 604 |
+
custom_intro="""
|
| 605 |
+
DeiT Model transformer with image classification heads on top (a linear layer on top of the final hidden state of
|
| 606 |
+
the [CLS] token and a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet.
|
| 607 |
+
|
| 608 |
+
.. warning::
|
| 609 |
+
|
| 610 |
+
This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
|
| 611 |
+
supported.
|
| 612 |
+
"""
|
| 613 |
+
)
|
| 614 |
+
class DeiTForImageClassificationWithTeacher(DeiTPreTrainedModel):
|
| 615 |
+
def __init__(self, config: DeiTConfig) -> None:
|
| 616 |
+
super().__init__(config)
|
| 617 |
+
|
| 618 |
+
self.num_labels = config.num_labels
|
| 619 |
+
self.deit = DeiTModel(config, add_pooling_layer=False)
|
| 620 |
+
|
| 621 |
+
# Classifier heads
|
| 622 |
+
self.cls_classifier = (
|
| 623 |
+
nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 624 |
+
)
|
| 625 |
+
self.distillation_classifier = (
|
| 626 |
+
nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
# Initialize weights and apply final processing
|
| 630 |
+
self.post_init()
|
| 631 |
+
|
| 632 |
+
@can_return_tuple
|
| 633 |
+
@auto_docstring
|
| 634 |
+
def forward(
|
| 635 |
+
self,
|
| 636 |
+
pixel_values: torch.Tensor | None = None,
|
| 637 |
+
interpolate_pos_encoding: bool = False,
|
| 638 |
+
attention_mask: torch.Tensor | None = None,
|
| 639 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 640 |
+
) -> DeiTForImageClassificationWithTeacherOutput:
|
| 641 |
+
outputs: BaseModelOutputWithPooling = self.deit(
|
| 642 |
+
pixel_values,
|
| 643 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 644 |
+
attention_mask=attention_mask,
|
| 645 |
+
**kwargs,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
sequence_output = outputs.last_hidden_state
|
| 649 |
+
|
| 650 |
+
cls_logits = self.cls_classifier(sequence_output[:, 0, :])
|
| 651 |
+
distillation_logits = self.distillation_classifier(sequence_output[:, 1, :])
|
| 652 |
+
|
| 653 |
+
# during inference, return the average of both classifier predictions
|
| 654 |
+
logits = (cls_logits + distillation_logits) / 2
|
| 655 |
+
|
| 656 |
+
return DeiTForImageClassificationWithTeacherOutput(
|
| 657 |
+
logits=logits,
|
| 658 |
+
cls_logits=cls_logits,
|
| 659 |
+
distillation_logits=distillation_logits,
|
| 660 |
+
hidden_states=outputs.hidden_states,
|
| 661 |
+
attentions=outputs.attentions,
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
__all__ = [
|
| 666 |
+
"DeiTForImageClassification",
|
| 667 |
+
"DeiTForImageClassificationWithTeacher",
|
| 668 |
+
"DeiTForMaskedImageModeling",
|
| 669 |
+
"DeiTModel",
|
| 670 |
+
"DeiTPreTrainedModel",
|
| 671 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/configuration_imagegpt.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 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 |
+
"""OpenAI ImageGPT configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="openai/imagegpt-small")
|
| 23 |
+
@strict
|
| 24 |
+
class ImageGPTConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
|
| 27 |
+
Whether to additionally scale attention weights by `1 / layer_idx + 1`.
|
| 28 |
+
reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
|
| 29 |
+
Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
|
| 30 |
+
dot-product/softmax to float() when training with mixed precision.
|
| 31 |
+
|
| 32 |
+
Example:
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
>>> from transformers import ImageGPTConfig, ImageGPTModel
|
| 36 |
+
|
| 37 |
+
>>> # Initializing a ImageGPT configuration
|
| 38 |
+
>>> configuration = ImageGPTConfig()
|
| 39 |
+
|
| 40 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 41 |
+
>>> model = ImageGPTModel(configuration)
|
| 42 |
+
|
| 43 |
+
>>> # Accessing the model configuration
|
| 44 |
+
>>> configuration = model.config
|
| 45 |
+
```"""
|
| 46 |
+
|
| 47 |
+
model_type = "imagegpt"
|
| 48 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 49 |
+
attribute_map = {
|
| 50 |
+
"hidden_size": "n_embd",
|
| 51 |
+
"max_position_embeddings": "n_positions",
|
| 52 |
+
"num_attention_heads": "n_head",
|
| 53 |
+
"num_hidden_layers": "n_layer",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
vocab_size: int = 512 + 1 # add one for start of sentence (sos) token
|
| 57 |
+
n_positions: int = 32 * 32
|
| 58 |
+
n_embd: int = 512
|
| 59 |
+
n_layer: int = 24
|
| 60 |
+
n_head: int = 8
|
| 61 |
+
n_inner: int | None = None
|
| 62 |
+
activation_function: str = "quick_gelu"
|
| 63 |
+
resid_pdrop: float | int = 0.1
|
| 64 |
+
embd_pdrop: float | int = 0.1
|
| 65 |
+
attn_pdrop: float | int = 0.1
|
| 66 |
+
layer_norm_epsilon: float = 1e-5
|
| 67 |
+
initializer_range: float = 0.02
|
| 68 |
+
scale_attn_weights: bool = True
|
| 69 |
+
use_cache: bool = True
|
| 70 |
+
tie_word_embeddings: bool = False
|
| 71 |
+
scale_attn_by_inverse_layer_idx: bool = False
|
| 72 |
+
reorder_and_upcast_attn: bool = False
|
| 73 |
+
add_cross_attention: bool = False
|
| 74 |
+
pad_token_id: int | None = None
|
| 75 |
+
bos_token_id: int | None = None
|
| 76 |
+
eos_token_id: int | list[int] | None = None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
__all__ = ["ImageGPTConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/image_processing_imagegpt.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Image processor class for ImageGPT."""
|
| 15 |
+
|
| 16 |
+
from typing import Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from torchvision.transforms.v2 import functional as tvF
|
| 21 |
+
|
| 22 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 23 |
+
from ...image_processing_utils import BatchFeature
|
| 24 |
+
from ...image_transforms import group_images_by_shape, reorder_images
|
| 25 |
+
from ...image_utils import PILImageResampling, SizeDict
|
| 26 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 27 |
+
from ...utils import (
|
| 28 |
+
TensorType,
|
| 29 |
+
auto_docstring,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ImageGPTImageProcessorKwargs(ImagesKwargs, total=False):
|
| 34 |
+
r"""
|
| 35 |
+
clusters (`np.ndarray` or `list[list[int]]` or `torch.Tensor`, *optional*, defaults to `self.clusters`):
|
| 36 |
+
The color clusters to use, of shape `(n_clusters, 3)` when color quantizing. Can be overridden by `clusters`
|
| 37 |
+
in `preprocess`.
|
| 38 |
+
do_color_quantize (`bool`, *optional*, defaults to `self.do_color_quantize`):
|
| 39 |
+
Controls whether to apply color quantization to convert continuous pixel values to discrete cluster indices.
|
| 40 |
+
When True, each pixel is assigned to its nearest color cluster, enabling ImageGPT's discrete token modeling.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
clusters: Union[np.ndarray, list[list[int]], "torch.Tensor"] | None
|
| 44 |
+
do_color_quantize: bool
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def squared_euclidean_distance_torch(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
|
| 48 |
+
"""
|
| 49 |
+
Compute squared Euclidean distances between all pixels and clusters.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
a: (N, 3) tensor of pixel RGB values
|
| 53 |
+
b: (M, 3) tensor of cluster RGB values
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
(N, M) tensor of squared distances
|
| 57 |
+
"""
|
| 58 |
+
b = b.t() # (3, M)
|
| 59 |
+
a2 = torch.sum(a**2, dim=1) # (N,)
|
| 60 |
+
b2 = torch.sum(b**2, dim=0) # (M,)
|
| 61 |
+
ab = torch.matmul(a, b) # (N, M)
|
| 62 |
+
d = a2[:, None] - 2 * ab + b2[None, :] # Squared Euclidean Distance: a^2 - 2ab + b^2
|
| 63 |
+
return d # (N, M) tensor of squared distances
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def color_quantize_torch(x: torch.Tensor, clusters: torch.Tensor) -> torch.Tensor:
|
| 67 |
+
"""
|
| 68 |
+
Assign each pixel to its nearest color cluster.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
x: (H*W, 3) tensor of flattened pixel RGB values
|
| 72 |
+
clusters: (n_clusters, 3) tensor of cluster RGB values
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
(H*W,) tensor of cluster indices
|
| 76 |
+
"""
|
| 77 |
+
d = squared_euclidean_distance_torch(x, clusters)
|
| 78 |
+
return torch.argmin(d, dim=1)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@auto_docstring
|
| 82 |
+
class ImageGPTImageProcessor(TorchvisionBackend):
|
| 83 |
+
model_input_names = ["input_ids"]
|
| 84 |
+
valid_kwargs = ImageGPTImageProcessorKwargs
|
| 85 |
+
resample = PILImageResampling.BILINEAR
|
| 86 |
+
do_color_quantize = True
|
| 87 |
+
clusters = None
|
| 88 |
+
image_mean = [0.5, 0.5, 0.5]
|
| 89 |
+
image_std = [0.5, 0.5, 0.5]
|
| 90 |
+
do_rescale = True
|
| 91 |
+
do_normalize = True
|
| 92 |
+
size = {"height": 256, "width": 256}
|
| 93 |
+
do_resize = True
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
clusters: list | np.ndarray | torch.Tensor | None = None, # keep as arg for backwards compatibility
|
| 98 |
+
**kwargs: Unpack[ImageGPTImageProcessorKwargs],
|
| 99 |
+
):
|
| 100 |
+
r"""
|
| 101 |
+
clusters (`np.ndarray` or `list[list[int]]` or `torch.Tensor`, *optional*):
|
| 102 |
+
The color clusters to use, of shape `(n_clusters, 3)` when color quantizing. Can be overridden by `clusters`
|
| 103 |
+
in `preprocess`.
|
| 104 |
+
"""
|
| 105 |
+
clusters = torch.as_tensor(clusters, dtype=torch.float32) if clusters is not None else None
|
| 106 |
+
super().__init__(clusters=clusters, **kwargs)
|
| 107 |
+
|
| 108 |
+
def _preprocess(
|
| 109 |
+
self,
|
| 110 |
+
images: list["torch.Tensor"],
|
| 111 |
+
do_resize: bool,
|
| 112 |
+
size: SizeDict,
|
| 113 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 114 |
+
do_center_crop: bool,
|
| 115 |
+
crop_size: SizeDict,
|
| 116 |
+
do_rescale: bool,
|
| 117 |
+
rescale_factor: float,
|
| 118 |
+
do_normalize: bool,
|
| 119 |
+
image_mean: float | list[float] | None,
|
| 120 |
+
image_std: float | list[float] | None,
|
| 121 |
+
disable_grouping: bool | None,
|
| 122 |
+
return_tensors: str | TensorType | None,
|
| 123 |
+
do_color_quantize: bool | None = None,
|
| 124 |
+
clusters: list | np.ndarray | torch.Tensor | None = None,
|
| 125 |
+
**kwargs,
|
| 126 |
+
):
|
| 127 |
+
# Group images by size for batched resizing
|
| 128 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 129 |
+
resized_images_grouped = {}
|
| 130 |
+
for shape, stacked_images in grouped_images.items():
|
| 131 |
+
if do_resize:
|
| 132 |
+
stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
|
| 133 |
+
resized_images_grouped[shape] = stacked_images
|
| 134 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 135 |
+
|
| 136 |
+
# Group images by size for further processing
|
| 137 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 138 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 139 |
+
processed_images_grouped = {}
|
| 140 |
+
for shape, stacked_images in grouped_images.items():
|
| 141 |
+
if do_center_crop:
|
| 142 |
+
stacked_images = self.center_crop(stacked_images, crop_size)
|
| 143 |
+
# Fused rescale and normalize
|
| 144 |
+
stacked_images = self.rescale_and_normalize(
|
| 145 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 146 |
+
)
|
| 147 |
+
processed_images_grouped[shape] = stacked_images
|
| 148 |
+
|
| 149 |
+
pixel_values = reorder_images(processed_images_grouped, grouped_images_index)
|
| 150 |
+
|
| 151 |
+
# If color quantization is requested, perform it; otherwise return pixel values
|
| 152 |
+
if do_color_quantize:
|
| 153 |
+
# Prepare clusters
|
| 154 |
+
if clusters is None:
|
| 155 |
+
raise ValueError("Clusters must be provided for color quantization.")
|
| 156 |
+
# Convert to torch tensor if needed (clusters might be passed as list/numpy)
|
| 157 |
+
clusters_torch = (
|
| 158 |
+
torch.as_tensor(clusters, dtype=torch.float32) if not isinstance(clusters, torch.Tensor) else clusters
|
| 159 |
+
).to(pixel_values[0].device, dtype=pixel_values[0].dtype)
|
| 160 |
+
|
| 161 |
+
# Group images by shape for batch processing
|
| 162 |
+
# We need to check if the pixel values are a tensor or a list of tensors
|
| 163 |
+
grouped_images, grouped_images_index = group_images_by_shape(
|
| 164 |
+
pixel_values, disable_grouping=disable_grouping
|
| 165 |
+
)
|
| 166 |
+
# Process each group
|
| 167 |
+
input_ids_grouped = {}
|
| 168 |
+
|
| 169 |
+
for shape, stacked_images in grouped_images.items():
|
| 170 |
+
input_ids = color_quantize_torch(
|
| 171 |
+
stacked_images.permute(0, 2, 3, 1).reshape(-1, 3), clusters_torch
|
| 172 |
+
) # (B*H*W, C)
|
| 173 |
+
input_ids_grouped[shape] = input_ids.reshape(stacked_images.shape[0], -1).reshape(
|
| 174 |
+
stacked_images.shape[0], -1
|
| 175 |
+
) # (B, H, W)
|
| 176 |
+
|
| 177 |
+
input_ids = reorder_images(input_ids_grouped, grouped_images_index)
|
| 178 |
+
|
| 179 |
+
return BatchFeature(data={"input_ids": input_ids}, tensor_type=return_tensors)
|
| 180 |
+
|
| 181 |
+
return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors)
|
| 182 |
+
|
| 183 |
+
def to_dict(self):
|
| 184 |
+
# Convert torch tensors to lists for JSON serialization
|
| 185 |
+
output = super().to_dict()
|
| 186 |
+
if output.get("clusters") is not None and isinstance(output["clusters"], torch.Tensor):
|
| 187 |
+
output["clusters"] = output["clusters"].tolist()
|
| 188 |
+
|
| 189 |
+
return output
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
__all__ = ["ImageGPTImageProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/image_processing_pil_imagegpt.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Image processor class for ImageGPT."""
|
| 15 |
+
|
| 16 |
+
from typing import Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from ...image_processing_backends import PilBackend
|
| 21 |
+
from ...image_processing_utils import BatchFeature
|
| 22 |
+
from ...image_utils import (
|
| 23 |
+
PILImageResampling,
|
| 24 |
+
SizeDict,
|
| 25 |
+
)
|
| 26 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 27 |
+
from ...utils import (
|
| 28 |
+
TensorType,
|
| 29 |
+
auto_docstring,
|
| 30 |
+
is_torch_available,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_torch_available():
|
| 35 |
+
import torch
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def squared_euclidean_distance(a, b):
|
| 39 |
+
b = b.T
|
| 40 |
+
a2 = np.sum(np.square(a), axis=1)
|
| 41 |
+
b2 = np.sum(np.square(b), axis=0)
|
| 42 |
+
ab = np.matmul(a, b)
|
| 43 |
+
d = a2[:, None] - 2 * ab + b2[None, :]
|
| 44 |
+
return d
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def color_quantize(x, clusters):
|
| 48 |
+
x = x.reshape(-1, 3)
|
| 49 |
+
d = squared_euclidean_distance(x, clusters)
|
| 50 |
+
return np.argmin(d, axis=1)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Adapted from transformers.models.imagegpt.image_processing_imagegpt.ImageGPTImageProcessorKwargs
|
| 54 |
+
class ImageGPTImageProcessorKwargs(ImagesKwargs, total=False):
|
| 55 |
+
r"""
|
| 56 |
+
clusters (`np.ndarray` or `list[list[int]]` or `torch.Tensor`, *optional*, defaults to `self.clusters`):
|
| 57 |
+
The color clusters to use, of shape `(n_clusters, 3)` when color quantizing. Can be overridden by `clusters`
|
| 58 |
+
in `preprocess`.
|
| 59 |
+
do_color_quantize (`bool`, *optional*, defaults to `self.do_color_quantize`):
|
| 60 |
+
Controls whether to apply color quantization to convert continuous pixel values to discrete cluster indices.
|
| 61 |
+
When True, each pixel is assigned to its nearest color cluster, enabling ImageGPT's discrete token modeling.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
clusters: Union[np.ndarray, list[list[int]], "torch.Tensor"] | None
|
| 65 |
+
do_color_quantize: bool
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@auto_docstring
|
| 69 |
+
class ImageGPTImageProcessorPil(PilBackend):
|
| 70 |
+
model_input_names = ["input_ids"]
|
| 71 |
+
valid_kwargs = ImageGPTImageProcessorKwargs
|
| 72 |
+
resample = PILImageResampling.BILINEAR
|
| 73 |
+
do_color_quantize = True
|
| 74 |
+
clusters = None
|
| 75 |
+
image_mean = [0.5, 0.5, 0.5]
|
| 76 |
+
image_std = [0.5, 0.5, 0.5]
|
| 77 |
+
do_rescale = True
|
| 78 |
+
do_normalize = True
|
| 79 |
+
size = {"height": 256, "width": 256}
|
| 80 |
+
do_resize = True
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
clusters: "list | np.ndarray | torch.Tensor | None" = None, # keep as arg for backwards compatibility
|
| 85 |
+
**kwargs: Unpack[ImageGPTImageProcessorKwargs],
|
| 86 |
+
):
|
| 87 |
+
r"""
|
| 88 |
+
clusters (`np.ndarray` or `list[list[int]]` or `torch.Tensor`, *optional*):
|
| 89 |
+
The color clusters to use, of shape `(n_clusters, 3)` when color quantizing. Can be overridden by `clusters`
|
| 90 |
+
in `preprocess`.
|
| 91 |
+
"""
|
| 92 |
+
if clusters is not None:
|
| 93 |
+
clusters = np.array(clusters)
|
| 94 |
+
super().__init__(clusters=clusters, **kwargs)
|
| 95 |
+
|
| 96 |
+
def _preprocess(
|
| 97 |
+
self,
|
| 98 |
+
images: list[np.ndarray],
|
| 99 |
+
do_resize: bool,
|
| 100 |
+
size: SizeDict,
|
| 101 |
+
resample: "PILImageResampling | None",
|
| 102 |
+
do_rescale: bool,
|
| 103 |
+
rescale_factor: float,
|
| 104 |
+
do_normalize: bool,
|
| 105 |
+
image_mean: float | list[float] | None,
|
| 106 |
+
image_std: float | list[float] | None,
|
| 107 |
+
return_tensors: str | TensorType | None,
|
| 108 |
+
do_color_quantize: bool | None = None,
|
| 109 |
+
clusters: "list | np.ndarray | torch.Tensor | None" = None,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
processed_images = []
|
| 113 |
+
for image in images:
|
| 114 |
+
if do_resize:
|
| 115 |
+
image = self.resize(image, size, resample)
|
| 116 |
+
if do_rescale:
|
| 117 |
+
image = self.rescale(image, rescale_factor)
|
| 118 |
+
if do_normalize:
|
| 119 |
+
image = self.normalize(image, image_mean, image_std)
|
| 120 |
+
processed_images.append(image)
|
| 121 |
+
|
| 122 |
+
# If color quantization is requested, perform it; otherwise return pixel values
|
| 123 |
+
if do_color_quantize:
|
| 124 |
+
# Prepare clusters
|
| 125 |
+
if clusters is None:
|
| 126 |
+
raise ValueError("Clusters must be provided for color quantization.")
|
| 127 |
+
# Convert to numpy array if needed
|
| 128 |
+
clusters_np = np.array(clusters) if not isinstance(clusters, np.ndarray) else clusters
|
| 129 |
+
|
| 130 |
+
# Stack channel-first images (B, C, H, W) and transpose to (B, H, W, C) for color quantization
|
| 131 |
+
images_array = np.array(processed_images)
|
| 132 |
+
images_hwc = images_array.transpose(0, 2, 3, 1)
|
| 133 |
+
input_ids = color_quantize(images_hwc, clusters_np).reshape(
|
| 134 |
+
images_array.shape[0], images_array.shape[2], images_array.shape[3]
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# flatten to (batch_size, height*width)
|
| 138 |
+
batch_size = input_ids.shape[0]
|
| 139 |
+
input_ids = input_ids.reshape(batch_size, -1)
|
| 140 |
+
|
| 141 |
+
# We need to convert back to a list to keep consistent behaviour across processors.
|
| 142 |
+
input_ids = list(input_ids)
|
| 143 |
+
return BatchFeature(data={"input_ids": input_ids}, tensor_type=return_tensors)
|
| 144 |
+
|
| 145 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 146 |
+
|
| 147 |
+
def to_dict(self):
|
| 148 |
+
output = super().to_dict()
|
| 149 |
+
if output.get("clusters") is not None and isinstance(output["clusters"], np.ndarray | torch.Tensor):
|
| 150 |
+
output["clusters"] = output["clusters"].tolist()
|
| 151 |
+
|
| 152 |
+
return output
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
__all__ = ["ImageGPTImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilenet_v1/image_processing_mobilenet_v1.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Image processor class for MobileNetV1."""
|
| 15 |
+
|
| 16 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 17 |
+
from ...image_utils import (
|
| 18 |
+
IMAGENET_STANDARD_MEAN,
|
| 19 |
+
IMAGENET_STANDARD_STD,
|
| 20 |
+
PILImageResampling,
|
| 21 |
+
)
|
| 22 |
+
from ...utils import auto_docstring
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@auto_docstring(custom_intro="Constructs a MobileNetV1 image processor.")
|
| 26 |
+
class MobileNetV1ImageProcessor(TorchvisionBackend):
|
| 27 |
+
resample = PILImageResampling.BILINEAR
|
| 28 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 29 |
+
image_std = IMAGENET_STANDARD_STD
|
| 30 |
+
size = {"shortest_edge": 256}
|
| 31 |
+
default_to_square = False
|
| 32 |
+
crop_size = {"height": 224, "width": 224}
|
| 33 |
+
do_resize = True
|
| 34 |
+
do_center_crop = True
|
| 35 |
+
do_rescale = True
|
| 36 |
+
do_normalize = True
|
| 37 |
+
do_convert_rgb = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
__all__ = ["MobileNetV1ImageProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilenet_v1/image_processing_pil_mobilenet_v1.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Image processor class for MobileNetV1."""
|
| 15 |
+
|
| 16 |
+
from ...image_processing_backends import PilBackend
|
| 17 |
+
from ...image_utils import (
|
| 18 |
+
IMAGENET_STANDARD_MEAN,
|
| 19 |
+
IMAGENET_STANDARD_STD,
|
| 20 |
+
PILImageResampling,
|
| 21 |
+
)
|
| 22 |
+
from ...utils import auto_docstring
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@auto_docstring(custom_intro="Constructs a MobileNetV1 image processor.")
|
| 26 |
+
class MobileNetV1ImageProcessorPil(PilBackend):
|
| 27 |
+
resample = PILImageResampling.BILINEAR
|
| 28 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 29 |
+
image_std = IMAGENET_STANDARD_STD
|
| 30 |
+
size = {"shortest_edge": 256}
|
| 31 |
+
default_to_square = False
|
| 32 |
+
crop_size = {"height": 224, "width": 224}
|
| 33 |
+
do_resize = True
|
| 34 |
+
do_center_crop = True
|
| 35 |
+
do_rescale = True
|
| 36 |
+
do_normalize = True
|
| 37 |
+
do_convert_rgb = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
__all__ = ["MobileNetV1ImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 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 typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import _LazyModule
|
| 18 |
+
from ...utils.import_utils import define_import_structure
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from .configuration_slanet import *
|
| 23 |
+
from .modeling_slanet import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
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/slanet/configuration_slanet.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/slanet/modular_slanet.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_slanet.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
from huggingface_hub.dataclasses import strict
|
| 23 |
+
|
| 24 |
+
from ...backbone_utils import consolidate_backbone_kwargs_to_config
|
| 25 |
+
from ...configuration_utils import PreTrainedConfig
|
| 26 |
+
from ...utils import auto_docstring
|
| 27 |
+
from ..auto import AutoConfig
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@auto_docstring(checkpoint="PaddlePaddle/SLANet_plus_safetensors")
|
| 31 |
+
@strict
|
| 32 |
+
class SLANetConfig(PreTrainedConfig):
|
| 33 |
+
r"""
|
| 34 |
+
post_conv_out_channels (`int`, *optional*, defaults to 96):
|
| 35 |
+
Number of output channels for the post-encoder convolution layer.
|
| 36 |
+
out_channels (`int`, *optional*, defaults to 50):
|
| 37 |
+
Vocabulary size for the table structure token prediction head, i.e., the number of distinct structure
|
| 38 |
+
tokens the model can predict.
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 256):
|
| 40 |
+
Dimensionality of the hidden states in the attention GRU cell and the structure/location prediction heads.
|
| 41 |
+
max_text_length (`int`, *optional*, defaults to 500):
|
| 42 |
+
Maximum number of autoregressive decoding steps (tokens) for the structure and location decoder.
|
| 43 |
+
csp_kernel_size (`int`, *optional*, defaults to 5):
|
| 44 |
+
The kernel size of the Cross Stage Partial (CSP) layer.
|
| 45 |
+
csp_num_blocks (`int`, *optional*, defaults to 1):
|
| 46 |
+
Number of blocks within the Cross Stage Partial (CSP) layer.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
model_type = "slanet"
|
| 50 |
+
|
| 51 |
+
sub_configs = {"backbone_config": AutoConfig}
|
| 52 |
+
post_conv_out_channels: int = 96
|
| 53 |
+
out_channels: int = 50
|
| 54 |
+
hidden_size: int = 256
|
| 55 |
+
max_text_length: int = 500
|
| 56 |
+
backbone_config: dict | PreTrainedConfig | None = None
|
| 57 |
+
|
| 58 |
+
hidden_act: str = "hardswish"
|
| 59 |
+
csp_kernel_size: int = 5
|
| 60 |
+
csp_num_blocks: int = 1
|
| 61 |
+
|
| 62 |
+
def __post_init__(self, **kwargs):
|
| 63 |
+
self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
|
| 64 |
+
backbone_config=self.backbone_config,
|
| 65 |
+
default_config_type="pp_lcnet",
|
| 66 |
+
default_config_kwargs={
|
| 67 |
+
"scale": 1,
|
| 68 |
+
"out_features": ["stage2", "stage3", "stage4", "stage5"],
|
| 69 |
+
"out_indices": [2, 3, 4, 5],
|
| 70 |
+
"divisor": 16,
|
| 71 |
+
},
|
| 72 |
+
**kwargs,
|
| 73 |
+
)
|
| 74 |
+
super().__post_init__(**kwargs)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
__all__ = ["SLANetConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/modeling_slanet.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/slanet/modular_slanet.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_slanet.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
|
| 29 |
+
from ... import initialization as init
|
| 30 |
+
from ...activations import ACT2CLS, ACT2FN
|
| 31 |
+
from ...backbone_utils import filter_output_hidden_states, load_backbone
|
| 32 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 33 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithNoAttention
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...processing_utils import Unpack
|
| 36 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 37 |
+
from ...utils.generic import merge_with_config_defaults
|
| 38 |
+
from ...utils.output_capturing import capture_outputs
|
| 39 |
+
from .configuration_slanet import SLANetConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class SLANetPreTrainedModel(PreTrainedModel):
|
| 43 |
+
config: SLANetConfig
|
| 44 |
+
base_model_prefix = "backbone"
|
| 45 |
+
main_input_name = "pixel_values"
|
| 46 |
+
input_modalities = ("image",)
|
| 47 |
+
supports_gradient_checkpointing = True
|
| 48 |
+
_keep_in_fp32_modules_strict = []
|
| 49 |
+
|
| 50 |
+
@torch.no_grad()
|
| 51 |
+
def _init_weights(self, module):
|
| 52 |
+
"""Initialize the weights"""
|
| 53 |
+
super()._init_weights(module)
|
| 54 |
+
|
| 55 |
+
# Initialize GRUCell (replicates PyTorch default reset_parameters)
|
| 56 |
+
if isinstance(module, nn.GRUCell):
|
| 57 |
+
std = 1.0 / math.sqrt(module.hidden_size) if module.hidden_size > 0 else 0
|
| 58 |
+
init.uniform_(module.weight_ih, -std, std)
|
| 59 |
+
init.uniform_(module.weight_hh, -std, std)
|
| 60 |
+
if module.bias_ih is not None:
|
| 61 |
+
init.uniform_(module.bias_ih, -std, std)
|
| 62 |
+
if module.bias_hh is not None:
|
| 63 |
+
init.uniform_(module.bias_hh, -std, std)
|
| 64 |
+
|
| 65 |
+
# Initialize SLAHead layers
|
| 66 |
+
if isinstance(module, SLANetSLAHead):
|
| 67 |
+
std = 1.0 / math.sqrt(self.config.hidden_size * 1.0)
|
| 68 |
+
# Initialize structure_generator and loc_generator layers
|
| 69 |
+
for generator in (module.structure_generator,):
|
| 70 |
+
for layer in generator.children():
|
| 71 |
+
if isinstance(layer, nn.Linear):
|
| 72 |
+
init.uniform_(layer.weight, -std, std)
|
| 73 |
+
if layer.bias is not None:
|
| 74 |
+
init.uniform_(layer.bias, -std, std)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@auto_docstring
|
| 78 |
+
@dataclass
|
| 79 |
+
class SLANetForTableRecognitionOutput(BaseModelOutputWithNoAttention):
|
| 80 |
+
r"""
|
| 81 |
+
head_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 82 |
+
Hidden-states of the SLANetSLAHead at each prediction step, varies up to max `self.config.max_text_length` states (depending on early exits).
|
| 83 |
+
head_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 84 |
+
Attentions of the SLANetSLAHead at each prediction step, varies up to max `self.config.max_text_length` attentions (depending on early exits).
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
head_hidden_states: torch.FloatTensor | None = None
|
| 88 |
+
head_attentions: torch.FloatTensor | None = None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class SLANetAttentionGRUCell(nn.Module):
|
| 92 |
+
def __init__(self, input_size, hidden_size, num_embeddings):
|
| 93 |
+
super().__init__()
|
| 94 |
+
|
| 95 |
+
self.input_to_hidden = nn.Linear(input_size, hidden_size, bias=False)
|
| 96 |
+
self.hidden_to_hidden = nn.Linear(hidden_size, hidden_size)
|
| 97 |
+
self.score = nn.Linear(hidden_size, 1, bias=False)
|
| 98 |
+
|
| 99 |
+
self.rnn = nn.GRUCell(input_size + num_embeddings, hidden_size)
|
| 100 |
+
|
| 101 |
+
def forward(
|
| 102 |
+
self,
|
| 103 |
+
prev_hidden: torch.FloatTensor,
|
| 104 |
+
batch_hidden: torch.FloatTensor,
|
| 105 |
+
char_onehots: torch.FloatTensor,
|
| 106 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 107 |
+
):
|
| 108 |
+
batch_hidden_proj = self.input_to_hidden(batch_hidden)
|
| 109 |
+
prev_hidden_proj = self.hidden_to_hidden(prev_hidden).unsqueeze(1)
|
| 110 |
+
|
| 111 |
+
attention_scores = batch_hidden_proj + prev_hidden_proj
|
| 112 |
+
attention_scores = torch.tanh(attention_scores)
|
| 113 |
+
attention_scores = self.score(attention_scores)
|
| 114 |
+
|
| 115 |
+
attn_weights = F.softmax(attention_scores, dim=1, dtype=torch.float32).to(attention_scores.dtype)
|
| 116 |
+
attn_weights = attn_weights.transpose(1, 2)
|
| 117 |
+
context = torch.matmul(attn_weights, batch_hidden).squeeze(1)
|
| 118 |
+
concat_context = torch.cat([context, char_onehots], 1)
|
| 119 |
+
hidden_states = self.rnn(concat_context, prev_hidden)
|
| 120 |
+
|
| 121 |
+
return hidden_states, attn_weights
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class SLANetMLP(nn.Module):
|
| 125 |
+
def __init__(self, hidden_size, out_channels, activation=None):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.fc1 = nn.Linear(hidden_size, hidden_size)
|
| 128 |
+
self.fc2 = nn.Linear(hidden_size, out_channels)
|
| 129 |
+
self.act_fn = nn.Identity() if activation is None else ACT2CLS[activation]()
|
| 130 |
+
|
| 131 |
+
def forward(self, hidden_states):
|
| 132 |
+
hidden_states = self.fc1(hidden_states)
|
| 133 |
+
hidden_states = self.fc2(hidden_states)
|
| 134 |
+
hidden_states = self.act_fn(hidden_states)
|
| 135 |
+
return hidden_states
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class SLANetSLAHead(SLANetPreTrainedModel):
|
| 139 |
+
_can_record_outputs = {
|
| 140 |
+
"attentions": SLANetAttentionGRUCell,
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
config: dict | None = None,
|
| 146 |
+
**kwargs,
|
| 147 |
+
):
|
| 148 |
+
super().__init__(config)
|
| 149 |
+
|
| 150 |
+
self.structure_attention_cell = SLANetAttentionGRUCell(
|
| 151 |
+
config.post_conv_out_channels, config.hidden_size, config.out_channels
|
| 152 |
+
)
|
| 153 |
+
self.structure_generator = SLANetMLP(config.hidden_size, config.out_channels)
|
| 154 |
+
|
| 155 |
+
self.post_init()
|
| 156 |
+
|
| 157 |
+
@merge_with_config_defaults
|
| 158 |
+
@capture_outputs
|
| 159 |
+
@filter_output_hidden_states
|
| 160 |
+
def forward(
|
| 161 |
+
self,
|
| 162 |
+
hidden_states: torch.FloatTensor,
|
| 163 |
+
targets: torch.Tensor | None = None,
|
| 164 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 165 |
+
):
|
| 166 |
+
features = torch.zeros(
|
| 167 |
+
(hidden_states.shape[0], self.config.hidden_size), dtype=torch.float32, device=hidden_states.device
|
| 168 |
+
)
|
| 169 |
+
predicted_chars = torch.zeros(size=[hidden_states.shape[0]], dtype=torch.long, device=hidden_states.device)
|
| 170 |
+
|
| 171 |
+
structure_preds_list = []
|
| 172 |
+
structure_ids_list = []
|
| 173 |
+
for _ in range(self.config.max_text_length + 1):
|
| 174 |
+
embedding_feature = F.one_hot(predicted_chars, self.config.out_channels).float()
|
| 175 |
+
features, _ = self.structure_attention_cell(features, hidden_states.float(), embedding_feature)
|
| 176 |
+
structure_step = self.structure_generator(features)
|
| 177 |
+
predicted_chars = structure_step.argmax(dim=1)
|
| 178 |
+
|
| 179 |
+
structure_preds_list.append(structure_step)
|
| 180 |
+
structure_ids_list.append(predicted_chars)
|
| 181 |
+
if torch.stack(structure_ids_list, dim=1).eq(self.config.out_channels - 1).any(-1).all():
|
| 182 |
+
break
|
| 183 |
+
structure_preds = F.softmax(torch.stack(structure_preds_list, dim=1), dim=-1, dtype=torch.float32).to(
|
| 184 |
+
hidden_states.dtype
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
return BaseModelOutput(last_hidden_state=structure_preds, hidden_states=structure_preds_list)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class SLANetConvLayer(nn.Module):
|
| 191 |
+
def __init__(
|
| 192 |
+
self,
|
| 193 |
+
in_channels: int,
|
| 194 |
+
out_channels: int,
|
| 195 |
+
kernel_size: int = 3,
|
| 196 |
+
stride: int = 1,
|
| 197 |
+
bias: bool = False,
|
| 198 |
+
dilation: int | tuple[int, int] = 1,
|
| 199 |
+
groups: int = 1,
|
| 200 |
+
activation: str = "hardswish",
|
| 201 |
+
):
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.convolution = nn.Conv2d(
|
| 204 |
+
in_channels=in_channels,
|
| 205 |
+
out_channels=out_channels,
|
| 206 |
+
kernel_size=kernel_size,
|
| 207 |
+
stride=stride,
|
| 208 |
+
padding=kernel_size // 2,
|
| 209 |
+
bias=bias,
|
| 210 |
+
dilation=dilation,
|
| 211 |
+
groups=groups,
|
| 212 |
+
)
|
| 213 |
+
self.normalization = nn.BatchNorm2d(out_channels)
|
| 214 |
+
self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
|
| 215 |
+
|
| 216 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 217 |
+
hidden_states = self.convolution(hidden_states)
|
| 218 |
+
hidden_states = self.normalization(hidden_states)
|
| 219 |
+
hidden_states = self.activation(hidden_states)
|
| 220 |
+
return hidden_states
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class SLANetDepthwiseSeparableConvLayer(GradientCheckpointingLayer):
|
| 224 |
+
"""
|
| 225 |
+
Depthwise Separable Convolution Layer: Depthwise Conv -> Pointwise Conv
|
| 226 |
+
Core component of lightweight models (e.g., MobileNet, PP-LCNet) that significantly reduces
|
| 227 |
+
the number of parameters and computational cost.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def __init__(
|
| 231 |
+
self,
|
| 232 |
+
in_channels,
|
| 233 |
+
out_channels,
|
| 234 |
+
stride,
|
| 235 |
+
kernel_size,
|
| 236 |
+
config,
|
| 237 |
+
):
|
| 238 |
+
super().__init__()
|
| 239 |
+
self.depthwise_convolution = SLANetConvLayer(
|
| 240 |
+
in_channels=in_channels,
|
| 241 |
+
out_channels=in_channels,
|
| 242 |
+
kernel_size=kernel_size,
|
| 243 |
+
stride=stride,
|
| 244 |
+
groups=in_channels,
|
| 245 |
+
activation=config.hidden_act,
|
| 246 |
+
)
|
| 247 |
+
self.squeeze_excitation_module = nn.Identity()
|
| 248 |
+
self.pointwise_convolution = SLANetConvLayer(
|
| 249 |
+
in_channels=in_channels,
|
| 250 |
+
kernel_size=1,
|
| 251 |
+
out_channels=out_channels,
|
| 252 |
+
stride=1,
|
| 253 |
+
activation=config.hidden_act,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
def forward(self, hidden_state):
|
| 257 |
+
hidden_state = self.depthwise_convolution(hidden_state)
|
| 258 |
+
hidden_state = self.squeeze_excitation_module(hidden_state)
|
| 259 |
+
hidden_state = self.pointwise_convolution(hidden_state)
|
| 260 |
+
|
| 261 |
+
return hidden_state
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class SLANetBottleneck(nn.Module):
|
| 265 |
+
def __init__(
|
| 266 |
+
self,
|
| 267 |
+
in_channels,
|
| 268 |
+
out_channels,
|
| 269 |
+
kernel_size,
|
| 270 |
+
activation,
|
| 271 |
+
config,
|
| 272 |
+
):
|
| 273 |
+
super().__init__()
|
| 274 |
+
self.conv1 = SLANetConvLayer(
|
| 275 |
+
in_channels=in_channels, out_channels=out_channels, kernel_size=1, activation=activation
|
| 276 |
+
)
|
| 277 |
+
self.conv2 = SLANetDepthwiseSeparableConvLayer(
|
| 278 |
+
in_channels=out_channels,
|
| 279 |
+
out_channels=out_channels,
|
| 280 |
+
kernel_size=kernel_size,
|
| 281 |
+
stride=1,
|
| 282 |
+
config=config,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 286 |
+
hidden_states = self.conv1(hidden_states)
|
| 287 |
+
hidden_states = self.conv2(hidden_states)
|
| 288 |
+
|
| 289 |
+
return hidden_states
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class SLANetCSPLayer(nn.Module):
|
| 293 |
+
"""
|
| 294 |
+
Cross Stage Partial (CSP) network layer. Similar in structure to DFineCSPRepLayer, but with a different forward computation.
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
def __init__(
|
| 298 |
+
self,
|
| 299 |
+
config,
|
| 300 |
+
in_channels,
|
| 301 |
+
out_channels,
|
| 302 |
+
kernel_size=3,
|
| 303 |
+
expansion=0.5,
|
| 304 |
+
num_blocks=1,
|
| 305 |
+
activation="hardswish",
|
| 306 |
+
):
|
| 307 |
+
super().__init__()
|
| 308 |
+
hidden_channels = int(out_channels * expansion)
|
| 309 |
+
self.conv1 = SLANetConvLayer(in_channels, hidden_channels, 1, activation=activation)
|
| 310 |
+
self.conv2 = SLANetConvLayer(in_channels, hidden_channels, 1, activation=activation)
|
| 311 |
+
self.conv3 = SLANetConvLayer(2 * hidden_channels, out_channels, 1, activation=activation)
|
| 312 |
+
self.bottlenecks = nn.ModuleList(
|
| 313 |
+
[
|
| 314 |
+
SLANetBottleneck(hidden_channels, hidden_channels, kernel_size, activation, config)
|
| 315 |
+
for _ in range(num_blocks)
|
| 316 |
+
]
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 320 |
+
residual = self.conv1(hidden_states)
|
| 321 |
+
|
| 322 |
+
hidden_states = self.conv2(hidden_states)
|
| 323 |
+
for bottleneck in self.bottlenecks:
|
| 324 |
+
hidden_states = bottleneck(hidden_states)
|
| 325 |
+
|
| 326 |
+
hidden_states = torch.cat((hidden_states, residual), dim=1)
|
| 327 |
+
hidden_states = self.conv3(hidden_states)
|
| 328 |
+
|
| 329 |
+
return hidden_states
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class SLANetCSPPAN(nn.Module):
|
| 333 |
+
"""
|
| 334 |
+
CSP-PAN: Path Aggregation Network with CSP layers
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
def __init__(
|
| 338 |
+
self,
|
| 339 |
+
config,
|
| 340 |
+
in_channel_list,
|
| 341 |
+
):
|
| 342 |
+
super().__init__()
|
| 343 |
+
out_channels = config.post_conv_out_channels
|
| 344 |
+
activation = config.hidden_act
|
| 345 |
+
kernel_size = config.csp_kernel_size
|
| 346 |
+
csp_num_blocks = config.csp_num_blocks
|
| 347 |
+
|
| 348 |
+
self.channel_projector = nn.ModuleList(
|
| 349 |
+
[
|
| 350 |
+
SLANetConvLayer(
|
| 351 |
+
in_channels=in_channel_list[i], out_channels=out_channels, kernel_size=1, activation=activation
|
| 352 |
+
)
|
| 353 |
+
for i in range(len(in_channel_list))
|
| 354 |
+
]
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
# build top-down blocks
|
| 358 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
|
| 359 |
+
self.top_down_blocks = nn.ModuleList(
|
| 360 |
+
[
|
| 361 |
+
SLANetCSPLayer(
|
| 362 |
+
config,
|
| 363 |
+
out_channels * 2,
|
| 364 |
+
out_channels,
|
| 365 |
+
kernel_size=kernel_size,
|
| 366 |
+
num_blocks=csp_num_blocks,
|
| 367 |
+
activation=activation,
|
| 368 |
+
)
|
| 369 |
+
for _ in range(len(in_channel_list) - 1, 0, -1)
|
| 370 |
+
]
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
# build bottom-up blocks
|
| 374 |
+
self.downsamples = nn.ModuleList(
|
| 375 |
+
[
|
| 376 |
+
SLANetDepthwiseSeparableConvLayer(
|
| 377 |
+
out_channels,
|
| 378 |
+
out_channels,
|
| 379 |
+
kernel_size=kernel_size,
|
| 380 |
+
stride=2,
|
| 381 |
+
config=config,
|
| 382 |
+
)
|
| 383 |
+
for _ in range(len(in_channel_list) - 1)
|
| 384 |
+
]
|
| 385 |
+
)
|
| 386 |
+
self.bottom_up_blocks = nn.ModuleList(
|
| 387 |
+
[
|
| 388 |
+
SLANetCSPLayer(
|
| 389 |
+
config,
|
| 390 |
+
out_channels * 2,
|
| 391 |
+
out_channels,
|
| 392 |
+
kernel_size=kernel_size,
|
| 393 |
+
num_blocks=csp_num_blocks,
|
| 394 |
+
activation=activation,
|
| 395 |
+
)
|
| 396 |
+
for _ in range(len(in_channel_list) - 1)
|
| 397 |
+
]
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 401 |
+
projected_features = []
|
| 402 |
+
for idx in range(len(self.channel_projector)):
|
| 403 |
+
projected_features.append(self.channel_projector[idx](hidden_states[idx]))
|
| 404 |
+
|
| 405 |
+
top_down_features = [projected_features[-1]]
|
| 406 |
+
for top_down_block, low_level_feature in zip(self.top_down_blocks, reversed(projected_features[:-1])):
|
| 407 |
+
high_level_feature = top_down_features[-1]
|
| 408 |
+
upsampled_feature = F.interpolate(
|
| 409 |
+
high_level_feature,
|
| 410 |
+
size=low_level_feature.shape[-2:],
|
| 411 |
+
mode="nearest",
|
| 412 |
+
)
|
| 413 |
+
fused_feature = top_down_block(torch.cat([upsampled_feature, low_level_feature], dim=1))
|
| 414 |
+
top_down_features.append(fused_feature)
|
| 415 |
+
|
| 416 |
+
pyramid_features = list(reversed(top_down_features))
|
| 417 |
+
output_feature = pyramid_features[0]
|
| 418 |
+
for downsample_layer, bottom_up_block, high_level_feature in zip(
|
| 419 |
+
self.downsamples, self.bottom_up_blocks, pyramid_features[1:]
|
| 420 |
+
):
|
| 421 |
+
downsampled_feature = downsample_layer(output_feature)
|
| 422 |
+
output_feature = bottom_up_block(torch.cat([downsampled_feature, high_level_feature], dim=1))
|
| 423 |
+
|
| 424 |
+
hidden_states = output_feature.flatten(2).transpose(1, 2)
|
| 425 |
+
return hidden_states
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class SLANetBackbone(SLANetPreTrainedModel):
|
| 429 |
+
def __init__(self, config: SLANetConfig):
|
| 430 |
+
super().__init__(config)
|
| 431 |
+
self.vision_backbone = load_backbone(config)
|
| 432 |
+
self.post_csp_pan = SLANetCSPPAN(config, self.vision_backbone.num_features[2:])
|
| 433 |
+
|
| 434 |
+
self.post_init()
|
| 435 |
+
|
| 436 |
+
@can_return_tuple
|
| 437 |
+
@auto_docstring
|
| 438 |
+
def forward(
|
| 439 |
+
self, hidden_states: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
|
| 440 |
+
) -> tuple[torch.FloatTensor] | BaseModelOutputWithNoAttention:
|
| 441 |
+
outputs = self.vision_backbone(hidden_states, **kwargs)
|
| 442 |
+
hidden_states = self.post_csp_pan(outputs.feature_maps)
|
| 443 |
+
return BaseModelOutputWithNoAttention(
|
| 444 |
+
last_hidden_state=hidden_states,
|
| 445 |
+
hidden_states=outputs.hidden_states,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@auto_docstring(
|
| 450 |
+
custom_intro="""
|
| 451 |
+
SLANet Table Recognition model for table recognition tasks. Wraps the core SLANetPreTrainedModel
|
| 452 |
+
and returns outputs compatible with the Transformers table recognition API.
|
| 453 |
+
"""
|
| 454 |
+
)
|
| 455 |
+
class SLANetForTableRecognition(SLANetPreTrainedModel):
|
| 456 |
+
_keys_to_ignore_on_load_missing = ["num_batches_tracked"]
|
| 457 |
+
|
| 458 |
+
def __init__(self, config: SLANetConfig):
|
| 459 |
+
super().__init__(config)
|
| 460 |
+
self.backbone = SLANetBackbone(config=config)
|
| 461 |
+
self.head = SLANetSLAHead(config=config)
|
| 462 |
+
self.post_init()
|
| 463 |
+
|
| 464 |
+
@can_return_tuple
|
| 465 |
+
@auto_docstring
|
| 466 |
+
def forward(
|
| 467 |
+
self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
|
| 468 |
+
) -> tuple[torch.FloatTensor] | SLANetForTableRecognitionOutput:
|
| 469 |
+
outputs = self.backbone(pixel_values, **kwargs)
|
| 470 |
+
head_outputs = self.head(outputs.last_hidden_state, **kwargs)
|
| 471 |
+
# Key difference: no attentions in its vision model
|
| 472 |
+
return SLANetForTableRecognitionOutput(
|
| 473 |
+
last_hidden_state=head_outputs.last_hidden_state,
|
| 474 |
+
hidden_states=outputs.hidden_states,
|
| 475 |
+
head_hidden_states=head_outputs.hidden_states,
|
| 476 |
+
head_attentions=head_outputs.attentions,
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
__all__ = ["SLANetForTableRecognition", "SLANetPreTrainedModel", "SLANetSLAHead", "SLANetBackbone"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/slanet/modular_slanet.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The PaddlePaddle Team 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 |
+
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from huggingface_hub.dataclasses import strict
|
| 23 |
+
|
| 24 |
+
from ... import initialization as init
|
| 25 |
+
from ...backbone_utils import consolidate_backbone_kwargs_to_config, load_backbone
|
| 26 |
+
from ...configuration_utils import PreTrainedConfig
|
| 27 |
+
from ...modeling_outputs import BaseModelOutputWithNoAttention
|
| 28 |
+
from ...modeling_utils import PreTrainedModel
|
| 29 |
+
from ...processing_utils import Unpack
|
| 30 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
|
| 31 |
+
from ..auto import AutoConfig
|
| 32 |
+
from ..pp_lcnet.modeling_pp_lcnet import PPLCNetConvLayer, PPLCNetDepthwiseSeparableConvLayer
|
| 33 |
+
from ..slanext.configuration_slanext import SLANeXtConfig
|
| 34 |
+
from ..slanext.modeling_slanext import (
|
| 35 |
+
SLANeXtForTableRecognition,
|
| 36 |
+
SLANeXtPreTrainedModel,
|
| 37 |
+
SLANeXtSLAHead,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@auto_docstring(checkpoint="PaddlePaddle/SLANet_plus_safetensors")
|
| 45 |
+
@strict
|
| 46 |
+
class SLANetConfig(SLANeXtConfig):
|
| 47 |
+
r"""
|
| 48 |
+
post_conv_out_channels (`int`, *optional*, defaults to 96):
|
| 49 |
+
Number of output channels for the post-encoder convolution layer.
|
| 50 |
+
out_channels (`int`, *optional*, defaults to 50):
|
| 51 |
+
Vocabulary size for the table structure token prediction head, i.e., the number of distinct structure
|
| 52 |
+
tokens the model can predict.
|
| 53 |
+
hidden_size (`int`, *optional*, defaults to 256):
|
| 54 |
+
Dimensionality of the hidden states in the attention GRU cell and the structure/location prediction heads.
|
| 55 |
+
max_text_length (`int`, *optional*, defaults to 500):
|
| 56 |
+
Maximum number of autoregressive decoding steps (tokens) for the structure and location decoder.
|
| 57 |
+
csp_kernel_size (`int`, *optional*, defaults to 5):
|
| 58 |
+
The kernel size of the Cross Stage Partial (CSP) layer.
|
| 59 |
+
csp_num_blocks (`int`, *optional*, defaults to 1):
|
| 60 |
+
Number of blocks within the Cross Stage Partial (CSP) layer.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
sub_configs = {"backbone_config": AutoConfig}
|
| 64 |
+
|
| 65 |
+
vision_config = AttributeError()
|
| 66 |
+
backbone_config: dict | PreTrainedConfig | None = None
|
| 67 |
+
|
| 68 |
+
post_conv_in_channels = AttributeError()
|
| 69 |
+
post_conv_out_channels: int = 96
|
| 70 |
+
hidden_size: int = 256
|
| 71 |
+
|
| 72 |
+
hidden_act: str = "hardswish"
|
| 73 |
+
csp_kernel_size: int = 5
|
| 74 |
+
csp_num_blocks: int = 1
|
| 75 |
+
|
| 76 |
+
def __post_init__(self, **kwargs):
|
| 77 |
+
self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
|
| 78 |
+
backbone_config=self.backbone_config,
|
| 79 |
+
default_config_type="pp_lcnet",
|
| 80 |
+
default_config_kwargs={
|
| 81 |
+
"scale": 1,
|
| 82 |
+
"out_features": ["stage2", "stage3", "stage4", "stage5"],
|
| 83 |
+
"out_indices": [2, 3, 4, 5],
|
| 84 |
+
"divisor": 16,
|
| 85 |
+
},
|
| 86 |
+
**kwargs,
|
| 87 |
+
)
|
| 88 |
+
PreTrainedConfig.__post_init__(**kwargs)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class SLANetPreTrainedModel(SLANeXtPreTrainedModel):
|
| 92 |
+
_keep_in_fp32_modules_strict = []
|
| 93 |
+
|
| 94 |
+
@torch.no_grad()
|
| 95 |
+
def _init_weights(self, module):
|
| 96 |
+
"""Initialize the weights"""
|
| 97 |
+
PreTrainedModel._init_weights(module)
|
| 98 |
+
|
| 99 |
+
# Initialize GRUCell (replicates PyTorch default reset_parameters)
|
| 100 |
+
if isinstance(module, nn.GRUCell):
|
| 101 |
+
std = 1.0 / math.sqrt(module.hidden_size) if module.hidden_size > 0 else 0
|
| 102 |
+
init.uniform_(module.weight_ih, -std, std)
|
| 103 |
+
init.uniform_(module.weight_hh, -std, std)
|
| 104 |
+
if module.bias_ih is not None:
|
| 105 |
+
init.uniform_(module.bias_ih, -std, std)
|
| 106 |
+
if module.bias_hh is not None:
|
| 107 |
+
init.uniform_(module.bias_hh, -std, std)
|
| 108 |
+
|
| 109 |
+
# Initialize SLAHead layers
|
| 110 |
+
if isinstance(module, SLANetSLAHead):
|
| 111 |
+
std = 1.0 / math.sqrt(self.config.hidden_size * 1.0)
|
| 112 |
+
# Initialize structure_generator and loc_generator layers
|
| 113 |
+
for generator in (module.structure_generator,):
|
| 114 |
+
for layer in generator.children():
|
| 115 |
+
if isinstance(layer, nn.Linear):
|
| 116 |
+
init.uniform_(layer.weight, -std, std)
|
| 117 |
+
if layer.bias is not None:
|
| 118 |
+
init.uniform_(layer.bias, -std, std)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@auto_docstring
|
| 122 |
+
@dataclass
|
| 123 |
+
class SLANetForTableRecognitionOutput(BaseModelOutputWithNoAttention):
|
| 124 |
+
r"""
|
| 125 |
+
head_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 126 |
+
Hidden-states of the SLANetSLAHead at each prediction step, varies up to max `self.config.max_text_length` states (depending on early exits).
|
| 127 |
+
head_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 128 |
+
Attentions of the SLANetSLAHead at each prediction step, varies up to max `self.config.max_text_length` attentions (depending on early exits).
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
head_hidden_states: torch.FloatTensor | None = None
|
| 132 |
+
head_attentions: torch.FloatTensor | None = None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class SLANetSLAHead(SLANeXtSLAHead):
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class SLANetConvLayer(PPLCNetConvLayer):
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class SLANetDepthwiseSeparableConvLayer(PPLCNetDepthwiseSeparableConvLayer):
|
| 144 |
+
"""
|
| 145 |
+
Depthwise Separable Convolution Layer: Depthwise Conv -> Pointwise Conv
|
| 146 |
+
Core component of lightweight models (e.g., MobileNet, PP-LCNet) that significantly reduces
|
| 147 |
+
the number of parameters and computational cost.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def __init__(
|
| 151 |
+
self,
|
| 152 |
+
in_channels,
|
| 153 |
+
out_channels,
|
| 154 |
+
stride,
|
| 155 |
+
kernel_size,
|
| 156 |
+
config,
|
| 157 |
+
):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.squeeze_excitation_module = nn.Identity()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class SLANetBottleneck(nn.Module):
|
| 163 |
+
def __init__(
|
| 164 |
+
self,
|
| 165 |
+
in_channels,
|
| 166 |
+
out_channels,
|
| 167 |
+
kernel_size,
|
| 168 |
+
activation,
|
| 169 |
+
config,
|
| 170 |
+
):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.conv1 = SLANetConvLayer(
|
| 173 |
+
in_channels=in_channels, out_channels=out_channels, kernel_size=1, activation=activation
|
| 174 |
+
)
|
| 175 |
+
self.conv2 = SLANetDepthwiseSeparableConvLayer(
|
| 176 |
+
in_channels=out_channels,
|
| 177 |
+
out_channels=out_channels,
|
| 178 |
+
kernel_size=kernel_size,
|
| 179 |
+
stride=1,
|
| 180 |
+
config=config,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 184 |
+
hidden_states = self.conv1(hidden_states)
|
| 185 |
+
hidden_states = self.conv2(hidden_states)
|
| 186 |
+
|
| 187 |
+
return hidden_states
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class SLANetCSPLayer(nn.Module):
|
| 191 |
+
"""
|
| 192 |
+
Cross Stage Partial (CSP) network layer. Similar in structure to DFineCSPRepLayer, but with a different forward computation.
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
def __init__(
|
| 196 |
+
self,
|
| 197 |
+
config,
|
| 198 |
+
in_channels,
|
| 199 |
+
out_channels,
|
| 200 |
+
kernel_size=3,
|
| 201 |
+
expansion=0.5,
|
| 202 |
+
num_blocks=1,
|
| 203 |
+
activation="hardswish",
|
| 204 |
+
):
|
| 205 |
+
super().__init__()
|
| 206 |
+
hidden_channels = int(out_channels * expansion)
|
| 207 |
+
self.conv1 = SLANetConvLayer(in_channels, hidden_channels, 1, activation=activation)
|
| 208 |
+
self.conv2 = SLANetConvLayer(in_channels, hidden_channels, 1, activation=activation)
|
| 209 |
+
self.conv3 = SLANetConvLayer(2 * hidden_channels, out_channels, 1, activation=activation)
|
| 210 |
+
self.bottlenecks = nn.ModuleList(
|
| 211 |
+
[
|
| 212 |
+
SLANetBottleneck(hidden_channels, hidden_channels, kernel_size, activation, config)
|
| 213 |
+
for _ in range(num_blocks)
|
| 214 |
+
]
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 218 |
+
residual = self.conv1(hidden_states)
|
| 219 |
+
|
| 220 |
+
hidden_states = self.conv2(hidden_states)
|
| 221 |
+
for bottleneck in self.bottlenecks:
|
| 222 |
+
hidden_states = bottleneck(hidden_states)
|
| 223 |
+
|
| 224 |
+
hidden_states = torch.cat((hidden_states, residual), dim=1)
|
| 225 |
+
hidden_states = self.conv3(hidden_states)
|
| 226 |
+
|
| 227 |
+
return hidden_states
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class SLANetCSPPAN(nn.Module):
|
| 231 |
+
"""
|
| 232 |
+
CSP-PAN: Path Aggregation Network with CSP layers
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
def __init__(
|
| 236 |
+
self,
|
| 237 |
+
config,
|
| 238 |
+
in_channel_list,
|
| 239 |
+
):
|
| 240 |
+
super().__init__()
|
| 241 |
+
out_channels = config.post_conv_out_channels
|
| 242 |
+
activation = config.hidden_act
|
| 243 |
+
kernel_size = config.csp_kernel_size
|
| 244 |
+
csp_num_blocks = config.csp_num_blocks
|
| 245 |
+
|
| 246 |
+
self.channel_projector = nn.ModuleList(
|
| 247 |
+
[
|
| 248 |
+
SLANetConvLayer(
|
| 249 |
+
in_channels=in_channel_list[i], out_channels=out_channels, kernel_size=1, activation=activation
|
| 250 |
+
)
|
| 251 |
+
for i in range(len(in_channel_list))
|
| 252 |
+
]
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# build top-down blocks
|
| 256 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
|
| 257 |
+
self.top_down_blocks = nn.ModuleList(
|
| 258 |
+
[
|
| 259 |
+
SLANetCSPLayer(
|
| 260 |
+
config,
|
| 261 |
+
out_channels * 2,
|
| 262 |
+
out_channels,
|
| 263 |
+
kernel_size=kernel_size,
|
| 264 |
+
num_blocks=csp_num_blocks,
|
| 265 |
+
activation=activation,
|
| 266 |
+
)
|
| 267 |
+
for _ in range(len(in_channel_list) - 1, 0, -1)
|
| 268 |
+
]
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# build bottom-up blocks
|
| 272 |
+
self.downsamples = nn.ModuleList(
|
| 273 |
+
[
|
| 274 |
+
SLANetDepthwiseSeparableConvLayer(
|
| 275 |
+
out_channels,
|
| 276 |
+
out_channels,
|
| 277 |
+
kernel_size=kernel_size,
|
| 278 |
+
stride=2,
|
| 279 |
+
config=config,
|
| 280 |
+
)
|
| 281 |
+
for _ in range(len(in_channel_list) - 1)
|
| 282 |
+
]
|
| 283 |
+
)
|
| 284 |
+
self.bottom_up_blocks = nn.ModuleList(
|
| 285 |
+
[
|
| 286 |
+
SLANetCSPLayer(
|
| 287 |
+
config,
|
| 288 |
+
out_channels * 2,
|
| 289 |
+
out_channels,
|
| 290 |
+
kernel_size=kernel_size,
|
| 291 |
+
num_blocks=csp_num_blocks,
|
| 292 |
+
activation=activation,
|
| 293 |
+
)
|
| 294 |
+
for _ in range(len(in_channel_list) - 1)
|
| 295 |
+
]
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 299 |
+
projected_features = []
|
| 300 |
+
for idx in range(len(self.channel_projector)):
|
| 301 |
+
projected_features.append(self.channel_projector[idx](hidden_states[idx]))
|
| 302 |
+
|
| 303 |
+
top_down_features = [projected_features[-1]]
|
| 304 |
+
for top_down_block, low_level_feature in zip(self.top_down_blocks, reversed(projected_features[:-1])):
|
| 305 |
+
high_level_feature = top_down_features[-1]
|
| 306 |
+
upsampled_feature = F.interpolate(
|
| 307 |
+
high_level_feature,
|
| 308 |
+
size=low_level_feature.shape[-2:],
|
| 309 |
+
mode="nearest",
|
| 310 |
+
)
|
| 311 |
+
fused_feature = top_down_block(torch.cat([upsampled_feature, low_level_feature], dim=1))
|
| 312 |
+
top_down_features.append(fused_feature)
|
| 313 |
+
|
| 314 |
+
pyramid_features = list(reversed(top_down_features))
|
| 315 |
+
output_feature = pyramid_features[0]
|
| 316 |
+
for downsample_layer, bottom_up_block, high_level_feature in zip(
|
| 317 |
+
self.downsamples, self.bottom_up_blocks, pyramid_features[1:]
|
| 318 |
+
):
|
| 319 |
+
downsampled_feature = downsample_layer(output_feature)
|
| 320 |
+
output_feature = bottom_up_block(torch.cat([downsampled_feature, high_level_feature], dim=1))
|
| 321 |
+
|
| 322 |
+
hidden_states = output_feature.flatten(2).transpose(1, 2)
|
| 323 |
+
return hidden_states
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class SLANetBackbone(SLANetPreTrainedModel):
|
| 327 |
+
def __init__(self, config: SLANetConfig):
|
| 328 |
+
super().__init__(config)
|
| 329 |
+
self.vision_backbone = load_backbone(config)
|
| 330 |
+
self.post_csp_pan = SLANetCSPPAN(config, self.vision_backbone.num_features[2:])
|
| 331 |
+
|
| 332 |
+
self.post_init()
|
| 333 |
+
|
| 334 |
+
@can_return_tuple
|
| 335 |
+
@auto_docstring
|
| 336 |
+
def forward(
|
| 337 |
+
self, hidden_states: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
|
| 338 |
+
) -> tuple[torch.FloatTensor] | BaseModelOutputWithNoAttention:
|
| 339 |
+
outputs = self.vision_backbone(hidden_states, **kwargs)
|
| 340 |
+
hidden_states = self.post_csp_pan(outputs.feature_maps)
|
| 341 |
+
return BaseModelOutputWithNoAttention(
|
| 342 |
+
last_hidden_state=hidden_states,
|
| 343 |
+
hidden_states=outputs.hidden_states,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@auto_docstring(
|
| 348 |
+
custom_intro="""
|
| 349 |
+
SLANet Table Recognition model for table recognition tasks. Wraps the core SLANetPreTrainedModel
|
| 350 |
+
and returns outputs compatible with the Transformers table recognition API.
|
| 351 |
+
"""
|
| 352 |
+
)
|
| 353 |
+
class SLANetForTableRecognition(SLANeXtForTableRecognition):
|
| 354 |
+
_keys_to_ignore_on_load_missing = ["num_batches_tracked"]
|
| 355 |
+
|
| 356 |
+
@can_return_tuple
|
| 357 |
+
@auto_docstring
|
| 358 |
+
def forward(
|
| 359 |
+
self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
|
| 360 |
+
) -> tuple[torch.FloatTensor] | SLANetForTableRecognitionOutput:
|
| 361 |
+
outputs = self.backbone(pixel_values, **kwargs)
|
| 362 |
+
head_outputs = self.head(outputs.last_hidden_state, **kwargs)
|
| 363 |
+
# Key difference: no attentions in its vision model
|
| 364 |
+
return SLANetForTableRecognitionOutput(
|
| 365 |
+
last_hidden_state=head_outputs.last_hidden_state,
|
| 366 |
+
hidden_states=outputs.hidden_states,
|
| 367 |
+
head_hidden_states=head_outputs.hidden_states,
|
| 368 |
+
head_attentions=head_outputs.attentions,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
__all__ = ["SLANetConfig", "SLANetForTableRecognition", "SLANetPreTrainedModel", "SLANetSLAHead", "SLANetBackbone"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/videomt/configuration_videomt.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/videomt/modular_videomt.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_videomt.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from huggingface_hub.dataclasses import strict
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PreTrainedConfig
|
| 24 |
+
from ...utils import auto_docstring
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@auto_docstring(checkpoint="tue-mps/videomt-dinov2-small-ytvis2019")
|
| 28 |
+
@strict
|
| 29 |
+
class VideomtConfig(PreTrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
layerscale_value (`float`, *optional*, defaults to 1.0):
|
| 32 |
+
Initial value for the LayerScale parameter.
|
| 33 |
+
num_upscale_blocks (`int`, *optional*, defaults to 2):
|
| 34 |
+
Number of upsampling blocks used in the decoder or segmentation head.
|
| 35 |
+
use_swiglu_ffn (`bool`, *optional*, defaults to `False`):
|
| 36 |
+
Whether to use the SwiGLU feedforward neural network.
|
| 37 |
+
num_blocks (`int`, *optional*, defaults to 4):
|
| 38 |
+
Number of feature blocks or stages in the architecture.
|
| 39 |
+
no_object_weight (`float`, *optional*, defaults to 0.1):
|
| 40 |
+
Loss weight for the 'no object' class in panoptic/instance segmentation.
|
| 41 |
+
class_weight (`float`, *optional*, defaults to 2.0):
|
| 42 |
+
Loss weight for classification targets.
|
| 43 |
+
mask_weight (`float`, *optional*, defaults to 5.0):
|
| 44 |
+
Loss weight for mask prediction.
|
| 45 |
+
train_num_points (`int`, *optional*, defaults to 12544):
|
| 46 |
+
Number of points to sample for mask loss computation during training.
|
| 47 |
+
oversample_ratio (`float`, *optional*, defaults to 3.0):
|
| 48 |
+
Oversampling ratio used in point sampling for mask training.
|
| 49 |
+
importance_sample_ratio (`float`, *optional*, defaults to 0.75):
|
| 50 |
+
Ratio of points to sample based on importance during training.
|
| 51 |
+
num_queries (`int`, *optional*, defaults to 200):
|
| 52 |
+
Number of object queries in the Transformer.
|
| 53 |
+
num_register_tokens (`int`, *optional*, defaults to 4):
|
| 54 |
+
Number of learnable register tokens added to the transformer input.
|
| 55 |
+
|
| 56 |
+
Example:
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
>>> from transformers import VideomtConfig, VideomtForUniversalSegmentation
|
| 60 |
+
|
| 61 |
+
>>> # Initialize configuration
|
| 62 |
+
>>> config = VideomtConfig()
|
| 63 |
+
|
| 64 |
+
>>> # Initialize model
|
| 65 |
+
>>> model = VideomtForUniversalSegmentation(config)
|
| 66 |
+
|
| 67 |
+
>>> # Access config
|
| 68 |
+
>>> config = model.config
|
| 69 |
+
```"""
|
| 70 |
+
|
| 71 |
+
model_type = "videomt"
|
| 72 |
+
|
| 73 |
+
hidden_size: int = 1024
|
| 74 |
+
num_hidden_layers: int = 24
|
| 75 |
+
num_attention_heads: int = 16
|
| 76 |
+
hidden_act: str = "gelu"
|
| 77 |
+
hidden_dropout_prob: float | int = 0.0
|
| 78 |
+
initializer_range: float = 0.02
|
| 79 |
+
layer_norm_eps: float = 1e-6
|
| 80 |
+
image_size: int | list[int] | tuple[int, int] = 640
|
| 81 |
+
patch_size: int | list[int] | tuple[int, int] = 16
|
| 82 |
+
num_channels: int = 3
|
| 83 |
+
mlp_ratio: int = 4
|
| 84 |
+
layerscale_value: float = 1.0
|
| 85 |
+
drop_path_rate: float | int = 0.0
|
| 86 |
+
num_upscale_blocks: int = 2
|
| 87 |
+
attention_dropout: float | int = 0.0
|
| 88 |
+
use_swiglu_ffn: bool = False
|
| 89 |
+
num_blocks: int = 4
|
| 90 |
+
no_object_weight: float = 0.1
|
| 91 |
+
class_weight: float = 2.0
|
| 92 |
+
mask_weight: float = 5.0
|
| 93 |
+
dice_weight: float = 5.0
|
| 94 |
+
train_num_points: int = 12544
|
| 95 |
+
oversample_ratio: float = 3.0
|
| 96 |
+
importance_sample_ratio: float = 0.75
|
| 97 |
+
num_queries: int = 200
|
| 98 |
+
num_register_tokens: int = 4
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
__all__ = ["VideomtConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/videomt/modular_videomt.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 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 dataclasses import dataclass
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from huggingface_hub.dataclasses import strict
|
| 19 |
+
from torch import nn
|
| 20 |
+
|
| 21 |
+
from ...file_utils import ModelOutput
|
| 22 |
+
from ...processing_utils import Unpack
|
| 23 |
+
from ...utils import TransformersKwargs, auto_docstring
|
| 24 |
+
from ..eomt.configuration_eomt import EomtConfig
|
| 25 |
+
from ..eomt.modeling_eomt import (
|
| 26 |
+
EomtEmbeddings,
|
| 27 |
+
EomtForUniversalSegmentation,
|
| 28 |
+
EomtLayer,
|
| 29 |
+
EomtLayerNorm2d,
|
| 30 |
+
EomtLayerScale,
|
| 31 |
+
EomtMLP,
|
| 32 |
+
EomtPatchEmbeddings,
|
| 33 |
+
EomtPreTrainedModel,
|
| 34 |
+
EomtScaleBlock,
|
| 35 |
+
EomtScaleLayer,
|
| 36 |
+
EomtSwiGLUFFN,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@auto_docstring(checkpoint="tue-mps/videomt-dinov2-small-ytvis2019")
|
| 41 |
+
@strict
|
| 42 |
+
class VideomtConfig(EomtConfig):
|
| 43 |
+
model_type = "videomt"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class VideomtPatchEmbeddings(EomtPatchEmbeddings):
|
| 47 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 48 |
+
num_channels = pixel_values.shape[1]
|
| 49 |
+
if num_channels != self.num_channels:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 52 |
+
f" Expected {self.num_channels} but got {num_channels}."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
pixel_values = pixel_values.to(dtype=self.projection.weight.dtype)
|
| 56 |
+
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 57 |
+
return embeddings
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class VideomtEmbeddings(EomtEmbeddings):
|
| 61 |
+
def __init__(self, config: VideomtConfig):
|
| 62 |
+
super().__init__(config)
|
| 63 |
+
self.patch_embeddings = VideomtPatchEmbeddings(config)
|
| 64 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 65 |
+
|
| 66 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: torch.Tensor | None = None) -> torch.Tensor:
|
| 67 |
+
if pixel_values.ndim == 5:
|
| 68 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 69 |
+
pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
|
| 70 |
+
|
| 71 |
+
if bool_masked_pos is not None:
|
| 72 |
+
bool_masked_pos = bool_masked_pos.reshape(batch_size * num_frames, -1)
|
| 73 |
+
elif bool_masked_pos is not None and bool_masked_pos.ndim > 2:
|
| 74 |
+
bool_masked_pos = bool_masked_pos.reshape(bool_masked_pos.shape[0], -1)
|
| 75 |
+
|
| 76 |
+
batch_size = pixel_values.shape[0]
|
| 77 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 78 |
+
|
| 79 |
+
if bool_masked_pos is not None:
|
| 80 |
+
mask = bool_masked_pos.to(device=embeddings.device, dtype=torch.bool).unsqueeze(-1)
|
| 81 |
+
embeddings = torch.where(mask, self.mask_token, embeddings)
|
| 82 |
+
|
| 83 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 84 |
+
register_tokens = self.register_tokens.expand(batch_size, -1, -1)
|
| 85 |
+
|
| 86 |
+
embeddings = embeddings + self.position_embeddings(self.position_ids)
|
| 87 |
+
embeddings = torch.cat([cls_tokens, register_tokens, embeddings], dim=1)
|
| 88 |
+
embeddings = self.dropout(embeddings)
|
| 89 |
+
return embeddings
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class VideomtMLP(EomtMLP):
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class VideomtGatedMLP(EomtSwiGLUFFN):
|
| 97 |
+
pass
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class VideomtLayer(EomtLayer):
|
| 101 |
+
pass
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class VideomtLayerScale(EomtLayerScale):
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@auto_docstring(
|
| 109 |
+
custom_intro="""
|
| 110 |
+
Class for outputs of [`VideomtForUniversalSegmentationOutput`].
|
| 111 |
+
|
| 112 |
+
This output can be directly passed to [`~VideomtVideoProcessor.post_process_semantic_segmentation`] or
|
| 113 |
+
[`~VideomtVideoProcessor.post_process_instance_segmentation`] or
|
| 114 |
+
[`~VideomtVideoProcessor.post_process_panoptic_segmentation`] to compute final segmentation maps. Please, see
|
| 115 |
+
[`~VideomtVideoProcessor`] for details regarding usage.
|
| 116 |
+
"""
|
| 117 |
+
)
|
| 118 |
+
@dataclass
|
| 119 |
+
class VideomtForUniversalSegmentationOutput(ModelOutput):
|
| 120 |
+
r"""
|
| 121 |
+
loss (`torch.Tensor`, *optional*):
|
| 122 |
+
The computed loss, returned when labels are present.
|
| 123 |
+
class_queries_logits (`torch.FloatTensor`):
|
| 124 |
+
A tensor of shape `(batch_size, num_queries, num_labels + 1)` representing the proposed classes for each
|
| 125 |
+
query. Note the `+ 1` is needed because we incorporate the null class.
|
| 126 |
+
masks_queries_logits (`torch.FloatTensor`):
|
| 127 |
+
A tensor of shape `(batch_size, num_queries, height, width)` representing the proposed masks for each
|
| 128 |
+
query.
|
| 129 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 130 |
+
Last hidden states (final feature map) of the last layer.
|
| 131 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 132 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 133 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states all layers of the model.
|
| 134 |
+
attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 135 |
+
Tuple of `tuple(torch.FloatTensor)` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 136 |
+
sequence_length)`. Self and Cross Attentions weights from transformer decoder.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
loss: torch.FloatTensor | None = None
|
| 140 |
+
class_queries_logits: torch.FloatTensor | None = None
|
| 141 |
+
masks_queries_logits: torch.FloatTensor | None = None
|
| 142 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 143 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 144 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class VideomtPreTrainedModel(EomtPreTrainedModel):
|
| 148 |
+
main_input_name = "pixel_values_videos"
|
| 149 |
+
input_modalities = ("video",)
|
| 150 |
+
|
| 151 |
+
@torch.no_grad()
|
| 152 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 153 |
+
super()._init_weights(module)
|
| 154 |
+
if isinstance(module, VideomtEmbeddings):
|
| 155 |
+
nn.init.zeros_(module.mask_token)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class VideomtLayerNorm2d(EomtLayerNorm2d):
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class VideomtScaleLayer(EomtScaleLayer):
|
| 163 |
+
pass
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class VideomtScaleBlock(EomtScaleBlock):
|
| 167 |
+
pass
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class VideomtForUniversalSegmentation(EomtForUniversalSegmentation):
|
| 171 |
+
main_input_name = "pixel_values_videos"
|
| 172 |
+
|
| 173 |
+
def __init__(self, config: VideomtConfig):
|
| 174 |
+
super().__init__(config)
|
| 175 |
+
self.query_updater = nn.Linear(config.hidden_size, config.hidden_size)
|
| 176 |
+
|
| 177 |
+
def _disable_attention_mask(attn_mask, prob, num_query_tokens, encoder_start_tokens, device):
|
| 178 |
+
raise AttributeError("Not needed for Videomt")
|
| 179 |
+
|
| 180 |
+
def forward(
|
| 181 |
+
self,
|
| 182 |
+
pixel_values_videos: torch.Tensor | None = None,
|
| 183 |
+
mask_labels: list[torch.Tensor] | None = None,
|
| 184 |
+
class_labels: list[torch.Tensor] | None = None,
|
| 185 |
+
patch_offsets: list[torch.Tensor] | None = None, # Unused, kept for modular compatibility.
|
| 186 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 187 |
+
) -> VideomtForUniversalSegmentationOutput:
|
| 188 |
+
r"""
|
| 189 |
+
pixel_values_videos (`torch.Tensor`, *optional*):
|
| 190 |
+
Video inputs of shape `(batch_size, num_frames, num_channels, height, width)`.
|
| 191 |
+
mask_labels (`list[torch.Tensor]`, *optional*):
|
| 192 |
+
Not supported for 5D video inputs.
|
| 193 |
+
class_labels (`list[torch.LongTensor]`, *optional*):
|
| 194 |
+
Not supported for 5D video inputs.
|
| 195 |
+
patch_offsets (`list[torch.Tensor]`, *optional*):
|
| 196 |
+
Unused for video inputs and only kept for modular compatibility.
|
| 197 |
+
"""
|
| 198 |
+
if "pixel_values" in kwargs:
|
| 199 |
+
raise ValueError("Use `pixel_values_videos` with `VideomtForUniversalSegmentation`.")
|
| 200 |
+
|
| 201 |
+
if pixel_values_videos is None:
|
| 202 |
+
raise ValueError("You have to specify pixel_values_videos")
|
| 203 |
+
|
| 204 |
+
if pixel_values_videos.ndim != 5:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
"VideomtForUniversalSegmentation only supports 5D video inputs of shape "
|
| 207 |
+
"(batch_size, num_frames, channels, height, width)."
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
if mask_labels is not None or class_labels is not None:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"Training with 5D video inputs is not supported in `VideomtForUniversalSegmentation`. "
|
| 213 |
+
"Flatten frames and use `EomtForUniversalSegmentation` instead."
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
batch_size, num_frames, num_channels, height, width = pixel_values_videos.shape
|
| 217 |
+
flat_pixel_values = pixel_values_videos.reshape(batch_size * num_frames, num_channels, height, width)
|
| 218 |
+
|
| 219 |
+
hidden_states = self.embeddings(flat_pixel_values)
|
| 220 |
+
query_start_idx = self.num_hidden_layers - self.config.num_blocks
|
| 221 |
+
|
| 222 |
+
for layer_module in self.layers[:query_start_idx]:
|
| 223 |
+
hidden_states = layer_module(hidden_states)
|
| 224 |
+
|
| 225 |
+
hidden_states = hidden_states.view(batch_size, num_frames, hidden_states.shape[1], hidden_states.shape[2])
|
| 226 |
+
|
| 227 |
+
all_masks_queries_logits = []
|
| 228 |
+
all_class_queries_logits = []
|
| 229 |
+
all_last_hidden_states = []
|
| 230 |
+
propagated_query = None
|
| 231 |
+
|
| 232 |
+
for frame_idx in range(num_frames):
|
| 233 |
+
frame_hidden_states = hidden_states[:, frame_idx]
|
| 234 |
+
|
| 235 |
+
if propagated_query is None:
|
| 236 |
+
query_tokens = self.query.weight[None, :, :].expand(batch_size, -1, -1).to(frame_hidden_states.device)
|
| 237 |
+
else:
|
| 238 |
+
query_tokens = self.query_updater(propagated_query).to(frame_hidden_states.device) + self.query.weight[
|
| 239 |
+
None, :, :
|
| 240 |
+
].to(frame_hidden_states.device)
|
| 241 |
+
frame_hidden_states = torch.cat((query_tokens, frame_hidden_states), dim=1)
|
| 242 |
+
|
| 243 |
+
for layer_module in self.layers[query_start_idx:]:
|
| 244 |
+
frame_hidden_states = layer_module(frame_hidden_states)
|
| 245 |
+
|
| 246 |
+
sequence_output = self.layernorm(frame_hidden_states)
|
| 247 |
+
masks_queries_logits, class_queries_logits = self.predict(sequence_output)
|
| 248 |
+
|
| 249 |
+
all_masks_queries_logits.append(masks_queries_logits)
|
| 250 |
+
all_class_queries_logits.append(class_queries_logits)
|
| 251 |
+
all_last_hidden_states.append(sequence_output)
|
| 252 |
+
propagated_query = frame_hidden_states[:, : self.config.num_queries, :]
|
| 253 |
+
|
| 254 |
+
return VideomtForUniversalSegmentationOutput(
|
| 255 |
+
loss=None, # Training not supported yet
|
| 256 |
+
masks_queries_logits=torch.cat(all_masks_queries_logits, dim=0),
|
| 257 |
+
class_queries_logits=torch.cat(all_class_queries_logits, dim=0),
|
| 258 |
+
last_hidden_state=torch.cat(all_last_hidden_states, dim=0),
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
__all__ = [
|
| 263 |
+
"VideomtConfig",
|
| 264 |
+
"VideomtPreTrainedModel",
|
| 265 |
+
"VideomtForUniversalSegmentation",
|
| 266 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/videomt/video_processing_videomt.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Inc. team.
|
| 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 |
+
"""Video processor class for Videomt."""
|
| 15 |
+
|
| 16 |
+
from ...image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
|
| 17 |
+
from ...utils import is_torch_available, requires_backends
|
| 18 |
+
from ...video_processing_utils import BaseVideoProcessor
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if is_torch_available():
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def check_segment_validity(
|
| 27 |
+
mask_labels: "torch.Tensor",
|
| 28 |
+
mask_probs: "torch.Tensor",
|
| 29 |
+
query_idx: int,
|
| 30 |
+
mask_threshold: float = 0.5,
|
| 31 |
+
overlap_mask_area_threshold: float = 0.8,
|
| 32 |
+
) -> tuple[bool, "torch.Tensor"]:
|
| 33 |
+
"""
|
| 34 |
+
Checks whether a predicted query produces a valid panoptic segment.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
mask_labels (`torch.Tensor`):
|
| 38 |
+
Tensor of shape `(height, width)` containing the winning query index for each pixel.
|
| 39 |
+
mask_probs (`torch.Tensor`):
|
| 40 |
+
Tensor of shape `(num_queries, height, width)` containing per-query mask probabilities.
|
| 41 |
+
query_idx (`int`):
|
| 42 |
+
Index of the query to validate.
|
| 43 |
+
mask_threshold (`float`, *optional*, defaults to 0.5):
|
| 44 |
+
Threshold used to binarize the query mask probabilities.
|
| 45 |
+
overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
|
| 46 |
+
Minimum overlap ratio required between the assigned query area and the original query mask area.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
`tuple[bool, torch.Tensor]`: A tuple containing whether the segment is valid and the final boolean mask for
|
| 50 |
+
that segment.
|
| 51 |
+
"""
|
| 52 |
+
query_mask = mask_labels == query_idx
|
| 53 |
+
query_mask_area = query_mask.sum()
|
| 54 |
+
|
| 55 |
+
original_mask = mask_probs[query_idx] >= mask_threshold
|
| 56 |
+
original_area = original_mask.sum()
|
| 57 |
+
|
| 58 |
+
final_mask = query_mask & original_mask
|
| 59 |
+
final_mask_area = final_mask.sum()
|
| 60 |
+
|
| 61 |
+
mask_exists = query_mask_area > 0 and original_area > 0 and final_mask_area > 0
|
| 62 |
+
|
| 63 |
+
if mask_exists:
|
| 64 |
+
area_ratio = query_mask_area / original_area
|
| 65 |
+
if not area_ratio.item() > overlap_mask_area_threshold:
|
| 66 |
+
mask_exists = False
|
| 67 |
+
|
| 68 |
+
return mask_exists, final_mask
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def compute_segments(
|
| 72 |
+
mask_probs: "torch.Tensor",
|
| 73 |
+
pred_scores: "torch.Tensor",
|
| 74 |
+
pred_labels: "torch.Tensor",
|
| 75 |
+
label_ids_to_fuse: set[int] | None,
|
| 76 |
+
mask_threshold: float = 0.5,
|
| 77 |
+
overlap_mask_area_threshold: float = 0.8,
|
| 78 |
+
target_size: tuple[int, int] | None = None,
|
| 79 |
+
) -> tuple["torch.Tensor", list[dict[str, int | float]]]:
|
| 80 |
+
"""
|
| 81 |
+
Converts per-query mask predictions into a panoptic segmentation map.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
mask_probs (`torch.Tensor`):
|
| 85 |
+
Tensor of shape `(num_queries, height, width)` containing per-query mask logits.
|
| 86 |
+
pred_scores (`torch.Tensor`):
|
| 87 |
+
Tensor of shape `(num_queries,)` containing the confidence score of each predicted query.
|
| 88 |
+
pred_labels (`torch.Tensor`):
|
| 89 |
+
Tensor of shape `(num_queries,)` containing the predicted class ID of each query.
|
| 90 |
+
label_ids_to_fuse (`set[int]`, *optional*):
|
| 91 |
+
Label IDs that should be fused across disconnected regions.
|
| 92 |
+
mask_threshold (`float`, *optional*, defaults to 0.5):
|
| 93 |
+
Threshold used to binarize the query mask probabilities.
|
| 94 |
+
overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
|
| 95 |
+
Minimum overlap ratio required to keep a predicted segment.
|
| 96 |
+
target_size (`tuple[int, int]`, *optional*):
|
| 97 |
+
Final `(height, width)` of the segmentation map. If unset, uses the spatial size of `mask_probs`.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
`tuple[torch.Tensor, list[dict[str, int | float]]]`: The panoptic segmentation map and the metadata for each
|
| 101 |
+
predicted segment.
|
| 102 |
+
"""
|
| 103 |
+
height = mask_probs.shape[1] if target_size is None else target_size[0]
|
| 104 |
+
width = mask_probs.shape[2] if target_size is None else target_size[1]
|
| 105 |
+
|
| 106 |
+
segmentation = torch.zeros((height, width), dtype=torch.long, device=mask_probs.device) - 1
|
| 107 |
+
segments: list[dict] = []
|
| 108 |
+
|
| 109 |
+
mask_probs = mask_probs.sigmoid()
|
| 110 |
+
mask_labels = (pred_scores[:, None, None] * mask_probs).argmax(0)
|
| 111 |
+
|
| 112 |
+
current_segment_id = 0
|
| 113 |
+
stuff_memory_list: dict[int, int] = {}
|
| 114 |
+
|
| 115 |
+
for query_idx in range(pred_labels.shape[0]):
|
| 116 |
+
pred_class = pred_labels[query_idx].item()
|
| 117 |
+
|
| 118 |
+
mask_exists, final_mask = check_segment_validity(
|
| 119 |
+
mask_labels, mask_probs, query_idx, mask_threshold, overlap_mask_area_threshold
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
if not mask_exists:
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
if label_ids_to_fuse and pred_class in label_ids_to_fuse:
|
| 126 |
+
if pred_class in stuff_memory_list:
|
| 127 |
+
segmentation[final_mask] = stuff_memory_list[pred_class]
|
| 128 |
+
continue
|
| 129 |
+
else:
|
| 130 |
+
stuff_memory_list[pred_class] = current_segment_id
|
| 131 |
+
|
| 132 |
+
segmentation[final_mask] = current_segment_id
|
| 133 |
+
segment_score = round(pred_scores[query_idx].item(), 6)
|
| 134 |
+
segments.append(
|
| 135 |
+
{
|
| 136 |
+
"id": current_segment_id,
|
| 137 |
+
"label_id": pred_class,
|
| 138 |
+
"score": segment_score,
|
| 139 |
+
}
|
| 140 |
+
)
|
| 141 |
+
current_segment_id += 1
|
| 142 |
+
return segmentation, segments
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class VideomtVideoProcessor(BaseVideoProcessor):
|
| 146 |
+
resample = PILImageResampling.BILINEAR
|
| 147 |
+
image_mean = IMAGENET_DEFAULT_MEAN
|
| 148 |
+
image_std = IMAGENET_DEFAULT_STD
|
| 149 |
+
size = {"height": 640, "width": 640}
|
| 150 |
+
do_resize = True
|
| 151 |
+
do_center_crop = False
|
| 152 |
+
do_rescale = True
|
| 153 |
+
rescale_factor = 1 / 255
|
| 154 |
+
do_normalize = True
|
| 155 |
+
do_convert_rgb = True
|
| 156 |
+
do_sample_frames = False
|
| 157 |
+
model_input_names = ["pixel_values_videos"]
|
| 158 |
+
|
| 159 |
+
def _resize_mask_logits(
|
| 160 |
+
self,
|
| 161 |
+
masks_queries_logits: "torch.Tensor",
|
| 162 |
+
target_sizes: list[tuple[int, int]],
|
| 163 |
+
) -> list["torch.Tensor"]:
|
| 164 |
+
"""Interpolates mask logits to each frame's original resolution."""
|
| 165 |
+
resized = []
|
| 166 |
+
for idx, original_size in enumerate(target_sizes):
|
| 167 |
+
upsampled = F.interpolate(
|
| 168 |
+
masks_queries_logits[idx][None, ...],
|
| 169 |
+
size=original_size,
|
| 170 |
+
mode="bilinear",
|
| 171 |
+
align_corners=False,
|
| 172 |
+
)[0]
|
| 173 |
+
resized.append(upsampled)
|
| 174 |
+
return resized
|
| 175 |
+
|
| 176 |
+
def post_process_semantic_segmentation(
|
| 177 |
+
self,
|
| 178 |
+
outputs,
|
| 179 |
+
target_sizes: list[tuple[int, int]],
|
| 180 |
+
) -> list["torch.Tensor"]:
|
| 181 |
+
"""
|
| 182 |
+
Converts the output of [`VideomtForUniversalSegmentation`] into semantic segmentation predictions.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
outputs ([`VideomtForUniversalSegmentationOutput`]):
|
| 186 |
+
Raw outputs of the model.
|
| 187 |
+
target_sizes (`list[tuple[int, int]]`):
|
| 188 |
+
List of `(height, width)` tuples corresponding to the requested final size of each prediction.
|
| 189 |
+
Length should match the number of frames in the output.
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
`list[torch.Tensor]`: A list of tensors, each of shape `(height, width)`, where each value is the
|
| 193 |
+
predicted class index for the corresponding pixel.
|
| 194 |
+
"""
|
| 195 |
+
requires_backends(self, ["torch"])
|
| 196 |
+
|
| 197 |
+
masks_queries_logits = outputs.masks_queries_logits # [num_frames, num_queries, height, width]
|
| 198 |
+
class_queries_logits = outputs.class_queries_logits # [num_frames, num_queries, num_classes+1]
|
| 199 |
+
|
| 200 |
+
# Remove the null class `[..., :-1]`
|
| 201 |
+
masks_classes = class_queries_logits.float().softmax(dim=-1)[..., :-1]
|
| 202 |
+
masks_probs = masks_queries_logits.float().sigmoid()
|
| 203 |
+
|
| 204 |
+
segmentation_logits = torch.matmul(masks_classes.transpose(1, 2), masks_probs.flatten(2))
|
| 205 |
+
segmentation_logits = segmentation_logits.reshape(
|
| 206 |
+
masks_probs.shape[0], masks_classes.shape[-1], masks_probs.shape[-2], masks_probs.shape[-1]
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
output_logits = self._resize_mask_logits(segmentation_logits, target_sizes)
|
| 210 |
+
|
| 211 |
+
return [logit.argmax(dim=0) for logit in output_logits]
|
| 212 |
+
|
| 213 |
+
def post_process_instance_segmentation(
|
| 214 |
+
self,
|
| 215 |
+
outputs,
|
| 216 |
+
target_sizes: list[tuple[int, int]],
|
| 217 |
+
threshold: float = 0.5,
|
| 218 |
+
) -> list[dict]:
|
| 219 |
+
"""
|
| 220 |
+
Converts the output of [`VideomtForUniversalSegmentation`] into instance segmentation predictions.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
outputs ([`VideomtForUniversalSegmentationOutput`]):
|
| 224 |
+
Raw outputs of the model.
|
| 225 |
+
target_sizes (`list[tuple[int, int]]`):
|
| 226 |
+
List of `(height, width)` tuples corresponding to the requested final size of each prediction.
|
| 227 |
+
Length should match the number of frames in the output.
|
| 228 |
+
threshold (`float`, *optional*, defaults to 0.5):
|
| 229 |
+
Minimum combined score to keep an instance.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
`list[dict]`: A list of dicts (one per frame), each containing:
|
| 233 |
+
- `"segmentation"` -- A `torch.Tensor` of shape `(height, width)` with instance IDs (or -1 for background).
|
| 234 |
+
- `"segments_info"` -- A list of dicts with `"id"`, `"label_id"`, and `"score"` for each instance.
|
| 235 |
+
"""
|
| 236 |
+
requires_backends(self, ["torch"])
|
| 237 |
+
|
| 238 |
+
class_queries_logits = outputs.class_queries_logits
|
| 239 |
+
masks_queries_logits = outputs.masks_queries_logits
|
| 240 |
+
|
| 241 |
+
mask_probs_batch = self._resize_mask_logits(masks_queries_logits, target_sizes)
|
| 242 |
+
|
| 243 |
+
device = masks_queries_logits.device
|
| 244 |
+
num_frames = class_queries_logits.shape[0]
|
| 245 |
+
num_queries = class_queries_logits.shape[-2]
|
| 246 |
+
|
| 247 |
+
results = []
|
| 248 |
+
|
| 249 |
+
for frame_idx in range(num_frames):
|
| 250 |
+
mask_pred = mask_probs_batch[frame_idx]
|
| 251 |
+
mask_class = class_queries_logits[frame_idx]
|
| 252 |
+
|
| 253 |
+
class_probs = mask_class.float().softmax(dim=-1)[..., :-1]
|
| 254 |
+
scores, pred_classes = class_probs.max(-1)
|
| 255 |
+
pred_masks = mask_pred > 0
|
| 256 |
+
|
| 257 |
+
mask_probs = mask_pred.float().sigmoid()
|
| 258 |
+
mask_scores = (mask_probs.flatten(1) * pred_masks.flatten(1)).sum(1) / (
|
| 259 |
+
pred_masks.flatten(1).sum(1) + 1e-6
|
| 260 |
+
)
|
| 261 |
+
pred_scores = scores * mask_scores
|
| 262 |
+
|
| 263 |
+
segmentation = torch.full(target_sizes[frame_idx], fill_value=-1, dtype=torch.long, device=device)
|
| 264 |
+
|
| 265 |
+
segments = []
|
| 266 |
+
current_segment_id = 0
|
| 267 |
+
for query_idx in range(num_queries):
|
| 268 |
+
score = pred_scores[query_idx].item()
|
| 269 |
+
|
| 270 |
+
if torch.any(pred_masks[query_idx]) and score >= threshold:
|
| 271 |
+
segmentation[pred_masks[query_idx]] = current_segment_id
|
| 272 |
+
segments.append(
|
| 273 |
+
{
|
| 274 |
+
"id": current_segment_id,
|
| 275 |
+
"label_id": pred_classes[query_idx].item(),
|
| 276 |
+
"score": round(score, 6),
|
| 277 |
+
}
|
| 278 |
+
)
|
| 279 |
+
current_segment_id += 1
|
| 280 |
+
|
| 281 |
+
results.append({"segmentation": segmentation, "segments_info": segments})
|
| 282 |
+
return results
|
| 283 |
+
|
| 284 |
+
def post_process_panoptic_segmentation(
|
| 285 |
+
self,
|
| 286 |
+
outputs,
|
| 287 |
+
target_sizes: list[tuple[int, int]],
|
| 288 |
+
threshold: float = 0.8,
|
| 289 |
+
mask_threshold: float = 0.5,
|
| 290 |
+
overlap_mask_area_threshold: float = 0.8,
|
| 291 |
+
label_ids_to_fuse: set[int] | None = None,
|
| 292 |
+
) -> list[dict]:
|
| 293 |
+
"""
|
| 294 |
+
Converts the output of [`VideomtForUniversalSegmentation`] into panoptic segmentation predictions.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
outputs ([`VideomtForUniversalSegmentationOutput`]):
|
| 298 |
+
Raw outputs of the model.
|
| 299 |
+
target_sizes (`list[tuple[int, int]]`):
|
| 300 |
+
List of `(height, width)` tuples corresponding to the requested final size of each prediction.
|
| 301 |
+
Length should match the number of frames in the output.
|
| 302 |
+
threshold (`float`, *optional*, defaults to 0.8):
|
| 303 |
+
Minimum score to keep a predicted segment.
|
| 304 |
+
mask_threshold (`float`, *optional*, defaults to 0.5):
|
| 305 |
+
Threshold for binarizing mask probabilities.
|
| 306 |
+
overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
|
| 307 |
+
Overlap threshold to merge masks into a single segment.
|
| 308 |
+
label_ids_to_fuse (`set[int]`, *optional*):
|
| 309 |
+
Label IDs that should be fused across disconnected regions.
|
| 310 |
+
|
| 311 |
+
Returns:
|
| 312 |
+
`list[dict]`: A list of dicts (one per frame), each containing:
|
| 313 |
+
- `"segmentation"` -- A `torch.Tensor` of shape `(height, width)` with segment IDs (or -1 for background).
|
| 314 |
+
- `"segments_info"` -- A list of dicts with `"id"`, `"label_id"`, and `"score"` for each segment.
|
| 315 |
+
"""
|
| 316 |
+
requires_backends(self, ["torch"])
|
| 317 |
+
|
| 318 |
+
masks_queries_logits = outputs.masks_queries_logits
|
| 319 |
+
class_queries_logits = outputs.class_queries_logits
|
| 320 |
+
|
| 321 |
+
num_frames = class_queries_logits.shape[0]
|
| 322 |
+
num_labels = class_queries_logits.shape[-1] - 1
|
| 323 |
+
|
| 324 |
+
mask_probs_batch = self._resize_mask_logits(masks_queries_logits, target_sizes)
|
| 325 |
+
pred_scores_batch, pred_labels_batch = class_queries_logits.float().softmax(dim=-1).max(-1)
|
| 326 |
+
|
| 327 |
+
results: list = []
|
| 328 |
+
|
| 329 |
+
for frame_idx in range(num_frames):
|
| 330 |
+
mask_probs = mask_probs_batch[frame_idx]
|
| 331 |
+
pred_scores = pred_scores_batch[frame_idx]
|
| 332 |
+
pred_labels = pred_labels_batch[frame_idx]
|
| 333 |
+
|
| 334 |
+
if not (mask_probs.shape[0] == pred_scores.shape[0] == pred_labels.shape[0]):
|
| 335 |
+
raise ValueError("mask, scores and labels must have the same shape!")
|
| 336 |
+
|
| 337 |
+
to_keep = pred_labels.ne(num_labels) & (pred_scores > threshold)
|
| 338 |
+
mask_probs = mask_probs[to_keep]
|
| 339 |
+
pred_scores = pred_scores[to_keep]
|
| 340 |
+
pred_labels = pred_labels[to_keep]
|
| 341 |
+
|
| 342 |
+
if mask_probs.shape[0] <= 0:
|
| 343 |
+
height, width = target_sizes[frame_idx] if target_sizes is not None else mask_probs.shape[1:]
|
| 344 |
+
segmentation = torch.full(
|
| 345 |
+
(height, width), fill_value=-1, dtype=torch.long, device=masks_queries_logits.device
|
| 346 |
+
)
|
| 347 |
+
results.append({"segmentation": segmentation, "segments_info": []})
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
segmentation, segments = compute_segments(
|
| 351 |
+
mask_probs=mask_probs,
|
| 352 |
+
pred_scores=pred_scores,
|
| 353 |
+
pred_labels=pred_labels,
|
| 354 |
+
label_ids_to_fuse=label_ids_to_fuse,
|
| 355 |
+
mask_threshold=mask_threshold,
|
| 356 |
+
overlap_mask_area_threshold=overlap_mask_area_threshold,
|
| 357 |
+
target_size=target_sizes[frame_idx] if target_sizes is not None else None,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
results.append({"segmentation": segmentation, "segments_info": segments})
|
| 361 |
+
return results
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
__all__ = ["VideomtVideoProcessor"]
|