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_0015000_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_0021000_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_0033000_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_0034000_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_0038000_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_0046000_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_0070000_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_0086000_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_0087000_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_0091000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/processed_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_logistic_normal_steps128_t1p45_n256.txt +124 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/__init__.py +31 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/configuration_blip.py +175 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/image_processing_pil_blip.py +34 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/modeling_blip_text.py +709 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/configuration_qwen2_audio.py +128 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/configuration_switch_transformers.py +111 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/modeling_switch_transformers.py +1095 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/modular_switch_transformers.py +810 -0
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0015000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-22_23:53:28 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0015000.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_0015000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0015000.pt
|
| 3 |
+
[ckpt] step=15000
|
| 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_0015000.pt",
|
| 24 |
+
"step": 15000,
|
| 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": 37.75448781763157,
|
| 50 |
+
"nll_per_token": 3.631104351215326,
|
| 51 |
+
"tokens": 36230,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 52.234604086708096,
|
| 59 |
+
"nll_per_token": 3.955745188796941,
|
| 60 |
+
"tokens": 30384,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.7591066520179934,
|
| 68 |
+
"unique_tokens": 2225,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.067901611328125,
|
| 71 |
+
"distinct_2": 0.33172367125984253,
|
| 72 |
+
"top_token_mass": 0.096435546875
|
| 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_0015000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-22_23:55:47 done step_0015000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0021000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_00:30:51 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0021000.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_0021000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0021000.pt
|
| 3 |
+
[ckpt] step=21000
|
| 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_0021000.pt",
|
| 24 |
+
"step": 21000,
|
| 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": 28.971311537338988,
|
| 50 |
+
"nll_per_token": 3.366306083015355,
|
| 51 |
+
"tokens": 34053,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 32.04400658699901,
|
| 59 |
+
"nll_per_token": 3.467110163913922,
|
| 60 |
+
"tokens": 29919,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.203253674656506,
|
| 68 |
+
"unique_tokens": 1894,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.05780029296875,
|
| 71 |
+
"distinct_2": 0.26522514763779526,
|
| 72 |
+
"top_token_mass": 0.15106201171875
|
| 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_0021000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_00:32:18 done step_0021000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0033000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_01:38:41 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0033000.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_0033000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0033000.pt
|
| 3 |
+
[ckpt] step=33000
|
| 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_0033000.pt",
|
| 24 |
+
"step": 33000,
|
| 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.52794265924956,
|
| 50 |
+
"nll_per_token": 3.5980775200109547,
|
| 51 |
+
"tokens": 27157,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 48.37428762586346,
|
| 59 |
+
"nll_per_token": 3.8789684251611742,
|
| 60 |
+
"tokens": 22433,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 2.797182504419853,
|
| 68 |
+
"unique_tokens": 1406,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.04290771484375,
|
| 71 |
+
"distinct_2": 0.2140132874015748,
|
| 72 |
+
"top_token_mass": 0.345794677734375
|
| 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_0033000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_01:40:09 done step_0033000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0034000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_01:43:55 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0034000.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_0034000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0034000.pt
|
| 3 |
+
[ckpt] step=34000
|
| 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_0034000.pt",
|
| 24 |
+
"step": 34000,
|
| 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.12776251190259,
|
| 50 |
+
"nll_per_token": 3.500371677414823,
|
| 51 |
+
"tokens": 34032,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 42.39457963921305,
|
| 59 |
+
"nll_per_token": 3.747020515368044,
|
| 60 |
+
"tokens": 28823,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.5379146352037796,
|
| 68 |
+
"unique_tokens": 1620,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.0494384765625,
|
| 71 |
+
"distinct_2": 0.257689468503937,
|
| 72 |
+
"top_token_mass": 0.143035888671875
|
| 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_0034000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_01:45:23 done step_0034000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0038000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_02:06:16 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0038000.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_0038000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0038000.pt
|
| 3 |
+
[ckpt] step=38000
|
| 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_0038000.pt",
|
| 24 |
+
"step": 38000,
|
| 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.63094521372597,
|
| 50 |
+
"nll_per_token": 3.5154466316232162,
|
| 51 |
+
"tokens": 36373,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 46.12248543638734,
|
| 59 |
+
"nll_per_token": 3.8313005845903394,
|
| 60 |
+
"tokens": 30301,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.6560154748011517,
|
| 68 |
+
"unique_tokens": 2213,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.067535400390625,
|
| 71 |
+
"distinct_2": 0.3269869586614173,
|
| 72 |
+
"top_token_mass": 0.088470458984375
|
| 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_0038000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_02:07:44 done step_0038000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0046000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_02:51:01 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0046000.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_0046000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0046000.pt
|
| 3 |
+
[ckpt] step=46000
|
| 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_0046000.pt",
|
| 24 |
+
"step": 46000,
|
| 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": 31.36387952548299,
|
| 50 |
+
"nll_per_token": 3.445656897189349,
|
| 51 |
+
"tokens": 32110,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 41.301285095384074,
|
| 59 |
+
"nll_per_token": 3.7208936155938854,
|
| 60 |
+
"tokens": 27017,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.2403000800491895,
|
| 68 |
+
"unique_tokens": 1843,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.056243896484375,
|
| 71 |
+
"distinct_2": 0.28518700787401574,
|
| 72 |
+
"top_token_mass": 0.217864990234375
|
| 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_0046000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_02:52:29 done step_0046000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0070000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_05:04:36 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0070000.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_0070000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0070000.pt
|
| 3 |
+
[ckpt] step=70000
|
| 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_0070000.pt",
|
| 24 |
+
"step": 70000,
|
| 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": 34.62623490095348,
|
| 50 |
+
"nll_per_token": 3.544611628881008,
|
| 51 |
+
"tokens": 30022,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 46.91527187433584,
|
| 59 |
+
"nll_per_token": 3.8483432487659517,
|
| 60 |
+
"tokens": 24880,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.1183666256047453,
|
| 68 |
+
"unique_tokens": 2061,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.062896728515625,
|
| 71 |
+
"distinct_2": 0.30305733267716534,
|
| 72 |
+
"top_token_mass": 0.275146484375
|
| 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_0070000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_05:06:04 done step_0070000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0086000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_06:34:13 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0086000.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_0086000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0086000.pt
|
| 3 |
+
[ckpt] step=86000
|
| 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_0086000.pt",
|
| 24 |
+
"step": 86000,
|
| 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": 34.74809931980677,
|
| 50 |
+
"nll_per_token": 3.548124874682031,
|
| 51 |
+
"tokens": 34054,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 48.11665279080907,
|
| 59 |
+
"nll_per_token": 3.8736283290613485,
|
| 60 |
+
"tokens": 28218,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.514165014362856,
|
| 68 |
+
"unique_tokens": 2199,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.067108154296875,
|
| 71 |
+
"distinct_2": 0.3373216043307087,
|
| 72 |
+
"top_token_mass": 0.165069580078125
|
| 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_0086000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_06:35:42 done step_0086000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0087000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_06:39:28 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0087000.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_0087000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0087000.pt
|
| 3 |
+
[ckpt] step=87000
|
| 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_0087000.pt",
|
| 24 |
+
"step": 87000,
|
| 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": 37.572490028965,
|
| 50 |
+
"nll_per_token": 3.6262721344448807,
|
| 51 |
+
"tokens": 35507,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 48.67031168523643,
|
| 59 |
+
"nll_per_token": 3.885069227877383,
|
| 60 |
+
"tokens": 30112,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.6281564628090766,
|
| 68 |
+
"unique_tokens": 2318,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.07073974609375,
|
| 71 |
+
"distinct_2": 0.3623892716535433,
|
| 72 |
+
"top_token_mass": 0.10577392578125
|
| 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_0087000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_06:40:56 done step_0087000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0091000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_07:01:53 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0091000.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_0091000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0091000.pt
|
| 3 |
+
[ckpt] step=91000
|
| 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_0091000.pt",
|
| 24 |
+
"step": 91000,
|
| 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": 40.78150904177592,
|
| 50 |
+
"nll_per_token": 3.708228768919138,
|
| 51 |
+
"tokens": 26005,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 50.90887102234889,
|
| 59 |
+
"nll_per_token": 3.9300371917176355,
|
| 60 |
+
"tokens": 22154,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 2.7366672527527456,
|
| 68 |
+
"unique_tokens": 1634,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.04986572265625,
|
| 71 |
+
"distinct_2": 0.24818528543307086,
|
| 72 |
+
"top_token_mass": 0.362945556640625
|
| 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_0091000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_07:03:20 done step_0091000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/processed_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_logistic_normal_steps128_t1p45_n256.txt
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0001000.pt
|
| 2 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0002000.pt
|
| 3 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0003000.pt
|
| 4 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0004000.pt
|
| 5 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0005000.pt
|
| 6 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0006000.pt
|
| 7 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0007000.pt
|
| 8 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0008000.pt
|
| 9 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0009000.pt
|
| 10 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0010000.pt
|
| 11 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0011000.pt
|
| 12 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0012000.pt
|
| 13 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0013000.pt
|
| 14 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0014000.pt
|
| 15 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0015000.pt
|
| 16 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0016000.pt
|
| 17 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0017000.pt
|
| 18 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0018000.pt
|
| 19 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0019000.pt
|
| 20 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0020000.pt
|
| 21 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0021000.pt
|
| 22 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0022000.pt
|
| 23 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0023000.pt
|
| 24 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0024000.pt
|
| 25 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0025000.pt
|
| 26 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0026000.pt
|
| 27 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0027000.pt
|
| 28 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0028000.pt
|
| 29 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0029000.pt
|
| 30 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0030000.pt
|
| 31 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0031000.pt
|
| 32 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0032000.pt
|
| 33 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0033000.pt
|
| 34 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0034000.pt
|
| 35 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0035000.pt
|
| 36 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0036000.pt
|
| 37 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0037000.pt
|
| 38 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0038000.pt
|
| 39 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0039000.pt
|
| 40 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0040000.pt
|
| 41 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0041000.pt
|
| 42 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0042000.pt
|
| 43 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0043000.pt
|
| 44 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0044000.pt
|
| 45 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0045000.pt
|
| 46 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0046000.pt
|
| 47 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0047000.pt
|
| 48 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0048000.pt
|
| 49 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0049000.pt
|
| 50 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0050000.pt
|
| 51 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0051000.pt
|
| 52 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0052000.pt
|
| 53 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0053000.pt
|
| 54 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0054000.pt
|
| 55 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0055000.pt
|
| 56 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0056000.pt
|
| 57 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0057000.pt
|
| 58 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0058000.pt
|
| 59 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0059000.pt
|
| 60 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0060000.pt
|
| 61 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0061000.pt
|
| 62 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0062000.pt
|
| 63 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0063000.pt
|
| 64 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0064000.pt
|
| 65 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0065000.pt
|
| 66 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0066000.pt
|
| 67 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0067000.pt
|
| 68 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0068000.pt
|
| 69 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0069000.pt
|
| 70 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0070000.pt
|
| 71 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0071000.pt
|
| 72 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0072000.pt
|
| 73 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0073000.pt
|
| 74 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0074000.pt
|
| 75 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0075000.pt
|
| 76 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0076000.pt
|
| 77 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0077000.pt
|
| 78 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0078000.pt
|
| 79 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0079000.pt
|
| 80 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0080000.pt
|
| 81 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0081000.pt
|
| 82 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0082000.pt
|
| 83 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0083000.pt
|
| 84 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0084000.pt
|
| 85 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0085000.pt
|
| 86 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0086000.pt
|
| 87 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0087000.pt
|
| 88 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0088000.pt
|
| 89 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0089000.pt
|
| 90 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0090000.pt
|
| 91 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0091000.pt
|
| 92 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0092000.pt
|
| 93 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0093000.pt
|
| 94 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0094000.pt
|
| 95 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0095000.pt
|
| 96 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0096000.pt
|
| 97 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0097000.pt
|
| 98 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0098000.pt
|
| 99 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0099000.pt
|
| 100 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0100000.pt
|
| 101 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0101000.pt
|
| 102 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0102000.pt
|
| 103 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0103000.pt
|
| 104 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0104000.pt
|
| 105 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0105000.pt
|
| 106 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0106000.pt
|
| 107 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0107000.pt
|
| 108 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0108000.pt
|
| 109 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0109000.pt
|
| 110 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0110000.pt
|
| 111 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0111000.pt
|
| 112 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0112000.pt
|
| 113 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0113000.pt
|
| 114 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0114000.pt
|
| 115 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0115000.pt
|
| 116 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0116000.pt
|
| 117 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0117000.pt
|
| 118 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0118000.pt
|
| 119 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0119000.pt
|
| 120 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0120000.pt
|
| 121 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0121000.pt
|
| 122 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0122000.pt
|
| 123 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0123000.pt
|
| 124 |
+
runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0124000.pt
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_blip import *
|
| 22 |
+
from .image_processing_blip import *
|
| 23 |
+
from .image_processing_pil_blip import *
|
| 24 |
+
from .modeling_blip import *
|
| 25 |
+
from .modeling_blip_text import *
|
| 26 |
+
from .processing_blip import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
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/blip/configuration_blip.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Blip model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring, logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@auto_docstring(checkpoint="Salesforce/blip-vqa-base")
|
| 26 |
+
@strict
|
| 27 |
+
class BlipTextConfig(PreTrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
label_smoothing (float, *optional*):
|
| 30 |
+
A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
|
| 31 |
+
become a mixture of the original ground truth and a uniform distribution as described in
|
| 32 |
+
`Rethinking the Inception Architecture for Computer Vision <https://huggingface.co/papers/1512.00567>`__. Default: :math:`0.0`.
|
| 33 |
+
|
| 34 |
+
Example:
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
>>> from transformers import BlipTextConfig, BlipTextModel
|
| 38 |
+
|
| 39 |
+
>>> # Initializing a BlipTextConfig with Salesforce/blip-vqa-base style configuration
|
| 40 |
+
>>> configuration = BlipTextConfig()
|
| 41 |
+
|
| 42 |
+
>>> # Initializing a BlipTextModel (with random weights) from the Salesforce/blip-vqa-base style configuration
|
| 43 |
+
>>> model = BlipTextModel(configuration)
|
| 44 |
+
|
| 45 |
+
>>> # Accessing the model configuration
|
| 46 |
+
>>> configuration = model.config
|
| 47 |
+
```"""
|
| 48 |
+
|
| 49 |
+
model_type = "blip_text_model"
|
| 50 |
+
base_config_key = "text_config"
|
| 51 |
+
|
| 52 |
+
vocab_size: int = 30524
|
| 53 |
+
hidden_size: int = 768
|
| 54 |
+
encoder_hidden_size: int = 768
|
| 55 |
+
intermediate_size: int = 3072
|
| 56 |
+
projection_dim: int = 768
|
| 57 |
+
num_hidden_layers: int = 12
|
| 58 |
+
num_attention_heads: int = 8
|
| 59 |
+
max_position_embeddings: int = 512
|
| 60 |
+
hidden_act: str = "gelu"
|
| 61 |
+
layer_norm_eps: float = 1e-12
|
| 62 |
+
hidden_dropout_prob: float | int = 0.0
|
| 63 |
+
attention_probs_dropout_prob: float | int = 0.0
|
| 64 |
+
initializer_range: float = 0.02
|
| 65 |
+
bos_token_id: int | None = 30522
|
| 66 |
+
eos_token_id: int | list[int] | None = 2
|
| 67 |
+
pad_token_id: int | None = 0
|
| 68 |
+
sep_token_id: int | None = 102
|
| 69 |
+
is_decoder: bool = True
|
| 70 |
+
use_cache: bool = True
|
| 71 |
+
tie_word_embeddings: bool = True
|
| 72 |
+
label_smoothing: float = 0.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@auto_docstring(checkpoint="Salesforce/blip-vqa-base")
|
| 76 |
+
@strict
|
| 77 |
+
class BlipVisionConfig(PreTrainedConfig):
|
| 78 |
+
r"""
|
| 79 |
+
Example:
|
| 80 |
+
|
| 81 |
+
```python
|
| 82 |
+
>>> from transformers import BlipVisionConfig, BlipVisionModel
|
| 83 |
+
|
| 84 |
+
>>> # Initializing a BlipVisionConfig with Salesforce/blip-vqa-base style configuration
|
| 85 |
+
>>> configuration = BlipVisionConfig()
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a BlipVisionModel (with random weights) from the Salesforce/blip-vqa-base style configuration
|
| 88 |
+
>>> model = BlipVisionModel(configuration)
|
| 89 |
+
|
| 90 |
+
>>> # Accessing the model configuration
|
| 91 |
+
>>> configuration = model.config
|
| 92 |
+
```"""
|
| 93 |
+
|
| 94 |
+
model_type = "blip_vision_model"
|
| 95 |
+
base_config_key = "vision_config"
|
| 96 |
+
|
| 97 |
+
hidden_size: int = 768
|
| 98 |
+
intermediate_size: int = 3072
|
| 99 |
+
projection_dim: int = 512
|
| 100 |
+
num_hidden_layers: int = 12
|
| 101 |
+
num_attention_heads: int = 12
|
| 102 |
+
image_size: int | list[int] | tuple[int, int] = 384
|
| 103 |
+
patch_size: int | list[int] | tuple[int, int] = 16
|
| 104 |
+
hidden_act: str = "gelu"
|
| 105 |
+
layer_norm_eps: float = 1e-5
|
| 106 |
+
attention_dropout: float | int = 0.0
|
| 107 |
+
initializer_range: float = 1e-10
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@auto_docstring(checkpoint="Salesforce/blip-vqa-base")
|
| 111 |
+
@strict
|
| 112 |
+
class BlipConfig(PreTrainedConfig):
|
| 113 |
+
r"""
|
| 114 |
+
image_text_hidden_size (`int`, *optional*, defaults to 256):
|
| 115 |
+
Dimensionality of the hidden state of the image-text fusion layer.
|
| 116 |
+
label_smoothing (float, *optional*):
|
| 117 |
+
A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
|
| 118 |
+
become a mixture of the original ground truth and a uniform distribution as described in
|
| 119 |
+
`Rethinking the Inception Architecture for Computer Vision <https://huggingface.co/papers/1512.00567>`__. Default: :math:`0.0`.
|
| 120 |
+
|
| 121 |
+
Example:
|
| 122 |
+
|
| 123 |
+
```python
|
| 124 |
+
>>> from transformers import BlipConfig, BlipModel
|
| 125 |
+
|
| 126 |
+
>>> # Initializing a BlipConfig with Salesforce/blip-vqa-base style configuration
|
| 127 |
+
>>> configuration = BlipConfig()
|
| 128 |
+
|
| 129 |
+
>>> # Initializing a BlipPModel (with random weights) from the Salesforce/blip-vqa-base style configuration
|
| 130 |
+
>>> model = BlipModel(configuration)
|
| 131 |
+
|
| 132 |
+
>>> # Accessing the model configuration
|
| 133 |
+
>>> configuration = model.config
|
| 134 |
+
|
| 135 |
+
>>> # We can also initialize a BlipConfig from a BlipTextConfig and a BlipVisionConfig
|
| 136 |
+
|
| 137 |
+
>>> # Initializing a BLIPText and BLIPVision configuration
|
| 138 |
+
>>> config_text = BlipTextConfig()
|
| 139 |
+
>>> config_vision = BlipVisionConfig()
|
| 140 |
+
|
| 141 |
+
>>> config = BlipConfig(text_config=config_text, vision_config=config_vision)
|
| 142 |
+
```"""
|
| 143 |
+
|
| 144 |
+
model_type = "blip"
|
| 145 |
+
sub_configs = {"text_config": BlipTextConfig, "vision_config": BlipVisionConfig}
|
| 146 |
+
|
| 147 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 148 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 149 |
+
projection_dim: int = 512
|
| 150 |
+
logit_scale_init_value: float = 2.6592
|
| 151 |
+
image_text_hidden_size: int = 256
|
| 152 |
+
label_smoothing: float = 0.0
|
| 153 |
+
tie_word_embeddings: bool = True
|
| 154 |
+
initializer_factor: float = 1.0
|
| 155 |
+
initializer_range: float = 0.02
|
| 156 |
+
|
| 157 |
+
def __post_init__(self, **kwargs):
|
| 158 |
+
if self.text_config is None:
|
| 159 |
+
self.text_config = BlipTextConfig()
|
| 160 |
+
logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values.")
|
| 161 |
+
elif isinstance(self.text_config, dict):
|
| 162 |
+
self.text_config = BlipTextConfig(**self.text_config)
|
| 163 |
+
|
| 164 |
+
if self.vision_config is None:
|
| 165 |
+
self.vision_config = BlipVisionConfig()
|
| 166 |
+
logger.info("`vision_config` is `None`. initializing the `BlipVisionConfig` with default values.")
|
| 167 |
+
elif isinstance(self.vision_config, dict):
|
| 168 |
+
self.vision_config = BlipVisionConfig(**self.vision_config)
|
| 169 |
+
|
| 170 |
+
self.text_config.encoder_hidden_size = self.vision_config.hidden_size
|
| 171 |
+
|
| 172 |
+
super().__post_init__(**kwargs)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
__all__ = ["BlipConfig", "BlipTextConfig", "BlipVisionConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/image_processing_pil_blip.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 BLIP."""
|
| 15 |
+
|
| 16 |
+
from ...image_processing_backends import PilBackend
|
| 17 |
+
from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
|
| 18 |
+
from ...utils import auto_docstring
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@auto_docstring
|
| 22 |
+
class BlipImageProcessorPil(PilBackend):
|
| 23 |
+
resample = PILImageResampling.BICUBIC
|
| 24 |
+
image_mean = OPENAI_CLIP_MEAN
|
| 25 |
+
image_std = OPENAI_CLIP_STD
|
| 26 |
+
size = {"height": 384, "width": 384}
|
| 27 |
+
default_to_square = True
|
| 28 |
+
do_resize = True
|
| 29 |
+
do_rescale = True
|
| 30 |
+
do_normalize = True
|
| 31 |
+
do_convert_rgb = True
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = ["BlipImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/modeling_blip_text.py
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the BSD-3-clause license (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 |
+
# https://opensource.org/licenses/BSD-3-Clause
|
| 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 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import CrossEntropyLoss
|
| 21 |
+
|
| 22 |
+
from ... import initialization as init
|
| 23 |
+
from ...activations import ACT2FN
|
| 24 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 25 |
+
from ...generation import GenerationMixin
|
| 26 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 27 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 31 |
+
CausalLMOutputWithCrossAttentions,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import PreTrainedModel
|
| 34 |
+
from ...processing_utils import Unpack
|
| 35 |
+
from ...pytorch_utils import apply_chunking_to_forward
|
| 36 |
+
from ...utils import TransformersKwargs, can_return_tuple, logging
|
| 37 |
+
from ...utils.generic import merge_with_config_defaults
|
| 38 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 39 |
+
from .configuration_blip import BlipTextConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
|
| 46 |
+
class BlipTextEmbeddings(nn.Module):
|
| 47 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, config):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 52 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 53 |
+
|
| 54 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 55 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 56 |
+
|
| 57 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 58 |
+
self.register_buffer(
|
| 59 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
self.config = config
|
| 63 |
+
|
| 64 |
+
def forward(
|
| 65 |
+
self,
|
| 66 |
+
input_ids: torch.LongTensor | None = None,
|
| 67 |
+
position_ids: torch.LongTensor | None = None,
|
| 68 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 69 |
+
past_key_values_length: int = 0,
|
| 70 |
+
) -> torch.Tensor:
|
| 71 |
+
if input_ids is not None:
|
| 72 |
+
input_shape = input_ids.size()
|
| 73 |
+
else:
|
| 74 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 75 |
+
|
| 76 |
+
seq_length = input_shape[1]
|
| 77 |
+
|
| 78 |
+
if position_ids is None:
|
| 79 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 80 |
+
|
| 81 |
+
if inputs_embeds is None:
|
| 82 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 83 |
+
|
| 84 |
+
embeddings = inputs_embeds
|
| 85 |
+
|
| 86 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 87 |
+
embeddings += position_embeddings
|
| 88 |
+
|
| 89 |
+
embeddings = self.LayerNorm(embeddings)
|
| 90 |
+
embeddings = self.dropout(embeddings)
|
| 91 |
+
return embeddings
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
|
| 95 |
+
class BlipTextSelfAttention(nn.Module):
|
| 96 |
+
def __init__(self, config, is_cross_attention, layer_idx=None):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.config = config
|
| 99 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"The hidden size (%d) is not a multiple of the number of attention heads (%d)"
|
| 102 |
+
% (config.hidden_size, config.num_attention_heads)
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
self.num_attention_heads = config.num_attention_heads
|
| 106 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 107 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 108 |
+
self.layer_idx = layer_idx
|
| 109 |
+
|
| 110 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 111 |
+
if is_cross_attention:
|
| 112 |
+
self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
|
| 113 |
+
self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
|
| 114 |
+
else:
|
| 115 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 116 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 117 |
+
|
| 118 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 119 |
+
|
| 120 |
+
def save_attn_gradients(self, attn_gradients):
|
| 121 |
+
self.attn_gradients = attn_gradients
|
| 122 |
+
|
| 123 |
+
def get_attn_gradients(self):
|
| 124 |
+
return self.attn_gradients
|
| 125 |
+
|
| 126 |
+
def save_attention_map(self, attention_map):
|
| 127 |
+
self.attention_map = attention_map
|
| 128 |
+
|
| 129 |
+
def get_attention_map(self):
|
| 130 |
+
return self.attention_map
|
| 131 |
+
|
| 132 |
+
def forward(
|
| 133 |
+
self,
|
| 134 |
+
hidden_states: torch.Tensor,
|
| 135 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 136 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 137 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 138 |
+
past_key_values: Cache | None = None,
|
| 139 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 140 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 141 |
+
input_shape = hidden_states.shape[:-1]
|
| 142 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 143 |
+
query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 144 |
+
|
| 145 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 146 |
+
# and values come from an encoder; the attention mask needs to be
|
| 147 |
+
# such that the encoder's padding tokens are not attended to.
|
| 148 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 149 |
+
attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
|
| 150 |
+
|
| 151 |
+
is_updated = False
|
| 152 |
+
if past_key_values is not None:
|
| 153 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 154 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 155 |
+
if is_cross_attention:
|
| 156 |
+
# after the first generated id, we can subsequently re-use all key/value_layer from cache
|
| 157 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 158 |
+
else:
|
| 159 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 160 |
+
else:
|
| 161 |
+
curr_past_key_values = past_key_values
|
| 162 |
+
|
| 163 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 164 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 165 |
+
# reuse k,v, cross_attentions
|
| 166 |
+
key_layer = curr_past_key_values.layers[self.layer_idx].keys
|
| 167 |
+
value_layer = curr_past_key_values.layers[self.layer_idx].values
|
| 168 |
+
else:
|
| 169 |
+
kv_shape = (*current_states.shape[:-1], -1, self.attention_head_size)
|
| 170 |
+
key_layer = self.key(current_states).view(kv_shape).transpose(1, 2)
|
| 171 |
+
value_layer = self.value(current_states).view(kv_shape).transpose(1, 2)
|
| 172 |
+
|
| 173 |
+
if past_key_values is not None:
|
| 174 |
+
key_layer, value_layer = curr_past_key_values.update(key_layer, value_layer, self.layer_idx)
|
| 175 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 176 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 177 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 178 |
+
|
| 179 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 180 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 181 |
+
|
| 182 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 183 |
+
if attention_mask is not None:
|
| 184 |
+
# Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
|
| 185 |
+
attention_scores = attention_scores + attention_mask.to(attention_scores.device)
|
| 186 |
+
|
| 187 |
+
# Normalize the attention scores to probabilities.
|
| 188 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 189 |
+
|
| 190 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 191 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 192 |
+
attention_probs_dropped = self.dropout(attention_probs)
|
| 193 |
+
|
| 194 |
+
context_layer = torch.matmul(attention_probs_dropped, value_layer)
|
| 195 |
+
|
| 196 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 197 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 198 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 199 |
+
|
| 200 |
+
return context_layer, attention_probs
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert -> BlipText
|
| 204 |
+
class BlipTextSelfOutput(nn.Module):
|
| 205 |
+
def __init__(self, config):
|
| 206 |
+
super().__init__()
|
| 207 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 208 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 209 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 210 |
+
|
| 211 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 212 |
+
hidden_states = self.dense(hidden_states)
|
| 213 |
+
hidden_states = self.dropout(hidden_states)
|
| 214 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 215 |
+
return hidden_states
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
|
| 219 |
+
class BlipTextAttention(nn.Module):
|
| 220 |
+
def __init__(self, config, is_cross_attention=False, layer_idx=None):
|
| 221 |
+
super().__init__()
|
| 222 |
+
self.self = BlipTextSelfAttention(config, is_cross_attention, layer_idx=layer_idx)
|
| 223 |
+
self.output = BlipTextSelfOutput(config)
|
| 224 |
+
|
| 225 |
+
def forward(
|
| 226 |
+
self,
|
| 227 |
+
hidden_states: torch.Tensor,
|
| 228 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 229 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 230 |
+
past_key_values: Cache | None = None,
|
| 231 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 232 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 233 |
+
context_layer, attention_probs = self.self(
|
| 234 |
+
hidden_states,
|
| 235 |
+
attention_mask=attention_mask,
|
| 236 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 237 |
+
past_key_values=past_key_values,
|
| 238 |
+
)
|
| 239 |
+
attention_output = self.output(context_layer, hidden_states)
|
| 240 |
+
return attention_output, attention_probs
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert -> BlipText
|
| 244 |
+
class BlipTextIntermediate(nn.Module):
|
| 245 |
+
def __init__(self, config):
|
| 246 |
+
super().__init__()
|
| 247 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 248 |
+
if isinstance(config.hidden_act, str):
|
| 249 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 250 |
+
else:
|
| 251 |
+
self.intermediate_act_fn = config.hidden_act
|
| 252 |
+
|
| 253 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 254 |
+
hidden_states = self.dense(hidden_states)
|
| 255 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 256 |
+
return hidden_states
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert -> BlipText
|
| 260 |
+
class BlipTextOutput(nn.Module):
|
| 261 |
+
def __init__(self, config):
|
| 262 |
+
super().__init__()
|
| 263 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 264 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 265 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 266 |
+
|
| 267 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 268 |
+
hidden_states = self.dense(hidden_states)
|
| 269 |
+
hidden_states = self.dropout(hidden_states)
|
| 270 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 271 |
+
return hidden_states
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class BlipTextLayer(GradientCheckpointingLayer):
|
| 275 |
+
def __init__(self, config, layer_num):
|
| 276 |
+
super().__init__()
|
| 277 |
+
self.config = config
|
| 278 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 279 |
+
self.seq_len_dim = 1
|
| 280 |
+
self.attention = BlipTextAttention(config, layer_idx=layer_num)
|
| 281 |
+
self.layer_num = layer_num
|
| 282 |
+
if self.config.is_decoder:
|
| 283 |
+
self.crossattention = BlipTextAttention(
|
| 284 |
+
config, is_cross_attention=self.config.is_decoder, layer_idx=layer_num
|
| 285 |
+
)
|
| 286 |
+
self.intermediate = BlipTextIntermediate(config)
|
| 287 |
+
self.output = BlipTextOutput(config)
|
| 288 |
+
|
| 289 |
+
def forward(
|
| 290 |
+
self,
|
| 291 |
+
hidden_states: torch.Tensor,
|
| 292 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 293 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 294 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 295 |
+
past_key_values: Cache | None = None,
|
| 296 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 297 |
+
) -> torch.Tensor:
|
| 298 |
+
attention_output, _ = self.attention(
|
| 299 |
+
hidden_states,
|
| 300 |
+
attention_mask=attention_mask,
|
| 301 |
+
past_key_values=past_key_values,
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
if encoder_hidden_states is not None:
|
| 305 |
+
attention_output, _ = self.crossattention(
|
| 306 |
+
attention_output,
|
| 307 |
+
attention_mask=encoder_attention_mask,
|
| 308 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 309 |
+
past_key_values=past_key_values,
|
| 310 |
+
)
|
| 311 |
+
layer_output = apply_chunking_to_forward(
|
| 312 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 313 |
+
)
|
| 314 |
+
return layer_output
|
| 315 |
+
|
| 316 |
+
def feed_forward_chunk(self, attention_output):
|
| 317 |
+
intermediate_output = self.intermediate(attention_output)
|
| 318 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 319 |
+
return layer_output
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
|
| 323 |
+
class BlipTextEncoder(nn.Module):
|
| 324 |
+
def __init__(self, config):
|
| 325 |
+
super().__init__()
|
| 326 |
+
self.config = config
|
| 327 |
+
self.layer = nn.ModuleList([BlipTextLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 328 |
+
self.gradient_checkpointing = False
|
| 329 |
+
|
| 330 |
+
def forward(
|
| 331 |
+
self,
|
| 332 |
+
hidden_states: torch.Tensor,
|
| 333 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 334 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 335 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 336 |
+
past_key_values: Cache | None = None,
|
| 337 |
+
use_cache: bool | None = None,
|
| 338 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 339 |
+
) -> BaseModelOutputWithPastAndCrossAttentions:
|
| 340 |
+
if self.gradient_checkpointing and self.training:
|
| 341 |
+
if use_cache:
|
| 342 |
+
logger.warning(
|
| 343 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 344 |
+
)
|
| 345 |
+
use_cache = False
|
| 346 |
+
|
| 347 |
+
if use_cache:
|
| 348 |
+
# The model acts as encoder decoder but is not an encoder decoder. So we cast all cache objects to
|
| 349 |
+
# `EncoderDecoderCache` type assuming that the incoming cache is from `self_attention`
|
| 350 |
+
if isinstance(past_key_values, DynamicCache):
|
| 351 |
+
past_key_values = EncoderDecoderCache(past_key_values, DynamicCache(config=self.config))
|
| 352 |
+
elif past_key_values is None:
|
| 353 |
+
past_key_values = EncoderDecoderCache(
|
| 354 |
+
DynamicCache(config=self.config), DynamicCache(config=self.config)
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
for layer_module in self.layer:
|
| 358 |
+
hidden_states = layer_module(
|
| 359 |
+
hidden_states,
|
| 360 |
+
encoder_hidden_states,
|
| 361 |
+
attention_mask=attention_mask,
|
| 362 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 363 |
+
past_key_values=past_key_values,
|
| 364 |
+
**kwargs,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 368 |
+
last_hidden_state=hidden_states,
|
| 369 |
+
past_key_values=past_key_values,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BlipText
|
| 374 |
+
class BlipTextPooler(nn.Module):
|
| 375 |
+
def __init__(self, config):
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 378 |
+
self.activation = nn.Tanh()
|
| 379 |
+
|
| 380 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 381 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 382 |
+
# to the first token.
|
| 383 |
+
first_token_tensor = hidden_states[:, 0]
|
| 384 |
+
pooled_output = self.dense(first_token_tensor)
|
| 385 |
+
pooled_output = self.activation(pooled_output)
|
| 386 |
+
return pooled_output
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->BlipText
|
| 390 |
+
class BlipTextPredictionHeadTransform(nn.Module):
|
| 391 |
+
def __init__(self, config):
|
| 392 |
+
super().__init__()
|
| 393 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 394 |
+
if isinstance(config.hidden_act, str):
|
| 395 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 396 |
+
else:
|
| 397 |
+
self.transform_act_fn = config.hidden_act
|
| 398 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 399 |
+
|
| 400 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 401 |
+
hidden_states = self.dense(hidden_states)
|
| 402 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 403 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 404 |
+
return hidden_states
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->BlipText
|
| 408 |
+
class BlipTextLMPredictionHead(nn.Module):
|
| 409 |
+
def __init__(self, config):
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.transform = BlipTextPredictionHeadTransform(config)
|
| 412 |
+
|
| 413 |
+
# The output weights are the same as the input embeddings, but there is
|
| 414 |
+
# an output-only bias for each token.
|
| 415 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
| 416 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 417 |
+
|
| 418 |
+
def forward(self, hidden_states):
|
| 419 |
+
hidden_states = self.transform(hidden_states)
|
| 420 |
+
hidden_states = self.decoder(hidden_states)
|
| 421 |
+
return hidden_states
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->BlipText
|
| 425 |
+
class BlipTextOnlyMLMHead(nn.Module):
|
| 426 |
+
def __init__(self, config):
|
| 427 |
+
super().__init__()
|
| 428 |
+
self.predictions = BlipTextLMPredictionHead(config)
|
| 429 |
+
|
| 430 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
| 431 |
+
prediction_scores = self.predictions(sequence_output)
|
| 432 |
+
return prediction_scores
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
|
| 436 |
+
class BlipTextPreTrainedModel(PreTrainedModel):
|
| 437 |
+
"""
|
| 438 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 439 |
+
models.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
config: BlipTextConfig
|
| 443 |
+
base_model_prefix = "bert"
|
| 444 |
+
_no_split_modules = []
|
| 445 |
+
_can_record_outputs = {
|
| 446 |
+
"hidden_states": BlipTextLayer,
|
| 447 |
+
"attentions": [
|
| 448 |
+
OutputRecorder(BlipTextSelfAttention, index=1, layer_name=".attention."),
|
| 449 |
+
],
|
| 450 |
+
"cross_attentions": [
|
| 451 |
+
OutputRecorder(BlipTextSelfAttention, index=1, layer_name=".crossattention."),
|
| 452 |
+
],
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
def _init_weights(self, module):
|
| 456 |
+
super()._init_weights(module)
|
| 457 |
+
if isinstance(module, BlipTextEmbeddings):
|
| 458 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
|
| 462 |
+
class BlipTextModel(BlipTextPreTrainedModel):
|
| 463 |
+
"""
|
| 464 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 465 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 466 |
+
all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 467 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
|
| 468 |
+
`encoder_hidden_states` is then expected as an input to the forward pass.
|
| 469 |
+
"""
|
| 470 |
+
|
| 471 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 472 |
+
super().__init__(config)
|
| 473 |
+
self.config = config
|
| 474 |
+
|
| 475 |
+
self.embeddings = BlipTextEmbeddings(config)
|
| 476 |
+
self.encoder = BlipTextEncoder(config)
|
| 477 |
+
self.pooler = BlipTextPooler(config) if add_pooling_layer else None
|
| 478 |
+
|
| 479 |
+
self.post_init()
|
| 480 |
+
|
| 481 |
+
def get_input_embeddings(self):
|
| 482 |
+
return self.embeddings.word_embeddings
|
| 483 |
+
|
| 484 |
+
def set_input_embeddings(self, value):
|
| 485 |
+
self.embeddings.word_embeddings = value
|
| 486 |
+
|
| 487 |
+
@merge_with_config_defaults
|
| 488 |
+
@capture_outputs
|
| 489 |
+
def forward(
|
| 490 |
+
self,
|
| 491 |
+
input_ids: torch.Tensor | None = None,
|
| 492 |
+
attention_mask: torch.Tensor | None = None,
|
| 493 |
+
position_ids: torch.Tensor | None = None,
|
| 494 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 495 |
+
encoder_embeds: torch.Tensor | None = None,
|
| 496 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 497 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 498 |
+
past_key_values: Cache | None = None,
|
| 499 |
+
use_cache: bool | None = None,
|
| 500 |
+
is_decoder: bool | None = False,
|
| 501 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 502 |
+
) -> BaseModelOutputWithPoolingAndCrossAttentions:
|
| 503 |
+
r"""
|
| 504 |
+
encoder_hidden_states (`torch.FloatTensor`, *optional*):
|
| 505 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 506 |
+
the model is configured as a decoder.
|
| 507 |
+
encoder_attention_mask (`torch.FloatTensor`, *optional*):
|
| 508 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 509 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 510 |
+
- 1 for tokens that are **not masked**,
|
| 511 |
+
- 0 for tokens that are **masked**.
|
| 512 |
+
past_key_values (`Cache`, *optional*):
|
| 513 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 514 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 515 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 516 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 517 |
+
use_cache (`bool`, *optional*):
|
| 518 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 519 |
+
`past_key_values`).
|
| 520 |
+
"""
|
| 521 |
+
if not is_decoder:
|
| 522 |
+
use_cache = False
|
| 523 |
+
|
| 524 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 525 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 526 |
+
|
| 527 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 528 |
+
|
| 529 |
+
if encoder_embeds is None:
|
| 530 |
+
embedding_output = self.embeddings(
|
| 531 |
+
input_ids=input_ids,
|
| 532 |
+
position_ids=position_ids,
|
| 533 |
+
inputs_embeds=inputs_embeds,
|
| 534 |
+
past_key_values_length=past_key_values_length,
|
| 535 |
+
)
|
| 536 |
+
else:
|
| 537 |
+
embedding_output = encoder_embeds
|
| 538 |
+
|
| 539 |
+
if is_decoder:
|
| 540 |
+
attention_mask = create_causal_mask(
|
| 541 |
+
config=self.config,
|
| 542 |
+
inputs_embeds=embedding_output,
|
| 543 |
+
attention_mask=attention_mask,
|
| 544 |
+
past_key_values=past_key_values,
|
| 545 |
+
)
|
| 546 |
+
else:
|
| 547 |
+
attention_mask = create_bidirectional_mask(
|
| 548 |
+
config=self.config,
|
| 549 |
+
inputs_embeds=embedding_output,
|
| 550 |
+
attention_mask=attention_mask,
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
if encoder_attention_mask is not None:
|
| 554 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 555 |
+
config=self.config,
|
| 556 |
+
inputs_embeds=embedding_output,
|
| 557 |
+
attention_mask=encoder_attention_mask,
|
| 558 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
encoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.encoder(
|
| 562 |
+
embedding_output,
|
| 563 |
+
attention_mask=attention_mask,
|
| 564 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 565 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 566 |
+
past_key_values=past_key_values,
|
| 567 |
+
use_cache=use_cache,
|
| 568 |
+
**kwargs,
|
| 569 |
+
)
|
| 570 |
+
sequence_output = encoder_outputs.last_hidden_state
|
| 571 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 572 |
+
|
| 573 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 574 |
+
last_hidden_state=sequence_output,
|
| 575 |
+
pooler_output=pooled_output,
|
| 576 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 577 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 578 |
+
attentions=encoder_outputs.attentions,
|
| 579 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
|
| 584 |
+
class BlipTextLMHeadModel(BlipTextPreTrainedModel, GenerationMixin):
|
| 585 |
+
_tied_weights_keys = {
|
| 586 |
+
"cls.predictions.decoder.bias": "cls.predictions.bias",
|
| 587 |
+
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
def __init__(self, config):
|
| 591 |
+
super().__init__(config)
|
| 592 |
+
|
| 593 |
+
self.bert = BlipTextModel(config, add_pooling_layer=False)
|
| 594 |
+
self.cls = BlipTextOnlyMLMHead(config)
|
| 595 |
+
self.label_smoothing = config.label_smoothing
|
| 596 |
+
|
| 597 |
+
self.post_init()
|
| 598 |
+
|
| 599 |
+
def get_input_embeddings(self):
|
| 600 |
+
return self.bert.get_input_embeddings()
|
| 601 |
+
|
| 602 |
+
def set_input_embeddings(self, new_embeddings):
|
| 603 |
+
self.bert.set_input_embeddings(new_embeddings)
|
| 604 |
+
|
| 605 |
+
def get_output_embeddings(self):
|
| 606 |
+
return self.cls.predictions.decoder
|
| 607 |
+
|
| 608 |
+
def set_output_embeddings(self, new_embeddings):
|
| 609 |
+
self.cls.predictions.decoder = new_embeddings
|
| 610 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 611 |
+
|
| 612 |
+
@can_return_tuple
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
input_ids: torch.Tensor | None = None,
|
| 616 |
+
attention_mask: torch.Tensor | None = None,
|
| 617 |
+
position_ids: torch.Tensor | None = None,
|
| 618 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 619 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 620 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 621 |
+
labels: torch.Tensor | None = None,
|
| 622 |
+
past_key_values: Cache | None = None,
|
| 623 |
+
use_cache: bool | None = None,
|
| 624 |
+
return_logits: bool | None = False,
|
| 625 |
+
is_decoder: bool | None = True,
|
| 626 |
+
reduction: str | None = "mean",
|
| 627 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 628 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 629 |
+
) -> CausalLMOutputWithCrossAttentions:
|
| 630 |
+
r"""
|
| 631 |
+
encoder_hidden_states (`torch.FloatTensor`, *optional*): Sequence of
|
| 632 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
|
| 633 |
+
configured as a decoder.
|
| 634 |
+
encoder_attention_mask (`torch.FloatTensor`, *optional*):
|
| 635 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 636 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 637 |
+
- 1 for tokens that are **not masked**,
|
| 638 |
+
- 0 for tokens that are **masked**.
|
| 639 |
+
labels (`torch.LongTensor`, *optional*):
|
| 640 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 641 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 642 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
| 643 |
+
past_key_values (`Cache`, *optional*):
|
| 644 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 645 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 646 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 647 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 648 |
+
use_cache (`bool`, *optional*):
|
| 649 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 650 |
+
`past_key_values`).
|
| 651 |
+
"""
|
| 652 |
+
if labels is not None:
|
| 653 |
+
use_cache = False
|
| 654 |
+
|
| 655 |
+
outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.bert(
|
| 656 |
+
input_ids,
|
| 657 |
+
attention_mask=attention_mask,
|
| 658 |
+
position_ids=position_ids,
|
| 659 |
+
inputs_embeds=inputs_embeds,
|
| 660 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 661 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 662 |
+
past_key_values=past_key_values,
|
| 663 |
+
use_cache=use_cache,
|
| 664 |
+
is_decoder=is_decoder,
|
| 665 |
+
**kwargs,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
hidden_states = outputs.last_hidden_state
|
| 669 |
+
# Only compute necessary logits
|
| 670 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 671 |
+
prediction_scores = self.cls(hidden_states[:, slice_indices, :])
|
| 672 |
+
|
| 673 |
+
if return_logits:
|
| 674 |
+
return prediction_scores[:, :-1, :].contiguous()
|
| 675 |
+
|
| 676 |
+
lm_loss = None
|
| 677 |
+
if labels is not None:
|
| 678 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
| 679 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
| 680 |
+
labels = labels[:, 1:].contiguous().to(shifted_prediction_scores.device)
|
| 681 |
+
loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=self.label_smoothing)
|
| 682 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 683 |
+
if reduction == "none":
|
| 684 |
+
lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
|
| 685 |
+
|
| 686 |
+
return CausalLMOutputWithCrossAttentions(
|
| 687 |
+
loss=lm_loss,
|
| 688 |
+
logits=prediction_scores,
|
| 689 |
+
past_key_values=outputs.past_key_values,
|
| 690 |
+
hidden_states=outputs.hidden_states,
|
| 691 |
+
attentions=outputs.attentions,
|
| 692 |
+
cross_attentions=outputs.cross_attentions,
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
| 696 |
+
# Overwrite -- hardcoded key return (`is_decoder=True`)
|
| 697 |
+
|
| 698 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 699 |
+
input_ids,
|
| 700 |
+
past_key_values=past_key_values,
|
| 701 |
+
attention_mask=attention_mask,
|
| 702 |
+
**model_kwargs,
|
| 703 |
+
)
|
| 704 |
+
model_inputs["is_decoder"] = True
|
| 705 |
+
|
| 706 |
+
return model_inputs
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
__all__ = ["BlipTextModel", "BlipTextLMHeadModel", "BlipTextPreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_qwen2_audio import *
|
| 22 |
+
from .modeling_qwen2_audio import *
|
| 23 |
+
from .processing_qwen2_audio 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/qwen2_audio/configuration_qwen2_audio.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 3 |
+
# you may not use this file except in compliance with the License.
|
| 4 |
+
# You may obtain a copy of the License at
|
| 5 |
+
#
|
| 6 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
#
|
| 8 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 9 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 10 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 11 |
+
# See the License for the specific language governing permissions and
|
| 12 |
+
# limitations under the License.
|
| 13 |
+
"""Qwen2Audio model configuration"""
|
| 14 |
+
|
| 15 |
+
from huggingface_hub.dataclasses import strict
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PreTrainedConfig
|
| 18 |
+
from ...utils import auto_docstring
|
| 19 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="Qwen/Qwen2-Audio-7B")
|
| 23 |
+
@strict
|
| 24 |
+
class Qwen2AudioEncoderConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
max_source_positions (`int`, *optional*, defaults to 1500):
|
| 27 |
+
The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
|
| 28 |
+
|
| 29 |
+
Example:
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
>>> from transformers import Qwen2AudioEncoderConfig, Qwen2AudioEncoder
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a Qwen2AudioEncoderConfig
|
| 35 |
+
>>> configuration = Qwen2AudioEncoderConfig()
|
| 36 |
+
|
| 37 |
+
>>> # Initializing a Qwen2AudioEncoder (with random weights)
|
| 38 |
+
>>> model = Qwen2AudioEncoder(configuration)
|
| 39 |
+
|
| 40 |
+
>>> # Accessing the model configuration
|
| 41 |
+
>>> configuration = model.config
|
| 42 |
+
```"""
|
| 43 |
+
|
| 44 |
+
model_type = "qwen2_audio_encoder"
|
| 45 |
+
attribute_map = {
|
| 46 |
+
"num_hidden_layers": "encoder_layers",
|
| 47 |
+
"hidden_size": "d_model",
|
| 48 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 49 |
+
"intermediate_size": "encoder_ffn_dim",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
num_mel_bins: int = 128
|
| 53 |
+
encoder_layers: int = 32
|
| 54 |
+
encoder_attention_heads: int = 20
|
| 55 |
+
encoder_ffn_dim: int = 5120
|
| 56 |
+
encoder_layerdrop: float | int = 0.0
|
| 57 |
+
d_model: int = 1280
|
| 58 |
+
dropout: float | int = 0.0
|
| 59 |
+
attention_dropout: float | int = 0.0
|
| 60 |
+
activation_function: str = "gelu"
|
| 61 |
+
activation_dropout: float | int = 0.0
|
| 62 |
+
scale_embedding: bool = False
|
| 63 |
+
initializer_range: float = 0.02
|
| 64 |
+
max_source_positions: int = 1500
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@auto_docstring(checkpoint="Qwen/Qwen2-Audio-7B")
|
| 68 |
+
@strict
|
| 69 |
+
class Qwen2AudioConfig(PreTrainedConfig):
|
| 70 |
+
r"""
|
| 71 |
+
Example:
|
| 72 |
+
|
| 73 |
+
```python
|
| 74 |
+
>>> from transformers import Qwen2AudioForConditionalGeneration, Qwen2AudioConfig, Qwen2AudioEncoderConfig, Qwen2Config
|
| 75 |
+
|
| 76 |
+
>>> # Initializing a Qwen2AudioEncoder config
|
| 77 |
+
>>> audio_config = Qwen2AudioEncoderConfig()
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a Qwen2 config
|
| 80 |
+
>>> text_config = Qwen2Config()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a Qwen2Audio configuration
|
| 83 |
+
>>> configuration = Qwen2AudioConfig(audio_config, text_config)
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a model from the qwen2-audio style configuration
|
| 86 |
+
>>> model = Qwen2AudioForConditionalGeneration(configuration)
|
| 87 |
+
|
| 88 |
+
>>> # Accessing the model configuration
|
| 89 |
+
>>> configuration = model.config
|
| 90 |
+
```"""
|
| 91 |
+
|
| 92 |
+
model_type = "qwen2_audio"
|
| 93 |
+
attribute_map = {
|
| 94 |
+
"audio_token_id": "audio_token_index",
|
| 95 |
+
}
|
| 96 |
+
sub_configs = {"text_config": AutoConfig, "audio_config": AutoConfig}
|
| 97 |
+
|
| 98 |
+
audio_config: dict | PreTrainedConfig | None = None
|
| 99 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 100 |
+
audio_token_index: int = 151646
|
| 101 |
+
|
| 102 |
+
def __post_init__(self, **kwargs):
|
| 103 |
+
if isinstance(self.audio_config, dict):
|
| 104 |
+
self.audio_config["model_type"] = self.audio_config.get("model_type", "qwen2_audio_encoder")
|
| 105 |
+
self.audio_config = CONFIG_MAPPING[self.audio_config["model_type"]](**self.audio_config)
|
| 106 |
+
elif self.audio_config is None:
|
| 107 |
+
self.audio_config = CONFIG_MAPPING["qwen2_audio_encoder"](
|
| 108 |
+
d_model=1280,
|
| 109 |
+
encoder_attention_heads=20,
|
| 110 |
+
encoder_ffn_dim=5120,
|
| 111 |
+
encoder_layerdrop=0.0,
|
| 112 |
+
encoder_layers=32,
|
| 113 |
+
num_mel_bins=128,
|
| 114 |
+
max_source_positions=1500,
|
| 115 |
+
scale_embedding=False,
|
| 116 |
+
activation_function="gelu",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
if isinstance(self.text_config, dict):
|
| 120 |
+
self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
|
| 121 |
+
self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
|
| 122 |
+
elif self.text_config is None:
|
| 123 |
+
self.text_config = CONFIG_MAPPING["qwen2"]()
|
| 124 |
+
|
| 125 |
+
super().__post_init__(**kwargs)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
__all__ = ["Qwen2AudioConfig", "Qwen2AudioEncoderConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/configuration_switch_transformers.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022, Google and HuggingFace Inc.
|
| 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 |
+
"""Switch Transformers model configuration"""
|
| 15 |
+
|
| 16 |
+
from typing import Literal
|
| 17 |
+
|
| 18 |
+
from huggingface_hub.dataclasses import strict
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PreTrainedConfig
|
| 21 |
+
from ...utils import auto_docstring
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="google/switch-base-8")
|
| 25 |
+
@strict
|
| 26 |
+
class SwitchTransformersConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
num_sparse_encoder_layers (`int`, *optional*, defaults to 3):
|
| 29 |
+
Number of sparse (MoE) dense hidden layers in the Transformer encoder layer.
|
| 30 |
+
Note: When set to 0 with `num_layers=1`, the current implementation may still create a sparse layer
|
| 31 |
+
due to the sparse step calculation. This edge case is not encountered in existing checkpoints.
|
| 32 |
+
num_sparse_decoder_layers (`int`, *optional*, defaults to 3):
|
| 33 |
+
Number of sparse (MoE) dense hidden layers in the Transformer decoder layer.
|
| 34 |
+
Note: When set to 0 with `num_decoder_layers=1`, the current implementation may still create a sparse
|
| 35 |
+
layer due to the sparse step calculation. This edge case is not encountered in existing checkpoints.
|
| 36 |
+
router_bias (`bool`, *optional*, defaults to `False`):
|
| 37 |
+
Whether to add a bias to the router.
|
| 38 |
+
router_dtype (`str`, *optional*, default to `"float32"`):
|
| 39 |
+
The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
|
| 40 |
+
*selective precision* discussion in [the paper](https://huggingface.co/papers/2101.03961).
|
| 41 |
+
router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
|
| 42 |
+
Whether to ignore padding tokens when routing.
|
| 43 |
+
relative_attention_num_buckets (`int`, *optional*, defaults to 32):
|
| 44 |
+
The number of buckets to use for each attention layer.
|
| 45 |
+
relative_attention_max_distance (`int`, *optional*, defaults to 128):
|
| 46 |
+
The maximum distance of the longer sequences for the bucket separation.
|
| 47 |
+
dense_act_fn (`string`, *optional*, defaults to `"relu"`):
|
| 48 |
+
Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. SwitchTransformersv1.1
|
| 49 |
+
uses the `"gated-gelu"` feed forward projection. Original SwitchTransformers uses `"relu"`.
|
| 50 |
+
add_router_probs (`bool`, *optional*, defaults to `False`):
|
| 51 |
+
Whether to output router probabilities to compute router auxiliary loss.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
model_type = "switch_transformers"
|
| 55 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 56 |
+
attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
|
| 57 |
+
|
| 58 |
+
vocab_size: int = 32128
|
| 59 |
+
d_model: int = 768
|
| 60 |
+
d_kv: int = 64
|
| 61 |
+
d_ff: int = 2048
|
| 62 |
+
expert_capacity: int = 64
|
| 63 |
+
num_layers: int = 12
|
| 64 |
+
num_sparse_encoder_layers: int = 3
|
| 65 |
+
num_decoder_layers: int | None = 12
|
| 66 |
+
num_sparse_decoder_layers: int = 3
|
| 67 |
+
num_heads: int = 12
|
| 68 |
+
num_experts: int = 8
|
| 69 |
+
router_bias: bool = False
|
| 70 |
+
router_jitter_noise: int | float = 0.01
|
| 71 |
+
router_dtype: Literal["float32", "float16", "bfloat16"] = "float32"
|
| 72 |
+
router_ignore_padding_tokens: bool = False
|
| 73 |
+
relative_attention_num_buckets: int = 32
|
| 74 |
+
relative_attention_max_distance: int = 128
|
| 75 |
+
dropout_rate: float | int = 0.1
|
| 76 |
+
layer_norm_epsilon: float = 1e-6
|
| 77 |
+
router_z_loss_coef: float = 0.001
|
| 78 |
+
router_aux_loss_coef: float = 0.001
|
| 79 |
+
initializer_factor: float = 1.0
|
| 80 |
+
dense_act_fn: str = "relu"
|
| 81 |
+
is_encoder_decoder: bool = True
|
| 82 |
+
add_router_probs: bool = False
|
| 83 |
+
use_cache: bool = True
|
| 84 |
+
pad_token_id: int | None = 0
|
| 85 |
+
eos_token_id: int | list[int] | None = 1
|
| 86 |
+
bos_token_id: int | None = None
|
| 87 |
+
tie_word_embeddings: bool = True
|
| 88 |
+
is_decoder: bool = False
|
| 89 |
+
add_cross_attention: bool = False
|
| 90 |
+
|
| 91 |
+
def __post_init__(self, **kwargs):
|
| 92 |
+
self.num_decoder_layers = (
|
| 93 |
+
self.num_decoder_layers if self.num_decoder_layers is not None else self.num_layers
|
| 94 |
+
) # default = symmetry
|
| 95 |
+
|
| 96 |
+
# This tells us, each how many encoder layer we'll have to set a sparse layer.
|
| 97 |
+
if self.num_sparse_encoder_layers > 0:
|
| 98 |
+
self.encoder_sparse_step = self.num_layers // self.num_sparse_encoder_layers
|
| 99 |
+
else:
|
| 100 |
+
self.encoder_sparse_step = self.num_layers # HACK: this will create 0 sparse layers
|
| 101 |
+
|
| 102 |
+
# This tells us, each how many decoder layer we'll have to set a sparse layer.
|
| 103 |
+
if self.num_sparse_decoder_layers > 0:
|
| 104 |
+
self.decoder_sparse_step = self.num_decoder_layers // self.num_sparse_decoder_layers
|
| 105 |
+
else:
|
| 106 |
+
self.decoder_sparse_step = self.num_decoder_layers # HACK: this will create 0 sparse layers
|
| 107 |
+
|
| 108 |
+
super().__post_init__(**kwargs)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
__all__ = ["SwitchTransformersConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/modeling_switch_transformers.py
ADDED
|
@@ -0,0 +1,1095 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/switch_transformers/modular_switch_transformers.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_switch_transformers.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2022 SwitchTransformers Authors and HuggingFace Inc. team.
|
| 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 |
+
import copy
|
| 22 |
+
import math
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
from torch.nn import CrossEntropyLoss
|
| 27 |
+
|
| 28 |
+
from ... import initialization as init
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 31 |
+
from ...generation import GenerationMixin
|
| 32 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 33 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 34 |
+
from ...modeling_outputs import (
|
| 35 |
+
MoEModelOutput,
|
| 36 |
+
MoEModelOutputWithPastAndCrossAttentions,
|
| 37 |
+
Seq2SeqMoEModelOutput,
|
| 38 |
+
Seq2SeqMoEOutput,
|
| 39 |
+
)
|
| 40 |
+
from ...modeling_utils import PreTrainedModel
|
| 41 |
+
from ...processing_utils import Unpack
|
| 42 |
+
from ...utils import TransformersKwargs, auto_docstring, is_torchdynamo_compiling, logging
|
| 43 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 44 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 45 |
+
from .configuration_switch_transformers import SwitchTransformersConfig
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class SwitchTransformersTop1Router(nn.Module):
|
| 52 |
+
"""
|
| 53 |
+
Router using tokens choose top-1 experts assignment.
|
| 54 |
+
|
| 55 |
+
This router uses the same mechanism as in Switch Transformer (https://huggingface.co/papers/2101.03961) and V-MoE
|
| 56 |
+
(https://huggingface.co/papers/2106.05974): tokens choose their top experts. Items are sorted by router_probs and then
|
| 57 |
+
routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee that each
|
| 58 |
+
token is processed by an expert**, or that each expert receives at least one token.
|
| 59 |
+
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.num_experts = config.num_experts
|
| 65 |
+
self.expert_capacity = config.expert_capacity
|
| 66 |
+
self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
|
| 67 |
+
self.jitter_noise = config.router_jitter_noise
|
| 68 |
+
self.ignore_padding_tokens = config.router_ignore_padding_tokens
|
| 69 |
+
self.dtype = getattr(torch, config.router_dtype)
|
| 70 |
+
|
| 71 |
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 72 |
+
r"""
|
| 73 |
+
Computes router probabilities from input hidden states.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
hidden_states (`torch.Tensor`):
|
| 77 |
+
(batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
|
| 78 |
+
Returns:
|
| 79 |
+
router_probabilities (`torch.Tensor`):
|
| 80 |
+
Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
|
| 81 |
+
token and expert. Used for routing tokens to experts.
|
| 82 |
+
router_logits (`torch.Tensor`):
|
| 83 |
+
Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
|
| 84 |
+
This is used later for computing router z-loss.
|
| 85 |
+
"""
|
| 86 |
+
# float32 is used to ensure stability. See the discussion of "selective precision" in
|
| 87 |
+
# https://huggingface.co/papers/2101.03961.
|
| 88 |
+
# We also store the previous dtype to cast back the output to the previous dtype
|
| 89 |
+
self.input_dtype = hidden_states.dtype
|
| 90 |
+
hidden_states = hidden_states.to(self.dtype)
|
| 91 |
+
if self.training and self.jitter_noise > 0:
|
| 92 |
+
# Multiply the token inputs by the uniform distribution - adding some noise
|
| 93 |
+
hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
|
| 94 |
+
self.classifier = self.classifier.to(self.dtype)
|
| 95 |
+
router_logits = self.classifier(hidden_states)
|
| 96 |
+
|
| 97 |
+
# Apply Softmax and cast back to the original `dtype`
|
| 98 |
+
router_probs = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(self.input_dtype)
|
| 99 |
+
router_logits, expert_index = torch.max(router_probs, dim=-1, keepdim=True)
|
| 100 |
+
expert_index = torch.nn.functional.one_hot(expert_index, num_classes=self.num_experts)
|
| 101 |
+
token_priority = torch.cumsum(expert_index, dim=-2)
|
| 102 |
+
# mask if the token routed to the expert will overflow
|
| 103 |
+
expert_capacity_mask = token_priority <= self.expert_capacity
|
| 104 |
+
expert_index = expert_index * expert_capacity_mask
|
| 105 |
+
router_probs = torch.max(router_probs, dim=-1).values.unsqueeze(-1)
|
| 106 |
+
return router_probs, expert_index, router_logits
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class SwitchTransformersLayerNorm(nn.Module):
|
| 110 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 111 |
+
"""
|
| 112 |
+
Construct a layernorm module in the SWITCH_TRANSFORMERS style. No bias and no subtraction of mean.
|
| 113 |
+
"""
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 116 |
+
self.variance_epsilon = eps
|
| 117 |
+
|
| 118 |
+
def forward(self, hidden_states):
|
| 119 |
+
# SWITCH_TRANSFORMERS uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
|
| 120 |
+
# Square Layer Normalization https://huggingface.co/papers/1910.07467 thus variance is calculated
|
| 121 |
+
# w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
|
| 122 |
+
# half-precision inputs is done in fp32
|
| 123 |
+
|
| 124 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 125 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 126 |
+
|
| 127 |
+
# convert into half-precision if necessary
|
| 128 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
| 129 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
| 130 |
+
|
| 131 |
+
return self.weight * hidden_states
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class SwitchTransformersDenseActDense(nn.Module):
|
| 135 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 138 |
+
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
|
| 139 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 140 |
+
self.act = ACT2FN[config.dense_act_fn]
|
| 141 |
+
|
| 142 |
+
def forward(self, hidden_states):
|
| 143 |
+
hidden_states = self.wi(hidden_states)
|
| 144 |
+
hidden_states = self.act(hidden_states)
|
| 145 |
+
hidden_states = self.dropout(hidden_states)
|
| 146 |
+
if (
|
| 147 |
+
isinstance(self.wo.weight, torch.Tensor)
|
| 148 |
+
and hidden_states.dtype != self.wo.weight.dtype
|
| 149 |
+
and self.wo.weight.dtype != torch.int8
|
| 150 |
+
):
|
| 151 |
+
hidden_states = hidden_states.to(self.wo.weight.dtype)
|
| 152 |
+
hidden_states = self.wo(hidden_states)
|
| 153 |
+
return hidden_states
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SwitchTransformersExperts(nn.ModuleDict):
|
| 157 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.num_experts = config.num_experts
|
| 160 |
+
for idx in range(config.num_experts):
|
| 161 |
+
self[f"expert_{idx}"] = SwitchTransformersDenseActDense(config)
|
| 162 |
+
|
| 163 |
+
def forward(
|
| 164 |
+
self, hidden_states: torch.Tensor, selected_experts: torch.Tensor, routing_weights: torch.Tensor
|
| 165 |
+
) -> torch.Tensor:
|
| 166 |
+
final_hidden_states = torch.zeros_like(hidden_states)
|
| 167 |
+
expert_mask = selected_experts.permute(2, 1, 0)
|
| 168 |
+
|
| 169 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 170 |
+
for expert_idx in expert_hit:
|
| 171 |
+
idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
|
| 172 |
+
current_state = hidden_states[None, top_x].reshape(-1, hidden_states.shape[-1])
|
| 173 |
+
current_hidden_states = self[f"expert_{expert_idx[0]}"](current_state) * routing_weights[top_x, idx, None]
|
| 174 |
+
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
| 175 |
+
return final_hidden_states
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class SwitchTransformersSparseMLP(nn.Module): # inherit from mixtral
|
| 179 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.router = SwitchTransformersTop1Router(config)
|
| 182 |
+
self.experts = SwitchTransformersExperts(config)
|
| 183 |
+
|
| 184 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 185 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 186 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 187 |
+
_, selected_experts, routing_weights = self.router(hidden_states)
|
| 188 |
+
hidden_states = self.experts(hidden_states, selected_experts, routing_weights)
|
| 189 |
+
hidden_states = hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
| 190 |
+
return hidden_states
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SwitchTransformersLayerFF(nn.Module):
|
| 194 |
+
r"""
|
| 195 |
+
Switch Transformers Feed Forward layer module. This is a wrapper around the Mixture of Experts module.
|
| 196 |
+
|
| 197 |
+
Parameters:
|
| 198 |
+
config : ([`SwitchTransformersConfig`]): Model configuration class with all the parameters of the model.
|
| 199 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 200 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 201 |
+
is_sparse (`bool`):
|
| 202 |
+
Whether the MLP layer is a `Sparse` layer (contains a Mixture of Experts) or not
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
def __init__(self, config: SwitchTransformersConfig, is_sparse=False):
|
| 206 |
+
super().__init__()
|
| 207 |
+
self.is_sparse = is_sparse
|
| 208 |
+
|
| 209 |
+
# Check if it is a sparse layer, if not then it is a dense layer
|
| 210 |
+
if not self.is_sparse:
|
| 211 |
+
self.mlp = SwitchTransformersDenseActDense(config)
|
| 212 |
+
else:
|
| 213 |
+
self.mlp = SwitchTransformersSparseMLP(config)
|
| 214 |
+
|
| 215 |
+
self.layer_norm = SwitchTransformersLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 216 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 217 |
+
|
| 218 |
+
def forward(self, hidden_states, **kwargs):
|
| 219 |
+
forwarded_states = self.layer_norm(hidden_states)
|
| 220 |
+
forwarded_states = self.mlp(forwarded_states)
|
| 221 |
+
output = hidden_states + self.dropout(forwarded_states)
|
| 222 |
+
return output
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class SwitchTransformersAttention(nn.Module):
|
| 226 |
+
def __init__(
|
| 227 |
+
self,
|
| 228 |
+
config: SwitchTransformersConfig,
|
| 229 |
+
has_relative_attention_bias=False,
|
| 230 |
+
layer_idx: int | None = None,
|
| 231 |
+
):
|
| 232 |
+
super().__init__()
|
| 233 |
+
self.is_decoder = config.is_decoder
|
| 234 |
+
self.has_relative_attention_bias = has_relative_attention_bias
|
| 235 |
+
self.relative_attention_num_buckets = config.relative_attention_num_buckets
|
| 236 |
+
self.relative_attention_max_distance = config.relative_attention_max_distance
|
| 237 |
+
self.d_model = config.d_model
|
| 238 |
+
self.key_value_proj_dim = config.d_kv
|
| 239 |
+
self.n_heads = config.num_heads
|
| 240 |
+
self.dropout = config.dropout_rate
|
| 241 |
+
self.inner_dim = self.n_heads * self.key_value_proj_dim
|
| 242 |
+
self.layer_idx = layer_idx
|
| 243 |
+
if layer_idx is None and self.is_decoder:
|
| 244 |
+
logger.warning_once(
|
| 245 |
+
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
|
| 246 |
+
"will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 247 |
+
"when creating this class."
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
|
| 251 |
+
self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
|
| 252 |
+
self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
|
| 253 |
+
self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
|
| 254 |
+
|
| 255 |
+
if self.has_relative_attention_bias:
|
| 256 |
+
self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
|
| 257 |
+
|
| 258 |
+
self.gradient_checkpointing = False
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
|
| 262 |
+
"""
|
| 263 |
+
Adapted from Mesh Tensorflow:
|
| 264 |
+
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
|
| 265 |
+
|
| 266 |
+
Translate relative position to a bucket number for relative attention. The relative position is defined as
|
| 267 |
+
memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
|
| 268 |
+
position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
|
| 269 |
+
small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
|
| 270 |
+
positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
|
| 271 |
+
This should allow for more graceful generalization to longer sequences than the model has been trained on
|
| 272 |
+
|
| 273 |
+
Args:
|
| 274 |
+
relative_position: an int32 Tensor
|
| 275 |
+
bidirectional: a boolean - whether the attention is bidirectional
|
| 276 |
+
num_buckets: an integer
|
| 277 |
+
max_distance: an integer
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
|
| 281 |
+
"""
|
| 282 |
+
relative_buckets = 0
|
| 283 |
+
if bidirectional:
|
| 284 |
+
num_buckets //= 2
|
| 285 |
+
relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
|
| 286 |
+
relative_position = torch.abs(relative_position)
|
| 287 |
+
else:
|
| 288 |
+
relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
|
| 289 |
+
# now relative_position is in the range [0, inf)
|
| 290 |
+
|
| 291 |
+
# half of the buckets are for exact increments in positions
|
| 292 |
+
max_exact = num_buckets // 2
|
| 293 |
+
is_small = relative_position < max_exact
|
| 294 |
+
|
| 295 |
+
# The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
|
| 296 |
+
relative_position_if_large = max_exact + (
|
| 297 |
+
torch.log(relative_position.float() / max_exact)
|
| 298 |
+
/ math.log(max_distance / max_exact)
|
| 299 |
+
* (num_buckets - max_exact)
|
| 300 |
+
).to(torch.long)
|
| 301 |
+
relative_position_if_large = torch.min(
|
| 302 |
+
relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
|
| 306 |
+
return relative_buckets
|
| 307 |
+
|
| 308 |
+
def compute_bias(self, query_length, key_length, device=None, past_seen_tokens=0):
|
| 309 |
+
"""Compute binned relative position bias"""
|
| 310 |
+
if device is None:
|
| 311 |
+
device = self.relative_attention_bias.weight.device
|
| 312 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None] + past_seen_tokens
|
| 313 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
| 314 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
| 315 |
+
relative_position_bucket = self._relative_position_bucket(
|
| 316 |
+
relative_position, # shape (query_length, key_length)
|
| 317 |
+
bidirectional=(not self.is_decoder),
|
| 318 |
+
num_buckets=self.relative_attention_num_buckets,
|
| 319 |
+
max_distance=self.relative_attention_max_distance,
|
| 320 |
+
)
|
| 321 |
+
values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
|
| 322 |
+
values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
|
| 323 |
+
return values
|
| 324 |
+
|
| 325 |
+
def forward(
|
| 326 |
+
self,
|
| 327 |
+
hidden_states,
|
| 328 |
+
mask=None,
|
| 329 |
+
key_value_states=None,
|
| 330 |
+
position_bias=None,
|
| 331 |
+
past_key_values=None,
|
| 332 |
+
output_attentions=False,
|
| 333 |
+
**kwargs,
|
| 334 |
+
):
|
| 335 |
+
"""
|
| 336 |
+
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
|
| 337 |
+
"""
|
| 338 |
+
# Input is (batch_size, seq_length, dim)
|
| 339 |
+
# Mask is (batch_size, 1, 1, key_length) (non-causal encoder) or (batch_size, 1, seq_length, key_length) (causal decoder)
|
| 340 |
+
input_shape = hidden_states.shape[:-1]
|
| 341 |
+
hidden_shape = (*input_shape, -1, self.key_value_proj_dim)
|
| 342 |
+
past_seen_tokens = past_key_values.get_seq_length(self.layer_idx) if past_key_values is not None else 0
|
| 343 |
+
# We clone here for StaticCache, as we get the value before updating it, but use it after and it's the same ref
|
| 344 |
+
past_seen_tokens = past_seen_tokens.clone() if isinstance(past_seen_tokens, torch.Tensor) else past_seen_tokens
|
| 345 |
+
|
| 346 |
+
# if key_value_states are provided this layer is used as a cross-attention layer for the decoder
|
| 347 |
+
is_cross_attention = key_value_states is not None
|
| 348 |
+
|
| 349 |
+
query_states = self.q(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 350 |
+
|
| 351 |
+
# Check is encoder-decoder model is being used. Otherwise we'll get `DynamicCache`
|
| 352 |
+
is_updated = False
|
| 353 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 354 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 355 |
+
if is_cross_attention:
|
| 356 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 357 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 358 |
+
else:
|
| 359 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 360 |
+
else:
|
| 361 |
+
curr_past_key_values = past_key_values
|
| 362 |
+
|
| 363 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 364 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 365 |
+
# reuse k,v, cross_attentions
|
| 366 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 367 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 368 |
+
else:
|
| 369 |
+
kv_shape = (*current_states.shape[:-1], -1, self.key_value_proj_dim)
|
| 370 |
+
key_states = self.k(current_states).view(kv_shape).transpose(1, 2)
|
| 371 |
+
value_states = self.v(current_states).view(kv_shape).transpose(1, 2)
|
| 372 |
+
|
| 373 |
+
if past_key_values is not None:
|
| 374 |
+
key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
|
| 375 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 376 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 377 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 378 |
+
|
| 379 |
+
# compute scores, equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
|
| 380 |
+
scores = torch.matmul(query_states, key_states.transpose(3, 2))
|
| 381 |
+
|
| 382 |
+
if position_bias is None:
|
| 383 |
+
key_length = key_states.shape[-2]
|
| 384 |
+
if not self.has_relative_attention_bias:
|
| 385 |
+
position_bias = torch.zeros(
|
| 386 |
+
(1, query_states.shape[1], input_shape[1], key_length), device=scores.device, dtype=scores.dtype
|
| 387 |
+
)
|
| 388 |
+
if self.gradient_checkpointing and self.training:
|
| 389 |
+
position_bias.requires_grad = True
|
| 390 |
+
else:
|
| 391 |
+
position_bias = self.compute_bias(
|
| 392 |
+
input_shape[1], key_length, device=scores.device, past_seen_tokens=past_seen_tokens
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
if mask is not None:
|
| 396 |
+
causal_mask = mask[:, :, :, : key_states.shape[-2]]
|
| 397 |
+
position_bias = position_bias + causal_mask
|
| 398 |
+
|
| 399 |
+
position_bias_masked = position_bias
|
| 400 |
+
scores += position_bias_masked
|
| 401 |
+
|
| 402 |
+
# (batch_size, n_heads, seq_length, key_length)
|
| 403 |
+
attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores)
|
| 404 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 405 |
+
|
| 406 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 407 |
+
|
| 408 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 409 |
+
attn_output = attn_output.reshape(*input_shape, -1)
|
| 410 |
+
attn_output = self.o(attn_output)
|
| 411 |
+
|
| 412 |
+
outputs = (attn_output, position_bias)
|
| 413 |
+
|
| 414 |
+
if output_attentions:
|
| 415 |
+
outputs = outputs + (attn_weights,)
|
| 416 |
+
return outputs
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class SwitchTransformersLayerSelfAttention(nn.Module):
|
| 420 |
+
def __init__(self, config, has_relative_attention_bias=False, layer_idx: int | None = None):
|
| 421 |
+
super().__init__()
|
| 422 |
+
self.SelfAttention = SwitchTransformersAttention(
|
| 423 |
+
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
|
| 424 |
+
)
|
| 425 |
+
self.layer_norm = SwitchTransformersLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 426 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 427 |
+
|
| 428 |
+
def forward(
|
| 429 |
+
self,
|
| 430 |
+
hidden_states,
|
| 431 |
+
attention_mask=None,
|
| 432 |
+
position_bias=None,
|
| 433 |
+
past_key_values=None,
|
| 434 |
+
use_cache=False,
|
| 435 |
+
output_attentions=False,
|
| 436 |
+
**kwargs,
|
| 437 |
+
):
|
| 438 |
+
normed_hidden_states = self.layer_norm(hidden_states)
|
| 439 |
+
attention_output = self.SelfAttention(
|
| 440 |
+
normed_hidden_states,
|
| 441 |
+
mask=attention_mask,
|
| 442 |
+
position_bias=position_bias,
|
| 443 |
+
past_key_values=past_key_values,
|
| 444 |
+
use_cache=use_cache,
|
| 445 |
+
output_attentions=output_attentions,
|
| 446 |
+
)
|
| 447 |
+
hidden_states = hidden_states + self.dropout(attention_output[0])
|
| 448 |
+
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
|
| 449 |
+
return outputs
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
class SwitchTransformersLayerCrossAttention(nn.Module):
|
| 453 |
+
def __init__(self, config, layer_idx: int | None = None):
|
| 454 |
+
super().__init__()
|
| 455 |
+
self.EncDecAttention = SwitchTransformersAttention(
|
| 456 |
+
config, has_relative_attention_bias=False, layer_idx=layer_idx
|
| 457 |
+
)
|
| 458 |
+
self.layer_norm = SwitchTransformersLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 459 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 460 |
+
|
| 461 |
+
def forward(
|
| 462 |
+
self,
|
| 463 |
+
hidden_states,
|
| 464 |
+
key_value_states,
|
| 465 |
+
attention_mask=None,
|
| 466 |
+
position_bias=None,
|
| 467 |
+
past_key_values=None,
|
| 468 |
+
output_attentions=False,
|
| 469 |
+
**kwargs,
|
| 470 |
+
):
|
| 471 |
+
normed_hidden_states = self.layer_norm(hidden_states)
|
| 472 |
+
attention_output = self.EncDecAttention(
|
| 473 |
+
normed_hidden_states,
|
| 474 |
+
mask=attention_mask,
|
| 475 |
+
key_value_states=key_value_states,
|
| 476 |
+
position_bias=position_bias,
|
| 477 |
+
past_key_values=past_key_values,
|
| 478 |
+
output_attentions=output_attentions,
|
| 479 |
+
)
|
| 480 |
+
layer_output = hidden_states + self.dropout(attention_output[0])
|
| 481 |
+
outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
|
| 482 |
+
return outputs
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
class SwitchTransformersBlock(GradientCheckpointingLayer):
|
| 486 |
+
def __init__(self, config, has_relative_attention_bias=False, is_sparse=False, layer_idx: int | None = None):
|
| 487 |
+
super().__init__()
|
| 488 |
+
self.is_decoder = config.is_decoder
|
| 489 |
+
self.is_sparse = is_sparse
|
| 490 |
+
self.layer = nn.ModuleList()
|
| 491 |
+
self.layer.append(
|
| 492 |
+
SwitchTransformersLayerSelfAttention(
|
| 493 |
+
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
|
| 494 |
+
)
|
| 495 |
+
)
|
| 496 |
+
if self.is_decoder:
|
| 497 |
+
self.layer.append(SwitchTransformersLayerCrossAttention(config, layer_idx=layer_idx))
|
| 498 |
+
|
| 499 |
+
self.layer.append(SwitchTransformersLayerFF(config, is_sparse=self.is_sparse))
|
| 500 |
+
|
| 501 |
+
def forward(
|
| 502 |
+
self,
|
| 503 |
+
hidden_states,
|
| 504 |
+
attention_mask=None,
|
| 505 |
+
position_bias=None,
|
| 506 |
+
encoder_hidden_states=None,
|
| 507 |
+
encoder_attention_mask=None,
|
| 508 |
+
encoder_decoder_position_bias=None,
|
| 509 |
+
past_key_values=None,
|
| 510 |
+
use_cache=False,
|
| 511 |
+
**kwargs,
|
| 512 |
+
):
|
| 513 |
+
hidden_states, _ = self.layer[0](
|
| 514 |
+
hidden_states,
|
| 515 |
+
attention_mask=attention_mask,
|
| 516 |
+
position_bias=position_bias,
|
| 517 |
+
past_key_values=past_key_values,
|
| 518 |
+
use_cache=use_cache,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
# clamp inf values to enable fp16 training
|
| 522 |
+
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
|
| 523 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 524 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 525 |
+
|
| 526 |
+
do_cross_attention = self.is_decoder and encoder_hidden_states is not None
|
| 527 |
+
if do_cross_attention:
|
| 528 |
+
hidden_states, _ = self.layer[1](
|
| 529 |
+
hidden_states,
|
| 530 |
+
key_value_states=encoder_hidden_states,
|
| 531 |
+
attention_mask=encoder_attention_mask,
|
| 532 |
+
position_bias=encoder_decoder_position_bias,
|
| 533 |
+
past_key_values=past_key_values,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
# clamp inf values to enable fp16 training
|
| 537 |
+
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
|
| 538 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 539 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 540 |
+
|
| 541 |
+
hidden_states = self.layer[-1](hidden_states)
|
| 542 |
+
# clamp inf values to enable fp16 training
|
| 543 |
+
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
|
| 544 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 545 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 546 |
+
return hidden_states
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
@auto_docstring
|
| 550 |
+
class SwitchTransformersPreTrainedModel(PreTrainedModel):
|
| 551 |
+
config: SwitchTransformersConfig
|
| 552 |
+
base_model_prefix = "switch_transformers"
|
| 553 |
+
supports_gradient_checkpointing = True
|
| 554 |
+
_can_compile_fullgraph = False
|
| 555 |
+
_no_split_modules = ["SwitchTransformersBlock"]
|
| 556 |
+
|
| 557 |
+
@torch.no_grad()
|
| 558 |
+
def _init_weights(self, module):
|
| 559 |
+
"""Initialize the weights"""
|
| 560 |
+
factor = self.config.initializer_factor # Used for testing weights initialization
|
| 561 |
+
if isinstance(module, SwitchTransformersLayerNorm):
|
| 562 |
+
init.constant_(module.weight, factor * 1.0)
|
| 563 |
+
elif isinstance(
|
| 564 |
+
module,
|
| 565 |
+
(SwitchTransformersModel, SwitchTransformersForConditionalGeneration, SwitchTransformersEncoderModel),
|
| 566 |
+
):
|
| 567 |
+
init.normal_(module.shared.weight, mean=0.0, std=factor * 1.0)
|
| 568 |
+
if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
|
| 569 |
+
init.normal_(module.lm_head.weight, mean=0.0, std=factor * 1.0)
|
| 570 |
+
elif isinstance(module, SwitchTransformersDenseActDense):
|
| 571 |
+
init.normal_(module.wi.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 572 |
+
if hasattr(module.wi, "bias") and module.wi.bias is not None:
|
| 573 |
+
init.zeros_(module.wi.bias)
|
| 574 |
+
init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
|
| 575 |
+
if hasattr(module.wo, "bias") and module.wo.bias is not None:
|
| 576 |
+
init.zeros_(module.wo.bias)
|
| 577 |
+
elif isinstance(module, SwitchTransformersAttention):
|
| 578 |
+
d_model = self.config.d_model
|
| 579 |
+
key_value_proj_dim = self.config.d_kv
|
| 580 |
+
n_heads = self.config.num_heads
|
| 581 |
+
init.normal_(module.q.weight, mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
|
| 582 |
+
init.normal_(module.k.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 583 |
+
init.normal_(module.v.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 584 |
+
init.normal_(module.o.weight, mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
|
| 585 |
+
if module.has_relative_attention_bias:
|
| 586 |
+
init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5))
|
| 587 |
+
elif isinstance(module, SwitchTransformersSparseMLP):
|
| 588 |
+
d_model = self.config.d_model
|
| 589 |
+
key_value_proj_dim = self.config.d_kv
|
| 590 |
+
n_heads = self.config.num_heads
|
| 591 |
+
init.normal_(module.router.classifier.weight, mean=0.0, std=factor * 1)
|
| 592 |
+
for idx in range(self.config.num_experts):
|
| 593 |
+
init.normal_(module.experts[f"expert_{idx}"].wi.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 594 |
+
init.normal_(module.experts[f"expert_{idx}"].wo.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 595 |
+
|
| 596 |
+
def _shift_right(self, input_ids):
|
| 597 |
+
decoder_start_token_id = self.config.decoder_start_token_id
|
| 598 |
+
pad_token_id = self.config.pad_token_id
|
| 599 |
+
|
| 600 |
+
if decoder_start_token_id is None:
|
| 601 |
+
raise ValueError(
|
| 602 |
+
"self.model.config.decoder_start_token_id has to be defined. In SwitchTransformers it is usually set"
|
| 603 |
+
" to the pad_token_id. See SwitchTransformers docs for more information"
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 607 |
+
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
|
| 608 |
+
shifted_input_ids[..., 0] = decoder_start_token_id
|
| 609 |
+
|
| 610 |
+
if pad_token_id is None:
|
| 611 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 612 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 613 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 614 |
+
|
| 615 |
+
return shifted_input_ids
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class SwitchTransformersStack(SwitchTransformersPreTrainedModel):
|
| 619 |
+
_can_record_outputs = {
|
| 620 |
+
"hidden_states": SwitchTransformersBlock,
|
| 621 |
+
"attentions": OutputRecorder(SwitchTransformersAttention, index=-1, layer_name="layer.0"),
|
| 622 |
+
"cross_attentions": OutputRecorder(SwitchTransformersAttention, index=-1, layer_name="layer.1"),
|
| 623 |
+
"router_logits": OutputRecorder(SwitchTransformersTop1Router, index=2),
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
def __init__(self, config):
|
| 627 |
+
super().__init__(config)
|
| 628 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
|
| 629 |
+
|
| 630 |
+
self.is_decoder = config.is_decoder
|
| 631 |
+
|
| 632 |
+
sparse_step = config.decoder_sparse_step if self.is_decoder else config.encoder_sparse_step
|
| 633 |
+
config.num_layers = config.num_decoder_layers if self.is_decoder else config.num_layers
|
| 634 |
+
self.block = nn.ModuleList()
|
| 635 |
+
for i in range(config.num_layers):
|
| 636 |
+
is_sparse = (i % sparse_step == 1 or sparse_step == 1) if sparse_step > 0 else False
|
| 637 |
+
|
| 638 |
+
self.block.append(
|
| 639 |
+
SwitchTransformersBlock(
|
| 640 |
+
config, has_relative_attention_bias=bool(i == 0), is_sparse=is_sparse, layer_idx=i
|
| 641 |
+
)
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
self.final_layer_norm = SwitchTransformersLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 645 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 646 |
+
self.post_init()
|
| 647 |
+
|
| 648 |
+
self.gradient_checkpointing = False
|
| 649 |
+
|
| 650 |
+
@merge_with_config_defaults
|
| 651 |
+
@capture_outputs
|
| 652 |
+
def forward(
|
| 653 |
+
self,
|
| 654 |
+
input_ids=None,
|
| 655 |
+
attention_mask=None,
|
| 656 |
+
encoder_hidden_states=None,
|
| 657 |
+
encoder_attention_mask=None,
|
| 658 |
+
inputs_embeds=None,
|
| 659 |
+
past_key_values=None,
|
| 660 |
+
use_cache=None,
|
| 661 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 662 |
+
) -> tuple | MoEModelOutputWithPastAndCrossAttentions:
|
| 663 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 664 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 665 |
+
|
| 666 |
+
if inputs_embeds is None:
|
| 667 |
+
if self.embed_tokens is None:
|
| 668 |
+
raise ValueError("You have to initialize the model with valid token embeddings")
|
| 669 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 670 |
+
|
| 671 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
| 672 |
+
|
| 673 |
+
if use_cache is True:
|
| 674 |
+
if not self.is_decoder:
|
| 675 |
+
raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
|
| 676 |
+
|
| 677 |
+
if self.is_decoder:
|
| 678 |
+
if use_cache and past_key_values is None:
|
| 679 |
+
if self.config.is_encoder_decoder:
|
| 680 |
+
past_key_values = EncoderDecoderCache(
|
| 681 |
+
DynamicCache(config=self.config), DynamicCache(config=self.config)
|
| 682 |
+
)
|
| 683 |
+
else:
|
| 684 |
+
past_key_values = DynamicCache(config=self.config)
|
| 685 |
+
elif not self.is_decoder:
|
| 686 |
+
# do not pass cache object down the line for encoder stack
|
| 687 |
+
# it messes indexing later in decoder-stack because cache object is modified in-place
|
| 688 |
+
past_key_values = None
|
| 689 |
+
|
| 690 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 691 |
+
if attention_mask is None and not is_torchdynamo_compiling():
|
| 692 |
+
# required mask seq length can be calculated via length of past cache
|
| 693 |
+
mask_seq_length = past_key_values_length + seq_length
|
| 694 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
| 695 |
+
|
| 696 |
+
if self.config.is_decoder:
|
| 697 |
+
causal_mask = create_causal_mask(
|
| 698 |
+
config=self.config,
|
| 699 |
+
inputs_embeds=inputs_embeds,
|
| 700 |
+
attention_mask=attention_mask,
|
| 701 |
+
past_key_values=past_key_values,
|
| 702 |
+
)
|
| 703 |
+
else:
|
| 704 |
+
causal_mask = attention_mask[:, None, None, :]
|
| 705 |
+
causal_mask = causal_mask.to(dtype=inputs_embeds.dtype)
|
| 706 |
+
causal_mask = (1.0 - causal_mask) * torch.finfo(inputs_embeds.dtype).min
|
| 707 |
+
|
| 708 |
+
if encoder_attention_mask is not None:
|
| 709 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 710 |
+
config=self.config,
|
| 711 |
+
inputs_embeds=inputs_embeds,
|
| 712 |
+
attention_mask=encoder_attention_mask,
|
| 713 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
position_bias = None
|
| 717 |
+
encoder_decoder_position_bias = None
|
| 718 |
+
|
| 719 |
+
hidden_states = self.dropout(inputs_embeds)
|
| 720 |
+
|
| 721 |
+
for i, layer_module in enumerate(self.block):
|
| 722 |
+
hidden_states = layer_module(
|
| 723 |
+
hidden_states,
|
| 724 |
+
causal_mask,
|
| 725 |
+
position_bias,
|
| 726 |
+
encoder_hidden_states,
|
| 727 |
+
encoder_attention_mask,
|
| 728 |
+
encoder_decoder_position_bias,
|
| 729 |
+
past_key_values=past_key_values,
|
| 730 |
+
use_cache=use_cache,
|
| 731 |
+
**kwargs,
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 735 |
+
hidden_states = self.dropout(hidden_states)
|
| 736 |
+
|
| 737 |
+
return MoEModelOutputWithPastAndCrossAttentions(
|
| 738 |
+
last_hidden_state=hidden_states,
|
| 739 |
+
past_key_values=past_key_values,
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
@auto_docstring
|
| 744 |
+
class SwitchTransformersModel(SwitchTransformersPreTrainedModel):
|
| 745 |
+
_tied_weights_keys = {
|
| 746 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 747 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 748 |
+
}
|
| 749 |
+
_input_embed_layer = "shared"
|
| 750 |
+
|
| 751 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 752 |
+
super().__init__(config)
|
| 753 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 754 |
+
|
| 755 |
+
encoder_config = copy.deepcopy(config)
|
| 756 |
+
encoder_config.is_decoder = False
|
| 757 |
+
encoder_config.use_cache = False
|
| 758 |
+
self.encoder = SwitchTransformersStack(encoder_config)
|
| 759 |
+
|
| 760 |
+
decoder_config = copy.deepcopy(config)
|
| 761 |
+
decoder_config.is_decoder = True
|
| 762 |
+
self.decoder = SwitchTransformersStack(decoder_config)
|
| 763 |
+
|
| 764 |
+
# Initialize weights and apply final processing
|
| 765 |
+
self.post_init()
|
| 766 |
+
|
| 767 |
+
def set_input_embeddings(self, new_embeddings):
|
| 768 |
+
self.shared = new_embeddings
|
| 769 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 770 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 771 |
+
|
| 772 |
+
@auto_docstring
|
| 773 |
+
@can_return_tuple
|
| 774 |
+
def forward(
|
| 775 |
+
self,
|
| 776 |
+
input_ids: torch.LongTensor | None = None,
|
| 777 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 778 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 779 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 780 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 781 |
+
past_key_values: Cache | None = None,
|
| 782 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 783 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 784 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 785 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqMoEModelOutput:
|
| 786 |
+
if encoder_outputs is None:
|
| 787 |
+
encoder_outputs = self.encoder(
|
| 788 |
+
input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
hidden_states = encoder_outputs[0]
|
| 792 |
+
decoder_outputs = self.decoder(
|
| 793 |
+
input_ids=decoder_input_ids,
|
| 794 |
+
attention_mask=decoder_attention_mask,
|
| 795 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 796 |
+
past_key_values=past_key_values,
|
| 797 |
+
encoder_hidden_states=hidden_states,
|
| 798 |
+
encoder_attention_mask=attention_mask,
|
| 799 |
+
**kwargs,
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
return Seq2SeqMoEModelOutput(
|
| 803 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 804 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 805 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 806 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 807 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 808 |
+
decoder_router_logits=decoder_outputs.router_logits,
|
| 809 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 810 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 811 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 812 |
+
encoder_router_logits=encoder_outputs.router_logits,
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
####################################################
|
| 817 |
+
# This dict contains ids and associated url
|
| 818 |
+
# for the pretrained weights provided with the models
|
| 819 |
+
####################################################
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def router_z_loss_func(router_logits: torch.Tensor) -> float:
|
| 823 |
+
r"""
|
| 824 |
+
Compute the router z-loss implemented in PyTorch.
|
| 825 |
+
|
| 826 |
+
The router z-loss was introduced in [Designing Effective Sparse Expert Models](https://huggingface.co/papers/2202.08906).
|
| 827 |
+
It encourages router logits to remain small in an effort to improve stability.
|
| 828 |
+
|
| 829 |
+
Args:
|
| 830 |
+
router_logits (`float`):
|
| 831 |
+
Input logits of shape [batch_size, sequence_length, num_experts]
|
| 832 |
+
|
| 833 |
+
Returns:
|
| 834 |
+
Scalar router z-loss.
|
| 835 |
+
"""
|
| 836 |
+
num_groups, tokens_per_group, _ = router_logits.shape
|
| 837 |
+
log_z = torch.logsumexp(router_logits, dim=-1)
|
| 838 |
+
z_loss = log_z**2
|
| 839 |
+
return torch.sum(z_loss) / (num_groups * tokens_per_group)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
|
| 843 |
+
r"""
|
| 844 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
| 845 |
+
|
| 846 |
+
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
| 847 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
| 848 |
+
experts is too unbalanced.
|
| 849 |
+
|
| 850 |
+
Args:
|
| 851 |
+
router_probs (`torch.Tensor`):
|
| 852 |
+
Probability assigned to each expert per token. Shape: [batch_size, sequence_length, num_experts].
|
| 853 |
+
expert_indices (`torch.Tensor`):
|
| 854 |
+
Indices tensor of shape [batch_size, sequence_length] identifying the selected expert for a given token.
|
| 855 |
+
|
| 856 |
+
Returns:
|
| 857 |
+
The auxiliary loss.
|
| 858 |
+
"""
|
| 859 |
+
num_experts = router_probs.shape[-1]
|
| 860 |
+
|
| 861 |
+
# cast the expert indices to int64, otherwise one-hot encoding will fail
|
| 862 |
+
if expert_indices.dtype != torch.int64:
|
| 863 |
+
expert_indices = expert_indices.to(torch.int64)
|
| 864 |
+
|
| 865 |
+
if len(expert_indices.shape) == 2:
|
| 866 |
+
expert_indices = expert_indices.unsqueeze(2)
|
| 867 |
+
|
| 868 |
+
expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
|
| 869 |
+
|
| 870 |
+
# For a given token, determine if it was routed to a given expert.
|
| 871 |
+
expert_mask = torch.max(expert_mask, axis=-2).values
|
| 872 |
+
|
| 873 |
+
# cast to float32 otherwise mean will fail
|
| 874 |
+
expert_mask = expert_mask.to(torch.float32)
|
| 875 |
+
tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
|
| 876 |
+
|
| 877 |
+
router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
|
| 878 |
+
return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
@auto_docstring(
|
| 882 |
+
custom_intro="""
|
| 883 |
+
SWITCH_TRANSFORMERS Model with a `language modeling` head on top.
|
| 884 |
+
"""
|
| 885 |
+
)
|
| 886 |
+
class SwitchTransformersForConditionalGeneration(SwitchTransformersPreTrainedModel, GenerationMixin):
|
| 887 |
+
_tied_weights_keys = {
|
| 888 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 889 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 890 |
+
"lm_head.weight": "shared.weight",
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 894 |
+
super().__init__(config)
|
| 895 |
+
self.model_dim = config.d_model
|
| 896 |
+
|
| 897 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 898 |
+
|
| 899 |
+
encoder_config = copy.deepcopy(config)
|
| 900 |
+
encoder_config.is_decoder = False
|
| 901 |
+
encoder_config.use_cache = False
|
| 902 |
+
self.encoder = SwitchTransformersStack(encoder_config)
|
| 903 |
+
|
| 904 |
+
decoder_config = copy.deepcopy(config)
|
| 905 |
+
decoder_config.is_decoder = True
|
| 906 |
+
decoder_config.num_layers = config.num_decoder_layers
|
| 907 |
+
self.decoder = SwitchTransformersStack(decoder_config)
|
| 908 |
+
|
| 909 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 910 |
+
|
| 911 |
+
self.router_z_loss_coef = config.router_z_loss_coef
|
| 912 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
| 913 |
+
self.post_init()
|
| 914 |
+
|
| 915 |
+
def get_input_embeddings(self):
|
| 916 |
+
return self.shared
|
| 917 |
+
|
| 918 |
+
def set_input_embeddings(self, new_embeddings):
|
| 919 |
+
self.shared = new_embeddings
|
| 920 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 921 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 922 |
+
|
| 923 |
+
@auto_docstring
|
| 924 |
+
@can_return_tuple
|
| 925 |
+
def forward(
|
| 926 |
+
self,
|
| 927 |
+
input_ids: torch.LongTensor | None = None,
|
| 928 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 929 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 930 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 931 |
+
encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
|
| 932 |
+
past_key_values: Cache | None = None,
|
| 933 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 934 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 935 |
+
labels: torch.LongTensor | None = None,
|
| 936 |
+
output_router_logits: bool | None = False,
|
| 937 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 938 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqMoEOutput:
|
| 939 |
+
if encoder_outputs is None:
|
| 940 |
+
encoder_outputs = self.encoder(
|
| 941 |
+
input_ids=input_ids,
|
| 942 |
+
attention_mask=attention_mask,
|
| 943 |
+
inputs_embeds=inputs_embeds,
|
| 944 |
+
output_router_logits=output_router_logits,
|
| 945 |
+
**kwargs,
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
hidden_states = encoder_outputs[0]
|
| 949 |
+
|
| 950 |
+
if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 951 |
+
# get decoder inputs from shifting lm labels to the right
|
| 952 |
+
decoder_input_ids = self._shift_right(labels)
|
| 953 |
+
|
| 954 |
+
# Decode
|
| 955 |
+
decoder_outputs = self.decoder(
|
| 956 |
+
input_ids=decoder_input_ids,
|
| 957 |
+
attention_mask=decoder_attention_mask,
|
| 958 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 959 |
+
past_key_values=past_key_values,
|
| 960 |
+
encoder_hidden_states=hidden_states,
|
| 961 |
+
encoder_attention_mask=attention_mask,
|
| 962 |
+
output_router_logits=output_router_logits,
|
| 963 |
+
**kwargs,
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
sequence_output = decoder_outputs.last_hidden_state
|
| 967 |
+
|
| 968 |
+
if self.config.tie_word_embeddings:
|
| 969 |
+
# Rescale output before projecting on vocab
|
| 970 |
+
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
|
| 971 |
+
sequence_output = sequence_output * (self.model_dim**-0.5)
|
| 972 |
+
|
| 973 |
+
lm_logits = self.lm_head(sequence_output)
|
| 974 |
+
|
| 975 |
+
loss = None
|
| 976 |
+
encoder_z_loss = None
|
| 977 |
+
encoder_aux_loss = None
|
| 978 |
+
decoder_z_loss = None
|
| 979 |
+
decoder_aux_loss = None
|
| 980 |
+
|
| 981 |
+
if output_router_logits:
|
| 982 |
+
# Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder
|
| 983 |
+
if self.encoder.config.encoder_sparse_step > 1:
|
| 984 |
+
encoder_router_logits, encoder_expert_indexes = self._unpack_router_logits(encoder_outputs[-1])
|
| 985 |
+
encoder_z_loss = router_z_loss_func(encoder_router_logits)
|
| 986 |
+
encoder_router_probs = nn.Softmax(dim=-1)(encoder_router_logits)
|
| 987 |
+
encoder_aux_loss = load_balancing_loss_func(encoder_router_probs, encoder_expert_indexes)
|
| 988 |
+
else:
|
| 989 |
+
encoder_z_loss = 0
|
| 990 |
+
encoder_aux_loss = 0
|
| 991 |
+
|
| 992 |
+
if self.decoder.config.decoder_sparse_step > 1:
|
| 993 |
+
decoder_router_logits, decoder_expert_indexes = self._unpack_router_logits(decoder_outputs[-1])
|
| 994 |
+
decoder_z_loss = router_z_loss_func(decoder_router_logits)
|
| 995 |
+
decoder_router_probs = nn.Softmax(dim=-1)(decoder_router_logits)
|
| 996 |
+
decoder_aux_loss = load_balancing_loss_func(decoder_router_probs, decoder_expert_indexes)
|
| 997 |
+
else:
|
| 998 |
+
decoder_z_loss = 0
|
| 999 |
+
decoder_aux_loss = 0
|
| 1000 |
+
|
| 1001 |
+
if labels is not None:
|
| 1002 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
| 1003 |
+
# move labels to correct device to enable PP
|
| 1004 |
+
labels = labels.to(lm_logits.device)
|
| 1005 |
+
loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
|
| 1006 |
+
|
| 1007 |
+
if output_router_logits:
|
| 1008 |
+
z_loss = self.router_z_loss_coef * (encoder_z_loss + decoder_z_loss)
|
| 1009 |
+
aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss)
|
| 1010 |
+
loss = loss + z_loss + aux_loss
|
| 1011 |
+
|
| 1012 |
+
return Seq2SeqMoEOutput(
|
| 1013 |
+
loss=loss,
|
| 1014 |
+
logits=lm_logits,
|
| 1015 |
+
encoder_z_loss=encoder_z_loss,
|
| 1016 |
+
encoder_aux_loss=encoder_aux_loss,
|
| 1017 |
+
decoder_z_loss=decoder_z_loss,
|
| 1018 |
+
decoder_aux_loss=decoder_aux_loss,
|
| 1019 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1020 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1021 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1022 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1023 |
+
decoder_router_logits=decoder_outputs.router_logits,
|
| 1024 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1025 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1026 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1027 |
+
encoder_router_logits=encoder_outputs.router_logits,
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
def _unpack_router_logits(self, router_outputs):
|
| 1031 |
+
total_router_logits = []
|
| 1032 |
+
total_expert_indexes = []
|
| 1033 |
+
for router_output in router_outputs:
|
| 1034 |
+
if len(router_output[0].shape) > 1:
|
| 1035 |
+
router_logits, expert_indexes = router_output
|
| 1036 |
+
total_router_logits.append(router_logits)
|
| 1037 |
+
total_expert_indexes.append(expert_indexes)
|
| 1038 |
+
return torch.cat(total_router_logits, dim=1), torch.cat(total_expert_indexes, dim=1)
|
| 1039 |
+
|
| 1040 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 1041 |
+
return self._shift_right(labels)
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
class SwitchTransformersEncoderModel(SwitchTransformersPreTrainedModel):
|
| 1045 |
+
_tied_weights_keys = {
|
| 1046 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 1047 |
+
}
|
| 1048 |
+
|
| 1049 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 1050 |
+
super().__init__(config)
|
| 1051 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1052 |
+
|
| 1053 |
+
encoder_config = copy.deepcopy(config)
|
| 1054 |
+
encoder_config.use_cache = False
|
| 1055 |
+
encoder_config.is_encoder_decoder = False
|
| 1056 |
+
self.encoder = SwitchTransformersStack(encoder_config)
|
| 1057 |
+
self.post_init()
|
| 1058 |
+
|
| 1059 |
+
def get_input_embeddings(self):
|
| 1060 |
+
return self.shared
|
| 1061 |
+
|
| 1062 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1063 |
+
self.shared = new_embeddings
|
| 1064 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 1065 |
+
|
| 1066 |
+
@auto_docstring
|
| 1067 |
+
@can_return_tuple
|
| 1068 |
+
def forward(
|
| 1069 |
+
self,
|
| 1070 |
+
input_ids: torch.LongTensor | None = None,
|
| 1071 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 1072 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1073 |
+
use_cache: bool | None = None,
|
| 1074 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1075 |
+
) -> tuple[torch.FloatTensor] | MoEModelOutput:
|
| 1076 |
+
use_cache = False
|
| 1077 |
+
encoder_outputs = self.encoder(
|
| 1078 |
+
input_ids=input_ids,
|
| 1079 |
+
attention_mask=attention_mask,
|
| 1080 |
+
inputs_embeds=inputs_embeds,
|
| 1081 |
+
use_cache=use_cache,
|
| 1082 |
+
**kwargs,
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
return encoder_outputs
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
__all__ = [
|
| 1089 |
+
"SwitchTransformersEncoderModel",
|
| 1090 |
+
"SwitchTransformersForConditionalGeneration",
|
| 1091 |
+
"SwitchTransformersModel",
|
| 1092 |
+
"SwitchTransformersPreTrainedModel",
|
| 1093 |
+
"SwitchTransformersTop1Router",
|
| 1094 |
+
"SwitchTransformersSparseMLP",
|
| 1095 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/modular_switch_transformers.py
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 SwitchTransformers Authors and 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 |
+
"""PyTorch SwitchTransformers model."""
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from torch.nn import CrossEntropyLoss
|
| 21 |
+
|
| 22 |
+
from ... import initialization as init
|
| 23 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 26 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
MoEModelOutput,
|
| 29 |
+
MoEModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
Seq2SeqMoEModelOutput,
|
| 31 |
+
Seq2SeqMoEOutput,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import PreTrainedModel
|
| 34 |
+
from ...processing_utils import Unpack
|
| 35 |
+
from ...utils import (
|
| 36 |
+
TransformersKwargs,
|
| 37 |
+
auto_docstring,
|
| 38 |
+
is_torchdynamo_compiling,
|
| 39 |
+
logging,
|
| 40 |
+
)
|
| 41 |
+
from ...utils.generic import (
|
| 42 |
+
can_return_tuple,
|
| 43 |
+
merge_with_config_defaults,
|
| 44 |
+
)
|
| 45 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 46 |
+
from ..t5.modeling_t5 import T5Attention, T5DenseActDense, T5LayerCrossAttention, T5LayerNorm, T5LayerSelfAttention
|
| 47 |
+
from .configuration_switch_transformers import SwitchTransformersConfig
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
####################################################
|
| 54 |
+
# This dict contains ids and associated url
|
| 55 |
+
# for the pretrained weights provided with the models
|
| 56 |
+
####################################################
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def router_z_loss_func(router_logits: torch.Tensor) -> float:
|
| 60 |
+
r"""
|
| 61 |
+
Compute the router z-loss implemented in PyTorch.
|
| 62 |
+
|
| 63 |
+
The router z-loss was introduced in [Designing Effective Sparse Expert Models](https://huggingface.co/papers/2202.08906).
|
| 64 |
+
It encourages router logits to remain small in an effort to improve stability.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
router_logits (`float`):
|
| 68 |
+
Input logits of shape [batch_size, sequence_length, num_experts]
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
Scalar router z-loss.
|
| 72 |
+
"""
|
| 73 |
+
num_groups, tokens_per_group, _ = router_logits.shape
|
| 74 |
+
log_z = torch.logsumexp(router_logits, dim=-1)
|
| 75 |
+
z_loss = log_z**2
|
| 76 |
+
return torch.sum(z_loss) / (num_groups * tokens_per_group)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
|
| 80 |
+
r"""
|
| 81 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
| 82 |
+
|
| 83 |
+
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
| 84 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
| 85 |
+
experts is too unbalanced.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
router_probs (`torch.Tensor`):
|
| 89 |
+
Probability assigned to each expert per token. Shape: [batch_size, sequence_length, num_experts].
|
| 90 |
+
expert_indices (`torch.Tensor`):
|
| 91 |
+
Indices tensor of shape [batch_size, sequence_length] identifying the selected expert for a given token.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
The auxiliary loss.
|
| 95 |
+
"""
|
| 96 |
+
num_experts = router_probs.shape[-1]
|
| 97 |
+
|
| 98 |
+
# cast the expert indices to int64, otherwise one-hot encoding will fail
|
| 99 |
+
if expert_indices.dtype != torch.int64:
|
| 100 |
+
expert_indices = expert_indices.to(torch.int64)
|
| 101 |
+
|
| 102 |
+
if len(expert_indices.shape) == 2:
|
| 103 |
+
expert_indices = expert_indices.unsqueeze(2)
|
| 104 |
+
|
| 105 |
+
expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
|
| 106 |
+
|
| 107 |
+
# For a given token, determine if it was routed to a given expert.
|
| 108 |
+
expert_mask = torch.max(expert_mask, axis=-2).values
|
| 109 |
+
|
| 110 |
+
# cast to float32 otherwise mean will fail
|
| 111 |
+
expert_mask = expert_mask.to(torch.float32)
|
| 112 |
+
tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
|
| 113 |
+
|
| 114 |
+
router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
|
| 115 |
+
return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class SwitchTransformersTop1Router(nn.Module):
|
| 119 |
+
"""
|
| 120 |
+
Router using tokens choose top-1 experts assignment.
|
| 121 |
+
|
| 122 |
+
This router uses the same mechanism as in Switch Transformer (https://huggingface.co/papers/2101.03961) and V-MoE
|
| 123 |
+
(https://huggingface.co/papers/2106.05974): tokens choose their top experts. Items are sorted by router_probs and then
|
| 124 |
+
routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee that each
|
| 125 |
+
token is processed by an expert**, or that each expert receives at least one token.
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 130 |
+
super().__init__()
|
| 131 |
+
self.num_experts = config.num_experts
|
| 132 |
+
self.expert_capacity = config.expert_capacity
|
| 133 |
+
self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
|
| 134 |
+
self.jitter_noise = config.router_jitter_noise
|
| 135 |
+
self.ignore_padding_tokens = config.router_ignore_padding_tokens
|
| 136 |
+
self.dtype = getattr(torch, config.router_dtype)
|
| 137 |
+
|
| 138 |
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 139 |
+
r"""
|
| 140 |
+
Computes router probabilities from input hidden states.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
hidden_states (`torch.Tensor`):
|
| 144 |
+
(batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
|
| 145 |
+
Returns:
|
| 146 |
+
router_probabilities (`torch.Tensor`):
|
| 147 |
+
Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
|
| 148 |
+
token and expert. Used for routing tokens to experts.
|
| 149 |
+
router_logits (`torch.Tensor`):
|
| 150 |
+
Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
|
| 151 |
+
This is used later for computing router z-loss.
|
| 152 |
+
"""
|
| 153 |
+
# float32 is used to ensure stability. See the discussion of "selective precision" in
|
| 154 |
+
# https://huggingface.co/papers/2101.03961.
|
| 155 |
+
# We also store the previous dtype to cast back the output to the previous dtype
|
| 156 |
+
self.input_dtype = hidden_states.dtype
|
| 157 |
+
hidden_states = hidden_states.to(self.dtype)
|
| 158 |
+
if self.training and self.jitter_noise > 0:
|
| 159 |
+
# Multiply the token inputs by the uniform distribution - adding some noise
|
| 160 |
+
hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
|
| 161 |
+
self.classifier = self.classifier.to(self.dtype)
|
| 162 |
+
router_logits = self.classifier(hidden_states)
|
| 163 |
+
|
| 164 |
+
# Apply Softmax and cast back to the original `dtype`
|
| 165 |
+
router_probs = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(self.input_dtype)
|
| 166 |
+
router_logits, expert_index = torch.max(router_probs, dim=-1, keepdim=True)
|
| 167 |
+
expert_index = torch.nn.functional.one_hot(expert_index, num_classes=self.num_experts)
|
| 168 |
+
token_priority = torch.cumsum(expert_index, dim=-2)
|
| 169 |
+
# mask if the token routed to the expert will overflow
|
| 170 |
+
expert_capacity_mask = token_priority <= self.expert_capacity
|
| 171 |
+
expert_index = expert_index * expert_capacity_mask
|
| 172 |
+
router_probs = torch.max(router_probs, dim=-1).values.unsqueeze(-1)
|
| 173 |
+
return router_probs, expert_index, router_logits
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class SwitchTransformersLayerNorm(T5LayerNorm):
|
| 177 |
+
pass
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class SwitchTransformersDenseActDense(T5DenseActDense):
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class SwitchTransformersExperts(nn.ModuleDict):
|
| 185 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 186 |
+
super().__init__()
|
| 187 |
+
self.num_experts = config.num_experts
|
| 188 |
+
for idx in range(config.num_experts):
|
| 189 |
+
self[f"expert_{idx}"] = SwitchTransformersDenseActDense(config)
|
| 190 |
+
|
| 191 |
+
def forward(
|
| 192 |
+
self, hidden_states: torch.Tensor, selected_experts: torch.Tensor, routing_weights: torch.Tensor
|
| 193 |
+
) -> torch.Tensor:
|
| 194 |
+
final_hidden_states = torch.zeros_like(hidden_states)
|
| 195 |
+
expert_mask = selected_experts.permute(2, 1, 0)
|
| 196 |
+
|
| 197 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 198 |
+
for expert_idx in expert_hit:
|
| 199 |
+
idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
|
| 200 |
+
current_state = hidden_states[None, top_x].reshape(-1, hidden_states.shape[-1])
|
| 201 |
+
current_hidden_states = self[f"expert_{expert_idx[0]}"](current_state) * routing_weights[top_x, idx, None]
|
| 202 |
+
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
| 203 |
+
return final_hidden_states
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class SwitchTransformersSparseMLP(nn.Module): # inherit from mixtral
|
| 207 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.router = SwitchTransformersTop1Router(config)
|
| 210 |
+
self.experts = SwitchTransformersExperts(config)
|
| 211 |
+
|
| 212 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 213 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 214 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 215 |
+
_, selected_experts, routing_weights = self.router(hidden_states)
|
| 216 |
+
hidden_states = self.experts(hidden_states, selected_experts, routing_weights)
|
| 217 |
+
hidden_states = hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
| 218 |
+
return hidden_states
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class SwitchTransformersLayerFF(nn.Module):
|
| 222 |
+
r"""
|
| 223 |
+
Switch Transformers Feed Forward layer module. This is a wrapper around the Mixture of Experts module.
|
| 224 |
+
|
| 225 |
+
Parameters:
|
| 226 |
+
config : ([`SwitchTransformersConfig`]): Model configuration class with all the parameters of the model.
|
| 227 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 228 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 229 |
+
is_sparse (`bool`):
|
| 230 |
+
Whether the MLP layer is a `Sparse` layer (contains a Mixture of Experts) or not
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
def __init__(self, config: SwitchTransformersConfig, is_sparse=False):
|
| 234 |
+
super().__init__()
|
| 235 |
+
self.is_sparse = is_sparse
|
| 236 |
+
|
| 237 |
+
# Check if it is a sparse layer, if not then it is a dense layer
|
| 238 |
+
if not self.is_sparse:
|
| 239 |
+
self.mlp = SwitchTransformersDenseActDense(config)
|
| 240 |
+
else:
|
| 241 |
+
self.mlp = SwitchTransformersSparseMLP(config)
|
| 242 |
+
|
| 243 |
+
self.layer_norm = SwitchTransformersLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 244 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 245 |
+
|
| 246 |
+
def forward(self, hidden_states, **kwargs):
|
| 247 |
+
forwarded_states = self.layer_norm(hidden_states)
|
| 248 |
+
forwarded_states = self.mlp(forwarded_states)
|
| 249 |
+
output = hidden_states + self.dropout(forwarded_states)
|
| 250 |
+
return output
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class SwitchTransformersAttention(T5Attention):
|
| 254 |
+
pass
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class SwitchTransformersLayerSelfAttention(T5LayerSelfAttention):
|
| 258 |
+
pass
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class SwitchTransformersLayerCrossAttention(T5LayerCrossAttention):
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class SwitchTransformersBlock(GradientCheckpointingLayer):
|
| 266 |
+
def __init__(self, config, has_relative_attention_bias=False, is_sparse=False, layer_idx: int | None = None):
|
| 267 |
+
super().__init__()
|
| 268 |
+
self.is_decoder = config.is_decoder
|
| 269 |
+
self.is_sparse = is_sparse
|
| 270 |
+
self.layer = nn.ModuleList()
|
| 271 |
+
self.layer.append(
|
| 272 |
+
SwitchTransformersLayerSelfAttention(
|
| 273 |
+
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
|
| 274 |
+
)
|
| 275 |
+
)
|
| 276 |
+
if self.is_decoder:
|
| 277 |
+
self.layer.append(SwitchTransformersLayerCrossAttention(config, layer_idx=layer_idx))
|
| 278 |
+
|
| 279 |
+
self.layer.append(SwitchTransformersLayerFF(config, is_sparse=self.is_sparse))
|
| 280 |
+
|
| 281 |
+
def forward(
|
| 282 |
+
self,
|
| 283 |
+
hidden_states,
|
| 284 |
+
attention_mask=None,
|
| 285 |
+
position_bias=None,
|
| 286 |
+
encoder_hidden_states=None,
|
| 287 |
+
encoder_attention_mask=None,
|
| 288 |
+
encoder_decoder_position_bias=None,
|
| 289 |
+
past_key_values=None,
|
| 290 |
+
use_cache=False,
|
| 291 |
+
**kwargs,
|
| 292 |
+
):
|
| 293 |
+
hidden_states, _ = self.layer[0](
|
| 294 |
+
hidden_states,
|
| 295 |
+
attention_mask=attention_mask,
|
| 296 |
+
position_bias=position_bias,
|
| 297 |
+
past_key_values=past_key_values,
|
| 298 |
+
use_cache=use_cache,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# clamp inf values to enable fp16 training
|
| 302 |
+
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
|
| 303 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 304 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 305 |
+
|
| 306 |
+
do_cross_attention = self.is_decoder and encoder_hidden_states is not None
|
| 307 |
+
if do_cross_attention:
|
| 308 |
+
hidden_states, _ = self.layer[1](
|
| 309 |
+
hidden_states,
|
| 310 |
+
key_value_states=encoder_hidden_states,
|
| 311 |
+
attention_mask=encoder_attention_mask,
|
| 312 |
+
position_bias=encoder_decoder_position_bias,
|
| 313 |
+
past_key_values=past_key_values,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# clamp inf values to enable fp16 training
|
| 317 |
+
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
|
| 318 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 319 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 320 |
+
|
| 321 |
+
hidden_states = self.layer[-1](hidden_states)
|
| 322 |
+
# clamp inf values to enable fp16 training
|
| 323 |
+
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
|
| 324 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 325 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 326 |
+
return hidden_states
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@auto_docstring
|
| 330 |
+
class SwitchTransformersPreTrainedModel(PreTrainedModel):
|
| 331 |
+
config: SwitchTransformersConfig
|
| 332 |
+
base_model_prefix = "switch_transformers"
|
| 333 |
+
supports_gradient_checkpointing = True
|
| 334 |
+
_can_compile_fullgraph = False
|
| 335 |
+
_no_split_modules = ["SwitchTransformersBlock"]
|
| 336 |
+
|
| 337 |
+
@torch.no_grad()
|
| 338 |
+
def _init_weights(self, module):
|
| 339 |
+
"""Initialize the weights"""
|
| 340 |
+
factor = self.config.initializer_factor # Used for testing weights initialization
|
| 341 |
+
if isinstance(module, SwitchTransformersLayerNorm):
|
| 342 |
+
init.constant_(module.weight, factor * 1.0)
|
| 343 |
+
elif isinstance(
|
| 344 |
+
module,
|
| 345 |
+
(SwitchTransformersModel, SwitchTransformersForConditionalGeneration, SwitchTransformersEncoderModel),
|
| 346 |
+
):
|
| 347 |
+
init.normal_(module.shared.weight, mean=0.0, std=factor * 1.0)
|
| 348 |
+
if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
|
| 349 |
+
init.normal_(module.lm_head.weight, mean=0.0, std=factor * 1.0)
|
| 350 |
+
elif isinstance(module, SwitchTransformersDenseActDense):
|
| 351 |
+
init.normal_(module.wi.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 352 |
+
if hasattr(module.wi, "bias") and module.wi.bias is not None:
|
| 353 |
+
init.zeros_(module.wi.bias)
|
| 354 |
+
init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
|
| 355 |
+
if hasattr(module.wo, "bias") and module.wo.bias is not None:
|
| 356 |
+
init.zeros_(module.wo.bias)
|
| 357 |
+
elif isinstance(module, SwitchTransformersAttention):
|
| 358 |
+
d_model = self.config.d_model
|
| 359 |
+
key_value_proj_dim = self.config.d_kv
|
| 360 |
+
n_heads = self.config.num_heads
|
| 361 |
+
init.normal_(module.q.weight, mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
|
| 362 |
+
init.normal_(module.k.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 363 |
+
init.normal_(module.v.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 364 |
+
init.normal_(module.o.weight, mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
|
| 365 |
+
if module.has_relative_attention_bias:
|
| 366 |
+
init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5))
|
| 367 |
+
elif isinstance(module, SwitchTransformersSparseMLP):
|
| 368 |
+
d_model = self.config.d_model
|
| 369 |
+
key_value_proj_dim = self.config.d_kv
|
| 370 |
+
n_heads = self.config.num_heads
|
| 371 |
+
init.normal_(module.router.classifier.weight, mean=0.0, std=factor * 1)
|
| 372 |
+
for idx in range(self.config.num_experts):
|
| 373 |
+
init.normal_(module.experts[f"expert_{idx}"].wi.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 374 |
+
init.normal_(module.experts[f"expert_{idx}"].wo.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 375 |
+
|
| 376 |
+
def _shift_right(self, input_ids):
|
| 377 |
+
decoder_start_token_id = self.config.decoder_start_token_id
|
| 378 |
+
pad_token_id = self.config.pad_token_id
|
| 379 |
+
|
| 380 |
+
if decoder_start_token_id is None:
|
| 381 |
+
raise ValueError(
|
| 382 |
+
"self.model.config.decoder_start_token_id has to be defined. In SwitchTransformers it is usually set"
|
| 383 |
+
" to the pad_token_id. See SwitchTransformers docs for more information"
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 387 |
+
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
|
| 388 |
+
shifted_input_ids[..., 0] = decoder_start_token_id
|
| 389 |
+
|
| 390 |
+
if pad_token_id is None:
|
| 391 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 392 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 393 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 394 |
+
|
| 395 |
+
return shifted_input_ids
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class SwitchTransformersStack(SwitchTransformersPreTrainedModel):
|
| 399 |
+
_can_record_outputs = {
|
| 400 |
+
"hidden_states": SwitchTransformersBlock,
|
| 401 |
+
"attentions": OutputRecorder(SwitchTransformersAttention, index=-1, layer_name="layer.0"),
|
| 402 |
+
"cross_attentions": OutputRecorder(SwitchTransformersAttention, index=-1, layer_name="layer.1"),
|
| 403 |
+
"router_logits": OutputRecorder(SwitchTransformersTop1Router, index=2),
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
def __init__(self, config):
|
| 407 |
+
super().__init__(config)
|
| 408 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
|
| 409 |
+
|
| 410 |
+
self.is_decoder = config.is_decoder
|
| 411 |
+
|
| 412 |
+
sparse_step = config.decoder_sparse_step if self.is_decoder else config.encoder_sparse_step
|
| 413 |
+
config.num_layers = config.num_decoder_layers if self.is_decoder else config.num_layers
|
| 414 |
+
self.block = nn.ModuleList()
|
| 415 |
+
for i in range(config.num_layers):
|
| 416 |
+
is_sparse = (i % sparse_step == 1 or sparse_step == 1) if sparse_step > 0 else False
|
| 417 |
+
|
| 418 |
+
self.block.append(
|
| 419 |
+
SwitchTransformersBlock(
|
| 420 |
+
config, has_relative_attention_bias=bool(i == 0), is_sparse=is_sparse, layer_idx=i
|
| 421 |
+
)
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
self.final_layer_norm = SwitchTransformersLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 425 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 426 |
+
self.post_init()
|
| 427 |
+
|
| 428 |
+
self.gradient_checkpointing = False
|
| 429 |
+
|
| 430 |
+
@merge_with_config_defaults
|
| 431 |
+
@capture_outputs
|
| 432 |
+
def forward(
|
| 433 |
+
self,
|
| 434 |
+
input_ids=None,
|
| 435 |
+
attention_mask=None,
|
| 436 |
+
encoder_hidden_states=None,
|
| 437 |
+
encoder_attention_mask=None,
|
| 438 |
+
inputs_embeds=None,
|
| 439 |
+
past_key_values=None,
|
| 440 |
+
use_cache=None,
|
| 441 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 442 |
+
) -> tuple | MoEModelOutputWithPastAndCrossAttentions:
|
| 443 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 444 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 445 |
+
|
| 446 |
+
if inputs_embeds is None:
|
| 447 |
+
if self.embed_tokens is None:
|
| 448 |
+
raise ValueError("You have to initialize the model with valid token embeddings")
|
| 449 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 450 |
+
|
| 451 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
| 452 |
+
|
| 453 |
+
if use_cache is True:
|
| 454 |
+
if not self.is_decoder:
|
| 455 |
+
raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
|
| 456 |
+
|
| 457 |
+
if self.is_decoder:
|
| 458 |
+
if use_cache and past_key_values is None:
|
| 459 |
+
if self.config.is_encoder_decoder:
|
| 460 |
+
past_key_values = EncoderDecoderCache(
|
| 461 |
+
DynamicCache(config=self.config), DynamicCache(config=self.config)
|
| 462 |
+
)
|
| 463 |
+
else:
|
| 464 |
+
past_key_values = DynamicCache(config=self.config)
|
| 465 |
+
elif not self.is_decoder:
|
| 466 |
+
# do not pass cache object down the line for encoder stack
|
| 467 |
+
# it messes indexing later in decoder-stack because cache object is modified in-place
|
| 468 |
+
past_key_values = None
|
| 469 |
+
|
| 470 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 471 |
+
if attention_mask is None and not is_torchdynamo_compiling():
|
| 472 |
+
# required mask seq length can be calculated via length of past cache
|
| 473 |
+
mask_seq_length = past_key_values_length + seq_length
|
| 474 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
| 475 |
+
|
| 476 |
+
if self.config.is_decoder:
|
| 477 |
+
causal_mask = create_causal_mask(
|
| 478 |
+
config=self.config,
|
| 479 |
+
inputs_embeds=inputs_embeds,
|
| 480 |
+
attention_mask=attention_mask,
|
| 481 |
+
past_key_values=past_key_values,
|
| 482 |
+
)
|
| 483 |
+
else:
|
| 484 |
+
causal_mask = attention_mask[:, None, None, :]
|
| 485 |
+
causal_mask = causal_mask.to(dtype=inputs_embeds.dtype)
|
| 486 |
+
causal_mask = (1.0 - causal_mask) * torch.finfo(inputs_embeds.dtype).min
|
| 487 |
+
|
| 488 |
+
if encoder_attention_mask is not None:
|
| 489 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 490 |
+
config=self.config,
|
| 491 |
+
inputs_embeds=inputs_embeds,
|
| 492 |
+
attention_mask=encoder_attention_mask,
|
| 493 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
position_bias = None
|
| 497 |
+
encoder_decoder_position_bias = None
|
| 498 |
+
|
| 499 |
+
hidden_states = self.dropout(inputs_embeds)
|
| 500 |
+
|
| 501 |
+
for i, layer_module in enumerate(self.block):
|
| 502 |
+
hidden_states = layer_module(
|
| 503 |
+
hidden_states,
|
| 504 |
+
causal_mask,
|
| 505 |
+
position_bias,
|
| 506 |
+
encoder_hidden_states,
|
| 507 |
+
encoder_attention_mask,
|
| 508 |
+
encoder_decoder_position_bias,
|
| 509 |
+
past_key_values=past_key_values,
|
| 510 |
+
use_cache=use_cache,
|
| 511 |
+
**kwargs,
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 515 |
+
hidden_states = self.dropout(hidden_states)
|
| 516 |
+
|
| 517 |
+
return MoEModelOutputWithPastAndCrossAttentions(
|
| 518 |
+
last_hidden_state=hidden_states,
|
| 519 |
+
past_key_values=past_key_values,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@auto_docstring
|
| 524 |
+
class SwitchTransformersModel(SwitchTransformersPreTrainedModel):
|
| 525 |
+
_tied_weights_keys = {
|
| 526 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 527 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 528 |
+
}
|
| 529 |
+
_input_embed_layer = "shared"
|
| 530 |
+
|
| 531 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 532 |
+
super().__init__(config)
|
| 533 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 534 |
+
|
| 535 |
+
encoder_config = copy.deepcopy(config)
|
| 536 |
+
encoder_config.is_decoder = False
|
| 537 |
+
encoder_config.use_cache = False
|
| 538 |
+
self.encoder = SwitchTransformersStack(encoder_config)
|
| 539 |
+
|
| 540 |
+
decoder_config = copy.deepcopy(config)
|
| 541 |
+
decoder_config.is_decoder = True
|
| 542 |
+
self.decoder = SwitchTransformersStack(decoder_config)
|
| 543 |
+
|
| 544 |
+
# Initialize weights and apply final processing
|
| 545 |
+
self.post_init()
|
| 546 |
+
|
| 547 |
+
def set_input_embeddings(self, new_embeddings):
|
| 548 |
+
self.shared = new_embeddings
|
| 549 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 550 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 551 |
+
|
| 552 |
+
@auto_docstring
|
| 553 |
+
@can_return_tuple
|
| 554 |
+
def forward(
|
| 555 |
+
self,
|
| 556 |
+
input_ids: torch.LongTensor | None = None,
|
| 557 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 558 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 559 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 560 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 561 |
+
past_key_values: Cache | None = None,
|
| 562 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 563 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 564 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 565 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqMoEModelOutput:
|
| 566 |
+
if encoder_outputs is None:
|
| 567 |
+
encoder_outputs = self.encoder(
|
| 568 |
+
input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
hidden_states = encoder_outputs[0]
|
| 572 |
+
decoder_outputs = self.decoder(
|
| 573 |
+
input_ids=decoder_input_ids,
|
| 574 |
+
attention_mask=decoder_attention_mask,
|
| 575 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 576 |
+
past_key_values=past_key_values,
|
| 577 |
+
encoder_hidden_states=hidden_states,
|
| 578 |
+
encoder_attention_mask=attention_mask,
|
| 579 |
+
**kwargs,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
return Seq2SeqMoEModelOutput(
|
| 583 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 584 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 585 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 586 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 587 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 588 |
+
decoder_router_logits=decoder_outputs.router_logits,
|
| 589 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 590 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 591 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 592 |
+
encoder_router_logits=encoder_outputs.router_logits,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
@auto_docstring(
|
| 597 |
+
custom_intro="""
|
| 598 |
+
SWITCH_TRANSFORMERS Model with a `language modeling` head on top.
|
| 599 |
+
"""
|
| 600 |
+
)
|
| 601 |
+
class SwitchTransformersForConditionalGeneration(SwitchTransformersPreTrainedModel, GenerationMixin):
|
| 602 |
+
_tied_weights_keys = {
|
| 603 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 604 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 605 |
+
"lm_head.weight": "shared.weight",
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 609 |
+
super().__init__(config)
|
| 610 |
+
self.model_dim = config.d_model
|
| 611 |
+
|
| 612 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 613 |
+
|
| 614 |
+
encoder_config = copy.deepcopy(config)
|
| 615 |
+
encoder_config.is_decoder = False
|
| 616 |
+
encoder_config.use_cache = False
|
| 617 |
+
self.encoder = SwitchTransformersStack(encoder_config)
|
| 618 |
+
|
| 619 |
+
decoder_config = copy.deepcopy(config)
|
| 620 |
+
decoder_config.is_decoder = True
|
| 621 |
+
decoder_config.num_layers = config.num_decoder_layers
|
| 622 |
+
self.decoder = SwitchTransformersStack(decoder_config)
|
| 623 |
+
|
| 624 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 625 |
+
|
| 626 |
+
self.router_z_loss_coef = config.router_z_loss_coef
|
| 627 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
| 628 |
+
self.post_init()
|
| 629 |
+
|
| 630 |
+
def get_input_embeddings(self):
|
| 631 |
+
return self.shared
|
| 632 |
+
|
| 633 |
+
def set_input_embeddings(self, new_embeddings):
|
| 634 |
+
self.shared = new_embeddings
|
| 635 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 636 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 637 |
+
|
| 638 |
+
@auto_docstring
|
| 639 |
+
@can_return_tuple
|
| 640 |
+
def forward(
|
| 641 |
+
self,
|
| 642 |
+
input_ids: torch.LongTensor | None = None,
|
| 643 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 644 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 645 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 646 |
+
encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
|
| 647 |
+
past_key_values: Cache | None = None,
|
| 648 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 649 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 650 |
+
labels: torch.LongTensor | None = None,
|
| 651 |
+
output_router_logits: bool | None = False,
|
| 652 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 653 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqMoEOutput:
|
| 654 |
+
if encoder_outputs is None:
|
| 655 |
+
encoder_outputs = self.encoder(
|
| 656 |
+
input_ids=input_ids,
|
| 657 |
+
attention_mask=attention_mask,
|
| 658 |
+
inputs_embeds=inputs_embeds,
|
| 659 |
+
output_router_logits=output_router_logits,
|
| 660 |
+
**kwargs,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
hidden_states = encoder_outputs[0]
|
| 664 |
+
|
| 665 |
+
if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 666 |
+
# get decoder inputs from shifting lm labels to the right
|
| 667 |
+
decoder_input_ids = self._shift_right(labels)
|
| 668 |
+
|
| 669 |
+
# Decode
|
| 670 |
+
decoder_outputs = self.decoder(
|
| 671 |
+
input_ids=decoder_input_ids,
|
| 672 |
+
attention_mask=decoder_attention_mask,
|
| 673 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 674 |
+
past_key_values=past_key_values,
|
| 675 |
+
encoder_hidden_states=hidden_states,
|
| 676 |
+
encoder_attention_mask=attention_mask,
|
| 677 |
+
output_router_logits=output_router_logits,
|
| 678 |
+
**kwargs,
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
sequence_output = decoder_outputs.last_hidden_state
|
| 682 |
+
|
| 683 |
+
if self.config.tie_word_embeddings:
|
| 684 |
+
# Rescale output before projecting on vocab
|
| 685 |
+
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
|
| 686 |
+
sequence_output = sequence_output * (self.model_dim**-0.5)
|
| 687 |
+
|
| 688 |
+
lm_logits = self.lm_head(sequence_output)
|
| 689 |
+
|
| 690 |
+
loss = None
|
| 691 |
+
encoder_z_loss = None
|
| 692 |
+
encoder_aux_loss = None
|
| 693 |
+
decoder_z_loss = None
|
| 694 |
+
decoder_aux_loss = None
|
| 695 |
+
|
| 696 |
+
if output_router_logits:
|
| 697 |
+
# Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder
|
| 698 |
+
if self.encoder.config.encoder_sparse_step > 1:
|
| 699 |
+
encoder_router_logits, encoder_expert_indexes = self._unpack_router_logits(encoder_outputs[-1])
|
| 700 |
+
encoder_z_loss = router_z_loss_func(encoder_router_logits)
|
| 701 |
+
encoder_router_probs = nn.Softmax(dim=-1)(encoder_router_logits)
|
| 702 |
+
encoder_aux_loss = load_balancing_loss_func(encoder_router_probs, encoder_expert_indexes)
|
| 703 |
+
else:
|
| 704 |
+
encoder_z_loss = 0
|
| 705 |
+
encoder_aux_loss = 0
|
| 706 |
+
|
| 707 |
+
if self.decoder.config.decoder_sparse_step > 1:
|
| 708 |
+
decoder_router_logits, decoder_expert_indexes = self._unpack_router_logits(decoder_outputs[-1])
|
| 709 |
+
decoder_z_loss = router_z_loss_func(decoder_router_logits)
|
| 710 |
+
decoder_router_probs = nn.Softmax(dim=-1)(decoder_router_logits)
|
| 711 |
+
decoder_aux_loss = load_balancing_loss_func(decoder_router_probs, decoder_expert_indexes)
|
| 712 |
+
else:
|
| 713 |
+
decoder_z_loss = 0
|
| 714 |
+
decoder_aux_loss = 0
|
| 715 |
+
|
| 716 |
+
if labels is not None:
|
| 717 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
| 718 |
+
# move labels to correct device to enable PP
|
| 719 |
+
labels = labels.to(lm_logits.device)
|
| 720 |
+
loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
|
| 721 |
+
|
| 722 |
+
if output_router_logits:
|
| 723 |
+
z_loss = self.router_z_loss_coef * (encoder_z_loss + decoder_z_loss)
|
| 724 |
+
aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss)
|
| 725 |
+
loss = loss + z_loss + aux_loss
|
| 726 |
+
|
| 727 |
+
return Seq2SeqMoEOutput(
|
| 728 |
+
loss=loss,
|
| 729 |
+
logits=lm_logits,
|
| 730 |
+
encoder_z_loss=encoder_z_loss,
|
| 731 |
+
encoder_aux_loss=encoder_aux_loss,
|
| 732 |
+
decoder_z_loss=decoder_z_loss,
|
| 733 |
+
decoder_aux_loss=decoder_aux_loss,
|
| 734 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 735 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 736 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 737 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 738 |
+
decoder_router_logits=decoder_outputs.router_logits,
|
| 739 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 740 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 741 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 742 |
+
encoder_router_logits=encoder_outputs.router_logits,
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
def _unpack_router_logits(self, router_outputs):
|
| 746 |
+
total_router_logits = []
|
| 747 |
+
total_expert_indexes = []
|
| 748 |
+
for router_output in router_outputs:
|
| 749 |
+
if len(router_output[0].shape) > 1:
|
| 750 |
+
router_logits, expert_indexes = router_output
|
| 751 |
+
total_router_logits.append(router_logits)
|
| 752 |
+
total_expert_indexes.append(expert_indexes)
|
| 753 |
+
return torch.cat(total_router_logits, dim=1), torch.cat(total_expert_indexes, dim=1)
|
| 754 |
+
|
| 755 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 756 |
+
return self._shift_right(labels)
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
class SwitchTransformersEncoderModel(SwitchTransformersPreTrainedModel):
|
| 760 |
+
_tied_weights_keys = {
|
| 761 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
def __init__(self, config: SwitchTransformersConfig):
|
| 765 |
+
super().__init__(config)
|
| 766 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 767 |
+
|
| 768 |
+
encoder_config = copy.deepcopy(config)
|
| 769 |
+
encoder_config.use_cache = False
|
| 770 |
+
encoder_config.is_encoder_decoder = False
|
| 771 |
+
self.encoder = SwitchTransformersStack(encoder_config)
|
| 772 |
+
self.post_init()
|
| 773 |
+
|
| 774 |
+
def get_input_embeddings(self):
|
| 775 |
+
return self.shared
|
| 776 |
+
|
| 777 |
+
def set_input_embeddings(self, new_embeddings):
|
| 778 |
+
self.shared = new_embeddings
|
| 779 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 780 |
+
|
| 781 |
+
@auto_docstring
|
| 782 |
+
@can_return_tuple
|
| 783 |
+
def forward(
|
| 784 |
+
self,
|
| 785 |
+
input_ids: torch.LongTensor | None = None,
|
| 786 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 787 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 788 |
+
use_cache: bool | None = None,
|
| 789 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 790 |
+
) -> tuple[torch.FloatTensor] | MoEModelOutput:
|
| 791 |
+
use_cache = False
|
| 792 |
+
encoder_outputs = self.encoder(
|
| 793 |
+
input_ids=input_ids,
|
| 794 |
+
attention_mask=attention_mask,
|
| 795 |
+
inputs_embeds=inputs_embeds,
|
| 796 |
+
use_cache=use_cache,
|
| 797 |
+
**kwargs,
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
return encoder_outputs
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
__all__ = [
|
| 804 |
+
"SwitchTransformersEncoderModel",
|
| 805 |
+
"SwitchTransformersForConditionalGeneration",
|
| 806 |
+
"SwitchTransformersModel",
|
| 807 |
+
"SwitchTransformersPreTrainedModel",
|
| 808 |
+
"SwitchTransformersTop1Router",
|
| 809 |
+
"SwitchTransformersSparseMLP",
|
| 810 |
+
]
|