Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/logs/eval_lm1b_latest_non_owt_methods_genppl_20260506_20260506_101041.log +90 -0
- LTA_openwebtext_dualt/logs/lta_lm1b_dirichlet_categorical_fullvocab_c1024_fullycoupled_flmpack_onehot_hardce_ddit_small_len128_allmask_gbs512_4gpu_1m_nw0.log +0 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/ada.py +144 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/elm.py +123 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/modula2.py +1579 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/smithy.py +77 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/textedit.py +205 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/configuration_deepseek_v3.py +115 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/modeling_deepseek_v3.py +722 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/modular_deepseek_v3.py +340 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/__init__.py +31 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/configuration_llava_onevision.py +147 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/image_processing_pil_llava_onevision.py +307 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/modeling_llava_onevision.py +848 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/processing_llava_onevision.py +290 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/video_processing_llava_onevision.py +36 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pegasus/configuration_pegasus.py +76 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pegasus/modeling_pegasus.py +1132 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py +27 -0
LTA_openwebtext_dualt/logs/eval_lm1b_latest_non_owt_methods_genppl_20260506_20260506_101041.log
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[load] mdlm_latest step=860000 ckpt=runs/lm1b_mdlm_unified_ddit_small_len128_gbs512_8gpu_1m_20260505_repro/latest.pt
|
| 2 |
+
[mdlm] generated 32/256
|
| 3 |
+
[mdlm] generated 64/256
|
| 4 |
+
[mdlm] generated 96/256
|
| 5 |
+
[mdlm] generated 128/256
|
| 6 |
+
[mdlm] generated 160/256
|
| 7 |
+
[mdlm] generated 192/256
|
| 8 |
+
[mdlm] generated 224/256
|
| 9 |
+
[mdlm] generated 256/256
|
| 10 |
+
[summary] {"type": "summary", "name": "mdlm_latest", "kind": "mdlm", "checkpoint": "runs/lm1b_mdlm_unified_ddit_small_len128_gbs512_8gpu_1m_20260505_repro/latest.pt", "step": 860000, "decode": {"kind": "mdlm", "steps": 256, "decode_rule": "stochastic_confidence_unmask", "start": "all_mask", "temp": 1.0, "selection_noise": 0.0, "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 13.254623394640433, "nll_per_token": 2.584346427012978, "tokens": 38421, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 15.945599491226918, "nll_per_token": 2.769182897198147, "tokens": 31758, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 3.5550877572540878, "unique_tokens": 2672, "token_count": 32768, "distinct_1": 0.08154296875, "distinct_2": 0.27294537401574803, "top_token_mass": 0.182861328125}}
|
| 11 |
+
[load] duo_latest step=698000 ckpt=runs/lm1b_duo_unified_ddit_small_len128_gbs512_8gpu_1m_20260505_repro/latest.pt
|
| 12 |
+
[duo discrete] generated 32/256
|
| 13 |
+
[duo discrete] generated 64/256
|
| 14 |
+
[duo discrete] generated 96/256
|
| 15 |
+
[duo discrete] generated 128/256
|
| 16 |
+
[duo discrete] generated 160/256
|
| 17 |
+
[duo discrete] generated 192/256
|
| 18 |
+
[duo discrete] generated 224/256
|
| 19 |
+
[duo discrete] generated 256/256
|
| 20 |
+
[summary] {"type": "summary", "name": "duo_latest", "kind": "duo", "checkpoint": "runs/lm1b_duo_unified_ddit_small_len128_gbs512_8gpu_1m_20260505_repro/latest.pt", "step": 698000, "decode": {"kind": "duo", "steps": 256, "decode_rule": "discrete_random_replace_confidence_lock", "temp": 1.0, "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 1.10513806766837, "nll_per_token": 0.09997027528052237, "tokens": 65280, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 1.0, "nll_per_token": 0.0, "tokens": 0, "kept_samples": 0, "total_samples": 0, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 0.0, "unique_tokens": 1, "token_count": 32768, "distinct_1": 3.0517578125e-05, "distinct_2": 3.075787401574803e-05, "top_token_mass": 1.0}}
|
| 21 |
+
[load] flm_latest step=369000 ckpt=runs/lm1b_flm_unified_ddit_small_len128_gbs512_8gpu_1m_20260506_repro/latest.pt
|
| 22 |
+
[flm] generated 32/256
|
| 23 |
+
[flm] generated 64/256
|
| 24 |
+
[flm] generated 96/256
|
| 25 |
+
[flm] generated 128/256
|
| 26 |
+
[flm] generated 160/256
|
| 27 |
+
[flm] generated 192/256
|
| 28 |
+
[flm] generated 224/256
|
| 29 |
+
[flm] generated 256/256
|
| 30 |
+
[summary] {"type": "summary", "name": "flm_latest", "kind": "flm", "checkpoint": "runs/lm1b_flm_unified_ddit_small_len128_gbs512_8gpu_1m_20260506_repro/latest.pt", "step": 369000, "decode": {"kind": "flm", "steps": 256, "decode_rule": "gaussian_to_endpoint_flow", "noise_init": "gaussian", "final_from": "blend", "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 149.36539937152122, "nll_per_token": 5.006395648630426, "tokens": 38794, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 279.18684360473856, "nll_per_token": 5.63188124801842, "tokens": 32329, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 4.3123598709846584, "unique_tokens": 5896, "token_count": 32768, "distinct_1": 0.179931640625, "distinct_2": 0.6859005905511811, "top_token_mass": 0.045074462890625}}
|
| 31 |
+
[load] categorical_fullvocab_latest step=609000 ckpt=runs/lta_lm1b_dirichlet_categorical_fullvocab_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_8gpu_1m_nw0/latest.pt
|
| 32 |
+
[categorical Cmax=1024] generated 32/256
|
| 33 |
+
[categorical Cmax=1024] generated 64/256
|
| 34 |
+
[categorical Cmax=1024] generated 96/256
|
| 35 |
+
[categorical Cmax=1024] generated 128/256
|
| 36 |
+
[categorical Cmax=1024] generated 160/256
|
| 37 |
+
[categorical Cmax=1024] generated 192/256
|
| 38 |
+
[categorical Cmax=1024] generated 224/256
|
| 39 |
+
[categorical Cmax=1024] generated 256/256
|
| 40 |
+
[summary] {"type": "summary", "name": "categorical_fullvocab_latest", "kind": "categorical_fullvocab", "checkpoint": "runs/lta_lm1b_dirichlet_categorical_fullvocab_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_8gpu_1m_nw0/latest.pt", "step": 609000, "decode": {"kind": "categorical_fullvocab", "steps": 1024, "model_t_mode": "const05", "decode_rule": "dual_line_resample", "support_power": 1.0, "semantic_power": 1.5, "anchor_mode": "state", "noise_init": "dirichlet", "dirichlet_concentration": 1.0, "concentration_min": 1.0, "concentration_max": 1024.0, "endpoint_temp": 1.3, "final_from": "blend", "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 26.097635854173753, "nll_per_token": 3.2618447299261484, "tokens": 38904, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 37.64924659414174, "nll_per_token": 3.6283129432659162, "tokens": 31619, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 4.01496464321082, "unique_tokens": 2943, "token_count": 32768, "distinct_1": 0.089813232421875, "distinct_2": 0.421751968503937, "top_token_mass": 0.0771484375}}
|
| 41 |
+
[load] categorical_fullvocab_c64_latest step=301000 ckpt=runs/lta_lm1b_dirichlet_categorical_fullvocab_c64p0_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_8gpu_1m_nw0/latest.pt
|
| 42 |
+
[categorical Cmax=64] generated 32/256
|
| 43 |
+
[categorical Cmax=64] generated 64/256
|
| 44 |
+
[categorical Cmax=64] generated 96/256
|
| 45 |
+
[categorical Cmax=64] generated 128/256
|
| 46 |
+
[categorical Cmax=64] generated 160/256
|
| 47 |
+
[categorical Cmax=64] generated 192/256
|
| 48 |
+
[categorical Cmax=64] generated 224/256
|
| 49 |
+
[categorical Cmax=64] generated 256/256
|
| 50 |
+
[summary] {"type": "summary", "name": "categorical_fullvocab_c64_latest", "kind": "categorical_fullvocab", "checkpoint": "runs/lta_lm1b_dirichlet_categorical_fullvocab_c64p0_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_8gpu_1m_nw0/latest.pt", "step": 301000, "decode": {"kind": "categorical_fullvocab", "steps": 1024, "model_t_mode": "const05", "decode_rule": "dual_line_resample", "support_power": 1.0, "semantic_power": 1.5, "anchor_mode": "state", "noise_init": "dirichlet", "dirichlet_concentration": 1.0, "concentration_min": 1.0, "concentration_max": 64.0, "endpoint_temp": 1.3, "final_from": "blend", "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 29.50899600665449, "nll_per_token": 3.3846951662362814, "tokens": 38725, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 43.028414020337806, "nll_per_token": 3.761860688637853, "tokens": 31666, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 3.9699503322445215, "unique_tokens": 2842, "token_count": 32768, "distinct_1": 0.08673095703125, "distinct_2": 0.41627706692913385, "top_token_mass": 0.0784912109375}}
|
| 51 |
+
[load] categorical_fullvocab_c256_latest step=264000 ckpt=runs/lta_lm1b_dirichlet_categorical_fullvocab_c256p0_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_8gpu_1m_nw0/latest.pt
|
| 52 |
+
[categorical Cmax=256] generated 32/256
|
| 53 |
+
[categorical Cmax=256] generated 64/256
|
| 54 |
+
[categorical Cmax=256] generated 96/256
|
| 55 |
+
[categorical Cmax=256] generated 128/256
|
| 56 |
+
[categorical Cmax=256] generated 160/256
|
| 57 |
+
[categorical Cmax=256] generated 192/256
|
| 58 |
+
[categorical Cmax=256] generated 224/256
|
| 59 |
+
[categorical Cmax=256] generated 256/256
|
| 60 |
+
[summary] {"type": "summary", "name": "categorical_fullvocab_c256_latest", "kind": "categorical_fullvocab", "checkpoint": "runs/lta_lm1b_dirichlet_categorical_fullvocab_c256p0_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_8gpu_1m_nw0/latest.pt", "step": 264000, "decode": {"kind": "categorical_fullvocab", "steps": 1024, "model_t_mode": "const05", "decode_rule": "dual_line_resample", "support_power": 1.0, "semantic_power": 1.5, "anchor_mode": "state", "noise_init": "dirichlet", "dirichlet_concentration": 1.0, "concentration_min": 1.0, "concentration_max": 256.0, "endpoint_temp": 1.3, "final_from": "blend", "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 29.0563917263388, "nll_per_token": 3.369238484099026, "tokens": 39236, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 42.82775902266668, "nll_per_token": 3.757186467649641, "tokens": 31964, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 3.9620396608009667, "unique_tokens": 3100, "token_count": 32768, "distinct_1": 0.0946044921875, "distinct_2": 0.42165969488188976, "top_token_mass": 0.091522216796875}}
|
| 61 |
+
[load] categorical_fullvocab_c16_4gpu_latest step=146000 ckpt=runs/lta_lm1b_dirichlet_categorical_fullvocab_c16p0_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_4gpu_1m_nw0/latest.pt
|
| 62 |
+
[categorical Cmax=16] generated 32/256
|
| 63 |
+
[categorical Cmax=16] generated 64/256
|
| 64 |
+
[categorical Cmax=16] generated 96/256
|
| 65 |
+
[categorical Cmax=16] generated 128/256
|
| 66 |
+
[categorical Cmax=16] generated 160/256
|
| 67 |
+
[categorical Cmax=16] generated 192/256
|
| 68 |
+
[categorical Cmax=16] generated 224/256
|
| 69 |
+
[categorical Cmax=16] generated 256/256
|
| 70 |
+
[summary] {"type": "summary", "name": "categorical_fullvocab_c16_4gpu_latest", "kind": "categorical_fullvocab", "checkpoint": "runs/lta_lm1b_dirichlet_categorical_fullvocab_c16p0_dualt_flmpack_onehot_hardce_ddit_small_len128_gbs512_4gpu_1m_nw0/latest.pt", "step": 146000, "decode": {"kind": "categorical_fullvocab", "steps": 1024, "model_t_mode": "const05", "decode_rule": "dual_line_resample", "support_power": 1.0, "semantic_power": 1.5, "anchor_mode": "state", "noise_init": "dirichlet", "dirichlet_concentration": 1.0, "concentration_min": 1.0, "concentration_max": 16.0, "endpoint_temp": 1.3, "final_from": "blend", "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 34.32179659456556, "nll_per_token": 3.535780621576138, "tokens": 38197, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 50.163586453004264, "nll_per_token": 3.915289394027899, "tokens": 31430, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 3.954715470318628, "unique_tokens": 2829, "token_count": 32768, "distinct_1": 0.086334228515625, "distinct_2": 0.4382689468503937, "top_token_mass": 0.07720947265625}}
|
| 71 |
+
[load] ar_rowshard_latest step=267000 ckpt=runs/ar_lm1b_flmpack_bert_small_len128_gbs512_4gpu_1m_rowshard_b64_resume4000_20260504_203021/latest.pt
|
| 72 |
+
[ar temp=0.8] generated 32/256
|
| 73 |
+
[ar temp=0.8] generated 64/256
|
| 74 |
+
[ar temp=0.8] generated 96/256
|
| 75 |
+
[ar temp=0.8] generated 128/256
|
| 76 |
+
[ar temp=0.8] generated 160/256
|
| 77 |
+
[ar temp=0.8] generated 192/256
|
| 78 |
+
[ar temp=0.8] generated 224/256
|
| 79 |
+
[ar temp=0.8] generated 256/256
|
| 80 |
+
[ar temp=1] generated 32/256
|
| 81 |
+
[ar temp=1] generated 64/256
|
| 82 |
+
[ar temp=1] generated 96/256
|
| 83 |
+
[ar temp=1] generated 128/256
|
| 84 |
+
[ar temp=1] generated 160/256
|
| 85 |
+
[ar temp=1] generated 192/256
|
| 86 |
+
[ar temp=1] generated 224/256
|
| 87 |
+
[ar temp=1] generated 256/256
|
| 88 |
+
[summary] {"type": "summary", "name": "ar_rowshard_latest_t0p8", "kind": "ar", "checkpoint": "runs/ar_lm1b_flmpack_bert_small_len128_gbs512_4gpu_1m_rowshard_b64_resume4000_20260504_203021/latest.pt", "step": 267000, "decode": {"kind": "ar_sample", "temp": 0.8, "max_new_tokens": 127, "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 32.75331929719446, "nll_per_token": 3.489004309531525, "tokens": 38672, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 46.344570351610095, "nll_per_token": 3.8361041406323277, "tokens": 31984, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 4.1883945709687715, "unique_tokens": 5282, "token_count": 32768, "distinct_1": 0.16119384765625, "distinct_2": 0.590089812992126, "top_token_mass": 0.065338134765625}}
|
| 89 |
+
[summary] {"type": "summary", "name": "ar_rowshard_latest_t1p0", "kind": "ar", "checkpoint": "runs/ar_lm1b_flmpack_bert_small_len128_gbs512_4gpu_1m_rowshard_b64_resume4000_20260504_203021/latest.pt", "step": 267000, "decode": {"kind": "ar_sample", "temp": 1.0, "max_new_tokens": 127, "n_samples": 256, "seed": 20260506}, "raw_genppl": {"ppl": 70.47566606515413, "nll_per_token": 4.255267488039646, "tokens": 38787, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "stripped_genppl": {"ppl": 111.28221270824383, "nll_per_token": 4.7120694315677865, "tokens": 32392, "kept_samples": 256, "total_samples": 256, "empty_rate": 0.0, "skipped_samples": 0}, "diversity": {"sample_entropy": 4.344022305264332, "unique_tokens": 6845, "token_count": 32768, "distinct_1": 0.208892822265625, "distinct_2": 0.7198572834645669, "top_token_mass": 0.043731689453125}}
|
| 90 |
+
[done] docs/lta_samples/metrics_20260506/latest_non_owt_all_methods
|
LTA_openwebtext_dualt/logs/lta_lm1b_dirichlet_categorical_fullvocab_c1024_fullycoupled_flmpack_onehot_hardce_ddit_small_len128_allmask_gbs512_4gpu_1m_nw0.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/ada.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.ada
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for Ada family languages.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
from pygments.lexer import RegexLexer, include, bygroups, words, using, this, \
|
| 14 |
+
default
|
| 15 |
+
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
|
| 16 |
+
Number, Punctuation
|
| 17 |
+
from pygments.lexers._ada_builtins import KEYWORD_LIST, BUILTIN_LIST
|
| 18 |
+
|
| 19 |
+
__all__ = ['AdaLexer']
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AdaLexer(RegexLexer):
|
| 23 |
+
"""
|
| 24 |
+
For Ada source code.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
name = 'Ada'
|
| 28 |
+
aliases = ['ada', 'ada95', 'ada2005']
|
| 29 |
+
filenames = ['*.adb', '*.ads', '*.ada']
|
| 30 |
+
mimetypes = ['text/x-ada']
|
| 31 |
+
url = 'https://www.adaic.org'
|
| 32 |
+
version_added = '1.3'
|
| 33 |
+
|
| 34 |
+
flags = re.MULTILINE | re.IGNORECASE
|
| 35 |
+
|
| 36 |
+
tokens = {
|
| 37 |
+
'root': [
|
| 38 |
+
(r'[^\S\n]+', Text),
|
| 39 |
+
(r'--.*?\n', Comment.Single),
|
| 40 |
+
(r'[^\S\n]+', Text),
|
| 41 |
+
(r'function|procedure|entry', Keyword.Declaration, 'subprogram'),
|
| 42 |
+
(r'(subtype|type)(\s+)(\w+)',
|
| 43 |
+
bygroups(Keyword.Declaration, Text, Keyword.Type), 'type_def'),
|
| 44 |
+
(r'task|protected', Keyword.Declaration),
|
| 45 |
+
(r'(subtype)(\s+)', bygroups(Keyword.Declaration, Text)),
|
| 46 |
+
(r'(end)(\s+)', bygroups(Keyword.Reserved, Text), 'end'),
|
| 47 |
+
(r'(pragma)(\s+)(\w+)', bygroups(Keyword.Reserved, Text,
|
| 48 |
+
Comment.Preproc)),
|
| 49 |
+
(r'(true|false|null)\b', Keyword.Constant),
|
| 50 |
+
# builtin types
|
| 51 |
+
(words(BUILTIN_LIST, suffix=r'\b'), Keyword.Type),
|
| 52 |
+
(r'(and(\s+then)?|in|mod|not|or(\s+else)|rem)\b', Operator.Word),
|
| 53 |
+
(r'generic|private', Keyword.Declaration),
|
| 54 |
+
(r'package', Keyword.Declaration, 'package'),
|
| 55 |
+
(r'array\b', Keyword.Reserved, 'array_def'),
|
| 56 |
+
(r'(with|use)(\s+)', bygroups(Keyword.Namespace, Text), 'import'),
|
| 57 |
+
(r'(\w+)(\s*)(:)(\s*)(constant)',
|
| 58 |
+
bygroups(Name.Constant, Text, Punctuation, Text,
|
| 59 |
+
Keyword.Reserved)),
|
| 60 |
+
(r'<<\w+>>', Name.Label),
|
| 61 |
+
(r'(\w+)(\s*)(:)(\s*)(declare|begin|loop|for|while)',
|
| 62 |
+
bygroups(Name.Label, Text, Punctuation, Text, Keyword.Reserved)),
|
| 63 |
+
# keywords
|
| 64 |
+
(words(KEYWORD_LIST, prefix=r'\b', suffix=r'\b'),
|
| 65 |
+
Keyword.Reserved),
|
| 66 |
+
(r'"[^"]*"', String),
|
| 67 |
+
include('attribute'),
|
| 68 |
+
include('numbers'),
|
| 69 |
+
(r"'[^']'", String.Character),
|
| 70 |
+
(r'(\w+)(\s*|[(,])', bygroups(Name, using(this))),
|
| 71 |
+
(r"(<>|=>|:=|@|[\[\]]|[()|:;,.'])", Punctuation),
|
| 72 |
+
(r'[*<>+=/&-]', Operator),
|
| 73 |
+
(r'\n+', Text),
|
| 74 |
+
],
|
| 75 |
+
'numbers': [
|
| 76 |
+
(r'[0-9_]+#[0-9a-f_\.]+#', Number.Hex),
|
| 77 |
+
(r'[0-9_]+\.[0-9_]*', Number.Float),
|
| 78 |
+
(r'[0-9_]+', Number.Integer),
|
| 79 |
+
],
|
| 80 |
+
'attribute': [
|
| 81 |
+
(r"(')(\w+)", bygroups(Punctuation, Name.Attribute)),
|
| 82 |
+
],
|
| 83 |
+
'subprogram': [
|
| 84 |
+
(r'\(', Punctuation, ('#pop', 'formal_part')),
|
| 85 |
+
(r';', Punctuation, '#pop'),
|
| 86 |
+
(r'is\b', Keyword.Reserved, '#pop'),
|
| 87 |
+
(r'"[^"]+"|\w+', Name.Function),
|
| 88 |
+
include('root'),
|
| 89 |
+
],
|
| 90 |
+
'end': [
|
| 91 |
+
('(if|case|record|loop|select)', Keyword.Reserved),
|
| 92 |
+
(r'"[^"]+"|[\w.]+', Name.Function),
|
| 93 |
+
(r'\s+', Text),
|
| 94 |
+
(';', Punctuation, '#pop'),
|
| 95 |
+
],
|
| 96 |
+
'type_def': [
|
| 97 |
+
(r';', Punctuation, '#pop'),
|
| 98 |
+
(r'\(', Punctuation, 'formal_part'),
|
| 99 |
+
(r'\[', Punctuation, 'formal_part'),
|
| 100 |
+
(r'with|and|use', Keyword.Reserved),
|
| 101 |
+
(r'array\b', Keyword.Reserved, ('#pop', 'array_def')),
|
| 102 |
+
(r'record\b', Keyword.Reserved, ('record_def')),
|
| 103 |
+
(r'(null record)(;)', bygroups(Keyword.Reserved, Punctuation), '#pop'),
|
| 104 |
+
include('root'),
|
| 105 |
+
],
|
| 106 |
+
'array_def': [
|
| 107 |
+
(r';', Punctuation, '#pop'),
|
| 108 |
+
(r'(\w+)(\s+)(range)', bygroups(Keyword.Type, Text, Keyword.Reserved)),
|
| 109 |
+
include('root'),
|
| 110 |
+
],
|
| 111 |
+
'record_def': [
|
| 112 |
+
(r'end record', Keyword.Reserved, '#pop'),
|
| 113 |
+
include('root'),
|
| 114 |
+
],
|
| 115 |
+
'import': [
|
| 116 |
+
# TODO: use Name.Namespace if appropriate. This needs
|
| 117 |
+
# work to disinguish imports from aspects.
|
| 118 |
+
(r'[\w.]+', Name, '#pop'),
|
| 119 |
+
default('#pop'),
|
| 120 |
+
],
|
| 121 |
+
'formal_part': [
|
| 122 |
+
(r'\)', Punctuation, '#pop'),
|
| 123 |
+
(r'\]', Punctuation, '#pop'),
|
| 124 |
+
(r'\w+', Name.Variable),
|
| 125 |
+
(r',|:[^=]', Punctuation),
|
| 126 |
+
(r'(in|not|null|out|access)\b', Keyword.Reserved),
|
| 127 |
+
include('root'),
|
| 128 |
+
],
|
| 129 |
+
'package': [
|
| 130 |
+
('body', Keyword.Declaration),
|
| 131 |
+
(r'is\s+new|renames', Keyword.Reserved),
|
| 132 |
+
('is', Keyword.Reserved, '#pop'),
|
| 133 |
+
(';', Punctuation, '#pop'),
|
| 134 |
+
(r'\(', Punctuation, 'package_instantiation'),
|
| 135 |
+
(r'([\w.]+)', Name.Class),
|
| 136 |
+
include('root'),
|
| 137 |
+
],
|
| 138 |
+
'package_instantiation': [
|
| 139 |
+
(r'("[^"]+"|\w+)(\s+)(=>)', bygroups(Name.Variable, Text, Punctuation)),
|
| 140 |
+
(r'[\w.\'"]', Text),
|
| 141 |
+
(r'\)', Punctuation, '#pop'),
|
| 142 |
+
include('root'),
|
| 143 |
+
],
|
| 144 |
+
}
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/elm.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.elm
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexer for the Elm programming language.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pygments.lexer import RegexLexer, words, include, bygroups
|
| 12 |
+
from pygments.token import Comment, Keyword, Name, Number, Punctuation, \
|
| 13 |
+
String, Whitespace
|
| 14 |
+
|
| 15 |
+
__all__ = ['ElmLexer']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ElmLexer(RegexLexer):
|
| 19 |
+
"""
|
| 20 |
+
For Elm source code.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
name = 'Elm'
|
| 24 |
+
url = 'https://elm-lang.org/'
|
| 25 |
+
aliases = ['elm']
|
| 26 |
+
filenames = ['*.elm']
|
| 27 |
+
mimetypes = ['text/x-elm']
|
| 28 |
+
version_added = '2.1'
|
| 29 |
+
|
| 30 |
+
validName = r'[a-z_][a-zA-Z0-9_\']*'
|
| 31 |
+
|
| 32 |
+
specialName = r'^main '
|
| 33 |
+
|
| 34 |
+
builtinOps = (
|
| 35 |
+
'~', '||', '|>', '|', '`', '^', '\\', '\'', '>>', '>=', '>', '==',
|
| 36 |
+
'=', '<~', '<|', '<=', '<<', '<-', '<', '::', ':', '/=', '//', '/',
|
| 37 |
+
'..', '.', '->', '-', '++', '+', '*', '&&', '%',
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
reservedWords = words((
|
| 41 |
+
'alias', 'as', 'case', 'else', 'if', 'import', 'in',
|
| 42 |
+
'let', 'module', 'of', 'port', 'then', 'type', 'where',
|
| 43 |
+
), suffix=r'\b')
|
| 44 |
+
|
| 45 |
+
tokens = {
|
| 46 |
+
'root': [
|
| 47 |
+
|
| 48 |
+
# Comments
|
| 49 |
+
(r'\{-', Comment.Multiline, 'comment'),
|
| 50 |
+
(r'--.*', Comment.Single),
|
| 51 |
+
|
| 52 |
+
# Whitespace
|
| 53 |
+
(r'\s+', Whitespace),
|
| 54 |
+
|
| 55 |
+
# Strings
|
| 56 |
+
(r'"', String, 'doublequote'),
|
| 57 |
+
|
| 58 |
+
# Modules
|
| 59 |
+
(r'^(\s*)(module)(\s*)', bygroups(Whitespace, Keyword.Namespace,
|
| 60 |
+
Whitespace), 'imports'),
|
| 61 |
+
|
| 62 |
+
# Imports
|
| 63 |
+
(r'^(\s*)(import)(\s*)', bygroups(Whitespace, Keyword.Namespace,
|
| 64 |
+
Whitespace), 'imports'),
|
| 65 |
+
|
| 66 |
+
# Shaders
|
| 67 |
+
(r'\[glsl\|.*', Name.Entity, 'shader'),
|
| 68 |
+
|
| 69 |
+
# Keywords
|
| 70 |
+
(reservedWords, Keyword.Reserved),
|
| 71 |
+
|
| 72 |
+
# Types
|
| 73 |
+
(r'[A-Z][a-zA-Z0-9_]*', Keyword.Type),
|
| 74 |
+
|
| 75 |
+
# Main
|
| 76 |
+
(specialName, Keyword.Reserved),
|
| 77 |
+
|
| 78 |
+
# Prefix Operators
|
| 79 |
+
(words((builtinOps), prefix=r'\(', suffix=r'\)'), Name.Function),
|
| 80 |
+
|
| 81 |
+
# Infix Operators
|
| 82 |
+
(words(builtinOps), Name.Function),
|
| 83 |
+
|
| 84 |
+
# Numbers
|
| 85 |
+
include('numbers'),
|
| 86 |
+
|
| 87 |
+
# Variable Names
|
| 88 |
+
(validName, Name.Variable),
|
| 89 |
+
|
| 90 |
+
# Parens
|
| 91 |
+
(r'[,()\[\]{}]', Punctuation),
|
| 92 |
+
|
| 93 |
+
],
|
| 94 |
+
|
| 95 |
+
'comment': [
|
| 96 |
+
(r'-(?!\})', Comment.Multiline),
|
| 97 |
+
(r'\{-', Comment.Multiline, 'comment'),
|
| 98 |
+
(r'[^-}]', Comment.Multiline),
|
| 99 |
+
(r'-\}', Comment.Multiline, '#pop'),
|
| 100 |
+
],
|
| 101 |
+
|
| 102 |
+
'doublequote': [
|
| 103 |
+
(r'\\u[0-9a-fA-F]{4}', String.Escape),
|
| 104 |
+
(r'\\[nrfvb\\"]', String.Escape),
|
| 105 |
+
(r'[^"]', String),
|
| 106 |
+
(r'"', String, '#pop'),
|
| 107 |
+
],
|
| 108 |
+
|
| 109 |
+
'imports': [
|
| 110 |
+
(r'\w+(\.\w+)*', Name.Class, '#pop'),
|
| 111 |
+
],
|
| 112 |
+
|
| 113 |
+
'numbers': [
|
| 114 |
+
(r'_?\d+\.(?=\d+)', Number.Float),
|
| 115 |
+
(r'_?\d+', Number.Integer),
|
| 116 |
+
],
|
| 117 |
+
|
| 118 |
+
'shader': [
|
| 119 |
+
(r'\|(?!\])', Name.Entity),
|
| 120 |
+
(r'\|\]', Name.Entity, '#pop'),
|
| 121 |
+
(r'(.*)(\n)', bygroups(Name.Entity, Whitespace)),
|
| 122 |
+
],
|
| 123 |
+
}
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/modula2.py
ADDED
|
@@ -0,0 +1,1579 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
from pygments.lexer import RegexLexer, include
|
| 14 |
+
from pygments.util import get_bool_opt, get_list_opt
|
| 15 |
+
from pygments.token import Text, Comment, Operator, Keyword, Name, \
|
| 16 |
+
String, Number, Punctuation, Error
|
| 17 |
+
|
| 18 |
+
__all__ = ['Modula2Lexer']
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Multi-Dialect Modula-2 Lexer
|
| 22 |
+
class Modula2Lexer(RegexLexer):
|
| 23 |
+
"""
|
| 24 |
+
For Modula-2 source code.
|
| 25 |
+
|
| 26 |
+
The Modula-2 lexer supports several dialects. By default, it operates in
|
| 27 |
+
fallback mode, recognising the *combined* literals, punctuation symbols
|
| 28 |
+
and operators of all supported dialects, and the *combined* reserved words
|
| 29 |
+
and builtins of PIM Modula-2, ISO Modula-2 and Modula-2 R10, while not
|
| 30 |
+
differentiating between library defined identifiers.
|
| 31 |
+
|
| 32 |
+
To select a specific dialect, a dialect option may be passed
|
| 33 |
+
or a dialect tag may be embedded into a source file.
|
| 34 |
+
|
| 35 |
+
Dialect Options:
|
| 36 |
+
|
| 37 |
+
`m2pim`
|
| 38 |
+
Select PIM Modula-2 dialect.
|
| 39 |
+
`m2iso`
|
| 40 |
+
Select ISO Modula-2 dialect.
|
| 41 |
+
`m2r10`
|
| 42 |
+
Select Modula-2 R10 dialect.
|
| 43 |
+
`objm2`
|
| 44 |
+
Select Objective Modula-2 dialect.
|
| 45 |
+
|
| 46 |
+
The PIM and ISO dialect options may be qualified with a language extension.
|
| 47 |
+
|
| 48 |
+
Language Extensions:
|
| 49 |
+
|
| 50 |
+
`+aglet`
|
| 51 |
+
Select Aglet Modula-2 extensions, available with m2iso.
|
| 52 |
+
`+gm2`
|
| 53 |
+
Select GNU Modula-2 extensions, available with m2pim.
|
| 54 |
+
`+p1`
|
| 55 |
+
Select p1 Modula-2 extensions, available with m2iso.
|
| 56 |
+
`+xds`
|
| 57 |
+
Select XDS Modula-2 extensions, available with m2iso.
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
Passing a Dialect Option via Unix Commandline Interface
|
| 61 |
+
|
| 62 |
+
Dialect options may be passed to the lexer using the `dialect` key.
|
| 63 |
+
Only one such option should be passed. If multiple dialect options are
|
| 64 |
+
passed, the first valid option is used, any subsequent options are ignored.
|
| 65 |
+
|
| 66 |
+
Examples:
|
| 67 |
+
|
| 68 |
+
`$ pygmentize -O full,dialect=m2iso -f html -o /path/to/output /path/to/input`
|
| 69 |
+
Use ISO dialect to render input to HTML output
|
| 70 |
+
`$ pygmentize -O full,dialect=m2iso+p1 -f rtf -o /path/to/output /path/to/input`
|
| 71 |
+
Use ISO dialect with p1 extensions to render input to RTF output
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
Embedding a Dialect Option within a source file
|
| 75 |
+
|
| 76 |
+
A dialect option may be embedded in a source file in form of a dialect
|
| 77 |
+
tag, a specially formatted comment that specifies a dialect option.
|
| 78 |
+
|
| 79 |
+
Dialect Tag EBNF::
|
| 80 |
+
|
| 81 |
+
dialectTag :
|
| 82 |
+
OpeningCommentDelim Prefix dialectOption ClosingCommentDelim ;
|
| 83 |
+
|
| 84 |
+
dialectOption :
|
| 85 |
+
'm2pim' | 'm2iso' | 'm2r10' | 'objm2' |
|
| 86 |
+
'm2iso+aglet' | 'm2pim+gm2' | 'm2iso+p1' | 'm2iso+xds' ;
|
| 87 |
+
|
| 88 |
+
Prefix : '!' ;
|
| 89 |
+
|
| 90 |
+
OpeningCommentDelim : '(*' ;
|
| 91 |
+
|
| 92 |
+
ClosingCommentDelim : '*)' ;
|
| 93 |
+
|
| 94 |
+
No whitespace is permitted between the tokens of a dialect tag.
|
| 95 |
+
|
| 96 |
+
In the event that a source file contains multiple dialect tags, the first
|
| 97 |
+
tag that contains a valid dialect option will be used and any subsequent
|
| 98 |
+
dialect tags will be ignored. Ideally, a dialect tag should be placed
|
| 99 |
+
at the beginning of a source file.
|
| 100 |
+
|
| 101 |
+
An embedded dialect tag overrides a dialect option set via command line.
|
| 102 |
+
|
| 103 |
+
Examples:
|
| 104 |
+
|
| 105 |
+
``(*!m2r10*) DEFINITION MODULE Foobar; ...``
|
| 106 |
+
Use Modula2 R10 dialect to render this source file.
|
| 107 |
+
``(*!m2pim+gm2*) DEFINITION MODULE Bazbam; ...``
|
| 108 |
+
Use PIM dialect with GNU extensions to render this source file.
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
Algol Publication Mode:
|
| 112 |
+
|
| 113 |
+
In Algol publication mode, source text is rendered for publication of
|
| 114 |
+
algorithms in scientific papers and academic texts, following the format
|
| 115 |
+
of the Revised Algol-60 Language Report. It is activated by passing
|
| 116 |
+
one of two corresponding styles as an option:
|
| 117 |
+
|
| 118 |
+
`algol`
|
| 119 |
+
render reserved words lowercase underline boldface
|
| 120 |
+
and builtins lowercase boldface italic
|
| 121 |
+
`algol_nu`
|
| 122 |
+
render reserved words lowercase boldface (no underlining)
|
| 123 |
+
and builtins lowercase boldface italic
|
| 124 |
+
|
| 125 |
+
The lexer automatically performs the required lowercase conversion when
|
| 126 |
+
this mode is activated.
|
| 127 |
+
|
| 128 |
+
Example:
|
| 129 |
+
|
| 130 |
+
``$ pygmentize -O full,style=algol -f latex -o /path/to/output /path/to/input``
|
| 131 |
+
Render input file in Algol publication mode to LaTeX output.
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
Rendering Mode of First Class ADT Identifiers:
|
| 135 |
+
|
| 136 |
+
The rendering of standard library first class ADT identifiers is controlled
|
| 137 |
+
by option flag "treat_stdlib_adts_as_builtins".
|
| 138 |
+
|
| 139 |
+
When this option is turned on, standard library ADT identifiers are rendered
|
| 140 |
+
as builtins. When it is turned off, they are rendered as ordinary library
|
| 141 |
+
identifiers.
|
| 142 |
+
|
| 143 |
+
`treat_stdlib_adts_as_builtins` (default: On)
|
| 144 |
+
|
| 145 |
+
The option is useful for dialects that support ADTs as first class objects
|
| 146 |
+
and provide ADTs in the standard library that would otherwise be built-in.
|
| 147 |
+
|
| 148 |
+
At present, only Modula-2 R10 supports library ADTs as first class objects
|
| 149 |
+
and therefore, no ADT identifiers are defined for any other dialects.
|
| 150 |
+
|
| 151 |
+
Example:
|
| 152 |
+
|
| 153 |
+
``$ pygmentize -O full,dialect=m2r10,treat_stdlib_adts_as_builtins=Off ...``
|
| 154 |
+
Render standard library ADTs as ordinary library types.
|
| 155 |
+
|
| 156 |
+
.. versionchanged:: 2.1
|
| 157 |
+
Added multi-dialect support.
|
| 158 |
+
"""
|
| 159 |
+
name = 'Modula-2'
|
| 160 |
+
url = 'http://www.modula2.org/'
|
| 161 |
+
aliases = ['modula2', 'm2']
|
| 162 |
+
filenames = ['*.def', '*.mod']
|
| 163 |
+
mimetypes = ['text/x-modula2']
|
| 164 |
+
version_added = '1.3'
|
| 165 |
+
|
| 166 |
+
flags = re.MULTILINE | re.DOTALL
|
| 167 |
+
|
| 168 |
+
tokens = {
|
| 169 |
+
'whitespace': [
|
| 170 |
+
(r'\n+', Text), # blank lines
|
| 171 |
+
(r'\s+', Text), # whitespace
|
| 172 |
+
],
|
| 173 |
+
'dialecttags': [
|
| 174 |
+
# PIM Dialect Tag
|
| 175 |
+
(r'\(\*!m2pim\*\)', Comment.Special),
|
| 176 |
+
# ISO Dialect Tag
|
| 177 |
+
(r'\(\*!m2iso\*\)', Comment.Special),
|
| 178 |
+
# M2R10 Dialect Tag
|
| 179 |
+
(r'\(\*!m2r10\*\)', Comment.Special),
|
| 180 |
+
# ObjM2 Dialect Tag
|
| 181 |
+
(r'\(\*!objm2\*\)', Comment.Special),
|
| 182 |
+
# Aglet Extensions Dialect Tag
|
| 183 |
+
(r'\(\*!m2iso\+aglet\*\)', Comment.Special),
|
| 184 |
+
# GNU Extensions Dialect Tag
|
| 185 |
+
(r'\(\*!m2pim\+gm2\*\)', Comment.Special),
|
| 186 |
+
# p1 Extensions Dialect Tag
|
| 187 |
+
(r'\(\*!m2iso\+p1\*\)', Comment.Special),
|
| 188 |
+
# XDS Extensions Dialect Tag
|
| 189 |
+
(r'\(\*!m2iso\+xds\*\)', Comment.Special),
|
| 190 |
+
],
|
| 191 |
+
'identifiers': [
|
| 192 |
+
(r'([a-zA-Z_$][\w$]*)', Name),
|
| 193 |
+
],
|
| 194 |
+
'prefixed_number_literals': [
|
| 195 |
+
#
|
| 196 |
+
# Base-2, whole number
|
| 197 |
+
(r'0b[01]+(\'[01]+)*', Number.Bin),
|
| 198 |
+
#
|
| 199 |
+
# Base-16, whole number
|
| 200 |
+
(r'0[ux][0-9A-F]+(\'[0-9A-F]+)*', Number.Hex),
|
| 201 |
+
],
|
| 202 |
+
'plain_number_literals': [
|
| 203 |
+
#
|
| 204 |
+
# Base-10, real number with exponent
|
| 205 |
+
(r'[0-9]+(\'[0-9]+)*' # integral part
|
| 206 |
+
r'\.[0-9]+(\'[0-9]+)*' # fractional part
|
| 207 |
+
r'[eE][+-]?[0-9]+(\'[0-9]+)*', # exponent
|
| 208 |
+
Number.Float),
|
| 209 |
+
#
|
| 210 |
+
# Base-10, real number without exponent
|
| 211 |
+
(r'[0-9]+(\'[0-9]+)*' # integral part
|
| 212 |
+
r'\.[0-9]+(\'[0-9]+)*', # fractional part
|
| 213 |
+
Number.Float),
|
| 214 |
+
#
|
| 215 |
+
# Base-10, whole number
|
| 216 |
+
(r'[0-9]+(\'[0-9]+)*', Number.Integer),
|
| 217 |
+
],
|
| 218 |
+
'suffixed_number_literals': [
|
| 219 |
+
#
|
| 220 |
+
# Base-8, whole number
|
| 221 |
+
(r'[0-7]+B', Number.Oct),
|
| 222 |
+
#
|
| 223 |
+
# Base-8, character code
|
| 224 |
+
(r'[0-7]+C', Number.Oct),
|
| 225 |
+
#
|
| 226 |
+
# Base-16, number
|
| 227 |
+
(r'[0-9A-F]+H', Number.Hex),
|
| 228 |
+
],
|
| 229 |
+
'string_literals': [
|
| 230 |
+
(r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
|
| 231 |
+
(r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
|
| 232 |
+
],
|
| 233 |
+
'digraph_operators': [
|
| 234 |
+
# Dot Product Operator
|
| 235 |
+
(r'\*\.', Operator),
|
| 236 |
+
# Array Concatenation Operator
|
| 237 |
+
(r'\+>', Operator), # M2R10 + ObjM2
|
| 238 |
+
# Inequality Operator
|
| 239 |
+
(r'<>', Operator), # ISO + PIM
|
| 240 |
+
# Less-Or-Equal, Subset
|
| 241 |
+
(r'<=', Operator),
|
| 242 |
+
# Greater-Or-Equal, Superset
|
| 243 |
+
(r'>=', Operator),
|
| 244 |
+
# Identity Operator
|
| 245 |
+
(r'==', Operator), # M2R10 + ObjM2
|
| 246 |
+
# Type Conversion Operator
|
| 247 |
+
(r'::', Operator), # M2R10 + ObjM2
|
| 248 |
+
# Assignment Symbol
|
| 249 |
+
(r':=', Operator),
|
| 250 |
+
# Postfix Increment Mutator
|
| 251 |
+
(r'\+\+', Operator), # M2R10 + ObjM2
|
| 252 |
+
# Postfix Decrement Mutator
|
| 253 |
+
(r'--', Operator), # M2R10 + ObjM2
|
| 254 |
+
],
|
| 255 |
+
'unigraph_operators': [
|
| 256 |
+
# Arithmetic Operators
|
| 257 |
+
(r'[+-]', Operator),
|
| 258 |
+
(r'[*/]', Operator),
|
| 259 |
+
# ISO 80000-2 compliant Set Difference Operator
|
| 260 |
+
(r'\\', Operator), # M2R10 + ObjM2
|
| 261 |
+
# Relational Operators
|
| 262 |
+
(r'[=#<>]', Operator),
|
| 263 |
+
# Dereferencing Operator
|
| 264 |
+
(r'\^', Operator),
|
| 265 |
+
# Dereferencing Operator Synonym
|
| 266 |
+
(r'@', Operator), # ISO
|
| 267 |
+
# Logical AND Operator Synonym
|
| 268 |
+
(r'&', Operator), # PIM + ISO
|
| 269 |
+
# Logical NOT Operator Synonym
|
| 270 |
+
(r'~', Operator), # PIM + ISO
|
| 271 |
+
# Smalltalk Message Prefix
|
| 272 |
+
(r'`', Operator), # ObjM2
|
| 273 |
+
],
|
| 274 |
+
'digraph_punctuation': [
|
| 275 |
+
# Range Constructor
|
| 276 |
+
(r'\.\.', Punctuation),
|
| 277 |
+
# Opening Chevron Bracket
|
| 278 |
+
(r'<<', Punctuation), # M2R10 + ISO
|
| 279 |
+
# Closing Chevron Bracket
|
| 280 |
+
(r'>>', Punctuation), # M2R10 + ISO
|
| 281 |
+
# Blueprint Punctuation
|
| 282 |
+
(r'->', Punctuation), # M2R10 + ISO
|
| 283 |
+
# Distinguish |# and # in M2 R10
|
| 284 |
+
(r'\|#', Punctuation),
|
| 285 |
+
# Distinguish ## and # in M2 R10
|
| 286 |
+
(r'##', Punctuation),
|
| 287 |
+
# Distinguish |* and * in M2 R10
|
| 288 |
+
(r'\|\*', Punctuation),
|
| 289 |
+
],
|
| 290 |
+
'unigraph_punctuation': [
|
| 291 |
+
# Common Punctuation
|
| 292 |
+
(r'[()\[\]{},.:;|]', Punctuation),
|
| 293 |
+
# Case Label Separator Synonym
|
| 294 |
+
(r'!', Punctuation), # ISO
|
| 295 |
+
# Blueprint Punctuation
|
| 296 |
+
(r'\?', Punctuation), # M2R10 + ObjM2
|
| 297 |
+
],
|
| 298 |
+
'comments': [
|
| 299 |
+
# Single Line Comment
|
| 300 |
+
(r'^//.*?\n', Comment.Single), # M2R10 + ObjM2
|
| 301 |
+
# Block Comment
|
| 302 |
+
(r'\(\*([^$].*?)\*\)', Comment.Multiline),
|
| 303 |
+
# Template Block Comment
|
| 304 |
+
(r'/\*(.*?)\*/', Comment.Multiline), # M2R10 + ObjM2
|
| 305 |
+
],
|
| 306 |
+
'pragmas': [
|
| 307 |
+
# ISO Style Pragmas
|
| 308 |
+
(r'<\*.*?\*>', Comment.Preproc), # ISO, M2R10 + ObjM2
|
| 309 |
+
# Pascal Style Pragmas
|
| 310 |
+
(r'\(\*\$.*?\*\)', Comment.Preproc), # PIM
|
| 311 |
+
],
|
| 312 |
+
'root': [
|
| 313 |
+
include('whitespace'),
|
| 314 |
+
include('dialecttags'),
|
| 315 |
+
include('pragmas'),
|
| 316 |
+
include('comments'),
|
| 317 |
+
include('identifiers'),
|
| 318 |
+
include('suffixed_number_literals'), # PIM + ISO
|
| 319 |
+
include('prefixed_number_literals'), # M2R10 + ObjM2
|
| 320 |
+
include('plain_number_literals'),
|
| 321 |
+
include('string_literals'),
|
| 322 |
+
include('digraph_punctuation'),
|
| 323 |
+
include('digraph_operators'),
|
| 324 |
+
include('unigraph_punctuation'),
|
| 325 |
+
include('unigraph_operators'),
|
| 326 |
+
]
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
# C o m m o n D a t a s e t s
|
| 330 |
+
|
| 331 |
+
# Common Reserved Words Dataset
|
| 332 |
+
common_reserved_words = (
|
| 333 |
+
# 37 common reserved words
|
| 334 |
+
'AND', 'ARRAY', 'BEGIN', 'BY', 'CASE', 'CONST', 'DEFINITION', 'DIV',
|
| 335 |
+
'DO', 'ELSE', 'ELSIF', 'END', 'EXIT', 'FOR', 'FROM', 'IF',
|
| 336 |
+
'IMPLEMENTATION', 'IMPORT', 'IN', 'LOOP', 'MOD', 'MODULE', 'NOT',
|
| 337 |
+
'OF', 'OR', 'POINTER', 'PROCEDURE', 'RECORD', 'REPEAT', 'RETURN',
|
| 338 |
+
'SET', 'THEN', 'TO', 'TYPE', 'UNTIL', 'VAR', 'WHILE',
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
# Common Builtins Dataset
|
| 342 |
+
common_builtins = (
|
| 343 |
+
# 16 common builtins
|
| 344 |
+
'ABS', 'BOOLEAN', 'CARDINAL', 'CHAR', 'CHR', 'FALSE', 'INTEGER',
|
| 345 |
+
'LONGINT', 'LONGREAL', 'MAX', 'MIN', 'NIL', 'ODD', 'ORD', 'REAL',
|
| 346 |
+
'TRUE',
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Common Pseudo-Module Builtins Dataset
|
| 350 |
+
common_pseudo_builtins = (
|
| 351 |
+
# 4 common pseudo builtins
|
| 352 |
+
'ADDRESS', 'BYTE', 'WORD', 'ADR'
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
# P I M M o d u l a - 2 D a t a s e t s
|
| 356 |
+
|
| 357 |
+
# Lexemes to Mark as Error Tokens for PIM Modula-2
|
| 358 |
+
pim_lexemes_to_reject = (
|
| 359 |
+
'!', '`', '@', '$', '%', '?', '\\', '==', '++', '--', '::', '*.',
|
| 360 |
+
'+>', '->', '<<', '>>', '|#', '##',
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
# PIM Modula-2 Additional Reserved Words Dataset
|
| 364 |
+
pim_additional_reserved_words = (
|
| 365 |
+
# 3 additional reserved words
|
| 366 |
+
'EXPORT', 'QUALIFIED', 'WITH',
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
# PIM Modula-2 Additional Builtins Dataset
|
| 370 |
+
pim_additional_builtins = (
|
| 371 |
+
# 16 additional builtins
|
| 372 |
+
'BITSET', 'CAP', 'DEC', 'DISPOSE', 'EXCL', 'FLOAT', 'HALT', 'HIGH',
|
| 373 |
+
'INC', 'INCL', 'NEW', 'NIL', 'PROC', 'SIZE', 'TRUNC', 'VAL',
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
# PIM Modula-2 Additional Pseudo-Module Builtins Dataset
|
| 377 |
+
pim_additional_pseudo_builtins = (
|
| 378 |
+
# 5 additional pseudo builtins
|
| 379 |
+
'SYSTEM', 'PROCESS', 'TSIZE', 'NEWPROCESS', 'TRANSFER',
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
# I S O M o d u l a - 2 D a t a s e t s
|
| 383 |
+
|
| 384 |
+
# Lexemes to Mark as Error Tokens for ISO Modula-2
|
| 385 |
+
iso_lexemes_to_reject = (
|
| 386 |
+
'`', '$', '%', '?', '\\', '==', '++', '--', '::', '*.', '+>', '->',
|
| 387 |
+
'<<', '>>', '|#', '##',
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# ISO Modula-2 Additional Reserved Words Dataset
|
| 391 |
+
iso_additional_reserved_words = (
|
| 392 |
+
# 9 additional reserved words (ISO 10514-1)
|
| 393 |
+
'EXCEPT', 'EXPORT', 'FINALLY', 'FORWARD', 'PACKEDSET', 'QUALIFIED',
|
| 394 |
+
'REM', 'RETRY', 'WITH',
|
| 395 |
+
# 10 additional reserved words (ISO 10514-2 & ISO 10514-3)
|
| 396 |
+
'ABSTRACT', 'AS', 'CLASS', 'GUARD', 'INHERIT', 'OVERRIDE', 'READONLY',
|
| 397 |
+
'REVEAL', 'TRACED', 'UNSAFEGUARDED',
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
# ISO Modula-2 Additional Builtins Dataset
|
| 401 |
+
iso_additional_builtins = (
|
| 402 |
+
# 26 additional builtins (ISO 10514-1)
|
| 403 |
+
'BITSET', 'CAP', 'CMPLX', 'COMPLEX', 'DEC', 'DISPOSE', 'EXCL', 'FLOAT',
|
| 404 |
+
'HALT', 'HIGH', 'IM', 'INC', 'INCL', 'INT', 'INTERRUPTIBLE', 'LENGTH',
|
| 405 |
+
'LFLOAT', 'LONGCOMPLEX', 'NEW', 'PROC', 'PROTECTION', 'RE', 'SIZE',
|
| 406 |
+
'TRUNC', 'UNINTERRUBTIBLE', 'VAL',
|
| 407 |
+
# 5 additional builtins (ISO 10514-2 & ISO 10514-3)
|
| 408 |
+
'CREATE', 'DESTROY', 'EMPTY', 'ISMEMBER', 'SELF',
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
# ISO Modula-2 Additional Pseudo-Module Builtins Dataset
|
| 412 |
+
iso_additional_pseudo_builtins = (
|
| 413 |
+
# 14 additional builtins (SYSTEM)
|
| 414 |
+
'SYSTEM', 'BITSPERLOC', 'LOCSPERBYTE', 'LOCSPERWORD', 'LOC',
|
| 415 |
+
'ADDADR', 'SUBADR', 'DIFADR', 'MAKEADR', 'ADR',
|
| 416 |
+
'ROTATE', 'SHIFT', 'CAST', 'TSIZE',
|
| 417 |
+
# 13 additional builtins (COROUTINES)
|
| 418 |
+
'COROUTINES', 'ATTACH', 'COROUTINE', 'CURRENT', 'DETACH', 'HANDLER',
|
| 419 |
+
'INTERRUPTSOURCE', 'IOTRANSFER', 'IsATTACHED', 'LISTEN',
|
| 420 |
+
'NEWCOROUTINE', 'PROT', 'TRANSFER',
|
| 421 |
+
# 9 additional builtins (EXCEPTIONS)
|
| 422 |
+
'EXCEPTIONS', 'AllocateSource', 'CurrentNumber', 'ExceptionNumber',
|
| 423 |
+
'ExceptionSource', 'GetMessage', 'IsCurrentSource',
|
| 424 |
+
'IsExceptionalExecution', 'RAISE',
|
| 425 |
+
# 3 additional builtins (TERMINATION)
|
| 426 |
+
'TERMINATION', 'IsTerminating', 'HasHalted',
|
| 427 |
+
# 4 additional builtins (M2EXCEPTION)
|
| 428 |
+
'M2EXCEPTION', 'M2Exceptions', 'M2Exception', 'IsM2Exception',
|
| 429 |
+
'indexException', 'rangeException', 'caseSelectException',
|
| 430 |
+
'invalidLocation', 'functionException', 'wholeValueException',
|
| 431 |
+
'wholeDivException', 'realValueException', 'realDivException',
|
| 432 |
+
'complexValueException', 'complexDivException', 'protException',
|
| 433 |
+
'sysException', 'coException', 'exException',
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# M o d u l a - 2 R 1 0 D a t a s e t s
|
| 437 |
+
|
| 438 |
+
# Lexemes to Mark as Error Tokens for Modula-2 R10
|
| 439 |
+
m2r10_lexemes_to_reject = (
|
| 440 |
+
'!', '`', '@', '$', '%', '&', '<>',
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# Modula-2 R10 reserved words in addition to the common set
|
| 444 |
+
m2r10_additional_reserved_words = (
|
| 445 |
+
# 12 additional reserved words
|
| 446 |
+
'ALIAS', 'ARGLIST', 'BLUEPRINT', 'COPY', 'GENLIB', 'INDETERMINATE',
|
| 447 |
+
'NEW', 'NONE', 'OPAQUE', 'REFERENTIAL', 'RELEASE', 'RETAIN',
|
| 448 |
+
# 2 additional reserved words with symbolic assembly option
|
| 449 |
+
'ASM', 'REG',
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
# Modula-2 R10 builtins in addition to the common set
|
| 453 |
+
m2r10_additional_builtins = (
|
| 454 |
+
# 26 additional builtins
|
| 455 |
+
'CARDINAL', 'COUNT', 'EMPTY', 'EXISTS', 'INSERT', 'LENGTH', 'LONGCARD',
|
| 456 |
+
'OCTET', 'PTR', 'PRED', 'READ', 'READNEW', 'REMOVE', 'RETRIEVE', 'SORT',
|
| 457 |
+
'STORE', 'SUBSET', 'SUCC', 'TLIMIT', 'TMAX', 'TMIN', 'TRUE', 'TSIZE',
|
| 458 |
+
'UNICHAR', 'WRITE', 'WRITEF',
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
# Modula-2 R10 Additional Pseudo-Module Builtins Dataset
|
| 462 |
+
m2r10_additional_pseudo_builtins = (
|
| 463 |
+
# 13 additional builtins (TPROPERTIES)
|
| 464 |
+
'TPROPERTIES', 'PROPERTY', 'LITERAL', 'TPROPERTY', 'TLITERAL',
|
| 465 |
+
'TBUILTIN', 'TDYN', 'TREFC', 'TNIL', 'TBASE', 'TPRECISION',
|
| 466 |
+
'TMAXEXP', 'TMINEXP',
|
| 467 |
+
# 4 additional builtins (CONVERSION)
|
| 468 |
+
'CONVERSION', 'TSXFSIZE', 'SXF', 'VAL',
|
| 469 |
+
# 35 additional builtins (UNSAFE)
|
| 470 |
+
'UNSAFE', 'CAST', 'INTRINSIC', 'AVAIL', 'ADD', 'SUB', 'ADDC', 'SUBC',
|
| 471 |
+
'FETCHADD', 'FETCHSUB', 'SHL', 'SHR', 'ASHR', 'ROTL', 'ROTR', 'ROTLC',
|
| 472 |
+
'ROTRC', 'BWNOT', 'BWAND', 'BWOR', 'BWXOR', 'BWNAND', 'BWNOR',
|
| 473 |
+
'SETBIT', 'TESTBIT', 'LSBIT', 'MSBIT', 'CSBITS', 'BAIL', 'HALT',
|
| 474 |
+
'TODO', 'FFI', 'ADDR', 'VARGLIST', 'VARGC',
|
| 475 |
+
# 11 additional builtins (ATOMIC)
|
| 476 |
+
'ATOMIC', 'INTRINSIC', 'AVAIL', 'SWAP', 'CAS', 'INC', 'DEC', 'BWAND',
|
| 477 |
+
'BWNAND', 'BWOR', 'BWXOR',
|
| 478 |
+
# 7 additional builtins (COMPILER)
|
| 479 |
+
'COMPILER', 'DEBUG', 'MODNAME', 'PROCNAME', 'LINENUM', 'DEFAULT',
|
| 480 |
+
'HASH',
|
| 481 |
+
# 5 additional builtins (ASSEMBLER)
|
| 482 |
+
'ASSEMBLER', 'REGISTER', 'SETREG', 'GETREG', 'CODE',
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
# O b j e c t i v e M o d u l a - 2 D a t a s e t s
|
| 486 |
+
|
| 487 |
+
# Lexemes to Mark as Error Tokens for Objective Modula-2
|
| 488 |
+
objm2_lexemes_to_reject = (
|
| 489 |
+
'!', '$', '%', '&', '<>',
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
# Objective Modula-2 Extensions
|
| 493 |
+
# reserved words in addition to Modula-2 R10
|
| 494 |
+
objm2_additional_reserved_words = (
|
| 495 |
+
# 16 additional reserved words
|
| 496 |
+
'BYCOPY', 'BYREF', 'CLASS', 'CONTINUE', 'CRITICAL', 'INOUT', 'METHOD',
|
| 497 |
+
'ON', 'OPTIONAL', 'OUT', 'PRIVATE', 'PROTECTED', 'PROTOCOL', 'PUBLIC',
|
| 498 |
+
'SUPER', 'TRY',
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
# Objective Modula-2 Extensions
|
| 502 |
+
# builtins in addition to Modula-2 R10
|
| 503 |
+
objm2_additional_builtins = (
|
| 504 |
+
# 3 additional builtins
|
| 505 |
+
'OBJECT', 'NO', 'YES',
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
# Objective Modula-2 Extensions
|
| 509 |
+
# pseudo-module builtins in addition to Modula-2 R10
|
| 510 |
+
objm2_additional_pseudo_builtins = (
|
| 511 |
+
# None
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
# A g l e t M o d u l a - 2 D a t a s e t s
|
| 515 |
+
|
| 516 |
+
# Aglet Extensions
|
| 517 |
+
# reserved words in addition to ISO Modula-2
|
| 518 |
+
aglet_additional_reserved_words = (
|
| 519 |
+
# None
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# Aglet Extensions
|
| 523 |
+
# builtins in addition to ISO Modula-2
|
| 524 |
+
aglet_additional_builtins = (
|
| 525 |
+
# 9 additional builtins
|
| 526 |
+
'BITSET8', 'BITSET16', 'BITSET32', 'CARDINAL8', 'CARDINAL16',
|
| 527 |
+
'CARDINAL32', 'INTEGER8', 'INTEGER16', 'INTEGER32',
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# Aglet Modula-2 Extensions
|
| 531 |
+
# pseudo-module builtins in addition to ISO Modula-2
|
| 532 |
+
aglet_additional_pseudo_builtins = (
|
| 533 |
+
# None
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
# G N U M o d u l a - 2 D a t a s e t s
|
| 537 |
+
|
| 538 |
+
# GNU Extensions
|
| 539 |
+
# reserved words in addition to PIM Modula-2
|
| 540 |
+
gm2_additional_reserved_words = (
|
| 541 |
+
# 10 additional reserved words
|
| 542 |
+
'ASM', '__ATTRIBUTE__', '__BUILTIN__', '__COLUMN__', '__DATE__',
|
| 543 |
+
'__FILE__', '__FUNCTION__', '__LINE__', '__MODULE__', 'VOLATILE',
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
# GNU Extensions
|
| 547 |
+
# builtins in addition to PIM Modula-2
|
| 548 |
+
gm2_additional_builtins = (
|
| 549 |
+
# 21 additional builtins
|
| 550 |
+
'BITSET8', 'BITSET16', 'BITSET32', 'CARDINAL8', 'CARDINAL16',
|
| 551 |
+
'CARDINAL32', 'CARDINAL64', 'COMPLEX32', 'COMPLEX64', 'COMPLEX96',
|
| 552 |
+
'COMPLEX128', 'INTEGER8', 'INTEGER16', 'INTEGER32', 'INTEGER64',
|
| 553 |
+
'REAL8', 'REAL16', 'REAL32', 'REAL96', 'REAL128', 'THROW',
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
# GNU Extensions
|
| 557 |
+
# pseudo-module builtins in addition to PIM Modula-2
|
| 558 |
+
gm2_additional_pseudo_builtins = (
|
| 559 |
+
# None
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
# p 1 M o d u l a - 2 D a t a s e t s
|
| 563 |
+
|
| 564 |
+
# p1 Extensions
|
| 565 |
+
# reserved words in addition to ISO Modula-2
|
| 566 |
+
p1_additional_reserved_words = (
|
| 567 |
+
# None
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
# p1 Extensions
|
| 571 |
+
# builtins in addition to ISO Modula-2
|
| 572 |
+
p1_additional_builtins = (
|
| 573 |
+
# None
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
# p1 Modula-2 Extensions
|
| 577 |
+
# pseudo-module builtins in addition to ISO Modula-2
|
| 578 |
+
p1_additional_pseudo_builtins = (
|
| 579 |
+
# 1 additional builtin
|
| 580 |
+
'BCD',
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
# X D S M o d u l a - 2 D a t a s e t s
|
| 584 |
+
|
| 585 |
+
# XDS Extensions
|
| 586 |
+
# reserved words in addition to ISO Modula-2
|
| 587 |
+
xds_additional_reserved_words = (
|
| 588 |
+
# 1 additional reserved word
|
| 589 |
+
'SEQ',
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
# XDS Extensions
|
| 593 |
+
# builtins in addition to ISO Modula-2
|
| 594 |
+
xds_additional_builtins = (
|
| 595 |
+
# 9 additional builtins
|
| 596 |
+
'ASH', 'ASSERT', 'DIFFADR_TYPE', 'ENTIER', 'INDEX', 'LEN',
|
| 597 |
+
'LONGCARD', 'SHORTCARD', 'SHORTINT',
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
# XDS Modula-2 Extensions
|
| 601 |
+
# pseudo-module builtins in addition to ISO Modula-2
|
| 602 |
+
xds_additional_pseudo_builtins = (
|
| 603 |
+
# 22 additional builtins (SYSTEM)
|
| 604 |
+
'PROCESS', 'NEWPROCESS', 'BOOL8', 'BOOL16', 'BOOL32', 'CARD8',
|
| 605 |
+
'CARD16', 'CARD32', 'INT8', 'INT16', 'INT32', 'REF', 'MOVE',
|
| 606 |
+
'FILL', 'GET', 'PUT', 'CC', 'int', 'unsigned', 'size_t', 'void'
|
| 607 |
+
# 3 additional builtins (COMPILER)
|
| 608 |
+
'COMPILER', 'OPTION', 'EQUATION'
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# P I M S t a n d a r d L i b r a r y D a t a s e t s
|
| 612 |
+
|
| 613 |
+
# PIM Modula-2 Standard Library Modules Dataset
|
| 614 |
+
pim_stdlib_module_identifiers = (
|
| 615 |
+
'Terminal', 'FileSystem', 'InOut', 'RealInOut', 'MathLib0', 'Storage',
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
# PIM Modula-2 Standard Library Types Dataset
|
| 619 |
+
pim_stdlib_type_identifiers = (
|
| 620 |
+
'Flag', 'FlagSet', 'Response', 'Command', 'Lock', 'Permission',
|
| 621 |
+
'MediumType', 'File', 'FileProc', 'DirectoryProc', 'FileCommand',
|
| 622 |
+
'DirectoryCommand',
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
# PIM Modula-2 Standard Library Procedures Dataset
|
| 626 |
+
pim_stdlib_proc_identifiers = (
|
| 627 |
+
'Read', 'BusyRead', 'ReadAgain', 'Write', 'WriteString', 'WriteLn',
|
| 628 |
+
'Create', 'Lookup', 'Close', 'Delete', 'Rename', 'SetRead', 'SetWrite',
|
| 629 |
+
'SetModify', 'SetOpen', 'Doio', 'SetPos', 'GetPos', 'Length', 'Reset',
|
| 630 |
+
'Again', 'ReadWord', 'WriteWord', 'ReadChar', 'WriteChar',
|
| 631 |
+
'CreateMedium', 'DeleteMedium', 'AssignName', 'DeassignName',
|
| 632 |
+
'ReadMedium', 'LookupMedium', 'OpenInput', 'OpenOutput', 'CloseInput',
|
| 633 |
+
'CloseOutput', 'ReadString', 'ReadInt', 'ReadCard', 'ReadWrd',
|
| 634 |
+
'WriteInt', 'WriteCard', 'WriteOct', 'WriteHex', 'WriteWrd',
|
| 635 |
+
'ReadReal', 'WriteReal', 'WriteFixPt', 'WriteRealOct', 'sqrt', 'exp',
|
| 636 |
+
'ln', 'sin', 'cos', 'arctan', 'entier', 'ALLOCATE', 'DEALLOCATE',
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
# PIM Modula-2 Standard Library Variables Dataset
|
| 640 |
+
pim_stdlib_var_identifiers = (
|
| 641 |
+
'Done', 'termCH', 'in', 'out'
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
# PIM Modula-2 Standard Library Constants Dataset
|
| 645 |
+
pim_stdlib_const_identifiers = (
|
| 646 |
+
'EOL',
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
# I S O S t a n d a r d L i b r a r y D a t a s e t s
|
| 650 |
+
|
| 651 |
+
# ISO Modula-2 Standard Library Modules Dataset
|
| 652 |
+
iso_stdlib_module_identifiers = (
|
| 653 |
+
# TO DO
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# ISO Modula-2 Standard Library Types Dataset
|
| 657 |
+
iso_stdlib_type_identifiers = (
|
| 658 |
+
# TO DO
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# ISO Modula-2 Standard Library Procedures Dataset
|
| 662 |
+
iso_stdlib_proc_identifiers = (
|
| 663 |
+
# TO DO
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
# ISO Modula-2 Standard Library Variables Dataset
|
| 667 |
+
iso_stdlib_var_identifiers = (
|
| 668 |
+
# TO DO
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
# ISO Modula-2 Standard Library Constants Dataset
|
| 672 |
+
iso_stdlib_const_identifiers = (
|
| 673 |
+
# TO DO
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
# M 2 R 1 0 S t a n d a r d L i b r a r y D a t a s e t s
|
| 677 |
+
|
| 678 |
+
# Modula-2 R10 Standard Library ADTs Dataset
|
| 679 |
+
m2r10_stdlib_adt_identifiers = (
|
| 680 |
+
'BCD', 'LONGBCD', 'BITSET', 'SHORTBITSET', 'LONGBITSET',
|
| 681 |
+
'LONGLONGBITSET', 'COMPLEX', 'LONGCOMPLEX', 'SHORTCARD', 'LONGLONGCARD',
|
| 682 |
+
'SHORTINT', 'LONGLONGINT', 'POSINT', 'SHORTPOSINT', 'LONGPOSINT',
|
| 683 |
+
'LONGLONGPOSINT', 'BITSET8', 'BITSET16', 'BITSET32', 'BITSET64',
|
| 684 |
+
'BITSET128', 'BS8', 'BS16', 'BS32', 'BS64', 'BS128', 'CARDINAL8',
|
| 685 |
+
'CARDINAL16', 'CARDINAL32', 'CARDINAL64', 'CARDINAL128', 'CARD8',
|
| 686 |
+
'CARD16', 'CARD32', 'CARD64', 'CARD128', 'INTEGER8', 'INTEGER16',
|
| 687 |
+
'INTEGER32', 'INTEGER64', 'INTEGER128', 'INT8', 'INT16', 'INT32',
|
| 688 |
+
'INT64', 'INT128', 'STRING', 'UNISTRING',
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
# Modula-2 R10 Standard Library Blueprints Dataset
|
| 692 |
+
m2r10_stdlib_blueprint_identifiers = (
|
| 693 |
+
'ProtoRoot', 'ProtoComputational', 'ProtoNumeric', 'ProtoScalar',
|
| 694 |
+
'ProtoNonScalar', 'ProtoCardinal', 'ProtoInteger', 'ProtoReal',
|
| 695 |
+
'ProtoComplex', 'ProtoVector', 'ProtoTuple', 'ProtoCompArray',
|
| 696 |
+
'ProtoCollection', 'ProtoStaticArray', 'ProtoStaticSet',
|
| 697 |
+
'ProtoStaticString', 'ProtoArray', 'ProtoString', 'ProtoSet',
|
| 698 |
+
'ProtoMultiSet', 'ProtoDictionary', 'ProtoMultiDict', 'ProtoExtension',
|
| 699 |
+
'ProtoIO', 'ProtoCardMath', 'ProtoIntMath', 'ProtoRealMath',
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
# Modula-2 R10 Standard Library Modules Dataset
|
| 703 |
+
m2r10_stdlib_module_identifiers = (
|
| 704 |
+
'ASCII', 'BooleanIO', 'CharIO', 'UnicharIO', 'OctetIO',
|
| 705 |
+
'CardinalIO', 'LongCardIO', 'IntegerIO', 'LongIntIO', 'RealIO',
|
| 706 |
+
'LongRealIO', 'BCDIO', 'LongBCDIO', 'CardMath', 'LongCardMath',
|
| 707 |
+
'IntMath', 'LongIntMath', 'RealMath', 'LongRealMath', 'BCDMath',
|
| 708 |
+
'LongBCDMath', 'FileIO', 'FileSystem', 'Storage', 'IOSupport',
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Modula-2 R10 Standard Library Types Dataset
|
| 712 |
+
m2r10_stdlib_type_identifiers = (
|
| 713 |
+
'File', 'Status',
|
| 714 |
+
# TO BE COMPLETED
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
# Modula-2 R10 Standard Library Procedures Dataset
|
| 718 |
+
m2r10_stdlib_proc_identifiers = (
|
| 719 |
+
'ALLOCATE', 'DEALLOCATE', 'SIZE',
|
| 720 |
+
# TO BE COMPLETED
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
# Modula-2 R10 Standard Library Variables Dataset
|
| 724 |
+
m2r10_stdlib_var_identifiers = (
|
| 725 |
+
'stdIn', 'stdOut', 'stdErr',
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Modula-2 R10 Standard Library Constants Dataset
|
| 729 |
+
m2r10_stdlib_const_identifiers = (
|
| 730 |
+
'pi', 'tau',
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
# D i a l e c t s
|
| 734 |
+
|
| 735 |
+
# Dialect modes
|
| 736 |
+
dialects = (
|
| 737 |
+
'unknown',
|
| 738 |
+
'm2pim', 'm2iso', 'm2r10', 'objm2',
|
| 739 |
+
'm2iso+aglet', 'm2pim+gm2', 'm2iso+p1', 'm2iso+xds',
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
# D a t a b a s e s
|
| 743 |
+
|
| 744 |
+
# Lexemes to Mark as Errors Database
|
| 745 |
+
lexemes_to_reject_db = {
|
| 746 |
+
# Lexemes to reject for unknown dialect
|
| 747 |
+
'unknown': (
|
| 748 |
+
# LEAVE THIS EMPTY
|
| 749 |
+
),
|
| 750 |
+
# Lexemes to reject for PIM Modula-2
|
| 751 |
+
'm2pim': (
|
| 752 |
+
pim_lexemes_to_reject,
|
| 753 |
+
),
|
| 754 |
+
# Lexemes to reject for ISO Modula-2
|
| 755 |
+
'm2iso': (
|
| 756 |
+
iso_lexemes_to_reject,
|
| 757 |
+
),
|
| 758 |
+
# Lexemes to reject for Modula-2 R10
|
| 759 |
+
'm2r10': (
|
| 760 |
+
m2r10_lexemes_to_reject,
|
| 761 |
+
),
|
| 762 |
+
# Lexemes to reject for Objective Modula-2
|
| 763 |
+
'objm2': (
|
| 764 |
+
objm2_lexemes_to_reject,
|
| 765 |
+
),
|
| 766 |
+
# Lexemes to reject for Aglet Modula-2
|
| 767 |
+
'm2iso+aglet': (
|
| 768 |
+
iso_lexemes_to_reject,
|
| 769 |
+
),
|
| 770 |
+
# Lexemes to reject for GNU Modula-2
|
| 771 |
+
'm2pim+gm2': (
|
| 772 |
+
pim_lexemes_to_reject,
|
| 773 |
+
),
|
| 774 |
+
# Lexemes to reject for p1 Modula-2
|
| 775 |
+
'm2iso+p1': (
|
| 776 |
+
iso_lexemes_to_reject,
|
| 777 |
+
),
|
| 778 |
+
# Lexemes to reject for XDS Modula-2
|
| 779 |
+
'm2iso+xds': (
|
| 780 |
+
iso_lexemes_to_reject,
|
| 781 |
+
),
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
# Reserved Words Database
|
| 785 |
+
reserved_words_db = {
|
| 786 |
+
# Reserved words for unknown dialect
|
| 787 |
+
'unknown': (
|
| 788 |
+
common_reserved_words,
|
| 789 |
+
pim_additional_reserved_words,
|
| 790 |
+
iso_additional_reserved_words,
|
| 791 |
+
m2r10_additional_reserved_words,
|
| 792 |
+
),
|
| 793 |
+
|
| 794 |
+
# Reserved words for PIM Modula-2
|
| 795 |
+
'm2pim': (
|
| 796 |
+
common_reserved_words,
|
| 797 |
+
pim_additional_reserved_words,
|
| 798 |
+
),
|
| 799 |
+
|
| 800 |
+
# Reserved words for Modula-2 R10
|
| 801 |
+
'm2iso': (
|
| 802 |
+
common_reserved_words,
|
| 803 |
+
iso_additional_reserved_words,
|
| 804 |
+
),
|
| 805 |
+
|
| 806 |
+
# Reserved words for ISO Modula-2
|
| 807 |
+
'm2r10': (
|
| 808 |
+
common_reserved_words,
|
| 809 |
+
m2r10_additional_reserved_words,
|
| 810 |
+
),
|
| 811 |
+
|
| 812 |
+
# Reserved words for Objective Modula-2
|
| 813 |
+
'objm2': (
|
| 814 |
+
common_reserved_words,
|
| 815 |
+
m2r10_additional_reserved_words,
|
| 816 |
+
objm2_additional_reserved_words,
|
| 817 |
+
),
|
| 818 |
+
|
| 819 |
+
# Reserved words for Aglet Modula-2 Extensions
|
| 820 |
+
'm2iso+aglet': (
|
| 821 |
+
common_reserved_words,
|
| 822 |
+
iso_additional_reserved_words,
|
| 823 |
+
aglet_additional_reserved_words,
|
| 824 |
+
),
|
| 825 |
+
|
| 826 |
+
# Reserved words for GNU Modula-2 Extensions
|
| 827 |
+
'm2pim+gm2': (
|
| 828 |
+
common_reserved_words,
|
| 829 |
+
pim_additional_reserved_words,
|
| 830 |
+
gm2_additional_reserved_words,
|
| 831 |
+
),
|
| 832 |
+
|
| 833 |
+
# Reserved words for p1 Modula-2 Extensions
|
| 834 |
+
'm2iso+p1': (
|
| 835 |
+
common_reserved_words,
|
| 836 |
+
iso_additional_reserved_words,
|
| 837 |
+
p1_additional_reserved_words,
|
| 838 |
+
),
|
| 839 |
+
|
| 840 |
+
# Reserved words for XDS Modula-2 Extensions
|
| 841 |
+
'm2iso+xds': (
|
| 842 |
+
common_reserved_words,
|
| 843 |
+
iso_additional_reserved_words,
|
| 844 |
+
xds_additional_reserved_words,
|
| 845 |
+
),
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
# Builtins Database
|
| 849 |
+
builtins_db = {
|
| 850 |
+
# Builtins for unknown dialect
|
| 851 |
+
'unknown': (
|
| 852 |
+
common_builtins,
|
| 853 |
+
pim_additional_builtins,
|
| 854 |
+
iso_additional_builtins,
|
| 855 |
+
m2r10_additional_builtins,
|
| 856 |
+
),
|
| 857 |
+
|
| 858 |
+
# Builtins for PIM Modula-2
|
| 859 |
+
'm2pim': (
|
| 860 |
+
common_builtins,
|
| 861 |
+
pim_additional_builtins,
|
| 862 |
+
),
|
| 863 |
+
|
| 864 |
+
# Builtins for ISO Modula-2
|
| 865 |
+
'm2iso': (
|
| 866 |
+
common_builtins,
|
| 867 |
+
iso_additional_builtins,
|
| 868 |
+
),
|
| 869 |
+
|
| 870 |
+
# Builtins for ISO Modula-2
|
| 871 |
+
'm2r10': (
|
| 872 |
+
common_builtins,
|
| 873 |
+
m2r10_additional_builtins,
|
| 874 |
+
),
|
| 875 |
+
|
| 876 |
+
# Builtins for Objective Modula-2
|
| 877 |
+
'objm2': (
|
| 878 |
+
common_builtins,
|
| 879 |
+
m2r10_additional_builtins,
|
| 880 |
+
objm2_additional_builtins,
|
| 881 |
+
),
|
| 882 |
+
|
| 883 |
+
# Builtins for Aglet Modula-2 Extensions
|
| 884 |
+
'm2iso+aglet': (
|
| 885 |
+
common_builtins,
|
| 886 |
+
iso_additional_builtins,
|
| 887 |
+
aglet_additional_builtins,
|
| 888 |
+
),
|
| 889 |
+
|
| 890 |
+
# Builtins for GNU Modula-2 Extensions
|
| 891 |
+
'm2pim+gm2': (
|
| 892 |
+
common_builtins,
|
| 893 |
+
pim_additional_builtins,
|
| 894 |
+
gm2_additional_builtins,
|
| 895 |
+
),
|
| 896 |
+
|
| 897 |
+
# Builtins for p1 Modula-2 Extensions
|
| 898 |
+
'm2iso+p1': (
|
| 899 |
+
common_builtins,
|
| 900 |
+
iso_additional_builtins,
|
| 901 |
+
p1_additional_builtins,
|
| 902 |
+
),
|
| 903 |
+
|
| 904 |
+
# Builtins for XDS Modula-2 Extensions
|
| 905 |
+
'm2iso+xds': (
|
| 906 |
+
common_builtins,
|
| 907 |
+
iso_additional_builtins,
|
| 908 |
+
xds_additional_builtins,
|
| 909 |
+
),
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
# Pseudo-Module Builtins Database
|
| 913 |
+
pseudo_builtins_db = {
|
| 914 |
+
# Builtins for unknown dialect
|
| 915 |
+
'unknown': (
|
| 916 |
+
common_pseudo_builtins,
|
| 917 |
+
pim_additional_pseudo_builtins,
|
| 918 |
+
iso_additional_pseudo_builtins,
|
| 919 |
+
m2r10_additional_pseudo_builtins,
|
| 920 |
+
),
|
| 921 |
+
|
| 922 |
+
# Builtins for PIM Modula-2
|
| 923 |
+
'm2pim': (
|
| 924 |
+
common_pseudo_builtins,
|
| 925 |
+
pim_additional_pseudo_builtins,
|
| 926 |
+
),
|
| 927 |
+
|
| 928 |
+
# Builtins for ISO Modula-2
|
| 929 |
+
'm2iso': (
|
| 930 |
+
common_pseudo_builtins,
|
| 931 |
+
iso_additional_pseudo_builtins,
|
| 932 |
+
),
|
| 933 |
+
|
| 934 |
+
# Builtins for ISO Modula-2
|
| 935 |
+
'm2r10': (
|
| 936 |
+
common_pseudo_builtins,
|
| 937 |
+
m2r10_additional_pseudo_builtins,
|
| 938 |
+
),
|
| 939 |
+
|
| 940 |
+
# Builtins for Objective Modula-2
|
| 941 |
+
'objm2': (
|
| 942 |
+
common_pseudo_builtins,
|
| 943 |
+
m2r10_additional_pseudo_builtins,
|
| 944 |
+
objm2_additional_pseudo_builtins,
|
| 945 |
+
),
|
| 946 |
+
|
| 947 |
+
# Builtins for Aglet Modula-2 Extensions
|
| 948 |
+
'm2iso+aglet': (
|
| 949 |
+
common_pseudo_builtins,
|
| 950 |
+
iso_additional_pseudo_builtins,
|
| 951 |
+
aglet_additional_pseudo_builtins,
|
| 952 |
+
),
|
| 953 |
+
|
| 954 |
+
# Builtins for GNU Modula-2 Extensions
|
| 955 |
+
'm2pim+gm2': (
|
| 956 |
+
common_pseudo_builtins,
|
| 957 |
+
pim_additional_pseudo_builtins,
|
| 958 |
+
gm2_additional_pseudo_builtins,
|
| 959 |
+
),
|
| 960 |
+
|
| 961 |
+
# Builtins for p1 Modula-2 Extensions
|
| 962 |
+
'm2iso+p1': (
|
| 963 |
+
common_pseudo_builtins,
|
| 964 |
+
iso_additional_pseudo_builtins,
|
| 965 |
+
p1_additional_pseudo_builtins,
|
| 966 |
+
),
|
| 967 |
+
|
| 968 |
+
# Builtins for XDS Modula-2 Extensions
|
| 969 |
+
'm2iso+xds': (
|
| 970 |
+
common_pseudo_builtins,
|
| 971 |
+
iso_additional_pseudo_builtins,
|
| 972 |
+
xds_additional_pseudo_builtins,
|
| 973 |
+
),
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
# Standard Library ADTs Database
|
| 977 |
+
stdlib_adts_db = {
|
| 978 |
+
# Empty entry for unknown dialect
|
| 979 |
+
'unknown': (
|
| 980 |
+
# LEAVE THIS EMPTY
|
| 981 |
+
),
|
| 982 |
+
# Standard Library ADTs for PIM Modula-2
|
| 983 |
+
'm2pim': (
|
| 984 |
+
# No first class library types
|
| 985 |
+
),
|
| 986 |
+
|
| 987 |
+
# Standard Library ADTs for ISO Modula-2
|
| 988 |
+
'm2iso': (
|
| 989 |
+
# No first class library types
|
| 990 |
+
),
|
| 991 |
+
|
| 992 |
+
# Standard Library ADTs for Modula-2 R10
|
| 993 |
+
'm2r10': (
|
| 994 |
+
m2r10_stdlib_adt_identifiers,
|
| 995 |
+
),
|
| 996 |
+
|
| 997 |
+
# Standard Library ADTs for Objective Modula-2
|
| 998 |
+
'objm2': (
|
| 999 |
+
m2r10_stdlib_adt_identifiers,
|
| 1000 |
+
),
|
| 1001 |
+
|
| 1002 |
+
# Standard Library ADTs for Aglet Modula-2
|
| 1003 |
+
'm2iso+aglet': (
|
| 1004 |
+
# No first class library types
|
| 1005 |
+
),
|
| 1006 |
+
|
| 1007 |
+
# Standard Library ADTs for GNU Modula-2
|
| 1008 |
+
'm2pim+gm2': (
|
| 1009 |
+
# No first class library types
|
| 1010 |
+
),
|
| 1011 |
+
|
| 1012 |
+
# Standard Library ADTs for p1 Modula-2
|
| 1013 |
+
'm2iso+p1': (
|
| 1014 |
+
# No first class library types
|
| 1015 |
+
),
|
| 1016 |
+
|
| 1017 |
+
# Standard Library ADTs for XDS Modula-2
|
| 1018 |
+
'm2iso+xds': (
|
| 1019 |
+
# No first class library types
|
| 1020 |
+
),
|
| 1021 |
+
}
|
| 1022 |
+
|
| 1023 |
+
# Standard Library Modules Database
|
| 1024 |
+
stdlib_modules_db = {
|
| 1025 |
+
# Empty entry for unknown dialect
|
| 1026 |
+
'unknown': (
|
| 1027 |
+
# LEAVE THIS EMPTY
|
| 1028 |
+
),
|
| 1029 |
+
# Standard Library Modules for PIM Modula-2
|
| 1030 |
+
'm2pim': (
|
| 1031 |
+
pim_stdlib_module_identifiers,
|
| 1032 |
+
),
|
| 1033 |
+
|
| 1034 |
+
# Standard Library Modules for ISO Modula-2
|
| 1035 |
+
'm2iso': (
|
| 1036 |
+
iso_stdlib_module_identifiers,
|
| 1037 |
+
),
|
| 1038 |
+
|
| 1039 |
+
# Standard Library Modules for Modula-2 R10
|
| 1040 |
+
'm2r10': (
|
| 1041 |
+
m2r10_stdlib_blueprint_identifiers,
|
| 1042 |
+
m2r10_stdlib_module_identifiers,
|
| 1043 |
+
m2r10_stdlib_adt_identifiers,
|
| 1044 |
+
),
|
| 1045 |
+
|
| 1046 |
+
# Standard Library Modules for Objective Modula-2
|
| 1047 |
+
'objm2': (
|
| 1048 |
+
m2r10_stdlib_blueprint_identifiers,
|
| 1049 |
+
m2r10_stdlib_module_identifiers,
|
| 1050 |
+
),
|
| 1051 |
+
|
| 1052 |
+
# Standard Library Modules for Aglet Modula-2
|
| 1053 |
+
'm2iso+aglet': (
|
| 1054 |
+
iso_stdlib_module_identifiers,
|
| 1055 |
+
),
|
| 1056 |
+
|
| 1057 |
+
# Standard Library Modules for GNU Modula-2
|
| 1058 |
+
'm2pim+gm2': (
|
| 1059 |
+
pim_stdlib_module_identifiers,
|
| 1060 |
+
),
|
| 1061 |
+
|
| 1062 |
+
# Standard Library Modules for p1 Modula-2
|
| 1063 |
+
'm2iso+p1': (
|
| 1064 |
+
iso_stdlib_module_identifiers,
|
| 1065 |
+
),
|
| 1066 |
+
|
| 1067 |
+
# Standard Library Modules for XDS Modula-2
|
| 1068 |
+
'm2iso+xds': (
|
| 1069 |
+
iso_stdlib_module_identifiers,
|
| 1070 |
+
),
|
| 1071 |
+
}
|
| 1072 |
+
|
| 1073 |
+
# Standard Library Types Database
|
| 1074 |
+
stdlib_types_db = {
|
| 1075 |
+
# Empty entry for unknown dialect
|
| 1076 |
+
'unknown': (
|
| 1077 |
+
# LEAVE THIS EMPTY
|
| 1078 |
+
),
|
| 1079 |
+
# Standard Library Types for PIM Modula-2
|
| 1080 |
+
'm2pim': (
|
| 1081 |
+
pim_stdlib_type_identifiers,
|
| 1082 |
+
),
|
| 1083 |
+
|
| 1084 |
+
# Standard Library Types for ISO Modula-2
|
| 1085 |
+
'm2iso': (
|
| 1086 |
+
iso_stdlib_type_identifiers,
|
| 1087 |
+
),
|
| 1088 |
+
|
| 1089 |
+
# Standard Library Types for Modula-2 R10
|
| 1090 |
+
'm2r10': (
|
| 1091 |
+
m2r10_stdlib_type_identifiers,
|
| 1092 |
+
),
|
| 1093 |
+
|
| 1094 |
+
# Standard Library Types for Objective Modula-2
|
| 1095 |
+
'objm2': (
|
| 1096 |
+
m2r10_stdlib_type_identifiers,
|
| 1097 |
+
),
|
| 1098 |
+
|
| 1099 |
+
# Standard Library Types for Aglet Modula-2
|
| 1100 |
+
'm2iso+aglet': (
|
| 1101 |
+
iso_stdlib_type_identifiers,
|
| 1102 |
+
),
|
| 1103 |
+
|
| 1104 |
+
# Standard Library Types for GNU Modula-2
|
| 1105 |
+
'm2pim+gm2': (
|
| 1106 |
+
pim_stdlib_type_identifiers,
|
| 1107 |
+
),
|
| 1108 |
+
|
| 1109 |
+
# Standard Library Types for p1 Modula-2
|
| 1110 |
+
'm2iso+p1': (
|
| 1111 |
+
iso_stdlib_type_identifiers,
|
| 1112 |
+
),
|
| 1113 |
+
|
| 1114 |
+
# Standard Library Types for XDS Modula-2
|
| 1115 |
+
'm2iso+xds': (
|
| 1116 |
+
iso_stdlib_type_identifiers,
|
| 1117 |
+
),
|
| 1118 |
+
}
|
| 1119 |
+
|
| 1120 |
+
# Standard Library Procedures Database
|
| 1121 |
+
stdlib_procedures_db = {
|
| 1122 |
+
# Empty entry for unknown dialect
|
| 1123 |
+
'unknown': (
|
| 1124 |
+
# LEAVE THIS EMPTY
|
| 1125 |
+
),
|
| 1126 |
+
# Standard Library Procedures for PIM Modula-2
|
| 1127 |
+
'm2pim': (
|
| 1128 |
+
pim_stdlib_proc_identifiers,
|
| 1129 |
+
),
|
| 1130 |
+
|
| 1131 |
+
# Standard Library Procedures for ISO Modula-2
|
| 1132 |
+
'm2iso': (
|
| 1133 |
+
iso_stdlib_proc_identifiers,
|
| 1134 |
+
),
|
| 1135 |
+
|
| 1136 |
+
# Standard Library Procedures for Modula-2 R10
|
| 1137 |
+
'm2r10': (
|
| 1138 |
+
m2r10_stdlib_proc_identifiers,
|
| 1139 |
+
),
|
| 1140 |
+
|
| 1141 |
+
# Standard Library Procedures for Objective Modula-2
|
| 1142 |
+
'objm2': (
|
| 1143 |
+
m2r10_stdlib_proc_identifiers,
|
| 1144 |
+
),
|
| 1145 |
+
|
| 1146 |
+
# Standard Library Procedures for Aglet Modula-2
|
| 1147 |
+
'm2iso+aglet': (
|
| 1148 |
+
iso_stdlib_proc_identifiers,
|
| 1149 |
+
),
|
| 1150 |
+
|
| 1151 |
+
# Standard Library Procedures for GNU Modula-2
|
| 1152 |
+
'm2pim+gm2': (
|
| 1153 |
+
pim_stdlib_proc_identifiers,
|
| 1154 |
+
),
|
| 1155 |
+
|
| 1156 |
+
# Standard Library Procedures for p1 Modula-2
|
| 1157 |
+
'm2iso+p1': (
|
| 1158 |
+
iso_stdlib_proc_identifiers,
|
| 1159 |
+
),
|
| 1160 |
+
|
| 1161 |
+
# Standard Library Procedures for XDS Modula-2
|
| 1162 |
+
'm2iso+xds': (
|
| 1163 |
+
iso_stdlib_proc_identifiers,
|
| 1164 |
+
),
|
| 1165 |
+
}
|
| 1166 |
+
|
| 1167 |
+
# Standard Library Variables Database
|
| 1168 |
+
stdlib_variables_db = {
|
| 1169 |
+
# Empty entry for unknown dialect
|
| 1170 |
+
'unknown': (
|
| 1171 |
+
# LEAVE THIS EMPTY
|
| 1172 |
+
),
|
| 1173 |
+
# Standard Library Variables for PIM Modula-2
|
| 1174 |
+
'm2pim': (
|
| 1175 |
+
pim_stdlib_var_identifiers,
|
| 1176 |
+
),
|
| 1177 |
+
|
| 1178 |
+
# Standard Library Variables for ISO Modula-2
|
| 1179 |
+
'm2iso': (
|
| 1180 |
+
iso_stdlib_var_identifiers,
|
| 1181 |
+
),
|
| 1182 |
+
|
| 1183 |
+
# Standard Library Variables for Modula-2 R10
|
| 1184 |
+
'm2r10': (
|
| 1185 |
+
m2r10_stdlib_var_identifiers,
|
| 1186 |
+
),
|
| 1187 |
+
|
| 1188 |
+
# Standard Library Variables for Objective Modula-2
|
| 1189 |
+
'objm2': (
|
| 1190 |
+
m2r10_stdlib_var_identifiers,
|
| 1191 |
+
),
|
| 1192 |
+
|
| 1193 |
+
# Standard Library Variables for Aglet Modula-2
|
| 1194 |
+
'm2iso+aglet': (
|
| 1195 |
+
iso_stdlib_var_identifiers,
|
| 1196 |
+
),
|
| 1197 |
+
|
| 1198 |
+
# Standard Library Variables for GNU Modula-2
|
| 1199 |
+
'm2pim+gm2': (
|
| 1200 |
+
pim_stdlib_var_identifiers,
|
| 1201 |
+
),
|
| 1202 |
+
|
| 1203 |
+
# Standard Library Variables for p1 Modula-2
|
| 1204 |
+
'm2iso+p1': (
|
| 1205 |
+
iso_stdlib_var_identifiers,
|
| 1206 |
+
),
|
| 1207 |
+
|
| 1208 |
+
# Standard Library Variables for XDS Modula-2
|
| 1209 |
+
'm2iso+xds': (
|
| 1210 |
+
iso_stdlib_var_identifiers,
|
| 1211 |
+
),
|
| 1212 |
+
}
|
| 1213 |
+
|
| 1214 |
+
# Standard Library Constants Database
|
| 1215 |
+
stdlib_constants_db = {
|
| 1216 |
+
# Empty entry for unknown dialect
|
| 1217 |
+
'unknown': (
|
| 1218 |
+
# LEAVE THIS EMPTY
|
| 1219 |
+
),
|
| 1220 |
+
# Standard Library Constants for PIM Modula-2
|
| 1221 |
+
'm2pim': (
|
| 1222 |
+
pim_stdlib_const_identifiers,
|
| 1223 |
+
),
|
| 1224 |
+
|
| 1225 |
+
# Standard Library Constants for ISO Modula-2
|
| 1226 |
+
'm2iso': (
|
| 1227 |
+
iso_stdlib_const_identifiers,
|
| 1228 |
+
),
|
| 1229 |
+
|
| 1230 |
+
# Standard Library Constants for Modula-2 R10
|
| 1231 |
+
'm2r10': (
|
| 1232 |
+
m2r10_stdlib_const_identifiers,
|
| 1233 |
+
),
|
| 1234 |
+
|
| 1235 |
+
# Standard Library Constants for Objective Modula-2
|
| 1236 |
+
'objm2': (
|
| 1237 |
+
m2r10_stdlib_const_identifiers,
|
| 1238 |
+
),
|
| 1239 |
+
|
| 1240 |
+
# Standard Library Constants for Aglet Modula-2
|
| 1241 |
+
'm2iso+aglet': (
|
| 1242 |
+
iso_stdlib_const_identifiers,
|
| 1243 |
+
),
|
| 1244 |
+
|
| 1245 |
+
# Standard Library Constants for GNU Modula-2
|
| 1246 |
+
'm2pim+gm2': (
|
| 1247 |
+
pim_stdlib_const_identifiers,
|
| 1248 |
+
),
|
| 1249 |
+
|
| 1250 |
+
# Standard Library Constants for p1 Modula-2
|
| 1251 |
+
'm2iso+p1': (
|
| 1252 |
+
iso_stdlib_const_identifiers,
|
| 1253 |
+
),
|
| 1254 |
+
|
| 1255 |
+
# Standard Library Constants for XDS Modula-2
|
| 1256 |
+
'm2iso+xds': (
|
| 1257 |
+
iso_stdlib_const_identifiers,
|
| 1258 |
+
),
|
| 1259 |
+
}
|
| 1260 |
+
|
| 1261 |
+
# M e t h o d s
|
| 1262 |
+
|
| 1263 |
+
# initialise a lexer instance
|
| 1264 |
+
def __init__(self, **options):
|
| 1265 |
+
#
|
| 1266 |
+
# check dialect options
|
| 1267 |
+
#
|
| 1268 |
+
dialects = get_list_opt(options, 'dialect', [])
|
| 1269 |
+
#
|
| 1270 |
+
for dialect_option in dialects:
|
| 1271 |
+
if dialect_option in self.dialects[1:-1]:
|
| 1272 |
+
# valid dialect option found
|
| 1273 |
+
self.set_dialect(dialect_option)
|
| 1274 |
+
break
|
| 1275 |
+
#
|
| 1276 |
+
# Fallback Mode (DEFAULT)
|
| 1277 |
+
else:
|
| 1278 |
+
# no valid dialect option
|
| 1279 |
+
self.set_dialect('unknown')
|
| 1280 |
+
#
|
| 1281 |
+
self.dialect_set_by_tag = False
|
| 1282 |
+
#
|
| 1283 |
+
# check style options
|
| 1284 |
+
#
|
| 1285 |
+
styles = get_list_opt(options, 'style', [])
|
| 1286 |
+
#
|
| 1287 |
+
# use lowercase mode for Algol style
|
| 1288 |
+
if 'algol' in styles or 'algol_nu' in styles:
|
| 1289 |
+
self.algol_publication_mode = True
|
| 1290 |
+
else:
|
| 1291 |
+
self.algol_publication_mode = False
|
| 1292 |
+
#
|
| 1293 |
+
# Check option flags
|
| 1294 |
+
#
|
| 1295 |
+
self.treat_stdlib_adts_as_builtins = get_bool_opt(
|
| 1296 |
+
options, 'treat_stdlib_adts_as_builtins', True)
|
| 1297 |
+
#
|
| 1298 |
+
# call superclass initialiser
|
| 1299 |
+
RegexLexer.__init__(self, **options)
|
| 1300 |
+
|
| 1301 |
+
# Set lexer to a specified dialect
|
| 1302 |
+
def set_dialect(self, dialect_id):
|
| 1303 |
+
#
|
| 1304 |
+
# if __debug__:
|
| 1305 |
+
# print 'entered set_dialect with arg: ', dialect_id
|
| 1306 |
+
#
|
| 1307 |
+
# check dialect name against known dialects
|
| 1308 |
+
if dialect_id not in self.dialects:
|
| 1309 |
+
dialect = 'unknown' # default
|
| 1310 |
+
else:
|
| 1311 |
+
dialect = dialect_id
|
| 1312 |
+
#
|
| 1313 |
+
# compose lexemes to reject set
|
| 1314 |
+
lexemes_to_reject_set = set()
|
| 1315 |
+
# add each list of reject lexemes for this dialect
|
| 1316 |
+
for list in self.lexemes_to_reject_db[dialect]:
|
| 1317 |
+
lexemes_to_reject_set.update(set(list))
|
| 1318 |
+
#
|
| 1319 |
+
# compose reserved words set
|
| 1320 |
+
reswords_set = set()
|
| 1321 |
+
# add each list of reserved words for this dialect
|
| 1322 |
+
for list in self.reserved_words_db[dialect]:
|
| 1323 |
+
reswords_set.update(set(list))
|
| 1324 |
+
#
|
| 1325 |
+
# compose builtins set
|
| 1326 |
+
builtins_set = set()
|
| 1327 |
+
# add each list of builtins for this dialect excluding reserved words
|
| 1328 |
+
for list in self.builtins_db[dialect]:
|
| 1329 |
+
builtins_set.update(set(list).difference(reswords_set))
|
| 1330 |
+
#
|
| 1331 |
+
# compose pseudo-builtins set
|
| 1332 |
+
pseudo_builtins_set = set()
|
| 1333 |
+
# add each list of builtins for this dialect excluding reserved words
|
| 1334 |
+
for list in self.pseudo_builtins_db[dialect]:
|
| 1335 |
+
pseudo_builtins_set.update(set(list).difference(reswords_set))
|
| 1336 |
+
#
|
| 1337 |
+
# compose ADTs set
|
| 1338 |
+
adts_set = set()
|
| 1339 |
+
# add each list of ADTs for this dialect excluding reserved words
|
| 1340 |
+
for list in self.stdlib_adts_db[dialect]:
|
| 1341 |
+
adts_set.update(set(list).difference(reswords_set))
|
| 1342 |
+
#
|
| 1343 |
+
# compose modules set
|
| 1344 |
+
modules_set = set()
|
| 1345 |
+
# add each list of builtins for this dialect excluding builtins
|
| 1346 |
+
for list in self.stdlib_modules_db[dialect]:
|
| 1347 |
+
modules_set.update(set(list).difference(builtins_set))
|
| 1348 |
+
#
|
| 1349 |
+
# compose types set
|
| 1350 |
+
types_set = set()
|
| 1351 |
+
# add each list of types for this dialect excluding builtins
|
| 1352 |
+
for list in self.stdlib_types_db[dialect]:
|
| 1353 |
+
types_set.update(set(list).difference(builtins_set))
|
| 1354 |
+
#
|
| 1355 |
+
# compose procedures set
|
| 1356 |
+
procedures_set = set()
|
| 1357 |
+
# add each list of procedures for this dialect excluding builtins
|
| 1358 |
+
for list in self.stdlib_procedures_db[dialect]:
|
| 1359 |
+
procedures_set.update(set(list).difference(builtins_set))
|
| 1360 |
+
#
|
| 1361 |
+
# compose variables set
|
| 1362 |
+
variables_set = set()
|
| 1363 |
+
# add each list of variables for this dialect excluding builtins
|
| 1364 |
+
for list in self.stdlib_variables_db[dialect]:
|
| 1365 |
+
variables_set.update(set(list).difference(builtins_set))
|
| 1366 |
+
#
|
| 1367 |
+
# compose constants set
|
| 1368 |
+
constants_set = set()
|
| 1369 |
+
# add each list of constants for this dialect excluding builtins
|
| 1370 |
+
for list in self.stdlib_constants_db[dialect]:
|
| 1371 |
+
constants_set.update(set(list).difference(builtins_set))
|
| 1372 |
+
#
|
| 1373 |
+
# update lexer state
|
| 1374 |
+
self.dialect = dialect
|
| 1375 |
+
self.lexemes_to_reject = lexemes_to_reject_set
|
| 1376 |
+
self.reserved_words = reswords_set
|
| 1377 |
+
self.builtins = builtins_set
|
| 1378 |
+
self.pseudo_builtins = pseudo_builtins_set
|
| 1379 |
+
self.adts = adts_set
|
| 1380 |
+
self.modules = modules_set
|
| 1381 |
+
self.types = types_set
|
| 1382 |
+
self.procedures = procedures_set
|
| 1383 |
+
self.variables = variables_set
|
| 1384 |
+
self.constants = constants_set
|
| 1385 |
+
#
|
| 1386 |
+
# if __debug__:
|
| 1387 |
+
# print 'exiting set_dialect'
|
| 1388 |
+
# print ' self.dialect: ', self.dialect
|
| 1389 |
+
# print ' self.lexemes_to_reject: ', self.lexemes_to_reject
|
| 1390 |
+
# print ' self.reserved_words: ', self.reserved_words
|
| 1391 |
+
# print ' self.builtins: ', self.builtins
|
| 1392 |
+
# print ' self.pseudo_builtins: ', self.pseudo_builtins
|
| 1393 |
+
# print ' self.adts: ', self.adts
|
| 1394 |
+
# print ' self.modules: ', self.modules
|
| 1395 |
+
# print ' self.types: ', self.types
|
| 1396 |
+
# print ' self.procedures: ', self.procedures
|
| 1397 |
+
# print ' self.variables: ', self.variables
|
| 1398 |
+
# print ' self.types: ', self.types
|
| 1399 |
+
# print ' self.constants: ', self.constants
|
| 1400 |
+
|
| 1401 |
+
# Extracts a dialect name from a dialect tag comment string and checks
|
| 1402 |
+
# the extracted name against known dialects. If a match is found, the
|
| 1403 |
+
# matching name is returned, otherwise dialect id 'unknown' is returned
|
| 1404 |
+
def get_dialect_from_dialect_tag(self, dialect_tag):
|
| 1405 |
+
#
|
| 1406 |
+
# if __debug__:
|
| 1407 |
+
# print 'entered get_dialect_from_dialect_tag with arg: ', dialect_tag
|
| 1408 |
+
#
|
| 1409 |
+
# constants
|
| 1410 |
+
left_tag_delim = '(*!'
|
| 1411 |
+
right_tag_delim = '*)'
|
| 1412 |
+
left_tag_delim_len = len(left_tag_delim)
|
| 1413 |
+
right_tag_delim_len = len(right_tag_delim)
|
| 1414 |
+
indicator_start = left_tag_delim_len
|
| 1415 |
+
indicator_end = -(right_tag_delim_len)
|
| 1416 |
+
#
|
| 1417 |
+
# check comment string for dialect indicator
|
| 1418 |
+
if len(dialect_tag) > (left_tag_delim_len + right_tag_delim_len) \
|
| 1419 |
+
and dialect_tag.startswith(left_tag_delim) \
|
| 1420 |
+
and dialect_tag.endswith(right_tag_delim):
|
| 1421 |
+
#
|
| 1422 |
+
# if __debug__:
|
| 1423 |
+
# print 'dialect tag found'
|
| 1424 |
+
#
|
| 1425 |
+
# extract dialect indicator
|
| 1426 |
+
indicator = dialect_tag[indicator_start:indicator_end]
|
| 1427 |
+
#
|
| 1428 |
+
# if __debug__:
|
| 1429 |
+
# print 'extracted: ', indicator
|
| 1430 |
+
#
|
| 1431 |
+
# check against known dialects
|
| 1432 |
+
for index in range(1, len(self.dialects)):
|
| 1433 |
+
#
|
| 1434 |
+
# if __debug__:
|
| 1435 |
+
# print 'dialects[', index, ']: ', self.dialects[index]
|
| 1436 |
+
#
|
| 1437 |
+
if indicator == self.dialects[index]:
|
| 1438 |
+
#
|
| 1439 |
+
# if __debug__:
|
| 1440 |
+
# print 'matching dialect found'
|
| 1441 |
+
#
|
| 1442 |
+
# indicator matches known dialect
|
| 1443 |
+
return indicator
|
| 1444 |
+
else:
|
| 1445 |
+
# indicator does not match any dialect
|
| 1446 |
+
return 'unknown' # default
|
| 1447 |
+
else:
|
| 1448 |
+
# invalid indicator string
|
| 1449 |
+
return 'unknown' # default
|
| 1450 |
+
|
| 1451 |
+
# intercept the token stream, modify token attributes and return them
|
| 1452 |
+
def get_tokens_unprocessed(self, text):
|
| 1453 |
+
for index, token, value in RegexLexer.get_tokens_unprocessed(self, text):
|
| 1454 |
+
#
|
| 1455 |
+
# check for dialect tag if dialect has not been set by tag
|
| 1456 |
+
if not self.dialect_set_by_tag and token == Comment.Special:
|
| 1457 |
+
indicated_dialect = self.get_dialect_from_dialect_tag(value)
|
| 1458 |
+
if indicated_dialect != 'unknown':
|
| 1459 |
+
# token is a dialect indicator
|
| 1460 |
+
# reset reserved words and builtins
|
| 1461 |
+
self.set_dialect(indicated_dialect)
|
| 1462 |
+
self.dialect_set_by_tag = True
|
| 1463 |
+
#
|
| 1464 |
+
# check for reserved words, predefined and stdlib identifiers
|
| 1465 |
+
if token is Name:
|
| 1466 |
+
if value in self.reserved_words:
|
| 1467 |
+
token = Keyword.Reserved
|
| 1468 |
+
if self.algol_publication_mode:
|
| 1469 |
+
value = value.lower()
|
| 1470 |
+
#
|
| 1471 |
+
elif value in self.builtins:
|
| 1472 |
+
token = Name.Builtin
|
| 1473 |
+
if self.algol_publication_mode:
|
| 1474 |
+
value = value.lower()
|
| 1475 |
+
#
|
| 1476 |
+
elif value in self.pseudo_builtins:
|
| 1477 |
+
token = Name.Builtin.Pseudo
|
| 1478 |
+
if self.algol_publication_mode:
|
| 1479 |
+
value = value.lower()
|
| 1480 |
+
#
|
| 1481 |
+
elif value in self.adts:
|
| 1482 |
+
if not self.treat_stdlib_adts_as_builtins:
|
| 1483 |
+
token = Name.Namespace
|
| 1484 |
+
else:
|
| 1485 |
+
token = Name.Builtin.Pseudo
|
| 1486 |
+
if self.algol_publication_mode:
|
| 1487 |
+
value = value.lower()
|
| 1488 |
+
#
|
| 1489 |
+
elif value in self.modules:
|
| 1490 |
+
token = Name.Namespace
|
| 1491 |
+
#
|
| 1492 |
+
elif value in self.types:
|
| 1493 |
+
token = Name.Class
|
| 1494 |
+
#
|
| 1495 |
+
elif value in self.procedures:
|
| 1496 |
+
token = Name.Function
|
| 1497 |
+
#
|
| 1498 |
+
elif value in self.variables:
|
| 1499 |
+
token = Name.Variable
|
| 1500 |
+
#
|
| 1501 |
+
elif value in self.constants:
|
| 1502 |
+
token = Name.Constant
|
| 1503 |
+
#
|
| 1504 |
+
elif token in Number:
|
| 1505 |
+
#
|
| 1506 |
+
# mark prefix number literals as error for PIM and ISO dialects
|
| 1507 |
+
if self.dialect not in ('unknown', 'm2r10', 'objm2'):
|
| 1508 |
+
if "'" in value or value[0:2] in ('0b', '0x', '0u'):
|
| 1509 |
+
token = Error
|
| 1510 |
+
#
|
| 1511 |
+
elif self.dialect in ('m2r10', 'objm2'):
|
| 1512 |
+
# mark base-8 number literals as errors for M2 R10 and ObjM2
|
| 1513 |
+
if token is Number.Oct:
|
| 1514 |
+
token = Error
|
| 1515 |
+
# mark suffix base-16 literals as errors for M2 R10 and ObjM2
|
| 1516 |
+
elif token is Number.Hex and 'H' in value:
|
| 1517 |
+
token = Error
|
| 1518 |
+
# mark real numbers with E as errors for M2 R10 and ObjM2
|
| 1519 |
+
elif token is Number.Float and 'E' in value:
|
| 1520 |
+
token = Error
|
| 1521 |
+
#
|
| 1522 |
+
elif token in Comment:
|
| 1523 |
+
#
|
| 1524 |
+
# mark single line comment as error for PIM and ISO dialects
|
| 1525 |
+
if token is Comment.Single:
|
| 1526 |
+
if self.dialect not in ('unknown', 'm2r10', 'objm2'):
|
| 1527 |
+
token = Error
|
| 1528 |
+
#
|
| 1529 |
+
if token is Comment.Preproc:
|
| 1530 |
+
# mark ISO pragma as error for PIM dialects
|
| 1531 |
+
if value.startswith('<*') and \
|
| 1532 |
+
self.dialect.startswith('m2pim'):
|
| 1533 |
+
token = Error
|
| 1534 |
+
# mark PIM pragma as comment for other dialects
|
| 1535 |
+
elif value.startswith('(*$') and \
|
| 1536 |
+
self.dialect != 'unknown' and \
|
| 1537 |
+
not self.dialect.startswith('m2pim'):
|
| 1538 |
+
token = Comment.Multiline
|
| 1539 |
+
#
|
| 1540 |
+
else: # token is neither Name nor Comment
|
| 1541 |
+
#
|
| 1542 |
+
# mark lexemes matching the dialect's error token set as errors
|
| 1543 |
+
if value in self.lexemes_to_reject:
|
| 1544 |
+
token = Error
|
| 1545 |
+
#
|
| 1546 |
+
# substitute lexemes when in Algol mode
|
| 1547 |
+
if self.algol_publication_mode:
|
| 1548 |
+
if value == '#':
|
| 1549 |
+
value = '≠'
|
| 1550 |
+
elif value == '<=':
|
| 1551 |
+
value = '≤'
|
| 1552 |
+
elif value == '>=':
|
| 1553 |
+
value = '≥'
|
| 1554 |
+
elif value == '==':
|
| 1555 |
+
value = '≡'
|
| 1556 |
+
elif value == '*.':
|
| 1557 |
+
value = '•'
|
| 1558 |
+
|
| 1559 |
+
# return result
|
| 1560 |
+
yield index, token, value
|
| 1561 |
+
|
| 1562 |
+
def analyse_text(text):
|
| 1563 |
+
"""It's Pascal-like, but does not use FUNCTION -- uses PROCEDURE
|
| 1564 |
+
instead."""
|
| 1565 |
+
|
| 1566 |
+
# Check if this looks like Pascal, if not, bail out early
|
| 1567 |
+
if not ('(*' in text and '*)' in text and ':=' in text):
|
| 1568 |
+
return
|
| 1569 |
+
|
| 1570 |
+
result = 0
|
| 1571 |
+
# Procedure is in Modula2
|
| 1572 |
+
if re.search(r'\bPROCEDURE\b', text):
|
| 1573 |
+
result += 0.6
|
| 1574 |
+
|
| 1575 |
+
# FUNCTION is only valid in Pascal, but not in Modula2
|
| 1576 |
+
if re.search(r'\bFUNCTION\b', text):
|
| 1577 |
+
result = 0.0
|
| 1578 |
+
|
| 1579 |
+
return result
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/smithy.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.smithy
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for the Smithy IDL.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pygments.lexer import RegexLexer, bygroups, words
|
| 12 |
+
from pygments.token import Text, Comment, Keyword, Name, String, \
|
| 13 |
+
Number, Whitespace, Punctuation
|
| 14 |
+
|
| 15 |
+
__all__ = ['SmithyLexer']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SmithyLexer(RegexLexer):
|
| 19 |
+
"""
|
| 20 |
+
For Smithy IDL
|
| 21 |
+
"""
|
| 22 |
+
name = 'Smithy'
|
| 23 |
+
url = 'https://awslabs.github.io/smithy/'
|
| 24 |
+
filenames = ['*.smithy']
|
| 25 |
+
aliases = ['smithy']
|
| 26 |
+
version_added = '2.10'
|
| 27 |
+
|
| 28 |
+
unquoted = r'[A-Za-z0-9_\.#$-]+'
|
| 29 |
+
identifier = r"[A-Za-z0-9_\.#$-]+"
|
| 30 |
+
|
| 31 |
+
simple_shapes = (
|
| 32 |
+
'use', 'byte', 'short', 'integer', 'long', 'float', 'document',
|
| 33 |
+
'double', 'bigInteger', 'bigDecimal', 'boolean', 'blob', 'string',
|
| 34 |
+
'timestamp',
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
aggregate_shapes = (
|
| 38 |
+
'apply', 'list', 'map', 'set', 'structure', 'union', 'resource',
|
| 39 |
+
'operation', 'service', 'trait'
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
tokens = {
|
| 43 |
+
'root': [
|
| 44 |
+
(r'///.*$', Comment.Multiline),
|
| 45 |
+
(r'//.*$', Comment),
|
| 46 |
+
(r'@[0-9a-zA-Z\.#-]*', Name.Decorator),
|
| 47 |
+
(r'(=)', Name.Decorator),
|
| 48 |
+
(r'^(\$version)(:)(.+)',
|
| 49 |
+
bygroups(Keyword.Declaration, Name.Decorator, Name.Class)),
|
| 50 |
+
(r'^(namespace)(\s+' + identifier + r')\b',
|
| 51 |
+
bygroups(Keyword.Declaration, Name.Class)),
|
| 52 |
+
(words(simple_shapes,
|
| 53 |
+
prefix=r'^', suffix=r'(\s+' + identifier + r')\b'),
|
| 54 |
+
bygroups(Keyword.Declaration, Name.Class)),
|
| 55 |
+
(words(aggregate_shapes,
|
| 56 |
+
prefix=r'^', suffix=r'(\s+' + identifier + r')'),
|
| 57 |
+
bygroups(Keyword.Declaration, Name.Class)),
|
| 58 |
+
(r'^(metadata)(\s+)((?:\S+)|(?:\"[^"]+\"))(\s*)(=)',
|
| 59 |
+
bygroups(Keyword.Declaration, Whitespace, Name.Class,
|
| 60 |
+
Whitespace, Name.Decorator)),
|
| 61 |
+
(r"(true|false|null)", Keyword.Constant),
|
| 62 |
+
(r"(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)", Number),
|
| 63 |
+
(identifier + ":", Name.Label),
|
| 64 |
+
(identifier, Name.Variable.Class),
|
| 65 |
+
(r'\[', Text, "#push"),
|
| 66 |
+
(r'\]', Text, "#pop"),
|
| 67 |
+
(r'\(', Text, "#push"),
|
| 68 |
+
(r'\)', Text, "#pop"),
|
| 69 |
+
(r'\{', Text, "#push"),
|
| 70 |
+
(r'\}', Text, "#pop"),
|
| 71 |
+
(r'"{3}(\\\\|\n|\\")*"{3}', String.Doc),
|
| 72 |
+
(r'"(\\\\|\n|\\"|[^"])*"', String.Double),
|
| 73 |
+
(r"'(\\\\|\n|\\'|[^'])*'", String.Single),
|
| 74 |
+
(r'[:,]+', Punctuation),
|
| 75 |
+
(r'\s+', Whitespace),
|
| 76 |
+
]
|
| 77 |
+
}
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/pygments/lexers/textedit.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
pygments.lexers.textedit
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for languages related to text processing.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
from bisect import bisect
|
| 13 |
+
|
| 14 |
+
from pygments.lexer import RegexLexer, bygroups, default, include, this, using
|
| 15 |
+
from pygments.lexers.python import PythonLexer
|
| 16 |
+
from pygments.token import Comment, Keyword, Name, Number, Operator, \
|
| 17 |
+
Punctuation, String, Text, Whitespace
|
| 18 |
+
|
| 19 |
+
__all__ = ['AwkLexer', 'SedLexer', 'VimLexer']
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AwkLexer(RegexLexer):
|
| 23 |
+
"""
|
| 24 |
+
For Awk scripts.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
name = 'Awk'
|
| 28 |
+
aliases = ['awk', 'gawk', 'mawk', 'nawk']
|
| 29 |
+
filenames = ['*.awk']
|
| 30 |
+
mimetypes = ['application/x-awk']
|
| 31 |
+
url = 'https://en.wikipedia.org/wiki/AWK'
|
| 32 |
+
version_added = '1.5'
|
| 33 |
+
|
| 34 |
+
tokens = {
|
| 35 |
+
'commentsandwhitespace': [
|
| 36 |
+
(r'\s+', Text),
|
| 37 |
+
(r'#.*$', Comment.Single)
|
| 38 |
+
],
|
| 39 |
+
'slashstartsregex': [
|
| 40 |
+
include('commentsandwhitespace'),
|
| 41 |
+
(r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
|
| 42 |
+
r'\B', String.Regex, '#pop'),
|
| 43 |
+
(r'(?=/)', Text, ('#pop', 'badregex')),
|
| 44 |
+
default('#pop')
|
| 45 |
+
],
|
| 46 |
+
'badregex': [
|
| 47 |
+
(r'\n', Text, '#pop')
|
| 48 |
+
],
|
| 49 |
+
'root': [
|
| 50 |
+
(r'^(?=\s|/)', Text, 'slashstartsregex'),
|
| 51 |
+
include('commentsandwhitespace'),
|
| 52 |
+
(r'\+\+|--|\|\||&&|in\b|\$|!?~|\?|:|'
|
| 53 |
+
r'(\*\*|[-<>+*%\^/!=|])=?', Operator, 'slashstartsregex'),
|
| 54 |
+
(r'[{(\[;,]', Punctuation, 'slashstartsregex'),
|
| 55 |
+
(r'[})\].]', Punctuation),
|
| 56 |
+
(r'(break|continue|do|while|exit|for|if|else|'
|
| 57 |
+
r'return)\b', Keyword, 'slashstartsregex'),
|
| 58 |
+
(r'function\b', Keyword.Declaration, 'slashstartsregex'),
|
| 59 |
+
(r'(atan2|cos|exp|int|log|rand|sin|sqrt|srand|gensub|gsub|index|'
|
| 60 |
+
r'length|match|split|sprintf|sub|substr|tolower|toupper|close|'
|
| 61 |
+
r'fflush|getline|next|nextfile|print|printf|strftime|systime|'
|
| 62 |
+
r'delete|system)\b', Keyword.Reserved),
|
| 63 |
+
(r'(ARGC|ARGIND|ARGV|BEGIN|CONVFMT|ENVIRON|END|ERRNO|FIELDWIDTHS|'
|
| 64 |
+
r'FILENAME|FNR|FS|IGNORECASE|NF|NR|OFMT|OFS|ORFS|RLENGTH|RS|'
|
| 65 |
+
r'RSTART|RT|SUBSEP)\b', Name.Builtin),
|
| 66 |
+
(r'[$a-zA-Z_]\w*', Name.Other),
|
| 67 |
+
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
|
| 68 |
+
(r'0x[0-9a-fA-F]+', Number.Hex),
|
| 69 |
+
(r'[0-9]+', Number.Integer),
|
| 70 |
+
(r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
|
| 71 |
+
(r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
|
| 72 |
+
]
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class SedLexer(RegexLexer):
|
| 77 |
+
"""
|
| 78 |
+
Lexer for Sed script files.
|
| 79 |
+
"""
|
| 80 |
+
name = 'Sed'
|
| 81 |
+
aliases = ['sed', 'gsed', 'ssed']
|
| 82 |
+
filenames = ['*.sed', '*.[gs]sed']
|
| 83 |
+
mimetypes = ['text/x-sed']
|
| 84 |
+
url = 'https://en.wikipedia.org/wiki/Sed'
|
| 85 |
+
version_added = ''
|
| 86 |
+
flags = re.MULTILINE
|
| 87 |
+
|
| 88 |
+
# Match the contents within delimiters such as /<contents>/
|
| 89 |
+
_inside_delims = r'((?:(?:\\[^\n]|[^\\])*?\\\n)*?(?:\\.|[^\\])*?)'
|
| 90 |
+
|
| 91 |
+
tokens = {
|
| 92 |
+
'root': [
|
| 93 |
+
(r'\s+', Whitespace),
|
| 94 |
+
(r'#.*$', Comment.Single),
|
| 95 |
+
(r'[0-9]+', Number.Integer),
|
| 96 |
+
(r'\$', Operator),
|
| 97 |
+
(r'[{};,!]', Punctuation),
|
| 98 |
+
(r'[dDFgGhHlnNpPqQxz=]', Keyword),
|
| 99 |
+
(r'([berRtTvwW:])([^;\n]*)', bygroups(Keyword, String.Single)),
|
| 100 |
+
(r'([aci])((?:.*?\\\n)*(?:.*?[^\\]$))', bygroups(Keyword, String.Double)),
|
| 101 |
+
(r'([qQ])([0-9]*)', bygroups(Keyword, Number.Integer)),
|
| 102 |
+
(r'(/)' + _inside_delims + r'(/)', bygroups(Punctuation, String.Regex, Punctuation)),
|
| 103 |
+
(r'(\\(.))' + _inside_delims + r'(\2)',
|
| 104 |
+
bygroups(Punctuation, None, String.Regex, Punctuation)),
|
| 105 |
+
(r'(y)(.)' + _inside_delims + r'(\2)' + _inside_delims + r'(\2)',
|
| 106 |
+
bygroups(Keyword, Punctuation, String.Single, Punctuation, String.Single, Punctuation)),
|
| 107 |
+
(r'(s)(.)' + _inside_delims + r'(\2)' + _inside_delims + r'(\2)((?:[gpeIiMm]|[0-9])*)',
|
| 108 |
+
bygroups(Keyword, Punctuation, String.Regex, Punctuation, String.Single, Punctuation,
|
| 109 |
+
Keyword))
|
| 110 |
+
]
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
class VimLexer(RegexLexer):
|
| 114 |
+
"""
|
| 115 |
+
Lexer for VimL script files.
|
| 116 |
+
"""
|
| 117 |
+
name = 'VimL'
|
| 118 |
+
aliases = ['vim']
|
| 119 |
+
filenames = ['*.vim', '.vimrc', '.exrc', '.gvimrc',
|
| 120 |
+
'_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc']
|
| 121 |
+
mimetypes = ['text/x-vim']
|
| 122 |
+
url = 'https://www.vim.org'
|
| 123 |
+
version_added = '0.8'
|
| 124 |
+
|
| 125 |
+
flags = re.MULTILINE
|
| 126 |
+
|
| 127 |
+
_python = r'py(?:t(?:h(?:o(?:n)?)?)?)?'
|
| 128 |
+
|
| 129 |
+
tokens = {
|
| 130 |
+
'root': [
|
| 131 |
+
(r'^([ \t:]*)(' + _python + r')([ \t]*)(<<)([ \t]*)(.*)((?:\n|.)*)(\6)',
|
| 132 |
+
bygroups(using(this), Keyword, Text, Operator, Text, Text,
|
| 133 |
+
using(PythonLexer), Text)),
|
| 134 |
+
(r'^([ \t:]*)(' + _python + r')([ \t])(.*)',
|
| 135 |
+
bygroups(using(this), Keyword, Text, using(PythonLexer))),
|
| 136 |
+
|
| 137 |
+
(r'^\s*".*', Comment),
|
| 138 |
+
|
| 139 |
+
(r'[ \t]+', Text),
|
| 140 |
+
# TODO: regexes can have other delims
|
| 141 |
+
(r'/[^/\\\n]*(?:\\[\s\S][^/\\\n]*)*/', String.Regex),
|
| 142 |
+
(r'"[^"\\\n]*(?:\\[\s\S][^"\\\n]*)*"', String.Double),
|
| 143 |
+
(r"'[^\n']*(?:''[^\n']*)*'", String.Single),
|
| 144 |
+
|
| 145 |
+
# Who decided that doublequote was a good comment character??
|
| 146 |
+
(r'(?<=\s)"[^\-:.%#=*].*', Comment),
|
| 147 |
+
(r'-?\d+', Number),
|
| 148 |
+
(r'#[0-9a-f]{6}', Number.Hex),
|
| 149 |
+
(r'^:', Punctuation),
|
| 150 |
+
(r'[()<>+=!|,~-]', Punctuation), # Inexact list. Looks decent.
|
| 151 |
+
(r'\b(let|if|else|endif|elseif|fun|function|endfunction)\b',
|
| 152 |
+
Keyword),
|
| 153 |
+
(r'\b(NONE|bold|italic|underline|dark|light)\b', Name.Builtin),
|
| 154 |
+
(r'\b\w+\b', Name.Other), # These are postprocessed below
|
| 155 |
+
(r'.', Text),
|
| 156 |
+
],
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
def __init__(self, **options):
|
| 160 |
+
from pygments.lexers._vim_builtins import auto, command, option
|
| 161 |
+
self._cmd = command
|
| 162 |
+
self._opt = option
|
| 163 |
+
self._aut = auto
|
| 164 |
+
|
| 165 |
+
RegexLexer.__init__(self, **options)
|
| 166 |
+
|
| 167 |
+
def is_in(self, w, mapping):
|
| 168 |
+
r"""
|
| 169 |
+
It's kind of difficult to decide if something might be a keyword
|
| 170 |
+
in VimL because it allows you to abbreviate them. In fact,
|
| 171 |
+
'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are
|
| 172 |
+
valid ways to call it so rather than making really awful regexps
|
| 173 |
+
like::
|
| 174 |
+
|
| 175 |
+
\bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b
|
| 176 |
+
|
| 177 |
+
we match `\b\w+\b` and then call is_in() on those tokens. See
|
| 178 |
+
`scripts/get_vimkw.py` for how the lists are extracted.
|
| 179 |
+
"""
|
| 180 |
+
p = bisect(mapping, (w,))
|
| 181 |
+
if p > 0:
|
| 182 |
+
if mapping[p-1][0] == w[:len(mapping[p-1][0])] and \
|
| 183 |
+
mapping[p-1][1][:len(w)] == w:
|
| 184 |
+
return True
|
| 185 |
+
if p < len(mapping):
|
| 186 |
+
return mapping[p][0] == w[:len(mapping[p][0])] and \
|
| 187 |
+
mapping[p][1][:len(w)] == w
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
+
def get_tokens_unprocessed(self, text):
|
| 191 |
+
# TODO: builtins are only subsequent tokens on lines
|
| 192 |
+
# and 'keywords' only happen at the beginning except
|
| 193 |
+
# for :au ones
|
| 194 |
+
for index, token, value in \
|
| 195 |
+
RegexLexer.get_tokens_unprocessed(self, text):
|
| 196 |
+
if token is Name.Other:
|
| 197 |
+
if self.is_in(value, self._cmd):
|
| 198 |
+
yield index, Keyword, value
|
| 199 |
+
elif self.is_in(value, self._opt) or \
|
| 200 |
+
self.is_in(value, self._aut):
|
| 201 |
+
yield index, Name.Builtin, value
|
| 202 |
+
else:
|
| 203 |
+
yield index, Text, value
|
| 204 |
+
else:
|
| 205 |
+
yield index, token, value
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 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 |
+
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_deepseek_v3 import *
|
| 22 |
+
from .modeling_deepseek_v3 import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/configuration_deepseek_v3.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 bzantium and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This code is based on the DeepSeekV3 implementations from the DeepSeek AI team. (https://huggingface.co/deepseek-ai/DeepSeek-V3)
|
| 4 |
+
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""DeepSeekV3 model configuration"""
|
| 17 |
+
|
| 18 |
+
from huggingface_hub.dataclasses import strict
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PreTrainedConfig
|
| 21 |
+
from ...modeling_rope_utils import RopeParameters
|
| 22 |
+
from ...utils import auto_docstring
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@auto_docstring(checkpoint="bzantium/tiny-deepseek-v3")
|
| 26 |
+
@strict
|
| 27 |
+
class DeepseekV3Config(PreTrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
n_group (`int`, *optional*, defaults to 8):
|
| 30 |
+
Number of groups for routed experts.
|
| 31 |
+
first_k_dense_replace (`int`, *optional*, defaults to 3):
|
| 32 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
| 33 |
+
\--k dense layers--/
|
| 34 |
+
rope_interleave (`bool`, *optional*, defaults to `True`):
|
| 35 |
+
Whether to interleave the rotary position embeddings.
|
| 36 |
+
|
| 37 |
+
Example:
|
| 38 |
+
|
| 39 |
+
```python
|
| 40 |
+
>>> from transformers import DeepseekV3Model, DeepseekV3Config
|
| 41 |
+
|
| 42 |
+
>>> # Initializing a Deepseek-V3 style configuration
|
| 43 |
+
>>> configuration = DeepseekV3Config()
|
| 44 |
+
|
| 45 |
+
>>> # Accessing the model configuration
|
| 46 |
+
>>> configuration = model.config
|
| 47 |
+
```"""
|
| 48 |
+
|
| 49 |
+
model_type = "deepseek_v3"
|
| 50 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 51 |
+
base_model_tp_plan = {
|
| 52 |
+
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
|
| 53 |
+
"layers.*.mlp.experts.down_proj": "rowwise",
|
| 54 |
+
"layers.*.mlp.experts": "moe_tp_experts",
|
| 55 |
+
"layers.*.mlp.shared_experts.gate_proj": "colwise",
|
| 56 |
+
"layers.*.mlp.shared_experts.up_proj": "colwise",
|
| 57 |
+
"layers.*.mlp.shared_experts.down_proj": "rowwise",
|
| 58 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 59 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 60 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 61 |
+
}
|
| 62 |
+
base_model_pp_plan = {
|
| 63 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 64 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 65 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 66 |
+
}
|
| 67 |
+
attribute_map = {
|
| 68 |
+
"num_local_experts": "n_routed_experts",
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
vocab_size: int = 129280
|
| 72 |
+
hidden_size: int = 7168
|
| 73 |
+
intermediate_size: int = 18432
|
| 74 |
+
moe_intermediate_size: int = 2048
|
| 75 |
+
num_hidden_layers: int = 61
|
| 76 |
+
num_attention_heads: int = 128
|
| 77 |
+
num_key_value_heads: int | None = 128
|
| 78 |
+
n_shared_experts: int = 1
|
| 79 |
+
n_routed_experts: int = 256
|
| 80 |
+
routed_scaling_factor: float = 2.5
|
| 81 |
+
kv_lora_rank: int = 512
|
| 82 |
+
q_lora_rank: int | None = 1536
|
| 83 |
+
qk_rope_head_dim: int = 64
|
| 84 |
+
v_head_dim: int | None = 128
|
| 85 |
+
qk_nope_head_dim: int = 128
|
| 86 |
+
n_group: int | None = 8
|
| 87 |
+
topk_group: int | None = 4
|
| 88 |
+
num_experts_per_tok: int | None = 8
|
| 89 |
+
first_k_dense_replace: int | None = 3
|
| 90 |
+
norm_topk_prob: bool | None = True
|
| 91 |
+
hidden_act: str = "silu"
|
| 92 |
+
max_position_embeddings: int = 4096
|
| 93 |
+
initializer_range: float = 0.02
|
| 94 |
+
rms_norm_eps: float = 1e-6
|
| 95 |
+
use_cache: bool = True
|
| 96 |
+
pad_token_id: int | None = None
|
| 97 |
+
bos_token_id: int | None = 0
|
| 98 |
+
eos_token_id: int | list[int] | None = 1
|
| 99 |
+
pretraining_tp: int | None = 1
|
| 100 |
+
tie_word_embeddings: bool = False
|
| 101 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 102 |
+
rope_interleave: bool | None = True
|
| 103 |
+
attention_bias: bool = False
|
| 104 |
+
attention_dropout: float | int | None = 0.0
|
| 105 |
+
|
| 106 |
+
def __post_init__(self, **kwargs):
|
| 107 |
+
if self.num_key_value_heads is None:
|
| 108 |
+
self.num_key_value_heads = self.num_attention_heads
|
| 109 |
+
|
| 110 |
+
self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
|
| 111 |
+
self.head_dim = self.qk_rope_head_dim
|
| 112 |
+
super().__post_init__(**kwargs)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
__all__ = ["DeepseekV3Config"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/modeling_deepseek_v3.py
ADDED
|
@@ -0,0 +1,722 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/deepseek_v3/modular_deepseek_v3.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_deepseek_v3.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
import math
|
| 8 |
+
from collections.abc import Callable
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from torch import nn
|
| 14 |
+
|
| 15 |
+
from ... import initialization as init
|
| 16 |
+
from ...activations import ACT2FN
|
| 17 |
+
from ...cache_utils import Cache, DynamicCache
|
| 18 |
+
from ...generation import GenerationMixin
|
| 19 |
+
from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernel_func_from_hub
|
| 20 |
+
from ...masking_utils import create_causal_mask
|
| 21 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 22 |
+
from ...modeling_layers import (
|
| 23 |
+
GenericForSequenceClassification,
|
| 24 |
+
GenericForTokenClassification,
|
| 25 |
+
GradientCheckpointingLayer,
|
| 26 |
+
)
|
| 27 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 28 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 29 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 30 |
+
from ...processing_utils import Unpack
|
| 31 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 32 |
+
from ...utils.generic import is_flash_attention_requested, maybe_autocast, merge_with_config_defaults
|
| 33 |
+
from ...utils.output_capturing import capture_outputs
|
| 34 |
+
from .configuration_deepseek_v3 import DeepseekV3Config
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 38 |
+
class DeepseekV3RMSNorm(nn.Module):
|
| 39 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 40 |
+
"""
|
| 41 |
+
DeepseekV3RMSNorm is equivalent to T5LayerNorm
|
| 42 |
+
"""
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 45 |
+
self.variance_epsilon = eps
|
| 46 |
+
|
| 47 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 48 |
+
input_dtype = hidden_states.dtype
|
| 49 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 50 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 51 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 52 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 53 |
+
|
| 54 |
+
def extra_repr(self):
|
| 55 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class DeepseekV3RotaryEmbedding(nn.Module):
|
| 59 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 60 |
+
|
| 61 |
+
def __init__(self, config: DeepseekV3Config, device=None):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 64 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 65 |
+
|
| 66 |
+
self.config = config
|
| 67 |
+
|
| 68 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 69 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 70 |
+
if self.rope_type != "default":
|
| 71 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 72 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 73 |
+
|
| 74 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 75 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def compute_default_rope_parameters(
|
| 79 |
+
config: DeepseekV3Config | None = None,
|
| 80 |
+
device: Optional["torch.device"] = None,
|
| 81 |
+
seq_len: int | None = None,
|
| 82 |
+
) -> tuple["torch.Tensor", float]:
|
| 83 |
+
"""
|
| 84 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 85 |
+
Args:
|
| 86 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 87 |
+
The model configuration.
|
| 88 |
+
device (`torch.device`):
|
| 89 |
+
The device to use for initialization of the inverse frequencies.
|
| 90 |
+
seq_len (`int`, *optional*):
|
| 91 |
+
The current sequence length. Unused for this type of RoPE.
|
| 92 |
+
Returns:
|
| 93 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 94 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 95 |
+
"""
|
| 96 |
+
base = config.rope_parameters["rope_theta"]
|
| 97 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 98 |
+
|
| 99 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 100 |
+
|
| 101 |
+
# Compute the inverse frequencies
|
| 102 |
+
inv_freq = 1.0 / (
|
| 103 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 104 |
+
)
|
| 105 |
+
return inv_freq, attention_factor
|
| 106 |
+
|
| 107 |
+
@torch.no_grad()
|
| 108 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 109 |
+
def forward(self, x, position_ids):
|
| 110 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 111 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 112 |
+
|
| 113 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 114 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 115 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 116 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 117 |
+
cos = emb.cos() * self.attention_scaling
|
| 118 |
+
sin = emb.sin() * self.attention_scaling
|
| 119 |
+
|
| 120 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class DeepseekV3MLP(nn.Module):
|
| 124 |
+
def __init__(self, config, intermediate_size=None):
|
| 125 |
+
super().__init__()
|
| 126 |
+
self.config = config
|
| 127 |
+
self.hidden_size = config.hidden_size
|
| 128 |
+
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
|
| 129 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 130 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 131 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 132 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 133 |
+
|
| 134 |
+
def forward(self, x):
|
| 135 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 136 |
+
return down_proj
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class DeepseekV3TopkRouter(nn.Module):
|
| 140 |
+
def __init__(self, config):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.config = config
|
| 143 |
+
self.n_routed_experts = config.n_routed_experts
|
| 144 |
+
|
| 145 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 146 |
+
self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
|
| 147 |
+
|
| 148 |
+
def forward(self, hidden_states):
|
| 149 |
+
hidden_states = hidden_states.view(-1, self.config.hidden_size)
|
| 150 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 151 |
+
return router_logits
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@use_experts_implementation
|
| 155 |
+
class DeepseekV3NaiveMoe(nn.Module):
|
| 156 |
+
"""Collection of expert weights stored as 3D tensors."""
|
| 157 |
+
|
| 158 |
+
def __init__(self, config):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.num_experts = config.num_local_experts
|
| 161 |
+
self.hidden_dim = config.hidden_size
|
| 162 |
+
self.intermediate_dim = config.moe_intermediate_size
|
| 163 |
+
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
|
| 164 |
+
self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
|
| 165 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 166 |
+
|
| 167 |
+
def forward(
|
| 168 |
+
self,
|
| 169 |
+
hidden_states: torch.Tensor,
|
| 170 |
+
top_k_index: torch.Tensor,
|
| 171 |
+
top_k_weights: torch.Tensor,
|
| 172 |
+
) -> torch.Tensor:
|
| 173 |
+
final_hidden_states = torch.zeros_like(hidden_states)
|
| 174 |
+
with torch.no_grad():
|
| 175 |
+
expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
|
| 176 |
+
expert_mask = expert_mask.permute(2, 1, 0)
|
| 177 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 178 |
+
|
| 179 |
+
for expert_idx in expert_hit:
|
| 180 |
+
expert_idx = expert_idx[0]
|
| 181 |
+
if expert_idx == self.num_experts:
|
| 182 |
+
continue
|
| 183 |
+
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
|
| 184 |
+
current_state = hidden_states[token_idx]
|
| 185 |
+
gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
|
| 186 |
+
current_hidden_states = self.act_fn(gate) * up
|
| 187 |
+
current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
|
| 188 |
+
current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
|
| 189 |
+
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
|
| 190 |
+
|
| 191 |
+
return final_hidden_states
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class DeepseekV3MoE(nn.Module):
|
| 195 |
+
"""
|
| 196 |
+
A mixed expert module containing shared experts.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self, config):
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.config = config
|
| 202 |
+
self.experts = DeepseekV3NaiveMoe(config)
|
| 203 |
+
self.gate = DeepseekV3TopkRouter(config)
|
| 204 |
+
self.shared_experts = DeepseekV3MLP(
|
| 205 |
+
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
|
| 206 |
+
)
|
| 207 |
+
self.n_routed_experts = config.n_routed_experts
|
| 208 |
+
self.n_group = config.n_group
|
| 209 |
+
self.topk_group = config.topk_group
|
| 210 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 211 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 212 |
+
self.top_k = config.num_experts_per_tok
|
| 213 |
+
|
| 214 |
+
def route_tokens_to_experts(self, router_logits):
|
| 215 |
+
router_logits = router_logits.sigmoid()
|
| 216 |
+
router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
|
| 217 |
+
group_scores = (
|
| 218 |
+
router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 219 |
+
.topk(2, dim=-1)[0]
|
| 220 |
+
.sum(dim=-1)
|
| 221 |
+
)
|
| 222 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 223 |
+
group_mask = torch.zeros_like(group_scores)
|
| 224 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 225 |
+
score_mask = (
|
| 226 |
+
group_mask.unsqueeze(-1)
|
| 227 |
+
.expand(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 228 |
+
.reshape(-1, self.n_routed_experts)
|
| 229 |
+
)
|
| 230 |
+
scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
|
| 231 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 232 |
+
topk_weights = router_logits.gather(1, topk_indices)
|
| 233 |
+
if self.norm_topk_prob:
|
| 234 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 235 |
+
topk_weights /= denominator
|
| 236 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 237 |
+
return topk_indices, topk_weights
|
| 238 |
+
|
| 239 |
+
def forward(self, hidden_states):
|
| 240 |
+
residuals = hidden_states
|
| 241 |
+
orig_shape = hidden_states.shape
|
| 242 |
+
router_logits = self.gate(hidden_states)
|
| 243 |
+
topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
|
| 244 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 245 |
+
hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)
|
| 246 |
+
hidden_states = hidden_states + self.shared_experts(residuals)
|
| 247 |
+
return hidden_states
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def rotate_half(x):
|
| 251 |
+
"""Rotates half the hidden dims of the input."""
|
| 252 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 253 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 254 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@use_kernel_func_from_hub("rotary_pos_emb")
|
| 258 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 259 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
q (`torch.Tensor`): The query tensor.
|
| 263 |
+
k (`torch.Tensor`): The key tensor.
|
| 264 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 265 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 266 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 267 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 268 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 269 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 270 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 271 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 272 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 273 |
+
Returns:
|
| 274 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 275 |
+
"""
|
| 276 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 277 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 278 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 279 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 280 |
+
return q_embed, k_embed
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 284 |
+
"""
|
| 285 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 286 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 287 |
+
"""
|
| 288 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 289 |
+
if n_rep == 1:
|
| 290 |
+
return hidden_states
|
| 291 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 292 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def eager_attention_forward(
|
| 296 |
+
module: nn.Module,
|
| 297 |
+
query: torch.Tensor,
|
| 298 |
+
key: torch.Tensor,
|
| 299 |
+
value: torch.Tensor,
|
| 300 |
+
attention_mask: torch.Tensor | None,
|
| 301 |
+
scaling: float,
|
| 302 |
+
dropout: float = 0.0,
|
| 303 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 304 |
+
):
|
| 305 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 306 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 307 |
+
|
| 308 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 309 |
+
if attention_mask is not None:
|
| 310 |
+
attn_weights = attn_weights + attention_mask
|
| 311 |
+
|
| 312 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 313 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 314 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 315 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 316 |
+
|
| 317 |
+
return attn_output, attn_weights
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 321 |
+
r"""
|
| 322 |
+
TODO let's just use the original freqcis computation to not have the view
|
| 323 |
+
transpose + reshape! This is not optimized!
|
| 324 |
+
Applies Rotary Position Embedding to the query and key tensors.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
q (`torch.Tensor`): The query tensor.
|
| 328 |
+
k (`torch.Tensor`): The key tensor.
|
| 329 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 330 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 331 |
+
position_ids (`torch.Tensor`):
|
| 332 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
| 333 |
+
used to pass offsetted position ids when working with a KV-cache.
|
| 334 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 335 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 336 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 337 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 338 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 339 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 340 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 341 |
+
Returns:
|
| 342 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 343 |
+
"""
|
| 344 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 345 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 346 |
+
|
| 347 |
+
b, h, s, d = q.shape
|
| 348 |
+
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
| 349 |
+
|
| 350 |
+
b, h, s, d = k.shape
|
| 351 |
+
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
| 352 |
+
|
| 353 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 354 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 355 |
+
return q_embed, k_embed
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def yarn_get_mscale(scale=1, mscale=1):
|
| 359 |
+
if scale <= 1:
|
| 360 |
+
return 1.0
|
| 361 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class DeepseekV3Attention(nn.Module):
|
| 365 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 366 |
+
|
| 367 |
+
def __init__(self, config: DeepseekV3Config, layer_idx: int):
|
| 368 |
+
super().__init__()
|
| 369 |
+
self.config = config
|
| 370 |
+
self.layer_idx = layer_idx
|
| 371 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 372 |
+
self.attention_dropout = config.attention_dropout
|
| 373 |
+
self.num_heads = config.num_attention_heads
|
| 374 |
+
|
| 375 |
+
self.q_lora_rank = config.q_lora_rank
|
| 376 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
| 377 |
+
self.kv_lora_rank = config.kv_lora_rank
|
| 378 |
+
self.v_head_dim = config.v_head_dim
|
| 379 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
| 380 |
+
self.qk_head_dim = config.qk_head_dim
|
| 381 |
+
|
| 382 |
+
self.is_causal = True
|
| 383 |
+
if self.q_lora_rank is None:
|
| 384 |
+
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
|
| 385 |
+
else:
|
| 386 |
+
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
|
| 387 |
+
self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
|
| 388 |
+
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
| 389 |
+
|
| 390 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
| 391 |
+
config.hidden_size,
|
| 392 |
+
self.kv_lora_rank + self.qk_rope_head_dim,
|
| 393 |
+
bias=config.attention_bias,
|
| 394 |
+
)
|
| 395 |
+
self.kv_a_layernorm = DeepseekV3RMSNorm(self.kv_lora_rank)
|
| 396 |
+
self.kv_b_proj = nn.Linear(
|
| 397 |
+
self.kv_lora_rank,
|
| 398 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
| 399 |
+
bias=False,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
self.o_proj = nn.Linear(
|
| 403 |
+
self.num_heads * self.v_head_dim,
|
| 404 |
+
config.hidden_size,
|
| 405 |
+
bias=config.attention_bias,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
self.scaling = self.qk_head_dim ** (-0.5)
|
| 409 |
+
if self.config.rope_parameters.get("rope_type", "default") != "default":
|
| 410 |
+
mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
|
| 411 |
+
scaling_factor = self.config.rope_parameters["factor"]
|
| 412 |
+
if mscale_all_dim:
|
| 413 |
+
mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
| 414 |
+
self.scaling = self.scaling * mscale * mscale
|
| 415 |
+
|
| 416 |
+
def forward(
|
| 417 |
+
self,
|
| 418 |
+
hidden_states: torch.Tensor,
|
| 419 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 420 |
+
attention_mask: torch.Tensor | None,
|
| 421 |
+
past_key_values: Cache | None = None,
|
| 422 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 423 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 424 |
+
batch_size, seq_length = hidden_states.shape[:-1]
|
| 425 |
+
query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
|
| 426 |
+
key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
|
| 427 |
+
|
| 428 |
+
if self.q_lora_rank is None:
|
| 429 |
+
q_states = self.q_proj(hidden_states)
|
| 430 |
+
else:
|
| 431 |
+
q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
| 432 |
+
q_states = q_states.view(query_shape).transpose(1, 2)
|
| 433 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
| 434 |
+
|
| 435 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
| 436 |
+
k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
| 437 |
+
|
| 438 |
+
k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
|
| 439 |
+
k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 440 |
+
|
| 441 |
+
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
|
| 442 |
+
|
| 443 |
+
cos, sin = position_embeddings
|
| 444 |
+
if self.config.rope_interleave: # support using interleaved weights for efficiency
|
| 445 |
+
q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
|
| 446 |
+
else:
|
| 447 |
+
q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
|
| 448 |
+
k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
|
| 449 |
+
|
| 450 |
+
query_states = torch.cat((q_pass, q_rot), dim=-1)
|
| 451 |
+
key_states = torch.cat((k_pass, k_rot), dim=-1)
|
| 452 |
+
|
| 453 |
+
if past_key_values is not None:
|
| 454 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 455 |
+
|
| 456 |
+
if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
|
| 457 |
+
value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
|
| 458 |
+
|
| 459 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 460 |
+
self.config._attn_implementation, eager_attention_forward
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
attn_output, attn_weights = attention_interface(
|
| 464 |
+
self,
|
| 465 |
+
query_states,
|
| 466 |
+
key_states,
|
| 467 |
+
value_states,
|
| 468 |
+
attention_mask,
|
| 469 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 470 |
+
scaling=self.scaling,
|
| 471 |
+
**kwargs,
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
|
| 475 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
| 476 |
+
|
| 477 |
+
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
|
| 478 |
+
attn_output = self.o_proj(attn_output)
|
| 479 |
+
return attn_output, attn_weights
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class DeepseekV3DecoderLayer(GradientCheckpointingLayer):
|
| 483 |
+
def __init__(self, config: DeepseekV3Config, layer_idx: int):
|
| 484 |
+
super().__init__()
|
| 485 |
+
self.hidden_size = config.hidden_size
|
| 486 |
+
|
| 487 |
+
self.self_attn = DeepseekV3Attention(config=config, layer_idx=layer_idx)
|
| 488 |
+
|
| 489 |
+
if layer_idx >= config.first_k_dense_replace:
|
| 490 |
+
self.mlp = DeepseekV3MoE(config)
|
| 491 |
+
else:
|
| 492 |
+
self.mlp = DeepseekV3MLP(config)
|
| 493 |
+
|
| 494 |
+
self.input_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 495 |
+
self.post_attention_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 496 |
+
|
| 497 |
+
def forward(
|
| 498 |
+
self,
|
| 499 |
+
hidden_states: torch.Tensor,
|
| 500 |
+
attention_mask: torch.Tensor | None = None,
|
| 501 |
+
position_ids: torch.LongTensor | None = None,
|
| 502 |
+
past_key_values: Cache | None = None,
|
| 503 |
+
use_cache: bool | None = False,
|
| 504 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 505 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 506 |
+
) -> torch.Tensor:
|
| 507 |
+
residual = hidden_states
|
| 508 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 509 |
+
# Self Attention
|
| 510 |
+
hidden_states, _ = self.self_attn(
|
| 511 |
+
hidden_states=hidden_states,
|
| 512 |
+
attention_mask=attention_mask,
|
| 513 |
+
position_ids=position_ids,
|
| 514 |
+
past_key_values=past_key_values,
|
| 515 |
+
use_cache=use_cache,
|
| 516 |
+
position_embeddings=position_embeddings,
|
| 517 |
+
**kwargs,
|
| 518 |
+
)
|
| 519 |
+
hidden_states = residual + hidden_states
|
| 520 |
+
|
| 521 |
+
# Fully Connected
|
| 522 |
+
residual = hidden_states
|
| 523 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 524 |
+
hidden_states = self.mlp(hidden_states)
|
| 525 |
+
hidden_states = residual + hidden_states
|
| 526 |
+
return hidden_states
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
@auto_docstring
|
| 530 |
+
class DeepseekV3PreTrainedModel(PreTrainedModel):
|
| 531 |
+
config: DeepseekV3Config
|
| 532 |
+
base_model_prefix = "model"
|
| 533 |
+
supports_gradient_checkpointing = True
|
| 534 |
+
_no_split_modules = ["DeepseekV3DecoderLayer"]
|
| 535 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 536 |
+
_supports_flash_attn = True
|
| 537 |
+
_supports_sdpa = True
|
| 538 |
+
_supports_flex_attn = True
|
| 539 |
+
|
| 540 |
+
_can_compile_fullgraph = True
|
| 541 |
+
_supports_attention_backend = True
|
| 542 |
+
_can_record_outputs = {
|
| 543 |
+
"hidden_states": DeepseekV3DecoderLayer,
|
| 544 |
+
"attentions": DeepseekV3Attention,
|
| 545 |
+
}
|
| 546 |
+
_keep_in_fp32_modules_strict = ["e_score_correction_bias"]
|
| 547 |
+
_keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
|
| 548 |
+
|
| 549 |
+
@torch.no_grad()
|
| 550 |
+
def _init_weights(self, module):
|
| 551 |
+
super()._init_weights(module)
|
| 552 |
+
if isinstance(module, DeepseekV3TopkRouter):
|
| 553 |
+
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 554 |
+
init.zeros_(module.e_score_correction_bias)
|
| 555 |
+
elif isinstance(module, DeepseekV3NaiveMoe):
|
| 556 |
+
init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
|
| 557 |
+
init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@auto_docstring
|
| 561 |
+
class DeepseekV3Model(DeepseekV3PreTrainedModel):
|
| 562 |
+
def __init__(self, config: DeepseekV3Config):
|
| 563 |
+
super().__init__(config)
|
| 564 |
+
self.padding_idx = config.pad_token_id
|
| 565 |
+
self.vocab_size = config.vocab_size
|
| 566 |
+
|
| 567 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 568 |
+
self.layers = nn.ModuleList(
|
| 569 |
+
[DeepseekV3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 570 |
+
)
|
| 571 |
+
self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 572 |
+
self.rotary_emb = DeepseekV3RotaryEmbedding(config=config)
|
| 573 |
+
self.gradient_checkpointing = False
|
| 574 |
+
|
| 575 |
+
# Initialize weights and apply final processing
|
| 576 |
+
self.post_init()
|
| 577 |
+
|
| 578 |
+
@merge_with_config_defaults
|
| 579 |
+
@capture_outputs
|
| 580 |
+
@auto_docstring
|
| 581 |
+
def forward(
|
| 582 |
+
self,
|
| 583 |
+
input_ids: torch.LongTensor | None = None,
|
| 584 |
+
attention_mask: torch.Tensor | None = None,
|
| 585 |
+
position_ids: torch.LongTensor | None = None,
|
| 586 |
+
past_key_values: Cache | None = None,
|
| 587 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 588 |
+
use_cache: bool | None = None,
|
| 589 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 590 |
+
) -> BaseModelOutputWithPast:
|
| 591 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 592 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 593 |
+
|
| 594 |
+
if inputs_embeds is None:
|
| 595 |
+
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
| 596 |
+
|
| 597 |
+
if use_cache and past_key_values is None:
|
| 598 |
+
past_key_values = DynamicCache(config=self.config)
|
| 599 |
+
|
| 600 |
+
if position_ids is None:
|
| 601 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 602 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 603 |
+
position_ids = position_ids.unsqueeze(0)
|
| 604 |
+
|
| 605 |
+
causal_mask = create_causal_mask(
|
| 606 |
+
config=self.config,
|
| 607 |
+
inputs_embeds=inputs_embeds,
|
| 608 |
+
attention_mask=attention_mask,
|
| 609 |
+
past_key_values=past_key_values,
|
| 610 |
+
position_ids=position_ids,
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
hidden_states = inputs_embeds
|
| 614 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 615 |
+
|
| 616 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 617 |
+
hidden_states = decoder_layer(
|
| 618 |
+
hidden_states,
|
| 619 |
+
attention_mask=causal_mask,
|
| 620 |
+
position_embeddings=position_embeddings,
|
| 621 |
+
position_ids=position_ids,
|
| 622 |
+
past_key_values=past_key_values,
|
| 623 |
+
use_cache=use_cache,
|
| 624 |
+
**kwargs,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
hidden_states = self.norm(hidden_states)
|
| 628 |
+
return BaseModelOutputWithPast(
|
| 629 |
+
last_hidden_state=hidden_states,
|
| 630 |
+
past_key_values=past_key_values,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
@auto_docstring
|
| 635 |
+
class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel, GenerationMixin):
|
| 636 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 637 |
+
_tp_plan = {"lm_head": "colwise_gather_output"}
|
| 638 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 639 |
+
|
| 640 |
+
def __init__(self, config):
|
| 641 |
+
super().__init__(config)
|
| 642 |
+
self.model = DeepseekV3Model(config)
|
| 643 |
+
self.vocab_size = config.vocab_size
|
| 644 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 645 |
+
|
| 646 |
+
# Initialize weights and apply final processing
|
| 647 |
+
self.post_init()
|
| 648 |
+
|
| 649 |
+
@can_return_tuple
|
| 650 |
+
@auto_docstring
|
| 651 |
+
def forward(
|
| 652 |
+
self,
|
| 653 |
+
input_ids: torch.LongTensor | None = None,
|
| 654 |
+
attention_mask: torch.Tensor | None = None,
|
| 655 |
+
position_ids: torch.LongTensor | None = None,
|
| 656 |
+
past_key_values: Cache | None = None,
|
| 657 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 658 |
+
labels: torch.LongTensor | None = None,
|
| 659 |
+
use_cache: bool | None = None,
|
| 660 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 661 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 662 |
+
) -> CausalLMOutputWithPast:
|
| 663 |
+
r"""
|
| 664 |
+
Example:
|
| 665 |
+
|
| 666 |
+
```python
|
| 667 |
+
>>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM
|
| 668 |
+
|
| 669 |
+
>>> model = DeepseekV3ForCausalLM.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")
|
| 670 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")
|
| 671 |
+
|
| 672 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 673 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 674 |
+
|
| 675 |
+
>>> # Generate
|
| 676 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 677 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 678 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 679 |
+
```"""
|
| 680 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 681 |
+
input_ids=input_ids,
|
| 682 |
+
attention_mask=attention_mask,
|
| 683 |
+
position_ids=position_ids,
|
| 684 |
+
past_key_values=past_key_values,
|
| 685 |
+
inputs_embeds=inputs_embeds,
|
| 686 |
+
use_cache=use_cache,
|
| 687 |
+
**kwargs,
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
hidden_states = outputs.last_hidden_state
|
| 691 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 692 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 693 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 694 |
+
|
| 695 |
+
loss = None
|
| 696 |
+
if labels is not None:
|
| 697 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 698 |
+
|
| 699 |
+
return CausalLMOutputWithPast(
|
| 700 |
+
loss=loss,
|
| 701 |
+
logits=logits,
|
| 702 |
+
past_key_values=outputs.past_key_values,
|
| 703 |
+
hidden_states=outputs.hidden_states,
|
| 704 |
+
attentions=outputs.attentions,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
class DeepseekV3ForSequenceClassification(GenericForSequenceClassification, DeepseekV3PreTrainedModel):
|
| 709 |
+
pass
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
class DeepseekV3ForTokenClassification(GenericForTokenClassification, DeepseekV3PreTrainedModel):
|
| 713 |
+
pass
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
__all__ = [
|
| 717 |
+
"DeepseekV3PreTrainedModel",
|
| 718 |
+
"DeepseekV3Model",
|
| 719 |
+
"DeepseekV3ForCausalLM",
|
| 720 |
+
"DeepseekV3ForSequenceClassification",
|
| 721 |
+
"DeepseekV3ForTokenClassification",
|
| 722 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_v3/modular_deepseek_v3.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import nn
|
| 7 |
+
|
| 8 |
+
from ... import initialization as init
|
| 9 |
+
from ...cache_utils import Cache
|
| 10 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 11 |
+
from ...modeling_layers import GenericForSequenceClassification, GenericForTokenClassification
|
| 12 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 13 |
+
from ...processing_utils import Unpack
|
| 14 |
+
from ...utils import logging
|
| 15 |
+
from ...utils.generic import is_flash_attention_requested
|
| 16 |
+
from ..llama.modeling_llama import (
|
| 17 |
+
LlamaDecoderLayer,
|
| 18 |
+
LlamaForCausalLM,
|
| 19 |
+
LlamaModel,
|
| 20 |
+
LlamaPreTrainedModel,
|
| 21 |
+
LlamaRMSNorm,
|
| 22 |
+
LlamaRotaryEmbedding,
|
| 23 |
+
apply_rotary_pos_emb,
|
| 24 |
+
eager_attention_forward,
|
| 25 |
+
rotate_half,
|
| 26 |
+
)
|
| 27 |
+
from ..mixtral.modeling_mixtral import MixtralExperts
|
| 28 |
+
from ..qwen2_moe.modeling_qwen2_moe import Qwen2MoeMLP
|
| 29 |
+
from .configuration_deepseek_v3 import DeepseekV3Config
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DeepseekV3RMSNorm(LlamaRMSNorm):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class DeepseekV3RotaryEmbedding(LlamaRotaryEmbedding):
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DeepseekV3MLP(Qwen2MoeMLP):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 48 |
+
r"""
|
| 49 |
+
TODO let's just use the original freqcis computation to not have the view
|
| 50 |
+
transpose + reshape! This is not optimized!
|
| 51 |
+
Applies Rotary Position Embedding to the query and key tensors.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
q (`torch.Tensor`): The query tensor.
|
| 55 |
+
k (`torch.Tensor`): The key tensor.
|
| 56 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 57 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 58 |
+
position_ids (`torch.Tensor`):
|
| 59 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
| 60 |
+
used to pass offsetted position ids when working with a KV-cache.
|
| 61 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 62 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 63 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 64 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 65 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 66 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 67 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 68 |
+
Returns:
|
| 69 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 70 |
+
"""
|
| 71 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 72 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 73 |
+
|
| 74 |
+
b, h, s, d = q.shape
|
| 75 |
+
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
| 76 |
+
|
| 77 |
+
b, h, s, d = k.shape
|
| 78 |
+
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
| 79 |
+
|
| 80 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 81 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 82 |
+
return q_embed, k_embed
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def yarn_get_mscale(scale=1, mscale=1):
|
| 86 |
+
if scale <= 1:
|
| 87 |
+
return 1.0
|
| 88 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class DeepseekV3TopkRouter(nn.Module):
|
| 92 |
+
def __init__(self, config):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.config = config
|
| 95 |
+
self.n_routed_experts = config.n_routed_experts
|
| 96 |
+
|
| 97 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 98 |
+
self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
|
| 99 |
+
|
| 100 |
+
def forward(self, hidden_states):
|
| 101 |
+
hidden_states = hidden_states.view(-1, self.config.hidden_size)
|
| 102 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 103 |
+
return router_logits
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class DeepseekV3NaiveMoe(MixtralExperts):
|
| 107 |
+
def __init__(self, config):
|
| 108 |
+
super().__init__(config)
|
| 109 |
+
self.num_experts = config.num_local_experts
|
| 110 |
+
self.intermediate_dim = config.moe_intermediate_size
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class DeepseekV3MoE(nn.Module):
|
| 114 |
+
"""
|
| 115 |
+
A mixed expert module containing shared experts.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def __init__(self, config):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.config = config
|
| 121 |
+
self.experts = DeepseekV3NaiveMoe(config)
|
| 122 |
+
self.gate = DeepseekV3TopkRouter(config)
|
| 123 |
+
self.shared_experts = DeepseekV3MLP(
|
| 124 |
+
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
|
| 125 |
+
)
|
| 126 |
+
self.n_routed_experts = config.n_routed_experts
|
| 127 |
+
self.n_group = config.n_group
|
| 128 |
+
self.topk_group = config.topk_group
|
| 129 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 130 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 131 |
+
self.top_k = config.num_experts_per_tok
|
| 132 |
+
|
| 133 |
+
def route_tokens_to_experts(self, router_logits):
|
| 134 |
+
router_logits = router_logits.sigmoid()
|
| 135 |
+
router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
|
| 136 |
+
group_scores = (
|
| 137 |
+
router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 138 |
+
.topk(2, dim=-1)[0]
|
| 139 |
+
.sum(dim=-1)
|
| 140 |
+
)
|
| 141 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 142 |
+
group_mask = torch.zeros_like(group_scores)
|
| 143 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 144 |
+
score_mask = (
|
| 145 |
+
group_mask.unsqueeze(-1)
|
| 146 |
+
.expand(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 147 |
+
.reshape(-1, self.n_routed_experts)
|
| 148 |
+
)
|
| 149 |
+
scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
|
| 150 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 151 |
+
topk_weights = router_logits.gather(1, topk_indices)
|
| 152 |
+
if self.norm_topk_prob:
|
| 153 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 154 |
+
topk_weights /= denominator
|
| 155 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 156 |
+
return topk_indices, topk_weights
|
| 157 |
+
|
| 158 |
+
def forward(self, hidden_states):
|
| 159 |
+
residuals = hidden_states
|
| 160 |
+
orig_shape = hidden_states.shape
|
| 161 |
+
router_logits = self.gate(hidden_states)
|
| 162 |
+
topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
|
| 163 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 164 |
+
hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)
|
| 165 |
+
hidden_states = hidden_states + self.shared_experts(residuals)
|
| 166 |
+
return hidden_states
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class DeepseekV3Attention(nn.Module):
|
| 170 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 171 |
+
|
| 172 |
+
def __init__(self, config: DeepseekV3Config, layer_idx: int):
|
| 173 |
+
super().__init__()
|
| 174 |
+
self.config = config
|
| 175 |
+
self.layer_idx = layer_idx
|
| 176 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 177 |
+
self.attention_dropout = config.attention_dropout
|
| 178 |
+
self.num_heads = config.num_attention_heads
|
| 179 |
+
|
| 180 |
+
self.q_lora_rank = config.q_lora_rank
|
| 181 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
| 182 |
+
self.kv_lora_rank = config.kv_lora_rank
|
| 183 |
+
self.v_head_dim = config.v_head_dim
|
| 184 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
| 185 |
+
self.qk_head_dim = config.qk_head_dim
|
| 186 |
+
|
| 187 |
+
self.is_causal = True
|
| 188 |
+
if self.q_lora_rank is None:
|
| 189 |
+
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
|
| 190 |
+
else:
|
| 191 |
+
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
|
| 192 |
+
self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
|
| 193 |
+
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
| 194 |
+
|
| 195 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
| 196 |
+
config.hidden_size,
|
| 197 |
+
self.kv_lora_rank + self.qk_rope_head_dim,
|
| 198 |
+
bias=config.attention_bias,
|
| 199 |
+
)
|
| 200 |
+
self.kv_a_layernorm = DeepseekV3RMSNorm(self.kv_lora_rank)
|
| 201 |
+
self.kv_b_proj = nn.Linear(
|
| 202 |
+
self.kv_lora_rank,
|
| 203 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
| 204 |
+
bias=False,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
self.o_proj = nn.Linear(
|
| 208 |
+
self.num_heads * self.v_head_dim,
|
| 209 |
+
config.hidden_size,
|
| 210 |
+
bias=config.attention_bias,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
self.scaling = self.qk_head_dim ** (-0.5)
|
| 214 |
+
if self.config.rope_parameters.get("rope_type", "default") != "default":
|
| 215 |
+
mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
|
| 216 |
+
scaling_factor = self.config.rope_parameters["factor"]
|
| 217 |
+
if mscale_all_dim:
|
| 218 |
+
mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
| 219 |
+
self.scaling = self.scaling * mscale * mscale
|
| 220 |
+
|
| 221 |
+
def forward(
|
| 222 |
+
self,
|
| 223 |
+
hidden_states: torch.Tensor,
|
| 224 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 225 |
+
attention_mask: torch.Tensor | None,
|
| 226 |
+
past_key_values: Cache | None = None,
|
| 227 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 228 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 229 |
+
batch_size, seq_length = hidden_states.shape[:-1]
|
| 230 |
+
query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
|
| 231 |
+
key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
|
| 232 |
+
|
| 233 |
+
if self.q_lora_rank is None:
|
| 234 |
+
q_states = self.q_proj(hidden_states)
|
| 235 |
+
else:
|
| 236 |
+
q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
| 237 |
+
q_states = q_states.view(query_shape).transpose(1, 2)
|
| 238 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
| 239 |
+
|
| 240 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
| 241 |
+
k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
| 242 |
+
|
| 243 |
+
k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
|
| 244 |
+
k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 245 |
+
|
| 246 |
+
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
|
| 247 |
+
|
| 248 |
+
cos, sin = position_embeddings
|
| 249 |
+
if self.config.rope_interleave: # support using interleaved weights for efficiency
|
| 250 |
+
q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
|
| 251 |
+
else:
|
| 252 |
+
q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
|
| 253 |
+
k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
|
| 254 |
+
|
| 255 |
+
query_states = torch.cat((q_pass, q_rot), dim=-1)
|
| 256 |
+
key_states = torch.cat((k_pass, k_rot), dim=-1)
|
| 257 |
+
|
| 258 |
+
if past_key_values is not None:
|
| 259 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 260 |
+
|
| 261 |
+
if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
|
| 262 |
+
value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
|
| 263 |
+
|
| 264 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 265 |
+
self.config._attn_implementation, eager_attention_forward
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
attn_output, attn_weights = attention_interface(
|
| 269 |
+
self,
|
| 270 |
+
query_states,
|
| 271 |
+
key_states,
|
| 272 |
+
value_states,
|
| 273 |
+
attention_mask,
|
| 274 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 275 |
+
scaling=self.scaling,
|
| 276 |
+
**kwargs,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
|
| 280 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
| 281 |
+
|
| 282 |
+
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
|
| 283 |
+
attn_output = self.o_proj(attn_output)
|
| 284 |
+
return attn_output, attn_weights
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class DeepseekV3DecoderLayer(LlamaDecoderLayer):
|
| 288 |
+
def __init__(self, config: DeepseekV3Config, layer_idx: int):
|
| 289 |
+
nn.Module.__init__(self)
|
| 290 |
+
self.hidden_size = config.hidden_size
|
| 291 |
+
|
| 292 |
+
self.self_attn = DeepseekV3Attention(config=config, layer_idx=layer_idx)
|
| 293 |
+
|
| 294 |
+
if layer_idx >= config.first_k_dense_replace:
|
| 295 |
+
self.mlp = DeepseekV3MoE(config)
|
| 296 |
+
else:
|
| 297 |
+
self.mlp = DeepseekV3MLP(config)
|
| 298 |
+
|
| 299 |
+
self.input_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 300 |
+
self.post_attention_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class DeepseekV3PreTrainedModel(LlamaPreTrainedModel):
|
| 304 |
+
_keep_in_fp32_modules_strict = ["e_score_correction_bias"]
|
| 305 |
+
_keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
|
| 306 |
+
|
| 307 |
+
@torch.no_grad()
|
| 308 |
+
def _init_weights(self, module):
|
| 309 |
+
PreTrainedModel._init_weights(self, module)
|
| 310 |
+
if isinstance(module, DeepseekV3TopkRouter):
|
| 311 |
+
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 312 |
+
init.zeros_(module.e_score_correction_bias)
|
| 313 |
+
elif isinstance(module, DeepseekV3NaiveMoe):
|
| 314 |
+
init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
|
| 315 |
+
init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class DeepseekV3Model(LlamaModel):
|
| 319 |
+
pass
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class DeepseekV3ForCausalLM(LlamaForCausalLM):
|
| 323 |
+
pass
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class DeepseekV3ForSequenceClassification(GenericForSequenceClassification, DeepseekV3PreTrainedModel):
|
| 327 |
+
pass
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class DeepseekV3ForTokenClassification(GenericForTokenClassification, DeepseekV3PreTrainedModel):
|
| 331 |
+
pass
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
__all__ = [
|
| 335 |
+
"DeepseekV3PreTrainedModel",
|
| 336 |
+
"DeepseekV3Model",
|
| 337 |
+
"DeepseekV3ForCausalLM",
|
| 338 |
+
"DeepseekV3ForSequenceClassification",
|
| 339 |
+
"DeepseekV3ForTokenClassification",
|
| 340 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/__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_llava_onevision import *
|
| 22 |
+
from .image_processing_llava_onevision import *
|
| 23 |
+
from .image_processing_pil_llava_onevision import *
|
| 24 |
+
from .modeling_llava_onevision import *
|
| 25 |
+
from .processing_llava_onevision import *
|
| 26 |
+
from .video_processing_llava_onevision 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/llava_onevision/configuration_llava_onevision.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Literal
|
| 16 |
+
|
| 17 |
+
from huggingface_hub.dataclasses import strict
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PreTrainedConfig
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="llava-hf/llava-onevision-qwen2-7b-ov-hf")
|
| 25 |
+
@strict
|
| 26 |
+
class LlavaOnevisionConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
image_grid_pinpoints (`List`, *optional*):
|
| 29 |
+
A list of possible resolutions to use for processing high resolution images. Each item in the list should be a tuple or list
|
| 30 |
+
of the form `(height, width)`.
|
| 31 |
+
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
|
| 32 |
+
Aspect ratio used when processong image features. The default value is "anyres_max_9".
|
| 33 |
+
|
| 34 |
+
Example:
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
>>> from transformers import LlavaOnevisionForConditionalGeneration, LlavaOnevisionConfig, SiglipVisionConfig, Qwen2Config
|
| 38 |
+
|
| 39 |
+
>>> # Initializing a CLIP-vision config
|
| 40 |
+
>>> vision_config = SiglipVisionConfig()
|
| 41 |
+
|
| 42 |
+
>>> # Initializing a Llama config
|
| 43 |
+
>>> text_config = Qwen2Config()
|
| 44 |
+
|
| 45 |
+
>>> # Initializing a Llava-Next llava-hf/llava-onevision-qwen2-7b-ov-hf style configuration
|
| 46 |
+
>>> configuration = LlavaOnevisionConfig(vision_config, text_config)
|
| 47 |
+
|
| 48 |
+
>>> # Initializing a model from the llava-hf/llava-onevision-qwen2-7b-ov-hf style configuration
|
| 49 |
+
>>> model = LlavaOnevisionForConditionalGeneration(configuration)
|
| 50 |
+
|
| 51 |
+
>>> # Accessing the model configuration
|
| 52 |
+
>>> configuration = model.config
|
| 53 |
+
```"""
|
| 54 |
+
|
| 55 |
+
model_type = "llava_onevision"
|
| 56 |
+
attribute_map = {
|
| 57 |
+
"image_token_id": "image_token_index",
|
| 58 |
+
"video_token_id": "video_token_index",
|
| 59 |
+
}
|
| 60 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
|
| 61 |
+
|
| 62 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 63 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 64 |
+
image_token_index: int = 151646
|
| 65 |
+
video_token_index: int = 151647
|
| 66 |
+
projector_hidden_act: str = "gelu"
|
| 67 |
+
vision_feature_select_strategy: Literal["default", "full"] = "full"
|
| 68 |
+
vision_feature_layer: int | list[int] = -1
|
| 69 |
+
multimodal_projector_bias: bool = True
|
| 70 |
+
tie_word_embeddings: bool = False
|
| 71 |
+
image_grid_pinpoints: list | None = None
|
| 72 |
+
vision_aspect_ratio: str = "anyres_max_9"
|
| 73 |
+
|
| 74 |
+
def __post_init__(self, **kwargs):
|
| 75 |
+
if isinstance(self.vision_config, dict):
|
| 76 |
+
self.vision_config["model_type"] = self.vision_config.get("model_type", "siglip_vision_model")
|
| 77 |
+
self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
|
| 78 |
+
elif self.vision_config is None:
|
| 79 |
+
self.vision_config = CONFIG_MAPPING["siglip_vision_model"](
|
| 80 |
+
hidden_size=1152,
|
| 81 |
+
intermediate_size=4304,
|
| 82 |
+
patch_size=14,
|
| 83 |
+
image_size=384,
|
| 84 |
+
num_hidden_layers=26,
|
| 85 |
+
num_attention_heads=16,
|
| 86 |
+
vision_use_head=False,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if isinstance(self.text_config, dict):
|
| 90 |
+
self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
|
| 91 |
+
self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
|
| 92 |
+
elif self.text_config is None:
|
| 93 |
+
self.text_config = CONFIG_MAPPING["qwen2"]()
|
| 94 |
+
|
| 95 |
+
self.image_grid_pinpoints = (
|
| 96 |
+
self.image_grid_pinpoints
|
| 97 |
+
if self.image_grid_pinpoints is not None
|
| 98 |
+
else [
|
| 99 |
+
[384, 384],
|
| 100 |
+
[384, 768],
|
| 101 |
+
[384, 1152],
|
| 102 |
+
[384, 1536],
|
| 103 |
+
[384, 1920],
|
| 104 |
+
[384, 2304],
|
| 105 |
+
[768, 384],
|
| 106 |
+
[768, 768],
|
| 107 |
+
[768, 1152],
|
| 108 |
+
[768, 1536],
|
| 109 |
+
[768, 1920],
|
| 110 |
+
[768, 2304],
|
| 111 |
+
[1152, 384],
|
| 112 |
+
[1152, 768],
|
| 113 |
+
[1152, 1152],
|
| 114 |
+
[1152, 1536],
|
| 115 |
+
[1152, 1920],
|
| 116 |
+
[1152, 2304],
|
| 117 |
+
[1536, 384],
|
| 118 |
+
[1536, 768],
|
| 119 |
+
[1536, 1152],
|
| 120 |
+
[1536, 1536],
|
| 121 |
+
[1536, 1920],
|
| 122 |
+
[1536, 2304],
|
| 123 |
+
[1920, 384],
|
| 124 |
+
[1920, 768],
|
| 125 |
+
[1920, 1152],
|
| 126 |
+
[1920, 1536],
|
| 127 |
+
[1920, 1920],
|
| 128 |
+
[1920, 2304],
|
| 129 |
+
[2304, 384],
|
| 130 |
+
[2304, 768],
|
| 131 |
+
[2304, 1152],
|
| 132 |
+
[2304, 1536],
|
| 133 |
+
[2304, 1920],
|
| 134 |
+
[2304, 2304],
|
| 135 |
+
]
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# The default value is `False` but this config is used with many model types
|
| 139 |
+
# Attr `tie_word_embeddings` was saved in text config for those models, so we
|
| 140 |
+
# need an ugly workaround and forward-pass the attr from text config
|
| 141 |
+
if not self.tie_word_embeddings and self.text_config.tie_word_embeddings:
|
| 142 |
+
self.tie_word_embeddings = self.text_config.tie_word_embeddings
|
| 143 |
+
|
| 144 |
+
super().__post_init__(**kwargs)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
__all__ = ["LlavaOnevisionConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/image_processing_pil_llava_onevision.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/llava_onevision/modular_llava_onevision.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_llava_onevision.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ...image_processing_backends import PilBackend
|
| 25 |
+
from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
|
| 26 |
+
from ...image_transforms import divide_to_patches
|
| 27 |
+
from ...image_utils import (
|
| 28 |
+
OPENAI_CLIP_MEAN,
|
| 29 |
+
OPENAI_CLIP_STD,
|
| 30 |
+
ChannelDimension,
|
| 31 |
+
ImageInput,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
SizeDict,
|
| 34 |
+
)
|
| 35 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 36 |
+
from ...utils import TensorType, auto_docstring
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class LlavaOnevisionImageProcessorKwargs(ImagesKwargs, total=False):
|
| 40 |
+
r"""
|
| 41 |
+
image_grid_pinpoints (`list[list[int]]`, *optional*):
|
| 42 |
+
A list of possible resolutions to use for processing high resolution images. The best resolution is selected
|
| 43 |
+
based on the original size of the image. Can be overridden by `image_grid_pinpoints` in the `preprocess`
|
| 44 |
+
method.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
image_grid_pinpoints: list[list[int]]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@auto_docstring
|
| 51 |
+
class LlavaOnevisionImageProcessorPil(PilBackend):
|
| 52 |
+
model_input_names = ["pixel_values", "image_sizes", "batch_num_images"]
|
| 53 |
+
valid_kwargs = LlavaOnevisionImageProcessorKwargs
|
| 54 |
+
resample = PILImageResampling.BICUBIC
|
| 55 |
+
image_mean = OPENAI_CLIP_MEAN
|
| 56 |
+
image_std = OPENAI_CLIP_STD
|
| 57 |
+
size = {"height": 384, "width": 384}
|
| 58 |
+
default_to_square = False
|
| 59 |
+
crop_size = None
|
| 60 |
+
do_resize = True
|
| 61 |
+
do_center_crop = None
|
| 62 |
+
do_rescale = True
|
| 63 |
+
do_normalize = True
|
| 64 |
+
do_convert_rgb = True
|
| 65 |
+
do_pad = True
|
| 66 |
+
image_grid_pinpoints = [[384, 384], [384, 768], [384, 1152], [384, 1536], [384, 1920], [384, 2304], [768, 384], [768, 768], [768, 1152], [768, 1536], [768, 1920], [768, 2304], [1152, 384], [1152, 768], [1152, 1152], [1152, 1536], [1152, 1920], [1152, 2304], [1536, 384], [1536, 768], [1536, 1152], [1536, 1536], [1536, 1920], [1536, 2304], [1920, 384], [1920, 768], [1920, 1152], [1920, 1536], [1920, 1920], [1920, 2304], [2304, 384], [2304, 768], [2304, 1152], [2304, 1536], [2304, 1920], [2304, 2304]] # fmt: skip
|
| 67 |
+
|
| 68 |
+
def __init__(self, **kwargs: Unpack[LlavaOnevisionImageProcessorKwargs]):
|
| 69 |
+
super().__init__(**kwargs)
|
| 70 |
+
|
| 71 |
+
@auto_docstring
|
| 72 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[LlavaOnevisionImageProcessorKwargs]) -> BatchFeature:
|
| 73 |
+
if isinstance(images, (tuple, list)) and isinstance(images[0], (tuple, list)):
|
| 74 |
+
# if the first element is a list, we assume that all elements are lists
|
| 75 |
+
images = [x for x in images if x] # handle text-only case
|
| 76 |
+
batch_num_images = [len(x) for x in images]
|
| 77 |
+
elif isinstance(images, (tuple, list)):
|
| 78 |
+
# treat this as a single-image case for backward compatibility
|
| 79 |
+
batch_num_images = [1] * len(images)
|
| 80 |
+
else:
|
| 81 |
+
batch_num_images = [1]
|
| 82 |
+
return super().preprocess(images, batch_num_images, **kwargs)
|
| 83 |
+
|
| 84 |
+
def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple):
|
| 85 |
+
"""Get padding size for patching (returns tuple format for np.pad)."""
|
| 86 |
+
original_height, original_width = original_resolution
|
| 87 |
+
target_height, target_width = target_resolution
|
| 88 |
+
paste_x, r_x = divmod(target_width - original_width, 2)
|
| 89 |
+
paste_y, r_y = divmod(target_height - original_height, 2)
|
| 90 |
+
return (paste_y, paste_y + r_y), (paste_x, paste_x + r_x)
|
| 91 |
+
|
| 92 |
+
def _resize_for_patching(
|
| 93 |
+
self,
|
| 94 |
+
image: np.ndarray,
|
| 95 |
+
target_resolution: tuple,
|
| 96 |
+
resample: PILImageResampling,
|
| 97 |
+
) -> np.ndarray:
|
| 98 |
+
"""Resizes an image to a target resolution while maintaining aspect ratio."""
|
| 99 |
+
new_height, new_width = get_patch_output_size(
|
| 100 |
+
image, target_resolution, input_data_format=ChannelDimension.FIRST
|
| 101 |
+
)
|
| 102 |
+
resized_image = self.resize(image=image, size=SizeDict(height=new_height, width=new_width), resample=resample)
|
| 103 |
+
|
| 104 |
+
return resized_image
|
| 105 |
+
|
| 106 |
+
def _pad_for_patching(self, image: np.ndarray, target_resolution: tuple) -> np.ndarray:
|
| 107 |
+
"""Pad an image to a target resolution while maintaining aspect ratio."""
|
| 108 |
+
new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
|
| 109 |
+
padding_hw = self._get_padding_size(new_resolution, target_resolution)
|
| 110 |
+
|
| 111 |
+
# For channels_first format (C, H, W), add (0, 0) for channel dimension
|
| 112 |
+
# padding_hw is ((before_h, after_h), (before_w, after_w))
|
| 113 |
+
# np.pad expects ((before_C, after_C), (before_H, after_H), (before_W, after_W))
|
| 114 |
+
padding = ((0, 0), padding_hw[0], padding_hw[1])
|
| 115 |
+
|
| 116 |
+
# Use np.pad directly for patching padding
|
| 117 |
+
padded_image = np.pad(image, padding, mode="constant", constant_values=0)
|
| 118 |
+
|
| 119 |
+
return padded_image
|
| 120 |
+
|
| 121 |
+
def get_image_patches(
|
| 122 |
+
self,
|
| 123 |
+
image: np.ndarray,
|
| 124 |
+
grid_pinpoints: list[list[int]],
|
| 125 |
+
size: tuple,
|
| 126 |
+
patch_size: int,
|
| 127 |
+
resample: PILImageResampling,
|
| 128 |
+
) -> list[np.ndarray]:
|
| 129 |
+
"""Process an image with variable resolutions by dividing it into patches."""
|
| 130 |
+
if not isinstance(grid_pinpoints, list):
|
| 131 |
+
raise TypeError("grid_pinpoints must be a list of possible resolutions.")
|
| 132 |
+
|
| 133 |
+
possible_resolutions = grid_pinpoints
|
| 134 |
+
|
| 135 |
+
image_size = image.shape[-2:]
|
| 136 |
+
best_resolution = select_best_resolution(image_size, possible_resolutions)
|
| 137 |
+
resized_image = self._resize_for_patching(image, best_resolution, resample=resample)
|
| 138 |
+
padded_image = self._pad_for_patching(resized_image, best_resolution)
|
| 139 |
+
|
| 140 |
+
patches = divide_to_patches(padded_image, patch_size=patch_size)
|
| 141 |
+
|
| 142 |
+
size_height, size_width = size
|
| 143 |
+
resized_original_image = self.resize(
|
| 144 |
+
image=image,
|
| 145 |
+
size=SizeDict(height=size_height, width=size_width),
|
| 146 |
+
resample=resample,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
image_patches = [resized_original_image] + patches
|
| 150 |
+
|
| 151 |
+
return image_patches
|
| 152 |
+
|
| 153 |
+
def _pad_for_batching(
|
| 154 |
+
self,
|
| 155 |
+
pixel_values: list[np.ndarray],
|
| 156 |
+
) -> list[np.ndarray]:
|
| 157 |
+
"""Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches."""
|
| 158 |
+
max_patch = max(len(x) for x in pixel_values)
|
| 159 |
+
# Use np.pad directly for patch dimension padding
|
| 160 |
+
padded_values = []
|
| 161 |
+
for image in pixel_values:
|
| 162 |
+
# Padding format: ((before_dim0, after_dim0), (before_dim1, after_dim1), ...)
|
| 163 |
+
padding = ((0, max_patch - image.shape[0]), (0, 0), (0, 0), (0, 0))
|
| 164 |
+
padded_image = np.pad(image, padding, mode="constant", constant_values=0)
|
| 165 |
+
padded_values.append(padded_image)
|
| 166 |
+
|
| 167 |
+
return padded_values
|
| 168 |
+
|
| 169 |
+
def _preprocess(
|
| 170 |
+
self,
|
| 171 |
+
images: list[np.ndarray],
|
| 172 |
+
batch_num_images: list[int],
|
| 173 |
+
do_resize: bool,
|
| 174 |
+
size: SizeDict,
|
| 175 |
+
image_grid_pinpoints: list[list[int]],
|
| 176 |
+
resample: "PILImageResampling | None",
|
| 177 |
+
do_center_crop: bool,
|
| 178 |
+
crop_size: SizeDict,
|
| 179 |
+
do_rescale: bool,
|
| 180 |
+
rescale_factor: float,
|
| 181 |
+
do_normalize: bool,
|
| 182 |
+
image_mean: float | list[float] | None,
|
| 183 |
+
image_std: float | list[float] | None,
|
| 184 |
+
do_pad: bool | None,
|
| 185 |
+
pad_size: SizeDict | None,
|
| 186 |
+
disable_grouping: bool | None,
|
| 187 |
+
return_tensors: str | TensorType | None,
|
| 188 |
+
**kwargs,
|
| 189 |
+
) -> BatchFeature:
|
| 190 |
+
"""Custom preprocessing for LLaVA-NeXT with patch processing."""
|
| 191 |
+
processed_images = []
|
| 192 |
+
image_sizes = []
|
| 193 |
+
# only single image patching is supported
|
| 194 |
+
need_patching = [n == 1 for n in batch_num_images for _ in range(n)]
|
| 195 |
+
|
| 196 |
+
# Backend's resize method handles resample conversion, so we can pass it directly
|
| 197 |
+
# Determine the size tuple
|
| 198 |
+
if size and size.height and size.width:
|
| 199 |
+
size_tuple = (size.height, size.width)
|
| 200 |
+
else:
|
| 201 |
+
size_tuple = (size.shortest_edge, size.shortest_edge)
|
| 202 |
+
|
| 203 |
+
# Determine the patch size
|
| 204 |
+
if crop_size and crop_size.height:
|
| 205 |
+
patch_size = crop_size.height
|
| 206 |
+
elif size and size.height:
|
| 207 |
+
patch_size = size.height
|
| 208 |
+
else:
|
| 209 |
+
patch_size = size.shortest_edge
|
| 210 |
+
|
| 211 |
+
for i, image in enumerate(images):
|
| 212 |
+
if need_patching[i]:
|
| 213 |
+
# convert image into a list of patches
|
| 214 |
+
# we intentionally use the same data format as the input data format
|
| 215 |
+
image_patches = self.get_image_patches(
|
| 216 |
+
image,
|
| 217 |
+
image_grid_pinpoints,
|
| 218 |
+
size=size_tuple,
|
| 219 |
+
patch_size=patch_size,
|
| 220 |
+
resample=resample,
|
| 221 |
+
)
|
| 222 |
+
else:
|
| 223 |
+
padded_image = self.pad_to_square(
|
| 224 |
+
image=image, background_color=tuple(int(x * 255) for x in self.image_mean)
|
| 225 |
+
)
|
| 226 |
+
image_patches = [padded_image]
|
| 227 |
+
|
| 228 |
+
# preprocess patches
|
| 229 |
+
pixel_values = []
|
| 230 |
+
for patch in image_patches:
|
| 231 |
+
if do_resize:
|
| 232 |
+
patch = self.resize(image=patch, size=size, resample=resample)
|
| 233 |
+
|
| 234 |
+
if do_center_crop:
|
| 235 |
+
patch = self.center_crop(image=patch, size=crop_size)
|
| 236 |
+
|
| 237 |
+
if do_rescale:
|
| 238 |
+
patch = self.rescale(image=patch, scale=rescale_factor)
|
| 239 |
+
|
| 240 |
+
if do_normalize:
|
| 241 |
+
patch = self.normalize(image=patch, mean=image_mean, std=image_std)
|
| 242 |
+
|
| 243 |
+
pixel_values.append(patch)
|
| 244 |
+
|
| 245 |
+
pixel_values = np.array(pixel_values)
|
| 246 |
+
processed_images.append(pixel_values)
|
| 247 |
+
image_sizes.append(image.shape[-2:])
|
| 248 |
+
|
| 249 |
+
if do_pad:
|
| 250 |
+
processed_images = self._pad_for_batching(processed_images)
|
| 251 |
+
|
| 252 |
+
return BatchFeature(
|
| 253 |
+
data={
|
| 254 |
+
"pixel_values": processed_images,
|
| 255 |
+
"image_sizes": image_sizes,
|
| 256 |
+
"batch_num_images": batch_num_images,
|
| 257 |
+
},
|
| 258 |
+
tensor_type=return_tensors,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def pad_to_square(
|
| 262 |
+
self,
|
| 263 |
+
image: np.ndarray,
|
| 264 |
+
background_color: int | tuple[int, int, int] = 0,
|
| 265 |
+
) -> np.ndarray:
|
| 266 |
+
"""
|
| 267 |
+
Pads an image to a square based on the longest edge.
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
image (`np.ndarray`):
|
| 271 |
+
The image to pad. Shape: (num_channels, height, width) - always channels_first in backend.
|
| 272 |
+
background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0):
|
| 273 |
+
The color to use for the padding.
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
`np.ndarray`: The padded image.
|
| 277 |
+
"""
|
| 278 |
+
# Backend always uses channels_first format: (num_channels, height, width)
|
| 279 |
+
num_channels, height, width = image.shape
|
| 280 |
+
|
| 281 |
+
if height == width:
|
| 282 |
+
return image
|
| 283 |
+
|
| 284 |
+
max_dim = max(height, width)
|
| 285 |
+
|
| 286 |
+
# Ensure background_color is the correct shape
|
| 287 |
+
if isinstance(background_color, int):
|
| 288 |
+
background_color = [background_color]
|
| 289 |
+
elif len(background_color) != num_channels:
|
| 290 |
+
raise ValueError(
|
| 291 |
+
f"background_color must have no more than {num_channels} elements to match the number of channels"
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
result = np.zeros((num_channels, max_dim, max_dim), dtype=image.dtype)
|
| 295 |
+
for i, color in enumerate(background_color):
|
| 296 |
+
result[i, :, :] = color
|
| 297 |
+
if width > height:
|
| 298 |
+
start = (max_dim - height) // 2
|
| 299 |
+
result[:, start : start + height, :] = image
|
| 300 |
+
else:
|
| 301 |
+
start = (max_dim - width) // 2
|
| 302 |
+
result[:, :, start : start + width] = image
|
| 303 |
+
|
| 304 |
+
return result
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
__all__ = ["LlavaOnevisionImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/modeling_llava_onevision.py
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/llava_onevision/modular_llava_onevision.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_llava_onevision.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
import math
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
|
| 28 |
+
from ... import initialization as init
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...cache_utils import Cache
|
| 31 |
+
from ...generation import GenerationMixin
|
| 32 |
+
from ...image_processing_utils import select_best_resolution
|
| 33 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 34 |
+
from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
|
| 35 |
+
from ...modeling_utils import PreTrainedModel
|
| 36 |
+
from ...processing_utils import Unpack
|
| 37 |
+
from ...utils import TransformersKwargs, auto_docstring, torch_compilable_check
|
| 38 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 39 |
+
from ..auto import AutoModel
|
| 40 |
+
from .configuration_llava_onevision import LlavaOnevisionConfig
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@auto_docstring(
|
| 44 |
+
custom_intro="""
|
| 45 |
+
Base class for Llava outputs, with hidden states and attentions.
|
| 46 |
+
"""
|
| 47 |
+
)
|
| 48 |
+
@dataclass
|
| 49 |
+
class LlavaOnevisionModelOutputWithPast(BaseModelOutputWithPast):
|
| 50 |
+
r"""
|
| 51 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 52 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 53 |
+
|
| 54 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 55 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 56 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 57 |
+
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
|
| 58 |
+
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 59 |
+
video_hidden_states (`torch.FloatTensor`, *optional*):
|
| 60 |
+
A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
|
| 61 |
+
video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 65 |
+
|
| 66 |
+
video_hidden_states: torch.FloatTensor | None = None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@auto_docstring(
|
| 70 |
+
custom_intro="""
|
| 71 |
+
Base class for LlavaOnevision causal language model (or autoregressive) outputs.
|
| 72 |
+
"""
|
| 73 |
+
)
|
| 74 |
+
@dataclass
|
| 75 |
+
class LlavaOnevisionCausalLMOutputWithPast(ModelOutput):
|
| 76 |
+
r"""
|
| 77 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 78 |
+
Language modeling loss (for next-token prediction).
|
| 79 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 80 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 81 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 82 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 83 |
+
|
| 84 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 85 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 86 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 87 |
+
A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
|
| 88 |
+
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 89 |
+
video_hidden_states (`torch.FloatTensor`, *optional*):
|
| 90 |
+
A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
|
| 91 |
+
video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
loss: torch.FloatTensor | None = None
|
| 95 |
+
logits: torch.FloatTensor | None = None
|
| 96 |
+
past_key_values: Cache | None = None
|
| 97 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 98 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 99 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 100 |
+
|
| 101 |
+
video_hidden_states: torch.FloatTensor | None = None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@auto_docstring
|
| 105 |
+
class LlavaOnevisionPreTrainedModel(PreTrainedModel):
|
| 106 |
+
config: LlavaOnevisionConfig
|
| 107 |
+
base_model_prefix = "model"
|
| 108 |
+
input_modalities = ("image", "video", "text")
|
| 109 |
+
supports_gradient_checkpointing = True
|
| 110 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
| 111 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 112 |
+
|
| 113 |
+
_supports_flash_attn = True
|
| 114 |
+
_supports_sdpa = True
|
| 115 |
+
|
| 116 |
+
_can_compile_fullgraph = True
|
| 117 |
+
_supports_flex_attn = True
|
| 118 |
+
_supports_attention_backend = True
|
| 119 |
+
_can_record_outputs = {
|
| 120 |
+
"hidden_states": "LlamaDecoderLayer",
|
| 121 |
+
"attentions": "LlamaAttention",
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
@torch.no_grad()
|
| 125 |
+
def _init_weights(self, module):
|
| 126 |
+
super()._init_weights(module)
|
| 127 |
+
if isinstance(module, LlavaOnevisionModel):
|
| 128 |
+
embed_std = 1 / math.sqrt(self.config.text_config.hidden_size)
|
| 129 |
+
init.normal_(module.image_newline, mean=0.0, std=embed_std)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class LlavaOnevisionMultiModalProjector(nn.Module):
|
| 133 |
+
def __init__(self, config: LlavaOnevisionConfig):
|
| 134 |
+
super().__init__()
|
| 135 |
+
# We have hidden_size * the number of vision feature layers
|
| 136 |
+
num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
|
| 137 |
+
self.linear_1 = nn.Linear(
|
| 138 |
+
config.vision_config.hidden_size * num_feature_layers,
|
| 139 |
+
config.text_config.hidden_size,
|
| 140 |
+
bias=config.multimodal_projector_bias,
|
| 141 |
+
)
|
| 142 |
+
self.act = ACT2FN[config.projector_hidden_act]
|
| 143 |
+
self.linear_2 = nn.Linear(
|
| 144 |
+
config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def forward(self, image_features):
|
| 148 |
+
hidden_states = self.linear_1(image_features)
|
| 149 |
+
hidden_states = self.act(hidden_states)
|
| 150 |
+
hidden_states = self.linear_2(hidden_states)
|
| 151 |
+
return hidden_states
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
|
| 155 |
+
"""
|
| 156 |
+
Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
image_size (`tuple`):
|
| 160 |
+
The size of the input image in the format (width, height).
|
| 161 |
+
grid_pinpoints (`List`):
|
| 162 |
+
A list containing possible resolutions. Each item in the list should be a tuple or list
|
| 163 |
+
of the form `(height, width)`.
|
| 164 |
+
patch_size (`int`):
|
| 165 |
+
The size of each image patch.
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
tuple: The shape of the image patch grid in the format (width, height).
|
| 169 |
+
"""
|
| 170 |
+
if not isinstance(grid_pinpoints, list):
|
| 171 |
+
raise TypeError("grid_pinpoints should be a list of tuples or lists")
|
| 172 |
+
|
| 173 |
+
# ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
|
| 174 |
+
if not isinstance(image_size, (list, tuple)):
|
| 175 |
+
if not isinstance(image_size, (torch.Tensor, np.ndarray)):
|
| 176 |
+
raise TypeError(
|
| 177 |
+
f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
|
| 178 |
+
)
|
| 179 |
+
image_size = image_size.tolist()
|
| 180 |
+
|
| 181 |
+
height, width = select_best_resolution(image_size, grid_pinpoints)
|
| 182 |
+
return height // patch_size, width // patch_size
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
|
| 186 |
+
"""
|
| 187 |
+
Calculate the number of patches after the preprocessing for images of any resolution.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
image_size (`torch.LongTensor` or `np.ndarray` or `tuple[int, int]`):
|
| 191 |
+
The size of the input image in the format (height, width). ?
|
| 192 |
+
grid_pinpoints (`List`):
|
| 193 |
+
A list containing possible resolutions. Each item in the list should be a tuple or list
|
| 194 |
+
of the form `(height, width)`.
|
| 195 |
+
patch_size (`int`):
|
| 196 |
+
The size of each image patch.
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
int: the number of patches
|
| 200 |
+
"""
|
| 201 |
+
if not isinstance(grid_pinpoints, list):
|
| 202 |
+
raise TypeError("grid_pinpoints should be a list of tuples or lists")
|
| 203 |
+
|
| 204 |
+
# ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
|
| 205 |
+
if not isinstance(image_size, (list, tuple)):
|
| 206 |
+
if not isinstance(image_size, (torch.Tensor, np.ndarray)):
|
| 207 |
+
raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
|
| 208 |
+
image_size = image_size.tolist()
|
| 209 |
+
|
| 210 |
+
best_resolution = select_best_resolution(image_size, grid_pinpoints)
|
| 211 |
+
height, width = best_resolution
|
| 212 |
+
num_patches = 0
|
| 213 |
+
# consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
|
| 214 |
+
for i in range(0, height, patch_size):
|
| 215 |
+
for j in range(0, width, patch_size):
|
| 216 |
+
num_patches += 1
|
| 217 |
+
# add the base patch
|
| 218 |
+
num_patches += 1
|
| 219 |
+
return num_patches
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def unpad_image(tensor, original_size):
|
| 223 |
+
"""
|
| 224 |
+
Unpads a PyTorch tensor of a padded and resized image.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
tensor (`torch.Tensor`):
|
| 228 |
+
The image tensor, assumed to be of shape (num_channels, height, width).
|
| 229 |
+
original_size (`tuple`):
|
| 230 |
+
The original size of the image (height, width).
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
`torch.Tensor`: The unpadded image tensor.
|
| 234 |
+
"""
|
| 235 |
+
if not isinstance(original_size, (list, tuple)):
|
| 236 |
+
if not isinstance(original_size, (torch.Tensor, np.ndarray)):
|
| 237 |
+
raise TypeError(
|
| 238 |
+
f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
|
| 239 |
+
)
|
| 240 |
+
original_size = original_size.tolist()
|
| 241 |
+
original_height, original_width = original_size
|
| 242 |
+
current_height, current_width = tensor.shape[1:]
|
| 243 |
+
|
| 244 |
+
original_aspect_ratio = original_width / original_height
|
| 245 |
+
current_aspect_ratio = current_width / current_height
|
| 246 |
+
|
| 247 |
+
if original_aspect_ratio > current_aspect_ratio:
|
| 248 |
+
scale_factor = current_width / original_width
|
| 249 |
+
new_height = int(round(original_height * scale_factor, 7))
|
| 250 |
+
padding = (current_height - new_height) // 2
|
| 251 |
+
unpadded_tensor = tensor[:, padding : current_height - padding, :]
|
| 252 |
+
else:
|
| 253 |
+
scale_factor = current_height / original_height
|
| 254 |
+
new_width = int(round(original_width * scale_factor, 7))
|
| 255 |
+
padding = (current_width - new_width) // 2
|
| 256 |
+
unpadded_tensor = tensor[:, :, padding : current_width - padding]
|
| 257 |
+
|
| 258 |
+
return unpadded_tensor
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@auto_docstring(
|
| 262 |
+
custom_intro="""
|
| 263 |
+
The Llava-Next model which consists of a vision backbone and a language model without language modeling head.
|
| 264 |
+
"""
|
| 265 |
+
)
|
| 266 |
+
class LlavaOnevisionModel(LlavaOnevisionPreTrainedModel):
|
| 267 |
+
base_model_prefix = "model"
|
| 268 |
+
|
| 269 |
+
def __init__(self, config):
|
| 270 |
+
super().__init__(config)
|
| 271 |
+
self.vision_tower = AutoModel.from_config(config.vision_config)
|
| 272 |
+
|
| 273 |
+
self.multi_modal_projector = LlavaOnevisionMultiModalProjector(config)
|
| 274 |
+
embed_std = 1 / math.sqrt(config.text_config.hidden_size)
|
| 275 |
+
self.image_newline = nn.Parameter(torch.randn(config.text_config.hidden_size, dtype=self.dtype) * embed_std)
|
| 276 |
+
|
| 277 |
+
self.vocab_size = config.text_config.vocab_size
|
| 278 |
+
self.language_model = AutoModel.from_config(config.text_config)
|
| 279 |
+
self.post_init()
|
| 280 |
+
|
| 281 |
+
def pack_image_features(self, image_features, image_sizes, image_newline=None, vision_aspect_ratio="anyres_max_9"):
|
| 282 |
+
"""
|
| 283 |
+
Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
image_features (`list[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
|
| 287 |
+
List of image feature tensor, each contains all the visual feature of all patches.
|
| 288 |
+
image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
|
| 289 |
+
Actual image size of each images (H, W).
|
| 290 |
+
image_newline (`torch.Tensor` of shape `(embed_dim)`)
|
| 291 |
+
New line embedding vector.
|
| 292 |
+
vision_aspect_ratio (`str`, *optional*, "anyres_max_9"):
|
| 293 |
+
Aspect ratio used when processing image features. The default value is "anyres_max_9".
|
| 294 |
+
Returns:
|
| 295 |
+
image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
|
| 296 |
+
feature_lens (`list[int]`)
|
| 297 |
+
token length of each image in image_features
|
| 298 |
+
"""
|
| 299 |
+
new_image_features = []
|
| 300 |
+
feature_lens = []
|
| 301 |
+
for image_idx, image_feature in enumerate(image_features):
|
| 302 |
+
if image_feature.shape[0] > 1:
|
| 303 |
+
base_image_feature = image_feature[0]
|
| 304 |
+
image_feature = image_feature[1:]
|
| 305 |
+
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
|
| 306 |
+
if height * width != base_image_feature.shape[0]:
|
| 307 |
+
raise ValueError("The number of patches is not consistent with the image size.")
|
| 308 |
+
num_patch_height, num_patch_width = get_anyres_image_grid_shape(
|
| 309 |
+
image_sizes[image_idx],
|
| 310 |
+
self.config.image_grid_pinpoints,
|
| 311 |
+
self.config.vision_config.image_size,
|
| 312 |
+
)
|
| 313 |
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
| 314 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 315 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 316 |
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
| 317 |
+
max_num_patches = int(vision_aspect_ratio.strip("anyres_max_"))
|
| 318 |
+
channels, curr_height, curr_width = image_feature.shape
|
| 319 |
+
ratio = math.sqrt(curr_height * curr_width / (max_num_patches * height**2))
|
| 320 |
+
if ratio > 1.1:
|
| 321 |
+
image_feature = image_feature[None]
|
| 322 |
+
image_feature = nn.functional.interpolate(
|
| 323 |
+
image_feature, [int(curr_height // ratio), int(curr_width // ratio)], mode="bilinear"
|
| 324 |
+
)[0]
|
| 325 |
+
if image_newline is not None:
|
| 326 |
+
image_feature = torch.cat(
|
| 327 |
+
(
|
| 328 |
+
image_feature,
|
| 329 |
+
image_newline[:, None, None]
|
| 330 |
+
.expand(*image_feature.shape[:-1], 1)
|
| 331 |
+
.to(image_feature.device, image_feature.dtype),
|
| 332 |
+
),
|
| 333 |
+
dim=-1,
|
| 334 |
+
)
|
| 335 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 336 |
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
| 337 |
+
else:
|
| 338 |
+
image_feature = image_feature[0]
|
| 339 |
+
if image_newline is not None:
|
| 340 |
+
image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
|
| 341 |
+
new_image_features.append(image_feature)
|
| 342 |
+
feature_lens.append(image_feature.size(0))
|
| 343 |
+
feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features[0].device)
|
| 344 |
+
return new_image_features, feature_lens
|
| 345 |
+
|
| 346 |
+
@merge_with_config_defaults
|
| 347 |
+
@can_return_tuple
|
| 348 |
+
@auto_docstring(
|
| 349 |
+
custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
|
| 350 |
+
)
|
| 351 |
+
def get_image_features(
|
| 352 |
+
self,
|
| 353 |
+
pixel_values: torch.FloatTensor,
|
| 354 |
+
image_sizes: torch.Tensor,
|
| 355 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 356 |
+
vision_feature_select_strategy: str | None = None,
|
| 357 |
+
vision_aspect_ratio: str | None = None,
|
| 358 |
+
batch_num_images: torch.LongTensor | None = None,
|
| 359 |
+
output_hidden_states: bool | None = None,
|
| 360 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 361 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 362 |
+
r"""
|
| 363 |
+
image_sizes (`torch.Tensor` of shape `(num_images, 2)`):
|
| 364 |
+
Actual image size of each images (H, W).
|
| 365 |
+
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
|
| 366 |
+
Aspect ratio used when processing image features. The default value is "anyres_max_9".
|
| 367 |
+
batch_num_images (`torch.LongTensor`, *optional*):
|
| 368 |
+
Number of images in each sample.
|
| 369 |
+
"""
|
| 370 |
+
# ! infer image_num_patches from image_sizes
|
| 371 |
+
if batch_num_images is None:
|
| 372 |
+
# treat this as a single-image case for backward compatibility
|
| 373 |
+
need_patching = [True] * len(image_sizes)
|
| 374 |
+
else:
|
| 375 |
+
need_patching = [n == 1 for n in batch_num_images for _ in range(n)]
|
| 376 |
+
image_num_patches = [
|
| 377 |
+
image_size_to_num_patches(
|
| 378 |
+
image_size=imsize,
|
| 379 |
+
grid_pinpoints=self.config.image_grid_pinpoints,
|
| 380 |
+
patch_size=self.config.vision_config.image_size,
|
| 381 |
+
)
|
| 382 |
+
if should_patch
|
| 383 |
+
else 1
|
| 384 |
+
for imsize, should_patch in zip(image_sizes, need_patching)
|
| 385 |
+
]
|
| 386 |
+
if pixel_values.dim() == 5:
|
| 387 |
+
# stacked if input is (batch_size, num_patches, num_channels, height, width)
|
| 388 |
+
_pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
|
| 389 |
+
pixel_values = torch.cat(_pixel_values_list, dim=0)
|
| 390 |
+
elif pixel_values.dim() != 4:
|
| 391 |
+
# otherwise has to be stacked from list of (num_patches, num_channels, height, width)
|
| 392 |
+
raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
|
| 393 |
+
|
| 394 |
+
image_outputs = self.vision_tower(
|
| 395 |
+
pixel_values,
|
| 396 |
+
output_hidden_states=True, # Ignore arg on purpose
|
| 397 |
+
return_dict=True,
|
| 398 |
+
**kwargs,
|
| 399 |
+
)
|
| 400 |
+
# If we have one vision feature layer, return the corresponding hidden states,
|
| 401 |
+
# otherwise, select the hidden states of each feature layer and concatenate them
|
| 402 |
+
if isinstance(vision_feature_layer, int):
|
| 403 |
+
selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
|
| 404 |
+
else:
|
| 405 |
+
hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
|
| 406 |
+
selected_image_feature = torch.cat(hs_pool, dim=-1)
|
| 407 |
+
|
| 408 |
+
if vision_feature_select_strategy == "default":
|
| 409 |
+
selected_image_feature = selected_image_feature[:, 1:]
|
| 410 |
+
image_features = self.multi_modal_projector(selected_image_feature)
|
| 411 |
+
image_features = torch.split(image_features, image_num_patches, dim=0)
|
| 412 |
+
|
| 413 |
+
image_features, feature_lens = self.pack_image_features(
|
| 414 |
+
image_features,
|
| 415 |
+
image_sizes,
|
| 416 |
+
image_newline=self.image_newline,
|
| 417 |
+
vision_aspect_ratio=vision_aspect_ratio,
|
| 418 |
+
)
|
| 419 |
+
image_outputs.pooler_output = image_features
|
| 420 |
+
|
| 421 |
+
return image_outputs
|
| 422 |
+
|
| 423 |
+
def get_placeholder_mask(
|
| 424 |
+
self,
|
| 425 |
+
input_ids: torch.LongTensor,
|
| 426 |
+
inputs_embeds: torch.FloatTensor,
|
| 427 |
+
image_features: torch.FloatTensor | None = None,
|
| 428 |
+
video_features: torch.FloatTensor | None = None,
|
| 429 |
+
):
|
| 430 |
+
"""
|
| 431 |
+
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
|
| 432 |
+
equal to the length of multimodal features. If the lengths are different, an error is raised.
|
| 433 |
+
"""
|
| 434 |
+
if input_ids is None:
|
| 435 |
+
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 436 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 437 |
+
)
|
| 438 |
+
special_image_mask = special_image_mask.all(-1)
|
| 439 |
+
special_video_mask = inputs_embeds == self.get_input_embeddings()(
|
| 440 |
+
torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 441 |
+
)
|
| 442 |
+
special_video_mask = special_video_mask.all(-1)
|
| 443 |
+
else:
|
| 444 |
+
special_image_mask = input_ids == self.config.image_token_id
|
| 445 |
+
special_video_mask = input_ids == self.config.video_token_id
|
| 446 |
+
|
| 447 |
+
n_image_tokens = special_image_mask.sum()
|
| 448 |
+
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 449 |
+
if image_features is not None:
|
| 450 |
+
torch_compilable_check(
|
| 451 |
+
inputs_embeds[special_image_mask].numel() == image_features.numel(),
|
| 452 |
+
f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}",
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
n_video_tokens = special_video_mask.sum()
|
| 456 |
+
special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 457 |
+
if video_features is not None:
|
| 458 |
+
torch_compilable_check(
|
| 459 |
+
inputs_embeds[special_video_mask].numel() == video_features.numel(),
|
| 460 |
+
f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0]}",
|
| 461 |
+
)
|
| 462 |
+
return special_image_mask, special_video_mask
|
| 463 |
+
|
| 464 |
+
@merge_with_config_defaults
|
| 465 |
+
@can_return_tuple
|
| 466 |
+
@auto_docstring
|
| 467 |
+
def forward(
|
| 468 |
+
self,
|
| 469 |
+
input_ids: torch.LongTensor | None = None,
|
| 470 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 471 |
+
image_sizes: torch.LongTensor | None = None,
|
| 472 |
+
pixel_values_videos: torch.FloatTensor | None = None,
|
| 473 |
+
image_sizes_videos: torch.LongTensor | None = None,
|
| 474 |
+
attention_mask: torch.Tensor | None = None,
|
| 475 |
+
position_ids: torch.LongTensor | None = None,
|
| 476 |
+
past_key_values: Cache | None = None,
|
| 477 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 478 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 479 |
+
vision_feature_select_strategy: str | None = None,
|
| 480 |
+
vision_aspect_ratio: str | None = None,
|
| 481 |
+
batch_num_images: torch.LongTensor | None = None,
|
| 482 |
+
use_cache: bool | None = None,
|
| 483 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 484 |
+
) -> tuple | LlavaOnevisionModelOutputWithPast:
|
| 485 |
+
r"""
|
| 486 |
+
image_sizes_videos (`torch.LongTensor` of shape `(batch_size, frames, 2)`, *optional*):
|
| 487 |
+
The sizes of the videos in the batch, being (height, width) for each frame in the video.
|
| 488 |
+
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
|
| 489 |
+
Aspect ratio used when processing image features. The default value is "anyres_max_9".
|
| 490 |
+
batch_num_images (`torch.LongTensor`, *optional*):
|
| 491 |
+
Number of images in each sample.
|
| 492 |
+
"""
|
| 493 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 494 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 495 |
+
|
| 496 |
+
if inputs_embeds is None:
|
| 497 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 498 |
+
|
| 499 |
+
image_features = None
|
| 500 |
+
if pixel_values is not None:
|
| 501 |
+
image_features = self.get_image_features(
|
| 502 |
+
pixel_values,
|
| 503 |
+
image_sizes,
|
| 504 |
+
vision_feature_layer=vision_feature_layer,
|
| 505 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 506 |
+
batch_num_images=batch_num_images,
|
| 507 |
+
return_dict=True,
|
| 508 |
+
).pooler_output
|
| 509 |
+
image_features = torch.cat(image_features, dim=0)
|
| 510 |
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 511 |
+
special_image_mask, _ = self.get_placeholder_mask(
|
| 512 |
+
input_ids, inputs_embeds=inputs_embeds, image_features=image_features
|
| 513 |
+
)
|
| 514 |
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
| 515 |
+
|
| 516 |
+
video_features = None
|
| 517 |
+
if pixel_values_videos is not None:
|
| 518 |
+
video_features = self.get_video_features(
|
| 519 |
+
pixel_values_videos,
|
| 520 |
+
vision_feature_layer=vision_feature_layer,
|
| 521 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 522 |
+
return_dict=True,
|
| 523 |
+
).pooler_output
|
| 524 |
+
image_newline = (
|
| 525 |
+
self.image_newline[None, None, :].repeat(video_features.shape[0], 1, 1).to(video_features.device)
|
| 526 |
+
)
|
| 527 |
+
video_features = torch.cat((video_features, image_newline), dim=1)
|
| 528 |
+
video_features = video_features.flatten(0, 1).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 529 |
+
_, special_video_mask = self.get_placeholder_mask(
|
| 530 |
+
input_ids, inputs_embeds=inputs_embeds, video_features=video_features
|
| 531 |
+
)
|
| 532 |
+
inputs_embeds = inputs_embeds.masked_scatter(special_video_mask, video_features)
|
| 533 |
+
|
| 534 |
+
outputs = self.language_model(
|
| 535 |
+
attention_mask=attention_mask,
|
| 536 |
+
position_ids=position_ids,
|
| 537 |
+
past_key_values=past_key_values,
|
| 538 |
+
inputs_embeds=inputs_embeds,
|
| 539 |
+
use_cache=use_cache,
|
| 540 |
+
**kwargs,
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
return LlavaOnevisionModelOutputWithPast(
|
| 544 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 545 |
+
past_key_values=outputs.past_key_values,
|
| 546 |
+
hidden_states=outputs.hidden_states,
|
| 547 |
+
attentions=outputs.attentions,
|
| 548 |
+
image_hidden_states=image_features,
|
| 549 |
+
video_hidden_states=video_features,
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
@merge_with_config_defaults
|
| 553 |
+
@can_return_tuple
|
| 554 |
+
@auto_docstring(
|
| 555 |
+
custom_intro="Obtains video last hidden states from the vision tower, apply multimodal projection and pooling."
|
| 556 |
+
)
|
| 557 |
+
def get_video_features(
|
| 558 |
+
self,
|
| 559 |
+
pixel_values: torch.FloatTensor,
|
| 560 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 561 |
+
vision_feature_select_strategy: str | None = None,
|
| 562 |
+
output_hidden_states: bool | None = None,
|
| 563 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 564 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 565 |
+
r"""
|
| 566 |
+
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
|
| 567 |
+
The tensors corresponding to the input video.
|
| 568 |
+
vision_feature_layer (`Union[int, list[int]], *optional*, defaults to -2`):
|
| 569 |
+
The index of the layer to select the vision feature. If multiple indices are provided,
|
| 570 |
+
the vision feature of the corresponding indices will be concatenated to form the
|
| 571 |
+
vision features.
|
| 572 |
+
vision_feature_select_strategy (`str`):
|
| 573 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 574 |
+
Can be one of `"default"` or `"full"`
|
| 575 |
+
"""
|
| 576 |
+
batch_size, frames, channels, height, width = pixel_values.shape
|
| 577 |
+
pixel_values = pixel_values.view(batch_size * frames, channels, height, width)
|
| 578 |
+
vision_outputs = self.vision_tower(
|
| 579 |
+
pixel_values,
|
| 580 |
+
output_hidden_states=True, # Ignore arg on purpose
|
| 581 |
+
return_dict=True,
|
| 582 |
+
**kwargs,
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
# If we have one vision feature layer, return the corresponding hidden states,
|
| 586 |
+
# otherwise, select the hidden states of each feature layer and concatenate them
|
| 587 |
+
if isinstance(vision_feature_layer, int):
|
| 588 |
+
selected_video_feature = vision_outputs.hidden_states[vision_feature_layer]
|
| 589 |
+
else:
|
| 590 |
+
hs_pool = [vision_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
|
| 591 |
+
selected_video_feature = torch.cat(hs_pool, dim=-1)
|
| 592 |
+
|
| 593 |
+
if vision_feature_select_strategy == "default":
|
| 594 |
+
selected_video_feature = selected_video_feature[:, 1:]
|
| 595 |
+
video_features = self.multi_modal_projector(selected_video_feature)
|
| 596 |
+
|
| 597 |
+
video_features = self.apply_pooling(video_features)
|
| 598 |
+
video_features = video_features.reshape(batch_size, frames * video_features.shape[1], -1)
|
| 599 |
+
vision_outputs.pooler_output = video_features
|
| 600 |
+
|
| 601 |
+
return vision_outputs
|
| 602 |
+
|
| 603 |
+
def apply_pooling(self, image_features):
|
| 604 |
+
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
|
| 605 |
+
batch_frames, seq_len, dim = image_features.shape
|
| 606 |
+
image_features = image_features.view(batch_frames, height, width, -1)
|
| 607 |
+
image_features = image_features.permute(0, 3, 1, 2).contiguous()
|
| 608 |
+
|
| 609 |
+
height, width = image_features.shape[2:]
|
| 610 |
+
scaled_shape = [math.ceil(height / 2), math.ceil(width / 2)]
|
| 611 |
+
image_features = nn.functional.interpolate(image_features, size=scaled_shape, mode="bilinear")
|
| 612 |
+
|
| 613 |
+
image_features = image_features.permute(0, 2, 3, 1)
|
| 614 |
+
image_features = image_features.view(batch_frames, -1, dim)
|
| 615 |
+
return image_features
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
@auto_docstring(
|
| 619 |
+
custom_intro="""
|
| 620 |
+
The LLAVA-NeXT model which consists of a vision backbone and a language model.
|
| 621 |
+
"""
|
| 622 |
+
)
|
| 623 |
+
class LlavaOnevisionForConditionalGeneration(LlavaOnevisionPreTrainedModel, GenerationMixin):
|
| 624 |
+
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
|
| 625 |
+
|
| 626 |
+
def __init__(self, config: LlavaOnevisionConfig):
|
| 627 |
+
super().__init__(config)
|
| 628 |
+
self.model = LlavaOnevisionModel(config)
|
| 629 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
|
| 630 |
+
self.post_init()
|
| 631 |
+
|
| 632 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 633 |
+
return self.lm_head
|
| 634 |
+
|
| 635 |
+
def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
|
| 636 |
+
return self.model.pack_image_features(
|
| 637 |
+
image_features=image_features,
|
| 638 |
+
image_sizes=image_sizes,
|
| 639 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 640 |
+
image_newline=image_newline,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
@merge_with_config_defaults
|
| 644 |
+
@can_return_tuple
|
| 645 |
+
@auto_docstring
|
| 646 |
+
def get_image_features(
|
| 647 |
+
self,
|
| 648 |
+
pixel_values: torch.FloatTensor,
|
| 649 |
+
image_sizes: torch.Tensor,
|
| 650 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 651 |
+
vision_feature_select_strategy: str | None = None,
|
| 652 |
+
vision_aspect_ratio: str | None = None,
|
| 653 |
+
batch_num_images: torch.LongTensor | None = None,
|
| 654 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 655 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 656 |
+
r"""
|
| 657 |
+
image_sizes (`torch.Tensor` of shape `(num_images, 2)`):
|
| 658 |
+
Actual image size of each images (H, W).
|
| 659 |
+
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
|
| 660 |
+
Aspect ratio used when processing image features. The default value is "anyres_max_9".
|
| 661 |
+
batch_num_images (`torch.LongTensor`, *optional*):
|
| 662 |
+
Number of images in each sample.
|
| 663 |
+
"""
|
| 664 |
+
return self.model.get_image_features(
|
| 665 |
+
pixel_values=pixel_values,
|
| 666 |
+
image_sizes=image_sizes,
|
| 667 |
+
vision_feature_layer=vision_feature_layer,
|
| 668 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 669 |
+
vision_aspect_ratio=vision_aspect_ratio,
|
| 670 |
+
batch_num_images=batch_num_images,
|
| 671 |
+
**kwargs,
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
@merge_with_config_defaults
|
| 675 |
+
@can_return_tuple
|
| 676 |
+
@auto_docstring
|
| 677 |
+
def forward(
|
| 678 |
+
self,
|
| 679 |
+
input_ids: torch.LongTensor | None = None,
|
| 680 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 681 |
+
image_sizes: torch.LongTensor | None = None,
|
| 682 |
+
pixel_values_videos: torch.FloatTensor | None = None,
|
| 683 |
+
image_sizes_videos: torch.LongTensor | None = None,
|
| 684 |
+
attention_mask: torch.Tensor | None = None,
|
| 685 |
+
position_ids: torch.LongTensor | None = None,
|
| 686 |
+
past_key_values: Cache | None = None,
|
| 687 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 688 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 689 |
+
vision_feature_select_strategy: str | None = None,
|
| 690 |
+
vision_aspect_ratio: str | None = None,
|
| 691 |
+
batch_num_images: torch.LongTensor | None = None,
|
| 692 |
+
labels: torch.LongTensor | None = None,
|
| 693 |
+
use_cache: bool | None = None,
|
| 694 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 695 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 696 |
+
) -> tuple | LlavaOnevisionCausalLMOutputWithPast:
|
| 697 |
+
r"""
|
| 698 |
+
image_sizes_videos (`torch.LongTensor` of shape `(batch_size, frames, 2)`, *optional*):
|
| 699 |
+
The sizes of the videos in the batch, being (height, width) for each frame in the video.
|
| 700 |
+
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
|
| 701 |
+
Aspect ratio used when processing image features. The default value is "anyres_max_9".
|
| 702 |
+
batch_num_images (`torch.LongTensor`, *optional*):
|
| 703 |
+
Number of images in each sample.
|
| 704 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 705 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 706 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 707 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 708 |
+
|
| 709 |
+
Example:
|
| 710 |
+
|
| 711 |
+
```python
|
| 712 |
+
>>> from PIL import Image
|
| 713 |
+
>>> import httpx
|
| 714 |
+
>>> from io import BytesIO
|
| 715 |
+
>>> import torch
|
| 716 |
+
>>> from transformers import LlavaOnevisionProcessor, LlavaOnevisionForConditionalGeneration
|
| 717 |
+
|
| 718 |
+
>>> model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", dtype="float16", device_map="cuda:0")
|
| 719 |
+
>>> processor = LlavaOnevisionProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf")
|
| 720 |
+
|
| 721 |
+
>>> conversation = [
|
| 722 |
+
... {
|
| 723 |
+
... "role": "user",
|
| 724 |
+
... "content": [
|
| 725 |
+
... {"type": "text", "text": "What is shown in this image?"},
|
| 726 |
+
... {"type": "image"},
|
| 727 |
+
... ],
|
| 728 |
+
... },
|
| 729 |
+
... ]
|
| 730 |
+
>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 731 |
+
|
| 732 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 733 |
+
>>> with httpx.stream("GET", url) as response:
|
| 734 |
+
... image = Image.open(BytesIO(response.read()))
|
| 735 |
+
>>> inputs = processor(text=prompt, images=image, return_tensors='pt').to(0, torch.float16)
|
| 736 |
+
|
| 737 |
+
>>> output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
|
| 738 |
+
>>> processor.batch_decode(output, skip_special_tokens=True)[0]
|
| 739 |
+
"user\n\nWhat is shown in this image?\nassistant\ncat"
|
| 740 |
+
```"""
|
| 741 |
+
outputs = self.model(
|
| 742 |
+
input_ids=input_ids,
|
| 743 |
+
pixel_values=pixel_values,
|
| 744 |
+
pixel_values_videos=pixel_values_videos,
|
| 745 |
+
image_sizes=image_sizes,
|
| 746 |
+
image_sizes_videos=image_sizes_videos,
|
| 747 |
+
vision_aspect_ratio=vision_aspect_ratio,
|
| 748 |
+
vision_feature_layer=vision_feature_layer,
|
| 749 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 750 |
+
batch_num_images=batch_num_images,
|
| 751 |
+
attention_mask=attention_mask,
|
| 752 |
+
position_ids=position_ids,
|
| 753 |
+
past_key_values=past_key_values,
|
| 754 |
+
inputs_embeds=inputs_embeds,
|
| 755 |
+
use_cache=use_cache,
|
| 756 |
+
logits_to_keep=logits_to_keep,
|
| 757 |
+
**kwargs,
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
hidden_states = outputs[0]
|
| 761 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 762 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 763 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 764 |
+
|
| 765 |
+
loss = None
|
| 766 |
+
if labels is not None:
|
| 767 |
+
loss = self.loss_function(
|
| 768 |
+
logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
return LlavaOnevisionCausalLMOutputWithPast(
|
| 772 |
+
loss=loss,
|
| 773 |
+
logits=logits,
|
| 774 |
+
past_key_values=outputs.past_key_values,
|
| 775 |
+
hidden_states=outputs.hidden_states,
|
| 776 |
+
attentions=outputs.attentions,
|
| 777 |
+
image_hidden_states=outputs.image_hidden_states,
|
| 778 |
+
video_hidden_states=outputs.video_hidden_states,
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
def prepare_inputs_for_generation(
|
| 782 |
+
self,
|
| 783 |
+
input_ids,
|
| 784 |
+
past_key_values=None,
|
| 785 |
+
inputs_embeds=None,
|
| 786 |
+
pixel_values=None,
|
| 787 |
+
image_sizes=None,
|
| 788 |
+
pixel_values_videos=None,
|
| 789 |
+
image_sizes_videos=None,
|
| 790 |
+
attention_mask=None,
|
| 791 |
+
logits_to_keep=None,
|
| 792 |
+
is_first_iteration=False,
|
| 793 |
+
**kwargs,
|
| 794 |
+
):
|
| 795 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
| 796 |
+
|
| 797 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 798 |
+
input_ids,
|
| 799 |
+
past_key_values=past_key_values,
|
| 800 |
+
inputs_embeds=inputs_embeds,
|
| 801 |
+
attention_mask=attention_mask,
|
| 802 |
+
logits_to_keep=logits_to_keep,
|
| 803 |
+
is_first_iteration=is_first_iteration,
|
| 804 |
+
**kwargs,
|
| 805 |
+
)
|
| 806 |
+
|
| 807 |
+
if is_first_iteration or not kwargs.get("use_cache", True):
|
| 808 |
+
# Pixel values are used only in the first iteration if available
|
| 809 |
+
# In subsequent iterations, they are already merged with text and cached
|
| 810 |
+
# NOTE: first iteration doesn't have to be prefill, it can be the first
|
| 811 |
+
# iteration with a question and cached system prompt (continue generate from cache)
|
| 812 |
+
model_inputs["pixel_values"] = pixel_values
|
| 813 |
+
model_inputs["image_sizes"] = image_sizes
|
| 814 |
+
model_inputs["pixel_values_videos"] = pixel_values_videos
|
| 815 |
+
model_inputs["image_sizes_videos"] = image_sizes_videos
|
| 816 |
+
|
| 817 |
+
return model_inputs
|
| 818 |
+
|
| 819 |
+
@merge_with_config_defaults
|
| 820 |
+
@can_return_tuple
|
| 821 |
+
@auto_docstring
|
| 822 |
+
def get_video_features(
|
| 823 |
+
self,
|
| 824 |
+
pixel_values: torch.FloatTensor,
|
| 825 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 826 |
+
vision_feature_select_strategy: str | None = None,
|
| 827 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 828 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 829 |
+
r"""
|
| 830 |
+
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
|
| 831 |
+
The tensors corresponding to the input video.
|
| 832 |
+
vision_feature_layer (`Union[int, list[int]]`, *optional;*):
|
| 833 |
+
The index of the layer to select the vision feature. If multiple indices are provided,
|
| 834 |
+
the vision feature of the corresponding indices will be concatenated to form the
|
| 835 |
+
vision features.
|
| 836 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 837 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 838 |
+
Can be one of `"default"` or `"full"`
|
| 839 |
+
"""
|
| 840 |
+
return self.model.get_video_features(
|
| 841 |
+
pixel_values=pixel_values,
|
| 842 |
+
vision_feature_layer=vision_feature_layer,
|
| 843 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 844 |
+
**kwargs,
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
__all__ = ["LlavaOnevisionModel", "LlavaOnevisionForConditionalGeneration", "LlavaOnevisionPreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/processing_llava_onevision.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Processor class for LLaVa-Onevision.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from collections.abc import Iterable
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from ...feature_extraction_utils import BatchFeature
|
| 24 |
+
from ...image_processing_utils import select_best_resolution
|
| 25 |
+
from ...image_utils import ImageInput, get_image_size, to_numpy_array
|
| 26 |
+
from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
|
| 27 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 28 |
+
from ...utils import auto_docstring, logging
|
| 29 |
+
from ...video_utils import VideoInput
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class LlavaOnevisionProcessorKwargs(ProcessingKwargs, total=False):
|
| 36 |
+
# see processing_utils.ProcessingKwargs documentation for usage.
|
| 37 |
+
_defaults = {
|
| 38 |
+
"text_kwargs": {
|
| 39 |
+
"padding": False,
|
| 40 |
+
"return_mm_token_type_ids": False,
|
| 41 |
+
},
|
| 42 |
+
"image_kwargs": {},
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@auto_docstring
|
| 47 |
+
class LlavaOnevisionProcessor(ProcessorMixin):
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
image_processor=None,
|
| 51 |
+
tokenizer=None,
|
| 52 |
+
video_processor=None,
|
| 53 |
+
num_image_tokens=None,
|
| 54 |
+
vision_feature_select_strategy=None,
|
| 55 |
+
chat_template=None,
|
| 56 |
+
image_token="<image>",
|
| 57 |
+
video_token="<video>",
|
| 58 |
+
vision_aspect_ratio="anyres_max_9",
|
| 59 |
+
**kwargs,
|
| 60 |
+
):
|
| 61 |
+
r"""
|
| 62 |
+
num_image_tokens (`int`, *optional*):
|
| 63 |
+
Number of image tokens for one imagethat will be returned by vision tower.
|
| 64 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 65 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 66 |
+
Should be same as in model's config
|
| 67 |
+
image_token (`str`, *optional*, defaults to `"<image>"`):
|
| 68 |
+
Special token used to denote image location.
|
| 69 |
+
video_token (`str`, *optional*, defaults to `"<video>"`):
|
| 70 |
+
Special token used to denote video location.
|
| 71 |
+
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
|
| 72 |
+
Aspect ratio used when processong image features. The default value is "anyres_max_9".
|
| 73 |
+
"""
|
| 74 |
+
self.num_image_tokens = num_image_tokens
|
| 75 |
+
self.vision_feature_select_strategy = vision_feature_select_strategy
|
| 76 |
+
self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
|
| 77 |
+
self.video_token = tokenizer.video_token if hasattr(tokenizer, "video_token") else video_token
|
| 78 |
+
self.image_token_id = (
|
| 79 |
+
tokenizer.image_token_id
|
| 80 |
+
if getattr(tokenizer, "image_token_id", None)
|
| 81 |
+
else tokenizer.convert_tokens_to_ids(self.image_token)
|
| 82 |
+
)
|
| 83 |
+
self.video_token_id = (
|
| 84 |
+
tokenizer.video_token_id
|
| 85 |
+
if getattr(tokenizer, "video_token_id", None)
|
| 86 |
+
else tokenizer.convert_tokens_to_ids(self.video_token)
|
| 87 |
+
)
|
| 88 |
+
self.vision_aspect_ratio = vision_aspect_ratio
|
| 89 |
+
super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
|
| 90 |
+
|
| 91 |
+
@auto_docstring
|
| 92 |
+
def __call__(
|
| 93 |
+
self,
|
| 94 |
+
images: ImageInput | None = None,
|
| 95 |
+
text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
|
| 96 |
+
videos: VideoInput | None = None,
|
| 97 |
+
**kwargs: Unpack[LlavaOnevisionProcessorKwargs],
|
| 98 |
+
) -> BatchFeature:
|
| 99 |
+
r"""
|
| 100 |
+
Returns:
|
| 101 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 102 |
+
|
| 103 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 104 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 105 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 106 |
+
`None`).
|
| 107 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 108 |
+
- **pixel_values_videos** -- Pixel values of a video input to be fed to a model. Returned when `videos` is not `None`.
|
| 109 |
+
- **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
output_kwargs = self._merge_kwargs(
|
| 113 |
+
LlavaOnevisionProcessorKwargs,
|
| 114 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 115 |
+
**kwargs,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if isinstance(text, str):
|
| 119 |
+
text = [text]
|
| 120 |
+
elif not isinstance(text, list) and not isinstance(text[0], str):
|
| 121 |
+
raise TypeError("Invalid input text. Please provide a string, or a list of strings")
|
| 122 |
+
|
| 123 |
+
image_inputs = video_inputs = {}
|
| 124 |
+
|
| 125 |
+
if images is not None:
|
| 126 |
+
image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 127 |
+
|
| 128 |
+
batch_num_images = iter(image_inputs["batch_num_images"])
|
| 129 |
+
image_sizes = iter(image_inputs["image_sizes"])
|
| 130 |
+
height, width = get_image_size(
|
| 131 |
+
to_numpy_array(image_inputs["pixel_values"][0][0]),
|
| 132 |
+
channel_dim=output_kwargs["images_kwargs"].get("data_format"),
|
| 133 |
+
)
|
| 134 |
+
text, num_image_tokens = self._expand_image_tokens(
|
| 135 |
+
text, image_sizes, height, width, self.image_token, batch_num_images
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
if videos is not None:
|
| 139 |
+
video_inputs = self.video_processor(videos, **output_kwargs["videos_kwargs"])
|
| 140 |
+
|
| 141 |
+
one_video = video_inputs.get("pixel_values_videos")[0]
|
| 142 |
+
if isinstance(video_inputs.get("pixel_values_videos")[0], (list, tuple)):
|
| 143 |
+
one_video = np.array(one_video)
|
| 144 |
+
else:
|
| 145 |
+
one_video = to_numpy_array(one_video)
|
| 146 |
+
height, width = get_image_size(one_video[0], channel_dim=output_kwargs["images_kwargs"].get("data_format"))
|
| 147 |
+
num_frames = one_video.shape[0] # frame dim is always after batch dim
|
| 148 |
+
patches_height_width = int(math.sqrt(self.num_image_tokens))
|
| 149 |
+
pooled_height_width = math.ceil(patches_height_width / 2)
|
| 150 |
+
num_video_tokens = (num_frames * pooled_height_width * pooled_height_width) + 1 # +1 for newline token
|
| 151 |
+
text = [sample.replace(self.video_token, self.video_token * num_video_tokens) for sample in text]
|
| 152 |
+
|
| 153 |
+
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
|
| 154 |
+
return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
|
| 155 |
+
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 156 |
+
self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
|
| 157 |
+
|
| 158 |
+
if return_mm_token_type_ids:
|
| 159 |
+
text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
|
| 160 |
+
return BatchFeature(data={**text_inputs, **image_inputs, **video_inputs}, tensor_type=return_tensors)
|
| 161 |
+
|
| 162 |
+
def _expand_image_tokens(
|
| 163 |
+
self,
|
| 164 |
+
text: list[TextInput],
|
| 165 |
+
image_sizes: Iterable[list[int] | int],
|
| 166 |
+
height: int,
|
| 167 |
+
width: int,
|
| 168 |
+
special_token: str,
|
| 169 |
+
batch_num_images: Iterable[int],
|
| 170 |
+
):
|
| 171 |
+
prompt_strings = []
|
| 172 |
+
max_num_vision_tokens = 0
|
| 173 |
+
for sample in text:
|
| 174 |
+
if special_token in sample:
|
| 175 |
+
num_images = next(batch_num_images) # should consume iterable
|
| 176 |
+
is_multi_image = num_images != 1
|
| 177 |
+
else:
|
| 178 |
+
is_multi_image = False
|
| 179 |
+
while special_token in sample:
|
| 180 |
+
original_size = next(image_sizes) # should consume iterable
|
| 181 |
+
if is_multi_image:
|
| 182 |
+
num_image_tokens = self.num_image_tokens + 1 # one for image_newline
|
| 183 |
+
else:
|
| 184 |
+
if not isinstance(original_size, (list, tuple)):
|
| 185 |
+
# cast to list to avoid numerical precision errors when calculating unpadding
|
| 186 |
+
original_size = original_size.tolist()
|
| 187 |
+
orig_height, orig_width = original_size
|
| 188 |
+
num_image_tokens = self._get_number_of_features(orig_height, orig_width, height, width)
|
| 189 |
+
max_num_vision_tokens = max(max_num_vision_tokens, num_image_tokens)
|
| 190 |
+
if self.vision_feature_select_strategy == "default":
|
| 191 |
+
num_image_tokens -= 1
|
| 192 |
+
sample = sample.replace(special_token, "<placeholder>" * num_image_tokens, 1)
|
| 193 |
+
prompt_strings.append(sample)
|
| 194 |
+
text = [sample.replace("<placeholder>", special_token) for sample in prompt_strings]
|
| 195 |
+
return text, max_num_vision_tokens
|
| 196 |
+
|
| 197 |
+
def _get_number_of_features(self, orig_height: int, orig_width: int, height: int, width: int) -> int:
|
| 198 |
+
image_grid_pinpoints = self.image_processor.image_grid_pinpoints
|
| 199 |
+
|
| 200 |
+
height_best_resolution, width_best_resolution = select_best_resolution(
|
| 201 |
+
[orig_height, orig_width], image_grid_pinpoints
|
| 202 |
+
)
|
| 203 |
+
scale_height, scale_width = height_best_resolution // height, width_best_resolution // width
|
| 204 |
+
|
| 205 |
+
patches_height = patches_width = int(math.sqrt(self.num_image_tokens))
|
| 206 |
+
unpadded_features, newline_features = self._get_unpadded_features(
|
| 207 |
+
orig_height, orig_width, patches_height, patches_width, scale_height, scale_width
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# The base patch covers the entire image (no CLS for SigLIP)
|
| 211 |
+
base_features = self.num_image_tokens
|
| 212 |
+
num_image_tokens = unpadded_features + newline_features + base_features
|
| 213 |
+
return num_image_tokens
|
| 214 |
+
|
| 215 |
+
# Adapted from transformers.models.llava_next.processing_llava_next.LlavaNextProcessor._get_unpadded_features
|
| 216 |
+
def _get_unpadded_features(self, height, width, patches_height, patches_width, scale_height, scale_width):
|
| 217 |
+
"""
|
| 218 |
+
Get number of features for a given image with height/width. LLaVA-NeXT is different from LLaVA
|
| 219 |
+
because it divided each image into patches depending on its resolution. Therefore we need to calculate how many
|
| 220 |
+
patches an image is divided into and get the number of features from that.
|
| 221 |
+
"""
|
| 222 |
+
current_height = patches_height * scale_height
|
| 223 |
+
current_width = patches_width * scale_width
|
| 224 |
+
|
| 225 |
+
original_aspect_ratio = width / height
|
| 226 |
+
current_aspect_ratio = current_width / current_height
|
| 227 |
+
if original_aspect_ratio > current_aspect_ratio:
|
| 228 |
+
new_height = int(round(height * (current_width / width), 7))
|
| 229 |
+
padding = (current_height - new_height) // 2
|
| 230 |
+
current_height -= padding * 2
|
| 231 |
+
else:
|
| 232 |
+
new_width = int(round(width * (current_height / height), 7))
|
| 233 |
+
padding = (current_width - new_width) // 2
|
| 234 |
+
current_width -= padding * 2
|
| 235 |
+
|
| 236 |
+
unpadded_features = current_height * current_width
|
| 237 |
+
newline_features = current_height
|
| 238 |
+
|
| 239 |
+
max_num_patches = int(self.vision_aspect_ratio.strip("anyres_max_"))
|
| 240 |
+
ratio = math.sqrt(current_height * current_width / (max_num_patches * patches_height**2))
|
| 241 |
+
if ratio > 1.1:
|
| 242 |
+
unpadded_features = int(current_height // ratio) * int(current_width // ratio)
|
| 243 |
+
newline_features = int(current_height // ratio)
|
| 244 |
+
|
| 245 |
+
return (unpadded_features, newline_features)
|
| 246 |
+
|
| 247 |
+
def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
|
| 248 |
+
"""
|
| 249 |
+
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
|
| 250 |
+
Args:
|
| 251 |
+
image_sizes (list[list[str]], *optional*):
|
| 252 |
+
The input sizes formatted as (height, width) per each image.
|
| 253 |
+
video_sizes (list[list[str]], *optional*):
|
| 254 |
+
The input sizes formatted as (num_frames, height, width) per each video.
|
| 255 |
+
audio_lengths (list[int], *optional*):
|
| 256 |
+
The input length formatted as per each audio.
|
| 257 |
+
Returns:
|
| 258 |
+
dict[str, list[int]]: A dictionary mapping each modality ("image", "video", "audio")
|
| 259 |
+
to a list containing the number of placeholder tokens required. If the model doesn't accept
|
| 260 |
+
a certain modality or no input sizes are provided, the dict value is set to an empty list.
|
| 261 |
+
"""
|
| 262 |
+
vision_data = {}
|
| 263 |
+
if image_sizes is not None:
|
| 264 |
+
images_kwargs = LlavaOnevisionProcessorKwargs._defaults.get("images_kwargs", {})
|
| 265 |
+
images_kwargs.update(kwargs)
|
| 266 |
+
|
| 267 |
+
size = images_kwargs.get("size", None) or self.image_processor.size
|
| 268 |
+
size = (
|
| 269 |
+
(size["shortest_edge"], size["shortest_edge"])
|
| 270 |
+
if "shortest_edge" in size
|
| 271 |
+
else (min(size["height"], size["width"]), min(size["height"], size["width"]))
|
| 272 |
+
)
|
| 273 |
+
processed_height, processed_width = size
|
| 274 |
+
|
| 275 |
+
batch_num_image_tokens = []
|
| 276 |
+
num_image_patches = [1] * len(image_sizes) # llava-ov doesn't batch pixels as Idefics, thus `1` patch`
|
| 277 |
+
for image_size in image_sizes:
|
| 278 |
+
orig_height, orig_width = image_size
|
| 279 |
+
num_image_tokens = self._get_number_of_features(
|
| 280 |
+
orig_height, orig_width, processed_height, processed_width
|
| 281 |
+
)
|
| 282 |
+
if self.vision_feature_select_strategy == "default":
|
| 283 |
+
num_image_tokens -= 1
|
| 284 |
+
batch_num_image_tokens.append(num_image_tokens)
|
| 285 |
+
vision_data.update({"num_image_tokens": batch_num_image_tokens, "num_image_patches": num_image_patches})
|
| 286 |
+
|
| 287 |
+
return MultiModalData(**vision_data)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
__all__ = ["LlavaOnevisionProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/llava_onevision/video_processing_llava_onevision.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 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 |
+
"""Video processor class for LLaVa-Onevision."""
|
| 15 |
+
|
| 16 |
+
from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
|
| 17 |
+
from ...video_processing_utils import BaseVideoProcessor
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class LlavaOnevisionVideoProcessor(BaseVideoProcessor):
|
| 21 |
+
resample = PILImageResampling.BICUBIC
|
| 22 |
+
image_mean = OPENAI_CLIP_MEAN
|
| 23 |
+
image_std = OPENAI_CLIP_STD
|
| 24 |
+
size = {"height": 384, "width": 384}
|
| 25 |
+
rescale_factor = 1 / 255
|
| 26 |
+
default_to_square = False
|
| 27 |
+
crop_size = None
|
| 28 |
+
do_resize = True
|
| 29 |
+
do_center_crop = None
|
| 30 |
+
do_rescale = True
|
| 31 |
+
do_normalize = True
|
| 32 |
+
do_convert_rgb = True
|
| 33 |
+
do_sample_frames = False # Set to False for BC, recommended to set `True` in new models
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
__all__ = ["LlavaOnevisionVideoProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pegasus/configuration_pegasus.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021, Google and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PEGASUS model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="google/pegasus-large")
|
| 23 |
+
@strict
|
| 24 |
+
class PegasusConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
Example:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
>>> from transformers import PegasusConfig, PegasusModel
|
| 30 |
+
|
| 31 |
+
>>> # Initializing a PEGASUS google/pegasus-large style configuration
|
| 32 |
+
>>> configuration = PegasusConfig()
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a model (with random weights) from the google/pegasus-large style configuration
|
| 35 |
+
>>> model = PegasusModel(configuration)
|
| 36 |
+
|
| 37 |
+
>>> # Accessing the model configuration
|
| 38 |
+
>>> configuration = model.config
|
| 39 |
+
```"""
|
| 40 |
+
|
| 41 |
+
model_type = "pegasus"
|
| 42 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 43 |
+
attribute_map = {
|
| 44 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 45 |
+
"hidden_size": "d_model",
|
| 46 |
+
"num_hidden_layers": "encoder_layers",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
vocab_size: int = 50265
|
| 50 |
+
max_position_embeddings: int = 1024
|
| 51 |
+
encoder_layers: int = 12
|
| 52 |
+
encoder_ffn_dim: int = 4096
|
| 53 |
+
encoder_attention_heads: int = 16
|
| 54 |
+
decoder_layers: int = 12
|
| 55 |
+
decoder_ffn_dim: int = 4096
|
| 56 |
+
decoder_attention_heads: int = 16
|
| 57 |
+
encoder_layerdrop: float | int = 0.0
|
| 58 |
+
decoder_layerdrop: float | int = 0.0
|
| 59 |
+
use_cache: bool = True
|
| 60 |
+
is_encoder_decoder: bool = True
|
| 61 |
+
activation_function: str = "gelu"
|
| 62 |
+
d_model: int = 1024
|
| 63 |
+
dropout: float | int = 0.1
|
| 64 |
+
attention_dropout: float | int = 0.0
|
| 65 |
+
activation_dropout: float | int = 0.0
|
| 66 |
+
init_std: float = 0.02
|
| 67 |
+
decoder_start_token_id: int | None = 0
|
| 68 |
+
scale_embedding: bool = False
|
| 69 |
+
pad_token_id: int | None = 0
|
| 70 |
+
eos_token_id: int | list[int] | None = 1
|
| 71 |
+
forced_eos_token_id: int | list[int] | None = 1
|
| 72 |
+
is_decoder: bool = False
|
| 73 |
+
tie_word_embeddings: bool = True
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
__all__ = ["PegasusConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pegasus/modeling_pegasus.py
ADDED
|
@@ -0,0 +1,1132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021, Google and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch PEGASUS model."""
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import math
|
| 18 |
+
from collections.abc import Callable
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ... import initialization as init
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 28 |
+
from ...generation import GenerationMixin
|
| 29 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 30 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 31 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
from ...modeling_outputs import (
|
| 33 |
+
BaseModelOutput,
|
| 34 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 35 |
+
CausalLMOutputWithCrossAttentions,
|
| 36 |
+
Seq2SeqLMOutput,
|
| 37 |
+
Seq2SeqModelOutput,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 40 |
+
from ...processing_utils import Unpack
|
| 41 |
+
from ...utils import (
|
| 42 |
+
TransformersKwargs,
|
| 43 |
+
auto_docstring,
|
| 44 |
+
can_return_tuple,
|
| 45 |
+
is_torchdynamo_compiling,
|
| 46 |
+
logging,
|
| 47 |
+
)
|
| 48 |
+
from ...utils.generic import merge_with_config_defaults
|
| 49 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 50 |
+
from .configuration_pegasus import PegasusConfig
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 57 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 58 |
+
"""
|
| 59 |
+
Shift input ids one token to the right.
|
| 60 |
+
"""
|
| 61 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 62 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 63 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 64 |
+
|
| 65 |
+
if pad_token_id is None:
|
| 66 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 67 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 68 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 69 |
+
|
| 70 |
+
return shifted_input_ids
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# Copied from transformers.models.marian.modeling_marian.MarianSinusoidalPositionalEmbedding with Marian->Pegasus
|
| 74 |
+
class PegasusSinusoidalPositionalEmbedding(nn.Embedding):
|
| 75 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 76 |
+
|
| 77 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None) -> None:
|
| 78 |
+
super().__init__(num_positions, embedding_dim, _freeze=True)
|
| 79 |
+
|
| 80 |
+
def create_weight(self):
|
| 81 |
+
"""
|
| 82 |
+
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
|
| 83 |
+
the 2nd half of the vector. [dim // 2:]
|
| 84 |
+
"""
|
| 85 |
+
n_pos, dim = self.weight.shape
|
| 86 |
+
position_enc = np.array(
|
| 87 |
+
[[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
|
| 88 |
+
)
|
| 89 |
+
out = torch.empty(n_pos, dim, dtype=self.weight.dtype, requires_grad=False)
|
| 90 |
+
sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
|
| 91 |
+
out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
|
| 92 |
+
out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
|
| 93 |
+
return out
|
| 94 |
+
|
| 95 |
+
@torch.no_grad()
|
| 96 |
+
def forward(
|
| 97 |
+
self, input_ids_shape: torch.Size, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
|
| 98 |
+
) -> torch.Tensor:
|
| 99 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 100 |
+
if position_ids is None:
|
| 101 |
+
bsz, seq_len = input_ids_shape[:2]
|
| 102 |
+
position_ids = torch.arange(
|
| 103 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 104 |
+
)
|
| 105 |
+
return super().forward(position_ids)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 109 |
+
def eager_attention_forward(
|
| 110 |
+
module: nn.Module,
|
| 111 |
+
query: torch.Tensor,
|
| 112 |
+
key: torch.Tensor,
|
| 113 |
+
value: torch.Tensor,
|
| 114 |
+
attention_mask: torch.Tensor | None,
|
| 115 |
+
scaling: float | None = None,
|
| 116 |
+
dropout: float = 0.0,
|
| 117 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 118 |
+
):
|
| 119 |
+
if scaling is None:
|
| 120 |
+
scaling = query.size(-1) ** -0.5
|
| 121 |
+
|
| 122 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 123 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 124 |
+
|
| 125 |
+
if attention_mask is not None:
|
| 126 |
+
attn_weights = attn_weights + attention_mask
|
| 127 |
+
|
| 128 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 129 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 130 |
+
|
| 131 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 132 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 133 |
+
|
| 134 |
+
return attn_output, attn_weights
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Pegasus
|
| 138 |
+
class PegasusAttention(nn.Module):
|
| 139 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 140 |
+
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
embed_dim: int,
|
| 144 |
+
num_heads: int,
|
| 145 |
+
dropout: float = 0.0,
|
| 146 |
+
is_decoder: bool = False,
|
| 147 |
+
bias: bool = True,
|
| 148 |
+
is_causal: bool = False,
|
| 149 |
+
config: PegasusConfig | None = None,
|
| 150 |
+
layer_idx: int | None = None,
|
| 151 |
+
):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.embed_dim = embed_dim
|
| 154 |
+
self.num_heads = num_heads
|
| 155 |
+
self.dropout = dropout
|
| 156 |
+
self.head_dim = embed_dim // num_heads
|
| 157 |
+
self.config = config
|
| 158 |
+
|
| 159 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 162 |
+
f" and `num_heads`: {num_heads})."
|
| 163 |
+
)
|
| 164 |
+
self.scaling = self.head_dim**-0.5
|
| 165 |
+
self.is_decoder = is_decoder
|
| 166 |
+
self.is_causal = is_causal
|
| 167 |
+
self.layer_idx = layer_idx
|
| 168 |
+
if layer_idx is None and self.is_decoder:
|
| 169 |
+
logger.warning_once(
|
| 170 |
+
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
|
| 171 |
+
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 172 |
+
"when creating this class."
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 176 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 177 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 178 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 179 |
+
|
| 180 |
+
def forward(
|
| 181 |
+
self,
|
| 182 |
+
hidden_states: torch.Tensor,
|
| 183 |
+
key_value_states: torch.Tensor | None = None,
|
| 184 |
+
past_key_values: Cache | None = None,
|
| 185 |
+
attention_mask: torch.Tensor | None = None,
|
| 186 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 187 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 188 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 189 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 190 |
+
"""Input shape: Batch x Time x Channel"""
|
| 191 |
+
|
| 192 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 193 |
+
# for the decoder
|
| 194 |
+
is_cross_attention = key_value_states is not None
|
| 195 |
+
|
| 196 |
+
# determine input shapes
|
| 197 |
+
input_shape = hidden_states.shape[:-1]
|
| 198 |
+
|
| 199 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 200 |
+
|
| 201 |
+
# get query proj
|
| 202 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 203 |
+
|
| 204 |
+
is_updated = False
|
| 205 |
+
if past_key_values is not None:
|
| 206 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 207 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 208 |
+
if is_cross_attention:
|
| 209 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 210 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 211 |
+
else:
|
| 212 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 213 |
+
else:
|
| 214 |
+
curr_past_key_values = past_key_values
|
| 215 |
+
|
| 216 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 217 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 218 |
+
# reuse k,v, cross_attentions
|
| 219 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 220 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 221 |
+
else:
|
| 222 |
+
key_states = self.k_proj(current_states)
|
| 223 |
+
value_states = self.v_proj(current_states)
|
| 224 |
+
kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
|
| 225 |
+
key_states = key_states.view(kv_shape).transpose(1, 2)
|
| 226 |
+
value_states = value_states.view(kv_shape).transpose(1, 2)
|
| 227 |
+
|
| 228 |
+
if past_key_values is not None:
|
| 229 |
+
key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
|
| 230 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 231 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 232 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 233 |
+
|
| 234 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 235 |
+
self.config._attn_implementation, eager_attention_forward
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
attn_output, attn_weights = attention_interface(
|
| 239 |
+
self,
|
| 240 |
+
query_states,
|
| 241 |
+
key_states,
|
| 242 |
+
value_states,
|
| 243 |
+
attention_mask,
|
| 244 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 245 |
+
scaling=self.scaling,
|
| 246 |
+
**kwargs,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 250 |
+
attn_output = self.out_proj(attn_output)
|
| 251 |
+
|
| 252 |
+
return attn_output, attn_weights
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Pegasus, MBART->PEGASUS
|
| 256 |
+
class PegasusEncoderLayer(GradientCheckpointingLayer):
|
| 257 |
+
def __init__(self, config: PegasusConfig):
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.embed_dim = config.d_model
|
| 260 |
+
|
| 261 |
+
self.self_attn = PegasusAttention(
|
| 262 |
+
embed_dim=self.embed_dim,
|
| 263 |
+
num_heads=config.encoder_attention_heads,
|
| 264 |
+
dropout=config.attention_dropout,
|
| 265 |
+
config=config,
|
| 266 |
+
)
|
| 267 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 268 |
+
self.dropout = config.dropout
|
| 269 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 270 |
+
self.activation_dropout = config.activation_dropout
|
| 271 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 272 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 273 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 274 |
+
|
| 275 |
+
def forward(
|
| 276 |
+
self,
|
| 277 |
+
hidden_states: torch.Tensor,
|
| 278 |
+
attention_mask: torch.Tensor,
|
| 279 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 280 |
+
) -> torch.Tensor:
|
| 281 |
+
"""
|
| 282 |
+
Args:
|
| 283 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 284 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 285 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 286 |
+
"""
|
| 287 |
+
residual = hidden_states
|
| 288 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 289 |
+
hidden_states, _ = self.self_attn(
|
| 290 |
+
hidden_states=hidden_states,
|
| 291 |
+
attention_mask=attention_mask,
|
| 292 |
+
**kwargs,
|
| 293 |
+
)
|
| 294 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 295 |
+
hidden_states = residual + hidden_states
|
| 296 |
+
|
| 297 |
+
residual = hidden_states
|
| 298 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 299 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 300 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 301 |
+
hidden_states = self.fc2(hidden_states)
|
| 302 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 303 |
+
hidden_states = residual + hidden_states
|
| 304 |
+
|
| 305 |
+
if hidden_states.dtype == torch.float16:
|
| 306 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 307 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 308 |
+
|
| 309 |
+
return hidden_states
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->Pegasus, MBART->PEGASUS
|
| 313 |
+
class PegasusDecoderLayer(GradientCheckpointingLayer):
|
| 314 |
+
def __init__(self, config: PegasusConfig, layer_idx: int | None = None):
|
| 315 |
+
super().__init__()
|
| 316 |
+
self.embed_dim = config.d_model
|
| 317 |
+
|
| 318 |
+
self.self_attn = PegasusAttention(
|
| 319 |
+
embed_dim=self.embed_dim,
|
| 320 |
+
num_heads=config.decoder_attention_heads,
|
| 321 |
+
dropout=config.attention_dropout,
|
| 322 |
+
is_decoder=True,
|
| 323 |
+
is_causal=True,
|
| 324 |
+
config=config,
|
| 325 |
+
layer_idx=layer_idx,
|
| 326 |
+
)
|
| 327 |
+
self.dropout = config.dropout
|
| 328 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 329 |
+
self.activation_dropout = config.activation_dropout
|
| 330 |
+
|
| 331 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 332 |
+
self.encoder_attn = PegasusAttention(
|
| 333 |
+
self.embed_dim,
|
| 334 |
+
config.decoder_attention_heads,
|
| 335 |
+
dropout=config.attention_dropout,
|
| 336 |
+
is_decoder=True,
|
| 337 |
+
config=config,
|
| 338 |
+
layer_idx=layer_idx,
|
| 339 |
+
)
|
| 340 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 341 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 342 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 343 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 344 |
+
|
| 345 |
+
def forward(
|
| 346 |
+
self,
|
| 347 |
+
hidden_states: torch.Tensor,
|
| 348 |
+
attention_mask: torch.Tensor | None = None,
|
| 349 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 350 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 351 |
+
past_key_values: Cache | None = None,
|
| 352 |
+
use_cache: bool | None = True,
|
| 353 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 354 |
+
) -> torch.Tensor:
|
| 355 |
+
"""
|
| 356 |
+
Args:
|
| 357 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 358 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 359 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 360 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 361 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 362 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 363 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 364 |
+
past_key_values (`Cache`): cached past key and value projection states
|
| 365 |
+
"""
|
| 366 |
+
residual = hidden_states
|
| 367 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 368 |
+
|
| 369 |
+
# Self Attention
|
| 370 |
+
hidden_states, _ = self.self_attn(
|
| 371 |
+
hidden_states=hidden_states,
|
| 372 |
+
past_key_values=past_key_values,
|
| 373 |
+
attention_mask=attention_mask,
|
| 374 |
+
**kwargs,
|
| 375 |
+
)
|
| 376 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 377 |
+
hidden_states = residual + hidden_states
|
| 378 |
+
|
| 379 |
+
# Cross-Attention Block
|
| 380 |
+
if encoder_hidden_states is not None:
|
| 381 |
+
residual = hidden_states
|
| 382 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 383 |
+
|
| 384 |
+
hidden_states, _ = self.encoder_attn(
|
| 385 |
+
hidden_states=hidden_states,
|
| 386 |
+
key_value_states=encoder_hidden_states,
|
| 387 |
+
attention_mask=encoder_attention_mask,
|
| 388 |
+
past_key_values=past_key_values,
|
| 389 |
+
**kwargs,
|
| 390 |
+
)
|
| 391 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 392 |
+
hidden_states = residual + hidden_states
|
| 393 |
+
|
| 394 |
+
# Fully Connected
|
| 395 |
+
residual = hidden_states
|
| 396 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 397 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 398 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 399 |
+
hidden_states = self.fc2(hidden_states)
|
| 400 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 401 |
+
hidden_states = residual + hidden_states
|
| 402 |
+
|
| 403 |
+
return hidden_states
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@auto_docstring
|
| 407 |
+
class PegasusPreTrainedModel(PreTrainedModel):
|
| 408 |
+
config: PegasusConfig
|
| 409 |
+
base_model_prefix = "model"
|
| 410 |
+
supports_gradient_checkpointing = True
|
| 411 |
+
_supports_flash_attn = True
|
| 412 |
+
_supports_sdpa = True
|
| 413 |
+
_supports_flex_attn = True
|
| 414 |
+
_can_compile_fullgraph = True
|
| 415 |
+
|
| 416 |
+
@torch.no_grad()
|
| 417 |
+
def _init_weights(self, module):
|
| 418 |
+
super()._init_weights(module)
|
| 419 |
+
if isinstance(module, PegasusSinusoidalPositionalEmbedding):
|
| 420 |
+
init.copy_(module.weight, module.create_weight())
|
| 421 |
+
elif isinstance(module, PegasusForConditionalGeneration):
|
| 422 |
+
init.zeros_(module.final_logits_bias)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class PegasusEncoder(PegasusPreTrainedModel):
|
| 426 |
+
"""
|
| 427 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 428 |
+
[`PegasusEncoderLayer`].
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
config: PegasusConfig
|
| 432 |
+
embed_tokens (nn.Embedding): output embedding
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
_can_record_outputs = {
|
| 436 |
+
"hidden_states": PegasusEncoderLayer,
|
| 437 |
+
"attentions": PegasusAttention,
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
def __init__(self, config: PegasusConfig):
|
| 441 |
+
super().__init__(config)
|
| 442 |
+
|
| 443 |
+
self.dropout = config.dropout
|
| 444 |
+
self.layerdrop = config.encoder_layerdrop
|
| 445 |
+
|
| 446 |
+
embed_dim = config.d_model
|
| 447 |
+
self.padding_idx = config.pad_token_id
|
| 448 |
+
self.max_source_positions = config.max_position_embeddings
|
| 449 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 450 |
+
|
| 451 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
|
| 452 |
+
|
| 453 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 454 |
+
config.max_position_embeddings,
|
| 455 |
+
embed_dim,
|
| 456 |
+
self.padding_idx,
|
| 457 |
+
)
|
| 458 |
+
self.layers = nn.ModuleList([PegasusEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 459 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 460 |
+
|
| 461 |
+
self.gradient_checkpointing = False
|
| 462 |
+
# Initialize weights and apply final processing
|
| 463 |
+
self.post_init()
|
| 464 |
+
|
| 465 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 466 |
+
"""
|
| 467 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 468 |
+
config.max_position_embeddings`.
|
| 469 |
+
|
| 470 |
+
Arguments:
|
| 471 |
+
new_num_position_embeddings (`int`):
|
| 472 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 473 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 474 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 475 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 476 |
+
will remove vectors from the end.
|
| 477 |
+
"""
|
| 478 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 479 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 480 |
+
|
| 481 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 482 |
+
self.config.max_position_embeddings,
|
| 483 |
+
self.config.d_model,
|
| 484 |
+
self.padding_idx,
|
| 485 |
+
)
|
| 486 |
+
init.copy_(self.embed_positions.weight, self.embed_positions.create_weight())
|
| 487 |
+
self.embed_positions.to(self.device)
|
| 488 |
+
|
| 489 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 490 |
+
"""
|
| 491 |
+
Returns the position embeddings matrix
|
| 492 |
+
"""
|
| 493 |
+
return self.embed_positions
|
| 494 |
+
|
| 495 |
+
@merge_with_config_defaults
|
| 496 |
+
@capture_outputs
|
| 497 |
+
@auto_docstring
|
| 498 |
+
def forward(
|
| 499 |
+
self,
|
| 500 |
+
input_ids=None,
|
| 501 |
+
attention_mask=None,
|
| 502 |
+
inputs_embeds=None,
|
| 503 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 504 |
+
) -> BaseModelOutput:
|
| 505 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 506 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 507 |
+
|
| 508 |
+
if inputs_embeds is None:
|
| 509 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 510 |
+
|
| 511 |
+
input_shape = inputs_embeds.shape[:-1]
|
| 512 |
+
embed_pos = self.embed_positions(input_shape)
|
| 513 |
+
|
| 514 |
+
hidden_states = inputs_embeds + embed_pos
|
| 515 |
+
|
| 516 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 517 |
+
|
| 518 |
+
attention_mask = create_bidirectional_mask(
|
| 519 |
+
config=self.config,
|
| 520 |
+
inputs_embeds=inputs_embeds,
|
| 521 |
+
attention_mask=attention_mask,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 525 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 526 |
+
to_drop = False
|
| 527 |
+
if self.training:
|
| 528 |
+
dropout_probability = torch.rand([])
|
| 529 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 530 |
+
to_drop = True
|
| 531 |
+
|
| 532 |
+
if not to_drop:
|
| 533 |
+
hidden_states = encoder_layer(
|
| 534 |
+
hidden_states,
|
| 535 |
+
attention_mask,
|
| 536 |
+
**kwargs,
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 540 |
+
|
| 541 |
+
return BaseModelOutput(
|
| 542 |
+
last_hidden_state=hidden_states,
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
class PegasusDecoder(PegasusPreTrainedModel):
|
| 547 |
+
"""
|
| 548 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]
|
| 549 |
+
|
| 550 |
+
Args:
|
| 551 |
+
config: PegasusConfig
|
| 552 |
+
embed_tokens (nn.Embedding): output embedding
|
| 553 |
+
"""
|
| 554 |
+
|
| 555 |
+
_can_record_outputs = {
|
| 556 |
+
"hidden_states": PegasusDecoderLayer,
|
| 557 |
+
"attentions": OutputRecorder(PegasusAttention, index=1, layer_name="self_attn"),
|
| 558 |
+
"cross_attentions": OutputRecorder(PegasusAttention, index=1, layer_name="encoder_attn"),
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
def __init__(self, config: PegasusConfig):
|
| 562 |
+
super().__init__(config)
|
| 563 |
+
self.dropout = config.dropout
|
| 564 |
+
self.layerdrop = config.decoder_layerdrop
|
| 565 |
+
self.padding_idx = config.pad_token_id
|
| 566 |
+
self.max_target_positions = config.max_position_embeddings
|
| 567 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 568 |
+
|
| 569 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 570 |
+
|
| 571 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 572 |
+
config.max_position_embeddings,
|
| 573 |
+
config.d_model,
|
| 574 |
+
self.padding_idx,
|
| 575 |
+
)
|
| 576 |
+
self.layers = nn.ModuleList([PegasusDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
|
| 577 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 578 |
+
|
| 579 |
+
self.gradient_checkpointing = False
|
| 580 |
+
# Initialize weights and apply final processing
|
| 581 |
+
self.post_init()
|
| 582 |
+
|
| 583 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 584 |
+
"""
|
| 585 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 586 |
+
config.max_position_embeddings`.
|
| 587 |
+
|
| 588 |
+
Arguments:
|
| 589 |
+
new_num_position_embeddings (`int`):
|
| 590 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 591 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 592 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 593 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 594 |
+
will remove vectors from the end.
|
| 595 |
+
"""
|
| 596 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 597 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 598 |
+
|
| 599 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 600 |
+
self.config.max_position_embeddings,
|
| 601 |
+
self.config.d_model,
|
| 602 |
+
self.padding_idx,
|
| 603 |
+
)
|
| 604 |
+
init.copy_(self.embed_positions.weight, self.embed_positions.create_weight())
|
| 605 |
+
self.embed_positions.to(self.device)
|
| 606 |
+
|
| 607 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 608 |
+
"""
|
| 609 |
+
Returns the position embeddings matrix
|
| 610 |
+
"""
|
| 611 |
+
return self.embed_positions
|
| 612 |
+
|
| 613 |
+
@merge_with_config_defaults
|
| 614 |
+
@capture_outputs
|
| 615 |
+
@auto_docstring
|
| 616 |
+
def forward(
|
| 617 |
+
self,
|
| 618 |
+
input_ids=None,
|
| 619 |
+
attention_mask=None,
|
| 620 |
+
encoder_hidden_states=None,
|
| 621 |
+
encoder_attention_mask=None,
|
| 622 |
+
past_key_values=None,
|
| 623 |
+
inputs_embeds=None,
|
| 624 |
+
use_cache=None,
|
| 625 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 626 |
+
) -> BaseModelOutputWithPastAndCrossAttentions:
|
| 627 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 628 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 629 |
+
|
| 630 |
+
if inputs_embeds is None:
|
| 631 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 632 |
+
|
| 633 |
+
# important to apply scale outside of `if` in case users pass `embeds`
|
| 634 |
+
inputs_embeds = inputs_embeds * self.embed_scale
|
| 635 |
+
|
| 636 |
+
# initialize `past_key_values`
|
| 637 |
+
if use_cache and past_key_values is None:
|
| 638 |
+
past_key_values = (
|
| 639 |
+
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 640 |
+
if encoder_hidden_states is not None or self.config.is_encoder_decoder
|
| 641 |
+
else DynamicCache(config=self.config)
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
batch_size, seq_length = inputs_embeds.size()[:-1]
|
| 645 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 646 |
+
position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
|
| 647 |
+
|
| 648 |
+
if attention_mask is None and not is_torchdynamo_compiling():
|
| 649 |
+
# required mask seq length can be calculated via length of past cache
|
| 650 |
+
mask_seq_length = past_key_values_length + seq_length
|
| 651 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
| 652 |
+
|
| 653 |
+
self_attn_cache = (
|
| 654 |
+
past_key_values.self_attention_cache
|
| 655 |
+
if isinstance(past_key_values, EncoderDecoderCache)
|
| 656 |
+
else past_key_values
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
causal_mask = create_causal_mask(
|
| 660 |
+
config=self.config,
|
| 661 |
+
inputs_embeds=inputs_embeds,
|
| 662 |
+
attention_mask=attention_mask,
|
| 663 |
+
past_key_values=self_attn_cache,
|
| 664 |
+
)
|
| 665 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 666 |
+
config=self.config,
|
| 667 |
+
inputs_embeds=inputs_embeds,
|
| 668 |
+
attention_mask=encoder_attention_mask,
|
| 669 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
# embed positions
|
| 673 |
+
positions = self.embed_positions((batch_size, seq_length), past_key_values_length, position_ids=position_ids)
|
| 674 |
+
hidden_states = inputs_embeds + positions
|
| 675 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 676 |
+
|
| 677 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 678 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 679 |
+
if self.training:
|
| 680 |
+
dropout_probability = torch.rand([])
|
| 681 |
+
if dropout_probability < self.layerdrop:
|
| 682 |
+
continue
|
| 683 |
+
|
| 684 |
+
hidden_states = decoder_layer(
|
| 685 |
+
hidden_states,
|
| 686 |
+
causal_mask,
|
| 687 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 688 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 689 |
+
past_key_values=past_key_values,
|
| 690 |
+
use_cache=use_cache,
|
| 691 |
+
**kwargs,
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 695 |
+
|
| 696 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 697 |
+
last_hidden_state=hidden_states,
|
| 698 |
+
past_key_values=past_key_values,
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
@auto_docstring
|
| 703 |
+
class PegasusModel(PegasusPreTrainedModel):
|
| 704 |
+
_tied_weights_keys = {
|
| 705 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 706 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
def __init__(self, config: PegasusConfig):
|
| 710 |
+
super().__init__(config)
|
| 711 |
+
|
| 712 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 713 |
+
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
|
| 714 |
+
|
| 715 |
+
self.encoder = PegasusEncoder(config)
|
| 716 |
+
self.decoder = PegasusDecoder(config)
|
| 717 |
+
|
| 718 |
+
# Initialize weights and apply final processing
|
| 719 |
+
self.post_init()
|
| 720 |
+
|
| 721 |
+
def get_input_embeddings(self):
|
| 722 |
+
return self.shared
|
| 723 |
+
|
| 724 |
+
def set_input_embeddings(self, value):
|
| 725 |
+
self.shared = value
|
| 726 |
+
self.encoder.embed_tokens = self.shared
|
| 727 |
+
self.decoder.embed_tokens = self.shared
|
| 728 |
+
|
| 729 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 730 |
+
"""
|
| 731 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 732 |
+
config.max_position_embeddings`.
|
| 733 |
+
|
| 734 |
+
Arguments:
|
| 735 |
+
new_num_position_embeddings (`int`):
|
| 736 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 737 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 738 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 739 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 740 |
+
will remove vectors from the end.
|
| 741 |
+
"""
|
| 742 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 743 |
+
self.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 744 |
+
self.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 745 |
+
|
| 746 |
+
def get_position_embeddings(self) -> tuple[nn.Embedding]:
|
| 747 |
+
"""
|
| 748 |
+
Returns the position embeddings matrix
|
| 749 |
+
"""
|
| 750 |
+
return (self.encoder.get_position_embeddings(), self.decoder.get_position_embeddings())
|
| 751 |
+
|
| 752 |
+
@can_return_tuple
|
| 753 |
+
@auto_docstring
|
| 754 |
+
def forward(
|
| 755 |
+
self,
|
| 756 |
+
input_ids: torch.Tensor | None = None,
|
| 757 |
+
attention_mask: torch.Tensor | None = None,
|
| 758 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 759 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 760 |
+
encoder_outputs: tuple[torch.FloatTensor] | None = None,
|
| 761 |
+
past_key_values: Cache | None = None,
|
| 762 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 763 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 764 |
+
use_cache: bool | None = None,
|
| 765 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 766 |
+
) -> tuple | Seq2SeqModelOutput:
|
| 767 |
+
r"""
|
| 768 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 769 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 770 |
+
|
| 771 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 772 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 773 |
+
|
| 774 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 775 |
+
|
| 776 |
+
Pegasus uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 777 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 778 |
+
`past_key_values`).
|
| 779 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 780 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 781 |
+
be used by default.
|
| 782 |
+
|
| 783 |
+
Example:
|
| 784 |
+
|
| 785 |
+
```python
|
| 786 |
+
>>> from transformers import AutoTokenizer, PegasusModel
|
| 787 |
+
|
| 788 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
|
| 789 |
+
>>> model = PegasusModel.from_pretrained("google/pegasus-large")
|
| 790 |
+
|
| 791 |
+
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
|
| 792 |
+
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
|
| 793 |
+
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
|
| 794 |
+
|
| 795 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 796 |
+
>>> list(last_hidden_states.shape)
|
| 797 |
+
[1, 4, 1024]
|
| 798 |
+
```"""
|
| 799 |
+
|
| 800 |
+
if encoder_outputs is None:
|
| 801 |
+
encoder_outputs = self.encoder(
|
| 802 |
+
input_ids=input_ids,
|
| 803 |
+
attention_mask=attention_mask,
|
| 804 |
+
inputs_embeds=inputs_embeds,
|
| 805 |
+
**kwargs,
|
| 806 |
+
)
|
| 807 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
|
| 808 |
+
elif not isinstance(encoder_outputs, BaseModelOutput):
|
| 809 |
+
encoder_outputs = BaseModelOutput(
|
| 810 |
+
last_hidden_state=encoder_outputs[0],
|
| 811 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 812 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
# decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
|
| 816 |
+
decoder_outputs = self.decoder(
|
| 817 |
+
input_ids=decoder_input_ids,
|
| 818 |
+
attention_mask=decoder_attention_mask,
|
| 819 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 820 |
+
encoder_attention_mask=attention_mask,
|
| 821 |
+
past_key_values=past_key_values,
|
| 822 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 823 |
+
use_cache=use_cache,
|
| 824 |
+
**kwargs,
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
return Seq2SeqModelOutput(
|
| 828 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 829 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 830 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 831 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 832 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 833 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 834 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 835 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
@auto_docstring(
|
| 840 |
+
custom_intro="""
|
| 841 |
+
The PEGASUS Model with a language modeling head. Can be used for summarization.
|
| 842 |
+
"""
|
| 843 |
+
)
|
| 844 |
+
class PegasusForConditionalGeneration(PegasusPreTrainedModel, GenerationMixin):
|
| 845 |
+
base_model_prefix = "model"
|
| 846 |
+
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
|
| 847 |
+
_tied_weights_keys = {
|
| 848 |
+
"lm_head.weight": "model.shared.weight",
|
| 849 |
+
}
|
| 850 |
+
|
| 851 |
+
def __init__(self, config: PegasusConfig):
|
| 852 |
+
super().__init__(config)
|
| 853 |
+
self.model = PegasusModel(config)
|
| 854 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 855 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 856 |
+
|
| 857 |
+
# Initialize weights and apply final processing
|
| 858 |
+
self.post_init()
|
| 859 |
+
|
| 860 |
+
def resize_token_embeddings(
|
| 861 |
+
self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
|
| 862 |
+
) -> nn.Embedding:
|
| 863 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
|
| 864 |
+
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
|
| 865 |
+
return new_embeddings
|
| 866 |
+
|
| 867 |
+
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
|
| 868 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 869 |
+
if new_num_tokens <= old_num_tokens:
|
| 870 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 871 |
+
else:
|
| 872 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 873 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 874 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 875 |
+
|
| 876 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 877 |
+
"""
|
| 878 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 879 |
+
config.max_position_embeddings`.
|
| 880 |
+
|
| 881 |
+
Arguments:
|
| 882 |
+
new_num_position_embeddings (`int`):
|
| 883 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 884 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 885 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 886 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 887 |
+
will remove vectors from the end.
|
| 888 |
+
"""
|
| 889 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 890 |
+
self.model.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 891 |
+
self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 892 |
+
|
| 893 |
+
def get_position_embeddings(self) -> tuple[nn.Embedding]:
|
| 894 |
+
"""
|
| 895 |
+
Returns the position embeddings matrix
|
| 896 |
+
"""
|
| 897 |
+
return (self.model.encoder.get_position_embeddings(), self.model.decoder.get_position_embeddings())
|
| 898 |
+
|
| 899 |
+
@can_return_tuple
|
| 900 |
+
@auto_docstring
|
| 901 |
+
def forward(
|
| 902 |
+
self,
|
| 903 |
+
input_ids: torch.Tensor | None = None,
|
| 904 |
+
attention_mask: torch.Tensor | None = None,
|
| 905 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 906 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 907 |
+
encoder_outputs: tuple[torch.FloatTensor] | None = None,
|
| 908 |
+
past_key_values: Cache | None = None,
|
| 909 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 910 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 911 |
+
labels: torch.Tensor | None = None,
|
| 912 |
+
use_cache: bool | None = None,
|
| 913 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 914 |
+
) -> tuple | Seq2SeqLMOutput:
|
| 915 |
+
r"""
|
| 916 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 917 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 918 |
+
|
| 919 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 920 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 921 |
+
|
| 922 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 923 |
+
|
| 924 |
+
Pegasus uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 925 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 926 |
+
`past_key_values`).
|
| 927 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 928 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 929 |
+
be used by default.
|
| 930 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 931 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 932 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 933 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 934 |
+
|
| 935 |
+
Example Summarization:
|
| 936 |
+
|
| 937 |
+
```python
|
| 938 |
+
>>> from transformers import AutoTokenizer, PegasusForConditionalGeneration
|
| 939 |
+
|
| 940 |
+
>>> model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")
|
| 941 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-xsum")
|
| 942 |
+
|
| 943 |
+
>>> ARTICLE_TO_SUMMARIZE = (
|
| 944 |
+
... "PG&E stated it scheduled the blackouts in response to forecasts for high winds "
|
| 945 |
+
... "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were "
|
| 946 |
+
... "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow."
|
| 947 |
+
... )
|
| 948 |
+
>>> inputs = tokenizer(ARTICLE_TO_SUMMARIZE, max_length=1024, return_tensors="pt")
|
| 949 |
+
|
| 950 |
+
>>> # Generate Summary
|
| 951 |
+
>>> summary_ids = model.generate(inputs["input_ids"])
|
| 952 |
+
>>> tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 953 |
+
"California's largest electricity provider has turned off power to hundreds of thousands of customers."
|
| 954 |
+
```
|
| 955 |
+
"""
|
| 956 |
+
if labels is not None:
|
| 957 |
+
if use_cache:
|
| 958 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 959 |
+
use_cache = False
|
| 960 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 961 |
+
decoder_input_ids = shift_tokens_right(
|
| 962 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 966 |
+
input_ids,
|
| 967 |
+
attention_mask=attention_mask,
|
| 968 |
+
decoder_input_ids=decoder_input_ids,
|
| 969 |
+
encoder_outputs=encoder_outputs,
|
| 970 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 971 |
+
past_key_values=past_key_values,
|
| 972 |
+
inputs_embeds=inputs_embeds,
|
| 973 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 974 |
+
use_cache=use_cache,
|
| 975 |
+
**kwargs,
|
| 976 |
+
)
|
| 977 |
+
lm_logits = self.lm_head(outputs.last_hidden_state) + self.final_logits_bias
|
| 978 |
+
|
| 979 |
+
masked_lm_loss = None
|
| 980 |
+
if labels is not None:
|
| 981 |
+
loss_fct = CrossEntropyLoss()
|
| 982 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 983 |
+
|
| 984 |
+
return Seq2SeqLMOutput(
|
| 985 |
+
loss=masked_lm_loss,
|
| 986 |
+
logits=lm_logits,
|
| 987 |
+
past_key_values=outputs.past_key_values,
|
| 988 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 989 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 990 |
+
cross_attentions=outputs.cross_attentions,
|
| 991 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 992 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 993 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 994 |
+
)
|
| 995 |
+
|
| 996 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 997 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Pegasus
|
| 1001 |
+
class PegasusDecoderWrapper(PegasusPreTrainedModel):
|
| 1002 |
+
"""
|
| 1003 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1004 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1005 |
+
"""
|
| 1006 |
+
|
| 1007 |
+
def __init__(self, config):
|
| 1008 |
+
super().__init__(config)
|
| 1009 |
+
self.decoder = PegasusDecoder(config)
|
| 1010 |
+
self.post_init()
|
| 1011 |
+
|
| 1012 |
+
def forward(self, *args, **kwargs):
|
| 1013 |
+
return self.decoder(*args, **kwargs)
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
class PegasusForCausalLM(PegasusPreTrainedModel, GenerationMixin):
|
| 1017 |
+
_tied_weights_keys = {
|
| 1018 |
+
"lm_head.weight": "model.decoder.embed_tokens.weight",
|
| 1019 |
+
}
|
| 1020 |
+
|
| 1021 |
+
def __init__(self, config):
|
| 1022 |
+
config = copy.deepcopy(config)
|
| 1023 |
+
config.is_decoder = True
|
| 1024 |
+
config.is_encoder_decoder = False
|
| 1025 |
+
super().__init__(config)
|
| 1026 |
+
self.model = PegasusDecoderWrapper(config)
|
| 1027 |
+
|
| 1028 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1029 |
+
|
| 1030 |
+
# Initialize weights and apply final processing
|
| 1031 |
+
self.post_init()
|
| 1032 |
+
|
| 1033 |
+
def get_input_embeddings(self):
|
| 1034 |
+
return self.model.decoder.embed_tokens
|
| 1035 |
+
|
| 1036 |
+
def set_input_embeddings(self, value):
|
| 1037 |
+
self.model.decoder.embed_tokens = value
|
| 1038 |
+
|
| 1039 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 1040 |
+
"""
|
| 1041 |
+
Returns the position embeddings matrix
|
| 1042 |
+
"""
|
| 1043 |
+
return self.model.decoder.get_position_embeddings()
|
| 1044 |
+
|
| 1045 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1046 |
+
"""
|
| 1047 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1048 |
+
config.max_position_embeddings`.
|
| 1049 |
+
|
| 1050 |
+
Arguments:
|
| 1051 |
+
new_num_position_embeddings (`int`):
|
| 1052 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1053 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1054 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1055 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1056 |
+
will remove vectors from the end.
|
| 1057 |
+
"""
|
| 1058 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1059 |
+
self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1060 |
+
|
| 1061 |
+
@can_return_tuple
|
| 1062 |
+
@auto_docstring
|
| 1063 |
+
# Copied from transformers.models.bart.modeling_bart.BartForCausalLM.forward with Bart->Pegasus, facebook/bart-base->google/pegasus-large
|
| 1064 |
+
def forward(
|
| 1065 |
+
self,
|
| 1066 |
+
input_ids: torch.LongTensor | None = None,
|
| 1067 |
+
attention_mask: torch.Tensor | None = None,
|
| 1068 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 1069 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 1070 |
+
past_key_values: Cache | None = None,
|
| 1071 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1072 |
+
labels: torch.LongTensor | None = None,
|
| 1073 |
+
use_cache: bool | None = None,
|
| 1074 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1075 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1076 |
+
) -> tuple | CausalLMOutputWithCrossAttentions:
|
| 1077 |
+
r"""
|
| 1078 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1079 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1080 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1081 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1082 |
+
|
| 1083 |
+
Example:
|
| 1084 |
+
|
| 1085 |
+
```python
|
| 1086 |
+
>>> from transformers import AutoTokenizer, PegasusForCausalLM
|
| 1087 |
+
|
| 1088 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
|
| 1089 |
+
>>> model = PegasusForCausalLM.from_pretrained("google/pegasus-large")
|
| 1090 |
+
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
|
| 1091 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1092 |
+
>>> outputs = model(**inputs)
|
| 1093 |
+
|
| 1094 |
+
>>> logits = outputs.logits
|
| 1095 |
+
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
|
| 1096 |
+
>>> list(logits.shape) == expected_shape
|
| 1097 |
+
True
|
| 1098 |
+
```"""
|
| 1099 |
+
|
| 1100 |
+
outputs: BaseModelOutputWithPastAndCrossAttentions = self.model.decoder(
|
| 1101 |
+
input_ids=input_ids,
|
| 1102 |
+
attention_mask=attention_mask,
|
| 1103 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1104 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1105 |
+
past_key_values=past_key_values,
|
| 1106 |
+
inputs_embeds=inputs_embeds,
|
| 1107 |
+
use_cache=use_cache,
|
| 1108 |
+
**kwargs,
|
| 1109 |
+
)
|
| 1110 |
+
|
| 1111 |
+
hidden_states = outputs[0]
|
| 1112 |
+
# Only compute necessary logits
|
| 1113 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1114 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 1115 |
+
|
| 1116 |
+
loss = None
|
| 1117 |
+
if labels is not None:
|
| 1118 |
+
labels = labels.to(logits.device)
|
| 1119 |
+
loss_fct = CrossEntropyLoss()
|
| 1120 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1121 |
+
|
| 1122 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1123 |
+
loss=loss,
|
| 1124 |
+
logits=logits,
|
| 1125 |
+
past_key_values=outputs.past_key_values,
|
| 1126 |
+
hidden_states=outputs.hidden_states,
|
| 1127 |
+
attentions=outputs.attentions,
|
| 1128 |
+
cross_attentions=outputs.cross_attentions,
|
| 1129 |
+
)
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
__all__ = ["PegasusForCausalLM", "PegasusForConditionalGeneration", "PegasusModel", "PegasusPreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_wavlm import *
|
| 22 |
+
from .modeling_wavlm import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|