JinghuiLuAstronaut commited on
Commit
348ac8f
·
verified ·
1 Parent(s): 7d90510

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/logs/owt_len1024_lognormal_atoms_sde_watch/infer_lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs_step_0004000_logistic_normal_modelt_support_t_t1p45.log +186 -0
  2. LTA_openwebtext_dualt/logs/owt_len1024_lognormal_atoms_sde_watch/infer_lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs_step_0008000_logistic_normal_modelt_support_t_t1p45.log +188 -0
  3. LTA_openwebtext_dualt/logs/owt_len1024_lognormal_atoms_sde_watch/processed_lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs_logistic_normal_modelt_support_t_steps128_t1p45_n128.txt +11 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/bin/activate.nu +102 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/bin/huggingface-cli +10 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jamba/__init__.py +27 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jamba/configuration_jamba.py +122 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jamba/modular_jamba.py +663 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mvp/__init__.py +28 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mvp/configuration_mvp.py +87 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mvp/modeling_mvp.py +1630 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pvt_v2/__init__.py +27 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pvt_v2/configuration_pvt_v2.py +93 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pvt_v2/modeling_pvt_v2.py +582 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py +27 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py +89 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py +1390 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_086000.pt +3 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_288000.pt +3 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_473000.pt +3 -0
LTA_openwebtext_dualt/logs/owt_len1024_lognormal_atoms_sde_watch/infer_lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs_step_0004000_logistic_normal_modelt_support_t_t1p45.log ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-owt-lognormal-sde] 2026-05-22_22:50:53 infer runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0004000.pt -> docs/lta_samples/metrics_20260522/owt_len1024_lognormal_atoms_every1k_logistic_normal_sde_modelt_support_t_t1p45_steps128_n128/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0004000
2
+ [load] runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0004000.pt
3
+ [ckpt] step=4000
4
+ [sde] generated 1/128
5
+ [sde] generated 2/128
6
+ [sde] generated 3/128
7
+ [sde] generated 4/128
8
+ [sde] generated 5/128
9
+ [sde] generated 6/128
10
+ [sde] generated 7/128
11
+ [sde] generated 8/128
12
+ [sde] generated 9/128
13
+ [sde] generated 10/128
14
+ [sde] generated 11/128
15
+ [sde] generated 12/128
16
+ [sde] generated 13/128
17
+ [sde] generated 14/128
18
+ [sde] generated 15/128
19
+ [sde] generated 16/128
20
+ [sde] generated 17/128
21
+ [sde] generated 18/128
22
+ [sde] generated 19/128
23
+ [sde] generated 20/128
24
+ [sde] generated 21/128
25
+ [sde] generated 22/128
26
+ [sde] generated 23/128
27
+ [sde] generated 24/128
28
+ [sde] generated 25/128
29
+ [sde] generated 26/128
30
+ [sde] generated 27/128
31
+ [sde] generated 28/128
32
+ [sde] generated 29/128
33
+ [sde] generated 30/128
34
+ [sde] generated 31/128
35
+ [sde] generated 32/128
36
+ [sde] generated 33/128
37
+ [sde] generated 34/128
38
+ [sde] generated 35/128
39
+ [sde] generated 36/128
40
+ [sde] generated 37/128
41
+ [sde] generated 38/128
42
+ [sde] generated 39/128
43
+ [sde] generated 40/128
44
+ [sde] generated 41/128
45
+ [sde] generated 42/128
46
+ [sde] generated 43/128
47
+ [sde] generated 44/128
48
+ [sde] generated 45/128
49
+ [sde] generated 46/128
50
+ [sde] generated 47/128
51
+ [sde] generated 48/128
52
+ [sde] generated 49/128
53
+ [sde] generated 50/128
54
+ [sde] generated 51/128
55
+ [sde] generated 52/128
56
+ [sde] generated 53/128
57
+ [sde] generated 54/128
58
+ [sde] generated 55/128
59
+ [sde] generated 56/128
60
+ [sde] generated 57/128
61
+ [sde] generated 58/128
62
+ [sde] generated 59/128
63
+ [sde] generated 60/128
64
+ [sde] generated 61/128
65
+ [sde] generated 62/128
66
+ [sde] generated 63/128
67
+ [sde] generated 64/128
68
+ [sde] generated 65/128
69
+ [sde] generated 66/128
70
+ [sde] generated 67/128
71
+ [sde] generated 68/128
72
+ [sde] generated 69/128
73
+ [sde] generated 70/128
74
+ [sde] generated 71/128
75
+ [sde] generated 72/128
76
+ [sde] generated 73/128
77
+ [sde] generated 74/128
78
+ [sde] generated 75/128
79
+ [sde] generated 76/128
80
+ [sde] generated 77/128
81
+ [sde] generated 78/128
82
+ [sde] generated 79/128
83
+ [sde] generated 80/128
84
+ [sde] generated 81/128
85
+ [sde] generated 82/128
86
+ [sde] generated 83/128
87
+ [sde] generated 84/128
88
+ [sde] generated 85/128
89
+ [sde] generated 86/128
90
+ [sde] generated 87/128
91
+ [sde] generated 88/128
92
+ [sde] generated 89/128
93
+ [sde] generated 90/128
94
+ [sde] generated 91/128
95
+ [sde] generated 92/128
96
+ [sde] generated 93/128
97
+ [sde] generated 94/128
98
+ [sde] generated 95/128
99
+ [sde] generated 96/128
100
+ [sde] generated 97/128
101
+ [sde] generated 98/128
102
+ [sde] generated 99/128
103
+ [sde] generated 100/128
104
+ [sde] generated 101/128
105
+ [sde] generated 102/128
106
+ [sde] generated 103/128
107
+ [sde] generated 104/128
108
+ [sde] generated 105/128
109
+ [sde] generated 106/128
110
+ [sde] generated 107/128
111
+ [sde] generated 108/128
112
+ [sde] generated 109/128
113
+ [sde] generated 110/128
114
+ [sde] generated 111/128
115
+ [sde] generated 112/128
116
+ [sde] generated 113/128
117
+ [sde] generated 114/128
118
+ [sde] generated 115/128
119
+ [sde] generated 116/128
120
+ [sde] generated 117/128
121
+ [sde] generated 118/128
122
+ [sde] generated 119/128
123
+ [sde] generated 120/128
124
+ [sde] generated 121/128
125
+ [sde] generated 122/128
126
+ [sde] generated 123/128
127
+ [sde] generated 124/128
128
+ [sde] generated 125/128
129
+ [sde] generated 126/128
130
+ [sde] generated 127/128
131
+ [sde] generated 128/128
132
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
133
+ [summary] {
134
+ "type": "summary",
135
+ "checkpoint": "runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0004000.pt",
136
+ "step": 4000,
137
+ "decode": {
138
+ "decode_rule": "logistic_normal_resample_sde",
139
+ "steps": 128,
140
+ "model_t_mode": "support_t",
141
+ "concentration_min": 1.0,
142
+ "concentration_max": 1024.0,
143
+ "endpoint_temp": 1.45,
144
+ "support_power": 1.0,
145
+ "semantic_power": 1.0,
146
+ "noise_init": "logistic_normal",
147
+ "noise_sigma": 3.0,
148
+ "noise_dirichlet_concentration": 1.0,
149
+ "sde_resample": "logistic_normal",
150
+ "logistic_normal_sigma_min": 0.18,
151
+ "logistic_normal_sigma_max": 3.0,
152
+ "logistic_normal_tau_min": 0.65,
153
+ "logistic_normal_tau_max": 1.0,
154
+ "final_from": "blend_0.5",
155
+ "n_samples": 128,
156
+ "seed": 20260522
157
+ },
158
+ "raw_genppl": {
159
+ "ppl": 1.3498743610191395,
160
+ "nll_per_token": 0.3000115222076889,
161
+ "tokens": 130943,
162
+ "kept_samples": 128,
163
+ "total_samples": 128,
164
+ "empty_rate": 0.0,
165
+ "skipped_samples": 0
166
+ },
167
+ "stripped_genppl": {
168
+ "ppl": 1.3493787614143011,
169
+ "nll_per_token": 0.2996443098063853,
170
+ "tokens": 130939,
171
+ "kept_samples": 128,
172
+ "total_samples": 128,
173
+ "empty_rate": 0.0,
174
+ "skipped_samples": 0
175
+ },
176
+ "diversity": {
177
+ "sample_entropy": 0.17097849287621605,
178
+ "unique_tokens": 22,
179
+ "token_count": 131072,
180
+ "distinct_1": 0.0001678466796875,
181
+ "distinct_2": 0.000946969696969697,
182
+ "top_token_mass": 0.5273208618164062
183
+ }
184
+ }
185
+ [done] docs/lta_samples/metrics_20260522/owt_len1024_lognormal_atoms_every1k_logistic_normal_sde_modelt_support_t_t1p45_steps128_n128/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0004000/sde_steps128_samples128_scored.jsonl
186
+ [watch-owt-lognormal-sde] 2026-05-22_22:57:56 done step_0004000
LTA_openwebtext_dualt/logs/owt_len1024_lognormal_atoms_sde_watch/infer_lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs_step_0008000_logistic_normal_modelt_support_t_t1p45.log ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-owt-lognormal-sde] 2026-05-22_23:22:06 infer runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0008000.pt -> docs/lta_samples/metrics_20260522/owt_len1024_lognormal_atoms_every1k_logistic_normal_sde_modelt_support_t_t1p45_steps128_n128/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0008000
2
+ [load] runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0008000.pt
3
+ [ckpt] step=8000
4
+ [sde] generated 1/128
5
+ [sde] generated 2/128
6
+ [sde] generated 3/128
7
+ [sde] generated 4/128
8
+ [sde] generated 5/128
9
+ [sde] generated 6/128
10
+ [sde] generated 7/128
11
+ [sde] generated 8/128
12
+ [sde] generated 9/128
13
+ [sde] generated 10/128
14
+ [sde] generated 11/128
15
+ [sde] generated 12/128
16
+ [sde] generated 13/128
17
+ [sde] generated 14/128
18
+ [sde] generated 15/128
19
+ [sde] generated 16/128
20
+ [sde] generated 17/128
21
+ [sde] generated 18/128
22
+ [sde] generated 19/128
23
+ [sde] generated 20/128
24
+ [sde] generated 21/128
25
+ [sde] generated 22/128
26
+ [sde] generated 23/128
27
+ [sde] generated 24/128
28
+ [sde] generated 25/128
29
+ [sde] generated 26/128
30
+ [sde] generated 27/128
31
+ [sde] generated 28/128
32
+ [sde] generated 29/128
33
+ [sde] generated 30/128
34
+ [sde] generated 31/128
35
+ [sde] generated 32/128
36
+ [sde] generated 33/128
37
+ [sde] generated 34/128
38
+ [sde] generated 35/128
39
+ [sde] generated 36/128
40
+ [sde] generated 37/128
41
+ [sde] generated 38/128
42
+ [sde] generated 39/128
43
+ [sde] generated 40/128
44
+ [sde] generated 41/128
45
+ [sde] generated 42/128
46
+ [sde] generated 43/128
47
+ [sde] generated 44/128
48
+ [sde] generated 45/128
49
+ [sde] generated 46/128
50
+ [sde] generated 47/128
51
+ [sde] generated 48/128
52
+ [sde] generated 49/128
53
+ [sde] generated 50/128
54
+ [sde] generated 51/128
55
+ [sde] generated 52/128
56
+ [sde] generated 53/128
57
+ [sde] generated 54/128
58
+ [sde] generated 55/128
59
+ [sde] generated 56/128
60
+ [sde] generated 57/128
61
+ [sde] generated 58/128
62
+ [sde] generated 59/128
63
+ [sde] generated 60/128
64
+ [sde] generated 61/128
65
+ [sde] generated 62/128
66
+ [sde] generated 63/128
67
+ [sde] generated 64/128
68
+ [sde] generated 65/128
69
+ [sde] generated 66/128
70
+ [sde] generated 67/128
71
+ [sde] generated 68/128
72
+ [sde] generated 69/128
73
+ [sde] generated 70/128
74
+ [sde] generated 71/128
75
+ [sde] generated 72/128
76
+ [sde] generated 73/128
77
+ [sde] generated 74/128
78
+ [sde] generated 75/128
79
+ [sde] generated 76/128
80
+ [sde] generated 77/128
81
+ [sde] generated 78/128
82
+ [sde] generated 79/128
83
+ [sde] generated 80/128
84
+ [sde] generated 81/128
85
+ [sde] generated 82/128
86
+ [sde] generated 83/128
87
+ [sde] generated 84/128
88
+ [sde] generated 85/128
89
+ [sde] generated 86/128
90
+ [sde] generated 87/128
91
+ [sde] generated 88/128
92
+ [sde] generated 89/128
93
+ [sde] generated 90/128
94
+ [sde] generated 91/128
95
+ [sde] generated 92/128
96
+ [sde] generated 93/128
97
+ [sde] generated 94/128
98
+ [sde] generated 95/128
99
+ [sde] generated 96/128
100
+ [sde] generated 97/128
101
+ [sde] generated 98/128
102
+ [sde] generated 99/128
103
+ [sde] generated 100/128
104
+ [sde] generated 101/128
105
+ [sde] generated 102/128
106
+ [sde] generated 103/128
107
+ [sde] generated 104/128
108
+ [sde] generated 105/128
109
+ [sde] generated 106/128
110
+ [sde] generated 107/128
111
+ [sde] generated 108/128
112
+ [sde] generated 109/128
113
+ [sde] generated 110/128
114
+ [sde] generated 111/128
115
+ [sde] generated 112/128
116
+ [sde] generated 113/128
117
+ [sde] generated 114/128
118
+ [sde] generated 115/128
119
+ [sde] generated 116/128
120
+ [sde] generated 117/128
121
+ [sde] generated 118/128
122
+ [sde] generated 119/128
123
+ [sde] generated 120/128
124
+ [sde] generated 121/128
125
+ [sde] generated 122/128
126
+ [sde] generated 123/128
127
+ [sde] generated 124/128
128
+ [sde] generated 125/128
129
+ [sde] generated 126/128
130
+ [sde] generated 127/128
131
+ [sde] generated 128/128
132
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
133
+ [summary] {
134
+ "type": "summary",
135
+ "checkpoint": "runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0008000.pt",
136
+ "step": 8000,
137
+ "decode": {
138
+ "decode_rule": "logistic_normal_resample_sde",
139
+ "steps": 128,
140
+ "model_t_mode": "support_t",
141
+ "mean_mode": "anchor_semantic",
142
+ "endpoint_floor": 0.0,
143
+ "concentration_min": 1.0,
144
+ "concentration_max": 1024.0,
145
+ "endpoint_temp": 1.45,
146
+ "support_power": 1.0,
147
+ "semantic_power": 1.0,
148
+ "noise_init": "logistic_normal",
149
+ "noise_sigma": 3.0,
150
+ "noise_dirichlet_concentration": 1.0,
151
+ "sde_resample": "logistic_normal",
152
+ "logistic_normal_sigma_min": 0.18,
153
+ "logistic_normal_sigma_max": 3.0,
154
+ "logistic_normal_tau_min": 0.65,
155
+ "logistic_normal_tau_max": 1.0,
156
+ "final_from": "blend_0.5",
157
+ "n_samples": 128,
158
+ "seed": 20260522
159
+ },
160
+ "raw_genppl": {
161
+ "ppl": 2.9034504689664646,
162
+ "nll_per_token": 1.0658998466062661,
163
+ "tokens": 130880,
164
+ "kept_samples": 128,
165
+ "total_samples": 128,
166
+ "empty_rate": 0.0,
167
+ "skipped_samples": 0
168
+ },
169
+ "stripped_genppl": {
170
+ "ppl": 2.9020334175740543,
171
+ "nll_per_token": 1.0654116697554654,
172
+ "tokens": 130866,
173
+ "kept_samples": 128,
174
+ "total_samples": 128,
175
+ "empty_rate": 0.0,
176
+ "skipped_samples": 0
177
+ },
178
+ "diversity": {
179
+ "sample_entropy": 1.0366477167361456,
180
+ "unique_tokens": 35,
181
+ "token_count": 131072,
182
+ "distinct_1": 0.00026702880859375,
183
+ "distinct_2": 0.0018328445747800588,
184
+ "top_token_mass": 0.23432159423828125
185
+ }
186
+ }
187
+ [done] docs/lta_samples/metrics_20260522/owt_len1024_lognormal_atoms_every1k_logistic_normal_sde_modelt_support_t_t1p45_steps128_n128/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0008000/sde_steps128_samples128_scored.jsonl
188
+ [watch-owt-lognormal-sde] 2026-05-22_23:30:11 done step_0008000
LTA_openwebtext_dualt/logs/owt_len1024_lognormal_atoms_sde_watch/processed_lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs_logistic_normal_modelt_support_t_steps128_t1p45_n128.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0003000.pt
2
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0001000.pt
3
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0002000.pt
4
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0004000.pt
5
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0005000.pt
6
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0006000.pt
7
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0007000.pt
8
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0008000.pt
9
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0009000.pt
10
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0010000.pt
11
+ runs/lta_owt_classic_fullvocab_bert_c1024_len1024_lognormalatoms_smax3.0_abspos0_d768_l12_h12_ff3072_lr3e-4_gbs512_2node8gpu_1m_save1k_t-20260523052744-twlvs/step_0011000.pt
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/bin/activate.nu ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # virtualenv activation module:
23
+ # - Activate with `overlay use activate.nu`
24
+ # - Deactivate with `deactivate`, as usual
25
+ #
26
+ # To customize the overlay name, you can call `overlay use activate.nu as foo`, but then simply `deactivate` won't work
27
+ # because it is just an alias to hide the "activate" overlay. You'd need to call `overlay hide foo` manually.
28
+
29
+ module warning {
30
+ export-env {
31
+ const file = path self
32
+ error make -u {
33
+ msg: $"`($file | path basename)` is meant to be used with `overlay use`, not `source`"
34
+ }
35
+ }
36
+
37
+ }
38
+
39
+ use warning
40
+
41
+ export-env {
42
+
43
+ let nu_ver = (version | get version | split row '.' | take 2 | each { into int })
44
+ if $nu_ver.0 == 0 and $nu_ver.1 < 106 {
45
+ error make {
46
+ msg: 'virtualenv Nushell activation requires Nushell 0.106 or greater.'
47
+ }
48
+ }
49
+
50
+ def is-string [x] {
51
+ ($x | describe) == 'string'
52
+ }
53
+
54
+ def has-env [...names] {
55
+ $names | each {|n| $n in $env } | all {|i| $i }
56
+ }
57
+
58
+ def is-env-true [name: string] {
59
+ if (has-env $name) {
60
+ let val = ($env | get --optional $name)
61
+ if ($val | describe) == 'bool' {
62
+ $val
63
+ } else {
64
+ not ($val | is-empty)
65
+ }
66
+ } else {
67
+ false
68
+ }
69
+ }
70
+
71
+ let virtual_env = '/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv'
72
+ let bin = 'bin'
73
+ let path_name = if (has-env 'Path') { 'Path' } else { 'PATH' }
74
+ let venv_path = ([$virtual_env $bin] | path join)
75
+ let new_path = ($env | get $path_name | prepend $venv_path)
76
+ let virtual_env_prompt = if ('' | is-empty) {
77
+ ($virtual_env | path basename)
78
+ } else {
79
+ ''
80
+ }
81
+ let new_env = { $path_name: $new_path VIRTUAL_ENV: $virtual_env VIRTUAL_ENV_PROMPT: $virtual_env_prompt }
82
+ let old_prompt_command = if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' }
83
+ let new_env = if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
84
+ $new_env
85
+ } else {
86
+ let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
87
+ let new_prompt = if (has-env 'PROMPT_COMMAND') {
88
+ if ('closure' in ($old_prompt_command | describe)) {
89
+ {|| $'($virtual_prefix)(do $old_prompt_command)' }
90
+ } else {
91
+ {|| $'($virtual_prefix)($old_prompt_command)' }
92
+ }
93
+ } else {
94
+ {|| $'($virtual_prefix)' }
95
+ }
96
+ $new_env | merge { PROMPT_COMMAND: $new_prompt VIRTUAL_PREFIX: $virtual_prefix }
97
+ }
98
+ load-env $new_env
99
+ }
100
+
101
+ export alias pydoc = python -m pydoc
102
+ export alias deactivate = overlay hide activate
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/bin/huggingface-cli ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from huggingface_hub.cli.deprecated_cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jamba/__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_jamba import *
22
+ from .modeling_jamba 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/jamba/configuration_jamba.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 AI21 Labs Ltd. 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
+ """Jamba model configuration"""
15
+
16
+ import math
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import auto_docstring
22
+
23
+
24
+ @auto_docstring(checkpoint="ai21labs/Jamba-v0.1")
25
+ @strict
26
+ class JambaConfig(PreTrainedConfig):
27
+ r"""
28
+ expert_layer_period (`int`, *optional*, defaults to 2):
29
+ Once in this many layers, we will have an expert layer
30
+ expert_layer_offset (`int`, *optional*, defaults to 1):
31
+ The first layer index that contains an expert mlp layer
32
+ attn_layer_period (`int`, *optional*, defaults to 8):
33
+ Once in this many layers, we will have a vanilla attention layer
34
+ attn_layer_offset (`int`, *optional*, defaults to 4):
35
+ The first layer index that contains a vanilla attention mlp layer
36
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
37
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
38
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device. Raises ValueError if
39
+ `True` and kernels are not available
40
+ mamba_dt_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
41
+ Rank of the mamba discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
42
+ """
43
+
44
+ model_type = "jamba"
45
+ keys_to_ignore_at_inference = ["past_key_values"]
46
+ attribute_map = {
47
+ "num_local_experts": "num_experts",
48
+ }
49
+
50
+ vocab_size: int = 65536
51
+ tie_word_embeddings: bool = False
52
+ hidden_size: int = 4096
53
+ intermediate_size: int = 14336
54
+ num_hidden_layers: int = 32
55
+ num_attention_heads: int = 32
56
+ num_key_value_heads: int = 8
57
+ hidden_act: str = "silu"
58
+ initializer_range: float = 0.02
59
+ rms_norm_eps: float = 1e-6
60
+ use_cache: bool = True
61
+ output_router_logits: bool = False
62
+ router_aux_loss_coef: float = 0.001
63
+ pad_token_id: int | None = 0
64
+ bos_token_id: int | None = 1
65
+ eos_token_id: int | list[int] | None = 2
66
+ max_position_embeddings: int = 262144
67
+ attention_dropout: float | int = 0.0
68
+ num_experts_per_tok: int = 2
69
+ num_experts: int = 16
70
+ expert_layer_period: int = 2
71
+ expert_layer_offset: int = 1
72
+ attn_layer_period: int = 8
73
+ attn_layer_offset: int = 4
74
+ use_mamba_kernels: bool = True
75
+ mamba_d_state: int = 16
76
+ mamba_d_conv: int = 4
77
+ mamba_expand: int = 2
78
+ mamba_dt_rank: int | str = "auto"
79
+ mamba_conv_bias: bool = True
80
+ mamba_proj_bias: bool = False
81
+
82
+ def __post_init__(self, **kwargs):
83
+ if self.num_key_value_heads is None:
84
+ self.num_key_value_heads = self.num_attention_heads
85
+
86
+ self.mamba_dt_rank = math.ceil(self.hidden_size / 16) if self.mamba_dt_rank == "auto" else self.mamba_dt_rank
87
+ super().__post_init__(**kwargs)
88
+
89
+ @property
90
+ def layers_block_type(self):
91
+ return [
92
+ "attention" if i % self.attn_layer_period == self.attn_layer_offset else "mamba"
93
+ for i in range(self.num_hidden_layers)
94
+ ]
95
+
96
+ @property
97
+ def layer_types(self):
98
+ # Follow the `layer_types` conventions
99
+ layer_types = self.layers_block_type
100
+ return ["full_attention" if x == "attention" else x for x in layer_types]
101
+
102
+ @property
103
+ def layers_num_experts(self):
104
+ return [
105
+ self.num_experts if i % self.expert_layer_period == self.expert_layer_offset else 1
106
+ for i in range(self.num_hidden_layers)
107
+ ]
108
+
109
+ def validate_architecture(self):
110
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
111
+ if self.attn_layer_offset >= self.attn_layer_period:
112
+ raise ValueError(
113
+ f"attention layer offset ({self.attn_layer_offset}) must be smaller than attention layer period ({self.attn_layer_period})"
114
+ )
115
+
116
+ if self.expert_layer_offset >= self.expert_layer_period:
117
+ raise ValueError(
118
+ f"expert layer offset ({self.expert_layer_offset}) must be smaller than expert layer period ({self.expert_layer_period})"
119
+ )
120
+
121
+
122
+ __all__ = ["JambaConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jamba/modular_jamba.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 AI21 Labs Ltd. and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ from collections.abc import Callable
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ... import initialization as init
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache
27
+ from ...integrations import lazy_load_kernel
28
+ from ...masking_utils import create_causal_mask
29
+ from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
30
+ from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
31
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
32
+ from ...processing_utils import Unpack
33
+ from ...utils import TransformersKwargs, auto_docstring, logging
34
+ from ...utils.generic import merge_with_config_defaults
35
+ from ...utils.import_utils import resolve_internal_import
36
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
37
+ from ..llama.modeling_llama import LlamaAttention, LlamaRMSNorm, eager_attention_forward
38
+ from ..mistral.modeling_mistral import MistralMLP
39
+ from ..mixtral.modeling_mixtral import MixtralExperts, MixtralForCausalLM
40
+ from .configuration_jamba import JambaConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class JambaRMSNorm(LlamaRMSNorm):
47
+ pass
48
+
49
+
50
+ class JambaAttention(LlamaAttention):
51
+ def __init__(self, config: JambaConfig, layer_idx: int):
52
+ super().__init__(config, layer_idx)
53
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
54
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
55
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
56
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
57
+
58
+ def forward(
59
+ self,
60
+ hidden_states: torch.Tensor,
61
+ attention_mask: torch.Tensor | None = None,
62
+ past_key_values: Cache | None = None,
63
+ **kwargs: Unpack[TransformersKwargs],
64
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
65
+ input_shape = hidden_states.shape[:-1]
66
+ hidden_shape = (*input_shape, -1, self.head_dim)
67
+
68
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
69
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
70
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
71
+
72
+ if past_key_values is not None:
73
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
74
+
75
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
76
+ self.config._attn_implementation, eager_attention_forward
77
+ )
78
+
79
+ attn_output, attn_weights = attention_interface(
80
+ self,
81
+ query_states,
82
+ key_states,
83
+ value_states,
84
+ attention_mask,
85
+ dropout=0.0 if not self.training else self.attention_dropout,
86
+ scaling=self.scaling,
87
+ **kwargs,
88
+ )
89
+
90
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
91
+ attn_output = self.o_proj(attn_output)
92
+ return attn_output, attn_weights
93
+
94
+
95
+ class JambaMambaMixer(nn.Module):
96
+ """
97
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
98
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
99
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
100
+ and is why Mamba is called **selective** state spaces)
101
+ """
102
+
103
+ def __init__(self, config: JambaConfig, layer_idx):
104
+ super().__init__()
105
+ self.config = config
106
+ self.layer_idx = layer_idx
107
+ self.hidden_size = config.hidden_size
108
+ self.ssm_state_size = config.mamba_d_state
109
+ self.conv_kernel_size = config.mamba_d_conv
110
+ self.intermediate_size = config.mamba_expand * config.hidden_size
111
+ self.time_step_rank = config.mamba_dt_rank
112
+ self.use_conv_bias = config.mamba_conv_bias
113
+ self.use_bias = config.mamba_proj_bias
114
+ self.conv1d = nn.Conv1d(
115
+ in_channels=self.intermediate_size,
116
+ out_channels=self.intermediate_size,
117
+ bias=self.use_conv_bias,
118
+ kernel_size=self.conv_kernel_size,
119
+ groups=self.intermediate_size,
120
+ padding=self.conv_kernel_size - 1,
121
+ )
122
+
123
+ self.activation = config.hidden_act
124
+ self.act = ACT2FN[config.hidden_act]
125
+
126
+ # projection of the input hidden states
127
+ self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=self.use_bias)
128
+ # selective projection used to make dt, B and C input dependent
129
+ self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False)
130
+ # time step projection (discretization)
131
+ self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True)
132
+
133
+ # S4D real initialization. These are not discretized!
134
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
135
+ A = torch.arange(1, self.ssm_state_size + 1)[None, :]
136
+ A = A.expand(self.intermediate_size, -1).contiguous()
137
+
138
+ self.A_log = nn.Parameter(torch.log(A))
139
+ self.D = nn.Parameter(torch.ones(self.intermediate_size))
140
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
141
+
142
+ self.dt_layernorm = JambaRMSNorm(self.time_step_rank, eps=config.rms_norm_eps)
143
+ self.b_layernorm = JambaRMSNorm(self.ssm_state_size, eps=config.rms_norm_eps)
144
+ self.c_layernorm = JambaRMSNorm(self.ssm_state_size, eps=config.rms_norm_eps)
145
+
146
+ global causal_conv1d_update, causal_conv1d_fn
147
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
148
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
149
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
150
+
151
+ global selective_state_update, mamba_inner_fn, selective_scan_fn
152
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
153
+ selective_state_update = resolve_internal_import(
154
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
155
+ )
156
+ selective_scan_fn = getattr(mamba_ssm, "selective_scan_fn", None)
157
+ mamba_inner_fn = getattr(mamba_ssm, "mamba_inner_fn", None)
158
+
159
+ global is_fast_path_available
160
+ is_fast_path_available = all(
161
+ (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)
162
+ )
163
+
164
+ if not is_fast_path_available:
165
+ logger.warning_once(
166
+ "The fast path is not available because on of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
167
+ " is None. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1d."
168
+ )
169
+
170
+ def cuda_kernels_forward(
171
+ self,
172
+ hidden_states: torch.Tensor,
173
+ cache_params: Cache | None = None,
174
+ attention_mask: torch.LongTensor | None = None,
175
+ ):
176
+ batch_size, seq_len, _ = hidden_states.shape
177
+ use_precomputed_states = (
178
+ cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
179
+ )
180
+ # 1. Gated MLP's linear projection
181
+ projected_states = self.in_proj(hidden_states).transpose(1, 2)
182
+
183
+ # We can't use `mamba_inner_fn` even if in training and without cache params because we have the
184
+ # inner layernorms which isn't supported by this fused kernel
185
+ hidden_states, gate = projected_states.chunk(2, dim=1)
186
+
187
+ if attention_mask is not None:
188
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
189
+
190
+ # 2. Convolution sequence transformation
191
+ conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
192
+ if use_precomputed_states:
193
+ hidden_states = causal_conv1d_update(
194
+ hidden_states.squeeze(-1),
195
+ cache_params.layers[self.layer_idx].conv_states,
196
+ conv_weights,
197
+ self.conv1d.bias,
198
+ self.activation,
199
+ )
200
+ hidden_states = hidden_states.unsqueeze(-1)
201
+ else:
202
+ if cache_params is not None:
203
+ conv_states = nn.functional.pad(hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0))
204
+ cache_params.update_conv_state(conv_states, self.layer_idx)
205
+ hidden_states = causal_conv1d_fn(hidden_states, conv_weights, self.conv1d.bias, activation=self.activation)
206
+
207
+ if attention_mask is not None:
208
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
209
+
210
+ # 3. State Space Model sequence transformation
211
+ # 3.a. input varying initialization of time_step, B and C
212
+ ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
213
+ time_step, B, C = torch.split(
214
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
215
+ )
216
+
217
+ time_step = self.dt_layernorm(time_step)
218
+ B = self.b_layernorm(B)
219
+ C = self.c_layernorm(C)
220
+
221
+ # Here we need to apply dt_proj without the bias, as the bias is added in the selective scan kernel.
222
+ # This is a hack to apply dt_proj while still using the forward pass of `torch.nn.Linear`, which is needed
223
+ # in order to make quantization work. Quantization code replaces `torch.nn.Linear` layers with quantized
224
+ # linear layers, and requires to call the forward pass directly.
225
+ # Quantized model can't work with the original code:
226
+ # ```discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2)```
227
+ time_proj_bias = self.dt_proj.bias.data
228
+ with torch.no_grad():
229
+ self.dt_proj.bias.data = torch.zeros_like(self.dt_proj.bias.data)
230
+ discrete_time_step = self.dt_proj(time_step).transpose(1, 2)
231
+ with torch.no_grad():
232
+ self.dt_proj.bias.data = time_proj_bias
233
+
234
+ A = -torch.exp(self.A_log.float())
235
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
236
+ time_proj_bias = time_proj_bias.float() if time_proj_bias is not None else None
237
+ if use_precomputed_states:
238
+ scan_outputs = selective_state_update(
239
+ cache_params.layers[self.layer_idx].recurrent_states,
240
+ hidden_states[..., 0],
241
+ discrete_time_step[..., 0],
242
+ A,
243
+ B[:, 0],
244
+ C[:, 0],
245
+ self.D,
246
+ gate[..., 0],
247
+ time_proj_bias,
248
+ dt_softplus=True,
249
+ ).unsqueeze(-1)
250
+ else:
251
+ scan_outputs, ssm_state = selective_scan_fn(
252
+ hidden_states,
253
+ discrete_time_step,
254
+ A,
255
+ B.transpose(1, 2),
256
+ C.transpose(1, 2),
257
+ self.D.float(),
258
+ gate,
259
+ time_proj_bias,
260
+ delta_softplus=True,
261
+ return_last_state=True,
262
+ )
263
+ if ssm_state is not None and cache_params is not None:
264
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
265
+
266
+ # 4. Final linear projection
267
+ contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
268
+
269
+ return contextualized_states
270
+
271
+ # fmt: off
272
+ def slow_forward(self, input_states, cache_params: Cache | None = None, attention_mask: torch.LongTensor | None = None):
273
+ batch_size, seq_len, _ = input_states.shape
274
+ dtype = input_states.dtype
275
+ # 1. Gated MLP's linear projection
276
+ projected_states = self.in_proj(input_states).transpose(1, 2)
277
+ hidden_states, gate = projected_states.chunk(2, dim=1)
278
+
279
+ if attention_mask is not None:
280
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
281
+
282
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
283
+ # In training mode, we don't want to perform in-place operations on ssm_state so we can compute the backwards pass
284
+ ssm_state = cache_params.layers[self.layer_idx].recurrent_states.clone()
285
+ else:
286
+ ssm_state = torch.zeros(
287
+ (batch_size, self.intermediate_size, self.ssm_state_size),
288
+ device=hidden_states.device, dtype=dtype
289
+ )
290
+
291
+ # 2. Convolution sequence transformation
292
+ if cache_params is not None:
293
+ if cache_params.has_previous_state(self.layer_idx) and seq_len == 1:
294
+ conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
295
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
296
+ if self.use_conv_bias:
297
+ hidden_states += self.conv1d.bias
298
+ hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1)
299
+ else:
300
+ conv_state = nn.functional.pad(
301
+ hidden_states,
302
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
303
+ )
304
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
305
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
306
+ else:
307
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
308
+
309
+ if attention_mask is not None:
310
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
311
+
312
+ # 3. State Space Model sequence transformation
313
+ # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
314
+ ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
315
+ time_step, B, C = torch.split(
316
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
317
+ )
318
+
319
+ time_step = self.dt_layernorm(time_step)
320
+ B = self.b_layernorm(B)
321
+ C = self.c_layernorm(C)
322
+
323
+ discrete_time_step = self.dt_proj(time_step)
324
+ discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2)
325
+
326
+ # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
327
+ A = -torch.exp(self.A_log.float())
328
+ discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None])
329
+ discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float()
330
+ deltaB_u = discrete_B * hidden_states[:, :, :, None].float()
331
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
332
+ scan_outputs = []
333
+ for i in range(seq_len):
334
+ ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :]
335
+ scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1))
336
+ scan_outputs.append(scan_output[:, :, 0])
337
+ scan_output = torch.stack(scan_outputs, dim=-1)
338
+ scan_output = scan_output + (hidden_states * self.D[None, :, None])
339
+ scan_output = (scan_output * self.act(gate))
340
+
341
+ if cache_params is not None:
342
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
343
+
344
+ # 4. Final linear projection
345
+ contextualized_states = self.out_proj(scan_output.transpose(1, 2))
346
+ return contextualized_states
347
+ # fmt: on
348
+
349
+ def forward(
350
+ self,
351
+ hidden_states,
352
+ cache_params: Cache | None = None,
353
+ attention_mask: torch.LongTensor | None = None,
354
+ ):
355
+ if self.config.use_mamba_kernels and (
356
+ not is_fast_path_available or "cuda" not in self.x_proj.weight.device.type
357
+ ):
358
+ logger.warning_once(
359
+ "Fast Mamba kernels are not available. Make sure that they are installed "
360
+ "and that the mamba module is on a CUDA device. Turning off the fast path "
361
+ "`config.use_mamba_kernels=False` and falling back to the slow path."
362
+ )
363
+ self.config.use_mamba_kernels = False
364
+
365
+ if self.config.use_mamba_kernels:
366
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
367
+ return self.slow_forward(hidden_states, cache_params, attention_mask)
368
+
369
+
370
+ class JambaMLP(MistralMLP):
371
+ pass
372
+
373
+
374
+ class JambaExperts(MixtralExperts):
375
+ pass
376
+
377
+
378
+ class JambaSparseMoeBlock(nn.Module):
379
+ """
380
+ This implementation is
381
+ strictly equivalent to standard MoE with full capacity (no
382
+ dropped tokens). It's faster since it formulates MoE operations
383
+ in terms of block-sparse operations to accommodate imbalanced
384
+ assignments of tokens to experts, whereas standard MoE either
385
+ (1) drop tokens at the cost of reduced performance or (2) set
386
+ capacity factor to number of experts and thus waste computation
387
+ and memory on padding.
388
+ """
389
+
390
+ def __init__(self, config: JambaConfig):
391
+ super().__init__()
392
+ self.hidden_dim = config.hidden_size
393
+ self.ffn_dim = config.intermediate_size
394
+ self.num_experts = config.num_experts
395
+ self.top_k = config.num_experts_per_tok
396
+
397
+ self.router = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
398
+ self.experts = JambaExperts(config)
399
+
400
+ def route_tokens_to_experts(self, hidden_states, router_logits):
401
+ routing_weights = torch.nn.functional.softmax(router_logits, dim=-1, dtype=torch.float)
402
+ top_k_weights, top_k_index = torch.topk(routing_weights, self.top_k, dim=-1)
403
+ return top_k_index, top_k_weights.to(hidden_states.dtype)
404
+
405
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
406
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
407
+ hidden_states = hidden_states.view(-1, hidden_dim)
408
+ router_logits = self.router(hidden_states)
409
+ top_k_index, top_k_weights = self.route_tokens_to_experts(hidden_states, router_logits)
410
+ hidden_states = self.experts(hidden_states, top_k_index, top_k_weights)
411
+ hidden_states = hidden_states.reshape(batch_size, sequence_length, hidden_dim)
412
+ return hidden_states
413
+
414
+
415
+ class JambaAttentionDecoderLayer(GradientCheckpointingLayer):
416
+ def __init__(self, config: JambaConfig, layer_idx: int):
417
+ super().__init__()
418
+ num_experts = config.layers_num_experts[layer_idx] if config.layers_num_experts else 1
419
+ self.self_attn = JambaAttention(config, layer_idx)
420
+
421
+ ffn_layer_class = JambaSparseMoeBlock if num_experts > 1 else JambaMLP
422
+ self.feed_forward = ffn_layer_class(config)
423
+ self.input_layernorm = JambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
424
+ self.pre_ff_layernorm = JambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
425
+
426
+ def forward(
427
+ self,
428
+ hidden_states: torch.Tensor,
429
+ attention_mask: torch.Tensor | None = None,
430
+ position_ids: torch.LongTensor | None = None,
431
+ past_key_values: Cache | None = None,
432
+ use_cache: bool | None = False,
433
+ **kwargs: Unpack[TransformersKwargs],
434
+ ) -> torch.FloatTensor:
435
+ residual = hidden_states
436
+ hidden_states = self.input_layernorm(hidden_states)
437
+ hidden_states, _ = self.self_attn(
438
+ hidden_states=hidden_states,
439
+ attention_mask=attention_mask,
440
+ position_ids=position_ids,
441
+ past_key_values=past_key_values,
442
+ use_cache=use_cache,
443
+ **kwargs,
444
+ )
445
+ hidden_states = residual + hidden_states
446
+ residual = hidden_states
447
+ hidden_states = self.pre_ff_layernorm(hidden_states)
448
+ hidden_states = self.feed_forward(hidden_states)
449
+ hidden_states = residual + hidden_states
450
+ return hidden_states
451
+
452
+
453
+ class JambaMambaDecoderLayer(GradientCheckpointingLayer):
454
+ def __init__(self, config: JambaConfig, layer_idx: int):
455
+ super().__init__()
456
+ num_experts = config.layers_num_experts[layer_idx] if config.layers_num_experts else 1
457
+ self.mamba = JambaMambaMixer(config=config, layer_idx=layer_idx)
458
+ ffn_layer_class = JambaSparseMoeBlock if num_experts > 1 else JambaMLP
459
+ self.feed_forward = ffn_layer_class(config)
460
+ self.input_layernorm = JambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
461
+ self.pre_ff_layernorm = JambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
462
+
463
+ def forward(
464
+ self,
465
+ hidden_states: torch.Tensor,
466
+ attention_mask: torch.Tensor | None = None,
467
+ position_ids: torch.LongTensor | None = None,
468
+ past_key_values: Cache | None = None,
469
+ **kwargs: Unpack[TransformersKwargs],
470
+ ) -> torch.FloatTensor:
471
+ residual = hidden_states
472
+ hidden_states = self.input_layernorm(hidden_states)
473
+ hidden_states = self.mamba(
474
+ hidden_states=hidden_states,
475
+ cache_params=past_key_values,
476
+ attention_mask=attention_mask,
477
+ )
478
+ hidden_states = residual + hidden_states
479
+ residual = hidden_states
480
+ hidden_states = self.pre_ff_layernorm(hidden_states)
481
+ hidden_states = self.feed_forward(hidden_states)
482
+ hidden_states = residual + hidden_states
483
+ return hidden_states
484
+
485
+
486
+ ALL_DECODER_LAYER_TYPES = {"attention": JambaAttentionDecoderLayer, "mamba": JambaMambaDecoderLayer}
487
+
488
+
489
+ class JambaPreTrainedModel(PreTrainedModel):
490
+ config: JambaConfig
491
+ base_model_prefix = "model"
492
+ supports_gradient_checkpointing = True
493
+ _no_split_modules = ["JambaAttentionDecoderLayer", "JambaMambaDecoderLayer"]
494
+ _skip_keys_device_placement = ["past_key_values"]
495
+ _supports_flash_attn = True
496
+ _supports_sdpa = True
497
+ _is_stateful = True
498
+ _can_record_outputs = {
499
+ "hidden_states": [JambaAttentionDecoderLayer, JambaMambaDecoderLayer],
500
+ "attentions": JambaAttention,
501
+ "router_logits": OutputRecorder(nn.Linear, layer_name="router"),
502
+ }
503
+
504
+ @torch.no_grad()
505
+ def _init_weights(self, module):
506
+ super()._init_weights(module)
507
+ if isinstance(module, JambaMambaMixer):
508
+ A = torch.arange(1, module.ssm_state_size + 1)[None, :]
509
+ A = A.expand(module.intermediate_size, -1).contiguous()
510
+ init.copy_(module.A_log, torch.log(A))
511
+ init.ones_(module.D)
512
+ elif isinstance(module, JambaExperts):
513
+ init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
514
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
515
+
516
+
517
+ @auto_docstring
518
+ class JambaModel(JambaPreTrainedModel):
519
+ def __init__(self, config: JambaConfig):
520
+ super().__init__(config)
521
+ self.padding_idx = config.pad_token_id
522
+ self.vocab_size = config.vocab_size
523
+
524
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
525
+ decoder_layers = []
526
+ for i in range(config.num_hidden_layers):
527
+ layer_class = ALL_DECODER_LAYER_TYPES[config.layers_block_type[i]]
528
+ decoder_layers.append(layer_class(config, layer_idx=i))
529
+ self.layers = nn.ModuleList(decoder_layers)
530
+
531
+ self.final_layernorm = JambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
532
+
533
+ self.gradient_checkpointing = False
534
+ # Initialize weights and apply final processing
535
+ self.post_init()
536
+
537
+ @merge_with_config_defaults
538
+ @capture_outputs
539
+ @auto_docstring
540
+ def forward(
541
+ self,
542
+ input_ids: torch.LongTensor | None = None,
543
+ attention_mask: torch.Tensor | None = None,
544
+ position_ids: torch.LongTensor | None = None,
545
+ past_key_values: Cache | None = None,
546
+ inputs_embeds: torch.FloatTensor | None = None,
547
+ use_cache: bool | None = None,
548
+ **kwargs: Unpack[TransformersKwargs],
549
+ ) -> MoeModelOutputWithPast:
550
+ if (input_ids is None) ^ (inputs_embeds is not None):
551
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
552
+
553
+ if inputs_embeds is None:
554
+ inputs_embeds = self.embed_tokens(input_ids)
555
+
556
+ if use_cache and past_key_values is None:
557
+ past_key_values = DynamicCache(config=self.config)
558
+
559
+ if position_ids is None:
560
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
561
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
562
+ position_ids = position_ids.unsqueeze(0)
563
+
564
+ causal_mask = create_causal_mask(
565
+ config=self.config,
566
+ inputs_embeds=inputs_embeds,
567
+ attention_mask=attention_mask,
568
+ past_key_values=past_key_values,
569
+ position_ids=position_ids,
570
+ )
571
+ mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
572
+ hidden_states = inputs_embeds
573
+ for decoder_layer in self.layers:
574
+ layer_mask = mamba_mask if isinstance(decoder_layer, JambaMambaDecoderLayer) else causal_mask
575
+
576
+ hidden_states = decoder_layer(
577
+ hidden_states,
578
+ attention_mask=layer_mask,
579
+ position_ids=position_ids,
580
+ past_key_values=past_key_values,
581
+ use_cache=use_cache,
582
+ **kwargs,
583
+ )
584
+
585
+ hidden_states = self.final_layernorm(hidden_states)
586
+
587
+ return MoeModelOutputWithPast(
588
+ last_hidden_state=hidden_states,
589
+ past_key_values=past_key_values,
590
+ )
591
+
592
+ def _update_mamba_mask(self, attention_mask, past_key_values):
593
+ """
594
+ No need for zeroing states when
595
+ 1. Cached forward
596
+ 2. Attending to all inputs
597
+ """
598
+ mamba_mask = attention_mask
599
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
600
+ attention_mask is not None and torch.all(attention_mask == 1)
601
+ ):
602
+ mamba_mask = None
603
+ return mamba_mask
604
+
605
+
606
+ class JambaForCausalLM(MixtralForCausalLM):
607
+ def __init__(self, config: JambaConfig):
608
+ super().__init__(config)
609
+ self.num_experts = config.num_experts
610
+
611
+ def forward(
612
+ self,
613
+ input_ids: torch.LongTensor | None = None,
614
+ attention_mask: torch.Tensor | None = None,
615
+ position_ids: torch.LongTensor | None = None,
616
+ past_key_values: Cache | None = None,
617
+ inputs_embeds: torch.FloatTensor | None = None,
618
+ labels: torch.LongTensor | None = None,
619
+ use_cache: bool | None = None,
620
+ output_router_logits: bool | None = None,
621
+ logits_to_keep: int | torch.Tensor = 0,
622
+ **kwargs: Unpack[TransformersKwargs],
623
+ ) -> MoeCausalLMOutputWithPast:
624
+ r"""
625
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
626
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
627
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
628
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
629
+
630
+ Example:
631
+
632
+ ```python
633
+ >>> from transformers import AutoTokenizer, JambaForCausalLM
634
+
635
+ >>> model = JambaForCausalLM.from_pretrained("ai21labs/Jamba-v0.1")
636
+ >>> tokenizer = AutoTokenizer.from_pretrained("ai21labs/Jamba-v0.1")
637
+
638
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
639
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
640
+
641
+ >>> # Generate
642
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
643
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
644
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
645
+ ```"""
646
+ return super().forward(
647
+ input_ids,
648
+ attention_mask,
649
+ position_ids,
650
+ past_key_values,
651
+ inputs_embeds,
652
+ labels,
653
+ use_cache,
654
+ logits_to_keep,
655
+ **kwargs,
656
+ )
657
+
658
+
659
+ class JambaForSequenceClassification(GenericForSequenceClassification, JambaPreTrainedModel):
660
+ pass
661
+
662
+
663
+ __all__ = ["JambaForCausalLM", "JambaForSequenceClassification", "JambaModel", "JambaPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mvp/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from ..roberta.tokenization_roberta import RobertaTokenizer as MvpTokenizer
22
+ from .configuration_mvp import *
23
+ from .modeling_mvp import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mvp/configuration_mvp.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Fairseq Authors 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
+ """MVP 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="RUCAIBox/mvp")
23
+ @strict
24
+ class MvpConfig(PreTrainedConfig):
25
+ r"""
26
+ use_prompt (`bool`, *optional*, defaults to `False`):
27
+ Whether or not to use prompt.
28
+ prompt_length (`int`, *optional*, defaults to 100):
29
+ The length of prompt.
30
+ prompt_mid_dim (`int`, *optional*, defaults to 800):
31
+ Dimensionality of the "intermediate" layer in prompt.
32
+
33
+ Example:
34
+
35
+ ```python
36
+ >>> from transformers import MvpConfig, MvpModel
37
+
38
+ >>> # Initializing a MVP RUCAIBox/mvp style configuration
39
+ >>> configuration = MvpConfig()
40
+
41
+ >>> # Initializing a model (with random weights) from the RUCAIBox/mvp style configuration
42
+ >>> model = MvpModel(configuration)
43
+
44
+ >>> # Accessing the model configuration
45
+ >>> configuration = model.config
46
+ ```"""
47
+
48
+ model_type = "mvp"
49
+ keys_to_ignore_at_inference = ["past_key_values"]
50
+ attribute_map = {
51
+ "num_attention_heads": "encoder_attention_heads",
52
+ "hidden_size": "d_model",
53
+ "num_hidden_layers": "encoder_layers",
54
+ }
55
+
56
+ vocab_size: int = 50267
57
+ max_position_embeddings: int = 1024
58
+ encoder_layers: int = 12
59
+ encoder_ffn_dim: int = 4096
60
+ encoder_attention_heads: int = 16
61
+ decoder_layers: int = 12
62
+ decoder_ffn_dim: int = 4096
63
+ decoder_attention_heads: int = 16
64
+ encoder_layerdrop: float | int = 0.0
65
+ decoder_layerdrop: float | int = 0.0
66
+ activation_function: str = "gelu"
67
+ d_model: int = 1024
68
+ dropout: float | int = 0.1
69
+ attention_dropout: float | int = 0.0
70
+ activation_dropout: float | int = 0.0
71
+ init_std: float = 0.02
72
+ classifier_dropout: float | int = 0.0
73
+ scale_embedding: bool = False
74
+ use_cache: bool = True
75
+ pad_token_id: int | None = 1
76
+ bos_token_id: int | None = 0
77
+ eos_token_id: int | list[int] | None = 2
78
+ is_encoder_decoder: bool = True
79
+ decoder_start_token_id: int | None = 2
80
+ use_prompt: bool = False
81
+ prompt_length: int = 100
82
+ prompt_mid_dim: int = 800
83
+ is_decoder: bool = False
84
+ tie_word_embeddings: bool = True
85
+
86
+
87
+ __all__ = ["MvpConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mvp/modeling_mvp.py ADDED
@@ -0,0 +1,1630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Fairseq Authors 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 MVP model."""
15
+
16
+ import math
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
25
+ from ...generation import GenerationMixin
26
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import (
29
+ BaseModelOutput,
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ Seq2SeqLMOutput,
33
+ Seq2SeqModelOutput,
34
+ Seq2SeqQuestionAnsweringModelOutput,
35
+ Seq2SeqSequenceClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...utils import auto_docstring, logging, torch_compilable_check
39
+ from .configuration_mvp import MvpConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
46
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
47
+ """
48
+ Shift input ids one token to the right.
49
+ """
50
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
51
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
52
+ shifted_input_ids[:, 0] = decoder_start_token_id
53
+
54
+ if pad_token_id is None:
55
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
56
+ # replace possible -100 values in labels by `pad_token_id`
57
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
58
+
59
+ return shifted_input_ids
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->Mvp
63
+ class MvpLearnedPositionalEmbedding(nn.Embedding):
64
+ """
65
+ This module learns positional embeddings up to a fixed maximum size.
66
+ """
67
+
68
+ def __init__(self, num_embeddings: int, embedding_dim: int):
69
+ # Mvp is set up so that if padding_idx is specified then offset the embedding ids by 2
70
+ # and adjust num_embeddings appropriately. Other models don't have this hack
71
+ self.offset = 2
72
+ super().__init__(num_embeddings + self.offset, embedding_dim)
73
+
74
+ def forward(
75
+ self, input_ids: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
76
+ ):
77
+ """`input_ids' shape is expected to be [bsz x seqlen]."""
78
+
79
+ if position_ids is None:
80
+ bsz, seq_len = input_ids.shape[:2]
81
+ position_ids = torch.arange(
82
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
83
+ ).expand(bsz, -1)
84
+ else:
85
+ position_ids = position_ids.unsqueeze(0)
86
+
87
+ return super().forward(position_ids + self.offset)
88
+
89
+
90
+ class MvpAttention(nn.Module):
91
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
92
+
93
+ def __init__(
94
+ self,
95
+ embed_dim: int,
96
+ num_heads: int,
97
+ dropout: float | None = 0.0,
98
+ is_decoder: bool | None = False,
99
+ bias: bool | None = True,
100
+ layer_idx: bool | None = None,
101
+ ):
102
+ super().__init__()
103
+ self.embed_dim = embed_dim
104
+ self.num_heads = num_heads
105
+ self.dropout = dropout
106
+ self.head_dim = embed_dim // num_heads
107
+
108
+ if (self.head_dim * num_heads) != self.embed_dim:
109
+ raise ValueError(
110
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
111
+ f" and `num_heads`: {num_heads})."
112
+ )
113
+ self.scaling = self.head_dim**-0.5
114
+ self.is_decoder = is_decoder
115
+ self.layer_idx = layer_idx
116
+
117
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
118
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
119
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
120
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
121
+
122
+ def forward(
123
+ self,
124
+ hidden_states: torch.Tensor,
125
+ key_value_states: torch.Tensor | None = None,
126
+ past_key_values: Cache | None = None,
127
+ attention_mask: torch.Tensor | None = None,
128
+ attn_prompt: torch.Tensor | None = None,
129
+ output_attentions: bool = False,
130
+ **kwargs,
131
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
132
+ """Input shape: Batch x Time x Channel"""
133
+
134
+ # if key_value_states are provided this layer is used as a cross-attention layer
135
+ # for the decoder
136
+ is_cross_attention = key_value_states is not None
137
+
138
+ bsz, tgt_len, _ = hidden_states.size()
139
+
140
+ # get query proj
141
+ query_states = self.q_proj(hidden_states) * self.scaling
142
+
143
+ is_updated = False
144
+ if past_key_values is not None:
145
+ if isinstance(past_key_values, EncoderDecoderCache):
146
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
147
+ if is_cross_attention:
148
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
149
+ curr_past_key_values = past_key_values.cross_attention_cache
150
+ else:
151
+ curr_past_key_values = past_key_values.self_attention_cache
152
+ else:
153
+ curr_past_key_values = past_key_values
154
+
155
+ current_states = key_value_states if is_cross_attention else hidden_states
156
+ if is_cross_attention and past_key_values is not None and is_updated:
157
+ # reuse k,v, cross_attentions
158
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
159
+ value_states = curr_past_key_values.layers[self.layer_idx].values
160
+ else:
161
+ key_states = self.k_proj(current_states)
162
+ value_states = self.v_proj(current_states)
163
+ key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
164
+ value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
165
+
166
+ if past_key_values is not None:
167
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
168
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
169
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
170
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
171
+ past_key_values.is_updated[self.layer_idx] = True
172
+
173
+ if attn_prompt is not None:
174
+ key_states = torch.cat([attn_prompt[0].expand(bsz, -1, -1, -1), key_states], dim=2)
175
+ value_states = torch.cat([attn_prompt[1].expand(bsz, -1, -1, -1), value_states], dim=2)
176
+ if attention_mask is not None:
177
+ prompt_mask = torch.zeros(bsz, 1, tgt_len, attn_prompt[0].size(1)).to(attention_mask.device)
178
+ attention_mask = torch.cat([prompt_mask, attention_mask], dim=(-1))
179
+
180
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
181
+ query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
182
+ query_states = query_states.reshape(*proj_shape)
183
+ key_states = key_states.reshape(*proj_shape)
184
+ value_states = value_states.reshape(*proj_shape)
185
+
186
+ src_len = key_states.size(1)
187
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
188
+
189
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
190
+ raise ValueError(
191
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
192
+ f" {attn_weights.size()}"
193
+ )
194
+
195
+ if attention_mask is not None:
196
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
197
+ raise ValueError(
198
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
199
+ )
200
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
201
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
202
+
203
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
204
+
205
+ if output_attentions:
206
+ # this operation is a bit awkward, but it's required to
207
+ # make sure that attn_weights keeps its gradient.
208
+ # In order to do so, attn_weights have to be reshaped
209
+ # twice and have to be reused in the following
210
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
211
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
212
+ else:
213
+ attn_weights_reshaped = None
214
+
215
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
216
+
217
+ attn_output = torch.bmm(attn_probs, value_states)
218
+
219
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
220
+ raise ValueError(
221
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
222
+ f" {attn_output.size()}"
223
+ )
224
+
225
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
226
+ attn_output = attn_output.transpose(1, 2)
227
+
228
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
229
+ # partitioned across GPUs when using tensor-parallelism.
230
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
231
+
232
+ attn_output = self.out_proj(attn_output)
233
+
234
+ return attn_output, attn_weights_reshaped
235
+
236
+
237
+ class MvpEncoderLayer(GradientCheckpointingLayer):
238
+ def __init__(self, config: MvpConfig):
239
+ super().__init__()
240
+ self.embed_dim = config.d_model
241
+ self.self_attn = MvpAttention(
242
+ embed_dim=self.embed_dim,
243
+ num_heads=config.encoder_attention_heads,
244
+ dropout=config.attention_dropout,
245
+ )
246
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
247
+ self.dropout = config.dropout
248
+ self.activation_fn = ACT2FN[config.activation_function]
249
+ self.activation_dropout = config.activation_dropout
250
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
251
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
252
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
253
+
254
+ def forward(
255
+ self,
256
+ hidden_states: torch.FloatTensor,
257
+ attention_mask: torch.FloatTensor,
258
+ self_attn_prompt: torch.FloatTensor,
259
+ output_attentions: bool | None = False,
260
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor | None]:
261
+ """
262
+ Args:
263
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
264
+ attention_mask (`torch.FloatTensor`): attention mask of size
265
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
266
+ self_attn_prompt (`torch.FloatTensor`): prompt of self attention of shape
267
+ `(2, encoder_attention_heads, pro_len, head_dim)`.
268
+ output_attentions (`bool`, *optional*):
269
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
270
+ returned tensors for more detail.
271
+ """
272
+ residual = hidden_states
273
+ hidden_states, attn_weights = self.self_attn(
274
+ hidden_states=hidden_states,
275
+ attention_mask=attention_mask,
276
+ attn_prompt=self_attn_prompt,
277
+ output_attentions=output_attentions,
278
+ )
279
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
280
+ hidden_states = residual + hidden_states
281
+ hidden_states = self.self_attn_layer_norm(hidden_states)
282
+
283
+ residual = hidden_states
284
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
285
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
286
+ hidden_states = self.fc2(hidden_states)
287
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
288
+ hidden_states = residual + hidden_states
289
+ hidden_states = self.final_layer_norm(hidden_states)
290
+
291
+ if hidden_states.dtype == torch.float16 and not torch.isfinite(hidden_states).all():
292
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
293
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
294
+
295
+ return hidden_states, attn_weights
296
+
297
+
298
+ class MvpDecoderLayer(GradientCheckpointingLayer):
299
+ def __init__(self, config: MvpConfig, layer_idx=None):
300
+ super().__init__()
301
+ self.embed_dim = config.d_model
302
+
303
+ self.self_attn = MvpAttention(
304
+ embed_dim=self.embed_dim,
305
+ num_heads=config.decoder_attention_heads,
306
+ dropout=config.attention_dropout,
307
+ is_decoder=True,
308
+ layer_idx=layer_idx,
309
+ )
310
+ self.dropout = config.dropout
311
+ self.activation_fn = ACT2FN[config.activation_function]
312
+ self.activation_dropout = config.activation_dropout
313
+
314
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
315
+ self.encoder_attn = MvpAttention(
316
+ self.embed_dim,
317
+ config.decoder_attention_heads,
318
+ dropout=config.attention_dropout,
319
+ is_decoder=True,
320
+ layer_idx=layer_idx,
321
+ )
322
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
323
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
324
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
325
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
326
+
327
+ def forward(
328
+ self,
329
+ hidden_states: torch.Tensor,
330
+ attention_mask: torch.Tensor | None = None,
331
+ encoder_hidden_states: torch.Tensor | None = None,
332
+ encoder_attention_mask: torch.Tensor | None = None,
333
+ self_attn_prompt: torch.Tensor | None = None,
334
+ cross_attn_prompt: torch.Tensor | None = None,
335
+ past_key_values: Cache | None = None,
336
+ output_attentions: bool | None = False,
337
+ use_cache: bool | None = True,
338
+ **kwargs,
339
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
340
+ """
341
+ Args:
342
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
343
+ attention_mask (`torch.FloatTensor`): attention mask of size
344
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
345
+ encoder_hidden_states (`torch.FloatTensor`):
346
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
347
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
348
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
349
+ self_attn_prompt (`torch.FloatTensor`): prompt of self attention of shape
350
+ `(2, decoder_attention_heads, pro_len, head_dim)`.
351
+ cross_attn_prompt (`torch.FloatTensor`): prompt of cross attention of shape
352
+ `(2, decoder_attention_heads, pro_len, head_dim)`.
353
+ past_key_values (`Cache`): cached past key and value projection states
354
+ output_attentions (`bool`, *optional*):
355
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
356
+ returned tensors for more detail.
357
+ """
358
+ residual = hidden_states
359
+
360
+ # Self Attention
361
+ hidden_states, self_attn_weights = self.self_attn(
362
+ hidden_states=hidden_states,
363
+ past_key_values=past_key_values,
364
+ attention_mask=attention_mask,
365
+ attn_prompt=self_attn_prompt,
366
+ output_attentions=output_attentions,
367
+ )
368
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
369
+ hidden_states = residual + hidden_states
370
+ hidden_states = self.self_attn_layer_norm(hidden_states)
371
+
372
+ # Cross-Attention Block
373
+ cross_attn_weights = None
374
+ if encoder_hidden_states is not None:
375
+ residual = hidden_states
376
+
377
+ hidden_states, cross_attn_weights = self.encoder_attn(
378
+ hidden_states=hidden_states,
379
+ key_value_states=encoder_hidden_states,
380
+ attention_mask=encoder_attention_mask,
381
+ attn_prompt=cross_attn_prompt,
382
+ past_key_values=past_key_values,
383
+ output_attentions=output_attentions,
384
+ )
385
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
386
+ hidden_states = residual + hidden_states
387
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
388
+
389
+ # Fully Connected
390
+ residual = hidden_states
391
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
392
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
393
+ hidden_states = self.fc2(hidden_states)
394
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
395
+ hidden_states = residual + hidden_states
396
+ hidden_states = self.final_layer_norm(hidden_states)
397
+
398
+ outputs = (hidden_states,)
399
+
400
+ if output_attentions:
401
+ outputs += (self_attn_weights, cross_attn_weights)
402
+
403
+ return outputs
404
+
405
+
406
+ # Copied from transformers.models.bart.modeling_bart.BartClassificationHead with Bart->MVP
407
+ class MvpClassificationHead(nn.Module):
408
+ """Head for sentence-level classification tasks."""
409
+
410
+ def __init__(
411
+ self,
412
+ input_dim: int,
413
+ inner_dim: int,
414
+ num_classes: int,
415
+ pooler_dropout: float,
416
+ ):
417
+ super().__init__()
418
+ self.dense = nn.Linear(input_dim, inner_dim)
419
+ self.dropout = nn.Dropout(p=pooler_dropout)
420
+ self.out_proj = nn.Linear(inner_dim, num_classes)
421
+
422
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
423
+ hidden_states = self.dropout(hidden_states)
424
+ hidden_states = self.dense(hidden_states)
425
+ hidden_states = torch.tanh(hidden_states)
426
+ hidden_states = self.dropout(hidden_states)
427
+ hidden_states = self.out_proj(hidden_states)
428
+ return hidden_states
429
+
430
+
431
+ class MvpPrompt(nn.Module):
432
+ """Layer-wise prompt for encoder or decoder."""
433
+
434
+ def __init__(self, config, num_layers, num_heads):
435
+ super().__init__()
436
+ self.prompt_length = config.prompt_length
437
+ self.num_layers = num_layers
438
+ self.num_heads = num_heads
439
+ self.head_dim = config.d_model // num_heads
440
+ self.dropout = nn.Dropout(p=config.dropout)
441
+ self.prompt_embedding = nn.Embedding(config.prompt_length, config.d_model)
442
+ self.prompt_trans = nn.Sequential(
443
+ nn.Linear(config.d_model, config.prompt_mid_dim),
444
+ nn.GELU(),
445
+ nn.Linear(config.prompt_mid_dim, num_layers * 2 * config.d_model),
446
+ )
447
+
448
+ def forward(self, prompt_ids: torch.Tensor) -> tuple[torch.Tensor]:
449
+ prompt = self.prompt_trans(self.prompt_embedding(prompt_ids))
450
+ prompt = prompt.view(self.prompt_length, self.num_layers * 2, self.num_heads, self.head_dim)
451
+ prompt = self.dropout(prompt)
452
+ prompt = prompt.permute([1, 2, 0, 3]).split(2)
453
+ return prompt
454
+
455
+
456
+ @auto_docstring
457
+ class MvpPreTrainedModel(PreTrainedModel):
458
+ config: MvpConfig
459
+ base_model_prefix = "model"
460
+ supports_gradient_checkpointing = True
461
+
462
+ def _init_weights(self, module):
463
+ super()._init_weights(module)
464
+ if isinstance(module, MvpForConditionalGeneration):
465
+ init.zeros_(module.final_logits_bias)
466
+
467
+ @property
468
+ def dummy_inputs(self):
469
+ pad_token = self.config.pad_token_id
470
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
471
+ dummy_inputs = {
472
+ "attention_mask": input_ids.ne(pad_token),
473
+ "input_ids": input_ids,
474
+ }
475
+ return dummy_inputs
476
+
477
+
478
+ class MvpEncoder(MvpPreTrainedModel):
479
+ """
480
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
481
+ [`MvpEncoderLayer`].
482
+
483
+ Args:
484
+ config: MvpConfig
485
+ embed_tokens (nn.Embedding): output embedding
486
+ use_prompt (bool): whether to use prompt
487
+ """
488
+
489
+ def __init__(self, config: MvpConfig, embed_tokens: nn.Embedding | None = None, use_prompt: bool | None = False):
490
+ super().__init__(config)
491
+
492
+ self.dropout = config.dropout
493
+ self.layerdrop = config.encoder_layerdrop
494
+
495
+ embed_dim = config.d_model
496
+ self.padding_idx = config.pad_token_id
497
+ self.max_source_positions = config.max_position_embeddings
498
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
499
+
500
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
501
+
502
+ self.embed_positions = MvpLearnedPositionalEmbedding(
503
+ config.max_position_embeddings,
504
+ embed_dim,
505
+ )
506
+ self.layers = nn.ModuleList([MvpEncoderLayer(config) for _ in range(config.encoder_layers)])
507
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
508
+
509
+ self.use_prompt = use_prompt
510
+ if use_prompt:
511
+ self.prompt_length = config.prompt_length
512
+ self.self_attn_prompt = MvpPrompt(
513
+ config,
514
+ config.encoder_layers,
515
+ config.encoder_attention_heads,
516
+ )
517
+
518
+ self.gradient_checkpointing = False
519
+ # Initialize weights and apply final processing
520
+ self.post_init()
521
+
522
+ def forward(
523
+ self,
524
+ input_ids: torch.LongTensor | None = None,
525
+ attention_mask: torch.Tensor | None = None,
526
+ inputs_embeds: torch.FloatTensor | None = None,
527
+ output_attentions: bool | None = None,
528
+ output_hidden_states: bool | None = None,
529
+ return_dict: bool | None = None,
530
+ **kwargs,
531
+ ) -> tuple | BaseModelOutput:
532
+ r"""
533
+ Args:
534
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
535
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
536
+ provide it.
537
+
538
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
539
+ [`PreTrainedTokenizer.__call__`] for details.
540
+
541
+ [What are input IDs?](../glossary#input-ids)
542
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
543
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
544
+
545
+ - 1 for tokens that are **not masked**,
546
+ - 0 for tokens that are **masked**.
547
+
548
+ [What are attention masks?](../glossary#attention-mask)
549
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
550
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
551
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
552
+ than the model's internal embedding lookup matrix.
553
+ output_attentions (`bool`, *optional*):
554
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
555
+ returned tensors for more detail.
556
+ output_hidden_states (`bool`, *optional*):
557
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
558
+ for more detail.
559
+ return_dict (`bool`, *optional*):
560
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
561
+ """
562
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
563
+ output_hidden_states = (
564
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
565
+ )
566
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
567
+
568
+ # retrieve input_ids and inputs_embeds
569
+ if input_ids is not None and inputs_embeds is not None:
570
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
571
+ elif input_ids is not None:
572
+ input = input_ids
573
+ input_shape = input.shape
574
+ input_ids = input_ids.view(-1, input_shape[-1])
575
+ elif inputs_embeds is not None:
576
+ input_shape = inputs_embeds.size()[:-1]
577
+ input = inputs_embeds[:, :, -1]
578
+ else:
579
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
580
+
581
+ if inputs_embeds is None:
582
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
583
+
584
+ embed_pos = self.embed_positions(input)
585
+
586
+ hidden_states = inputs_embeds + embed_pos
587
+ hidden_states = self.layernorm_embedding(hidden_states)
588
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
589
+
590
+ # layer-wise prompt
591
+ if self.use_prompt:
592
+ prompt_ids = torch.arange(self.prompt_length).to(self.device)
593
+ self_attn_prompt = self.self_attn_prompt(prompt_ids)
594
+
595
+ # expand attention_mask
596
+ if attention_mask is not None:
597
+ attention_mask = create_bidirectional_mask(
598
+ config=self.config,
599
+ inputs_embeds=hidden_states,
600
+ attention_mask=attention_mask,
601
+ )
602
+
603
+ encoder_states = () if output_hidden_states else None
604
+ all_attentions = () if output_attentions else None
605
+
606
+ for idx, encoder_layer in enumerate(self.layers):
607
+ if output_hidden_states:
608
+ encoder_states = encoder_states + (hidden_states,)
609
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
610
+ to_drop = False
611
+ if self.training:
612
+ dropout_probability = torch.rand([])
613
+ if dropout_probability < self.layerdrop: # skip the layer
614
+ to_drop = True
615
+
616
+ if to_drop:
617
+ layer_outputs = (None, None)
618
+ else:
619
+ layer_outputs = encoder_layer(
620
+ hidden_states,
621
+ attention_mask,
622
+ self_attn_prompt=(self_attn_prompt[idx] if self.use_prompt else None),
623
+ output_attentions=output_attentions,
624
+ )
625
+
626
+ hidden_states = layer_outputs[0]
627
+
628
+ if output_attentions:
629
+ all_attentions = all_attentions + (layer_outputs[1],)
630
+
631
+ if output_hidden_states:
632
+ encoder_states = encoder_states + (hidden_states,)
633
+
634
+ if not return_dict:
635
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
636
+ return BaseModelOutput(
637
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
638
+ )
639
+
640
+
641
+ class MvpDecoder(MvpPreTrainedModel):
642
+ """
643
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MvpDecoderLayer`]
644
+
645
+ Args:
646
+ config: MvpConfig
647
+ embed_tokens (nn.Embedding): output embedding
648
+ use_prompt (bool): whether to use prompt
649
+ """
650
+
651
+ def __init__(self, config: MvpConfig, use_prompt: bool | None = False):
652
+ super().__init__(config)
653
+ self.dropout = config.dropout
654
+ self.layerdrop = config.decoder_layerdrop
655
+ self.padding_idx = config.pad_token_id
656
+ self.max_target_positions = config.max_position_embeddings
657
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
658
+
659
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
660
+ self.embed_positions = MvpLearnedPositionalEmbedding(
661
+ config.max_position_embeddings,
662
+ config.d_model,
663
+ )
664
+ self.layers = nn.ModuleList([MvpDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
665
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
666
+
667
+ self.use_prompt = use_prompt
668
+ if use_prompt:
669
+ self.prompt_length = config.prompt_length
670
+ self.self_attn_prompt = MvpPrompt(
671
+ config,
672
+ config.decoder_layers,
673
+ config.decoder_attention_heads,
674
+ )
675
+ self.cross_attn_prompt = MvpPrompt(
676
+ config,
677
+ config.decoder_layers,
678
+ config.decoder_attention_heads,
679
+ )
680
+
681
+ self.gradient_checkpointing = False
682
+ # Initialize weights and apply final processing
683
+ self.post_init()
684
+
685
+ def forward(
686
+ self,
687
+ input_ids: torch.LongTensor | None = None,
688
+ attention_mask: torch.Tensor | None = None,
689
+ encoder_hidden_states: torch.FloatTensor | None = None,
690
+ encoder_attention_mask: torch.LongTensor | None = None,
691
+ past_key_values: Cache | None = None,
692
+ inputs_embeds: torch.FloatTensor | None = None,
693
+ use_cache: bool | None = None,
694
+ output_attentions: bool | None = None,
695
+ output_hidden_states: bool | None = None,
696
+ return_dict: bool | None = None,
697
+ **kwargs,
698
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
699
+ r"""
700
+ Args:
701
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
702
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
703
+ provide it.
704
+
705
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
706
+ [`PreTrainedTokenizer.__call__`] for details.
707
+
708
+ [What are input IDs?](../glossary#input-ids)
709
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
710
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
711
+
712
+ - 1 for tokens that are **not masked**,
713
+ - 0 for tokens that are **masked**.
714
+
715
+ [What are attention masks?](../glossary#attention-mask)
716
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
717
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
718
+ of the decoder.
719
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
720
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
721
+ selected in `[0, 1]`:
722
+
723
+ - 1 for tokens that are **not masked**,
724
+ - 0 for tokens that are **masked**.
725
+
726
+ [What are attention masks?](../glossary#attention-mask)
727
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
728
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
729
+
730
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
731
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
732
+
733
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
734
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
735
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
736
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
737
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
738
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
739
+ than the model's internal embedding lookup matrix.
740
+ output_attentions (`bool`, *optional*):
741
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
742
+ returned tensors for more detail.
743
+ output_hidden_states (`bool`, *optional*):
744
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
745
+ for more detail.
746
+ return_dict (`bool`, *optional*):
747
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
748
+ """
749
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
750
+ output_hidden_states = (
751
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
752
+ )
753
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
754
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
755
+
756
+ # retrieve input_ids and inputs_embeds
757
+ if input_ids is not None and inputs_embeds is not None:
758
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
759
+ elif input_ids is not None:
760
+ input = input_ids
761
+ input_shape = input_ids.shape
762
+ input_ids = input_ids.view(-1, input_shape[-1])
763
+ elif inputs_embeds is not None:
764
+ input_shape = inputs_embeds.size()[:-1]
765
+ input = inputs_embeds[:, :, -1]
766
+ else:
767
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
768
+
769
+ if inputs_embeds is None:
770
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
771
+
772
+ if self.gradient_checkpointing and self.training:
773
+ if use_cache:
774
+ logger.warning_once(
775
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
776
+ )
777
+ use_cache = False
778
+
779
+ if use_cache and past_key_values is None:
780
+ past_key_values = (
781
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
782
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
783
+ else DynamicCache(config=self.config)
784
+ )
785
+
786
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
787
+
788
+ attention_mask = create_causal_mask(
789
+ config=self.config,
790
+ inputs_embeds=inputs_embeds,
791
+ attention_mask=attention_mask,
792
+ past_key_values=past_key_values,
793
+ )
794
+
795
+ # expand encoder attention mask
796
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
797
+ encoder_attention_mask = create_bidirectional_mask(
798
+ config=self.config,
799
+ inputs_embeds=inputs_embeds,
800
+ attention_mask=encoder_attention_mask,
801
+ encoder_hidden_states=encoder_hidden_states,
802
+ )
803
+
804
+ # embed positions
805
+ positions = self.embed_positions(input, past_key_values_length)
806
+
807
+ hidden_states = inputs_embeds + positions
808
+ hidden_states = self.layernorm_embedding(hidden_states)
809
+
810
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
811
+
812
+ # layer-wise prompt
813
+ if self.use_prompt:
814
+ prompt_ids = torch.arange(self.prompt_length).to(self.device)
815
+ self_attn_prompt = self.self_attn_prompt(prompt_ids)
816
+ cross_attn_prompt = self.cross_attn_prompt(prompt_ids)
817
+
818
+ # decoder layers
819
+ all_hidden_states = () if output_hidden_states else None
820
+ all_self_attns = () if output_attentions else None
821
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
822
+
823
+ for idx, decoder_layer in enumerate(self.layers):
824
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
825
+ if output_hidden_states:
826
+ all_hidden_states += (hidden_states,)
827
+ if self.training:
828
+ dropout_probability = torch.rand([])
829
+ if dropout_probability < self.layerdrop:
830
+ continue
831
+
832
+ layer_outputs = decoder_layer(
833
+ hidden_states,
834
+ attention_mask,
835
+ encoder_hidden_states, # as positional argument for gradient checkpointing
836
+ encoder_attention_mask=encoder_attention_mask,
837
+ self_attn_prompt=(self_attn_prompt[idx] if self.use_prompt else None),
838
+ cross_attn_prompt=(cross_attn_prompt[idx] if self.use_prompt else None),
839
+ past_key_values=past_key_values,
840
+ output_attentions=output_attentions,
841
+ use_cache=use_cache,
842
+ )
843
+ hidden_states = layer_outputs[0]
844
+ if output_attentions:
845
+ all_self_attns += (layer_outputs[1],)
846
+
847
+ if encoder_hidden_states is not None:
848
+ all_cross_attentions += (layer_outputs[2],)
849
+
850
+ # add hidden states from the last decoder layer
851
+ if output_hidden_states:
852
+ all_hidden_states += (hidden_states,)
853
+
854
+ if not return_dict:
855
+ return tuple(
856
+ v
857
+ for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
858
+ if v is not None
859
+ )
860
+ return BaseModelOutputWithPastAndCrossAttentions(
861
+ last_hidden_state=hidden_states,
862
+ past_key_values=past_key_values,
863
+ hidden_states=all_hidden_states,
864
+ attentions=all_self_attns,
865
+ cross_attentions=all_cross_attentions,
866
+ )
867
+
868
+
869
+ @auto_docstring
870
+ class MvpModel(MvpPreTrainedModel):
871
+ _keys_to_ignore_on_load_unexpected = ["final_logits_bias"]
872
+ _tied_weights_keys = {
873
+ "encoder.embed_tokens.weight": "shared.weight",
874
+ "decoder.embed_tokens.weight": "shared.weight",
875
+ }
876
+
877
+ def __init__(self, config: MvpConfig):
878
+ super().__init__(config)
879
+
880
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
881
+ self.use_prompt = config.use_prompt
882
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
883
+
884
+ self.encoder = MvpEncoder(config, config.use_prompt)
885
+ self.decoder = MvpDecoder(config, config.use_prompt)
886
+
887
+ # Initialize weights and apply final processing
888
+ self.post_init()
889
+
890
+ def get_input_embeddings(self):
891
+ return self.shared
892
+
893
+ def set_input_embeddings(self, value):
894
+ self.shared = value
895
+ self.encoder.embed_tokens = self.shared
896
+ self.decoder.embed_tokens = self.shared
897
+
898
+ def set_lightweight_tuning(self):
899
+ assert self.use_prompt, "If you want to use lightweight tuning, make sure that `use_prompt=True`."
900
+
901
+ self.requires_grad_(False)
902
+ self.encoder.self_attn_prompt.requires_grad_(True)
903
+ self.decoder.self_attn_prompt.requires_grad_(True)
904
+ self.decoder.cross_attn_prompt.requires_grad_(True)
905
+
906
+ @auto_docstring
907
+ def forward(
908
+ self,
909
+ input_ids: torch.LongTensor | None = None,
910
+ attention_mask: torch.Tensor | None = None,
911
+ decoder_input_ids: torch.LongTensor | None = None,
912
+ decoder_attention_mask: torch.LongTensor | None = None,
913
+ encoder_outputs: list[torch.FloatTensor] | None = None,
914
+ past_key_values: Cache | None = None,
915
+ inputs_embeds: torch.FloatTensor | None = None,
916
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
917
+ use_cache: bool | None = None,
918
+ output_attentions: bool | None = None,
919
+ output_hidden_states: bool | None = None,
920
+ return_dict: bool | None = None,
921
+ **kwargs,
922
+ ) -> tuple | Seq2SeqModelOutput:
923
+ r"""
924
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
925
+ Indices of decoder input sequence tokens in the vocabulary.
926
+
927
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
928
+ [`PreTrainedTokenizer.__call__`] for details.
929
+
930
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
931
+
932
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
933
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
934
+
935
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
936
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
937
+ for denoising pre-training following the paper.
938
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
939
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
940
+ be used by default.
941
+
942
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
943
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
944
+ information on the default strategy.
945
+ """
946
+ # different to other models, Mvp automatically creates decoder_input_ids from
947
+ # input_ids if no decoder_input_ids are provided
948
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
949
+ if input_ids is None:
950
+ raise ValueError(
951
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
952
+ "passed, `input_ids` cannot be `None`. Please pass either "
953
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
954
+ )
955
+
956
+ decoder_input_ids = shift_tokens_right(
957
+ input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
958
+ )
959
+
960
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
961
+ output_hidden_states = (
962
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
963
+ )
964
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
965
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
966
+
967
+ if encoder_outputs is None:
968
+ encoder_outputs = self.encoder(
969
+ input_ids=input_ids,
970
+ attention_mask=attention_mask,
971
+ inputs_embeds=inputs_embeds,
972
+ output_attentions=output_attentions,
973
+ output_hidden_states=output_hidden_states,
974
+ return_dict=return_dict,
975
+ )
976
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
977
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
978
+ encoder_outputs = BaseModelOutput(
979
+ last_hidden_state=encoder_outputs[0],
980
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
981
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
982
+ )
983
+
984
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
985
+ decoder_outputs = self.decoder(
986
+ input_ids=decoder_input_ids,
987
+ attention_mask=decoder_attention_mask,
988
+ encoder_hidden_states=encoder_outputs[0],
989
+ encoder_attention_mask=attention_mask,
990
+ past_key_values=past_key_values,
991
+ inputs_embeds=decoder_inputs_embeds,
992
+ use_cache=use_cache,
993
+ output_attentions=output_attentions,
994
+ output_hidden_states=output_hidden_states,
995
+ return_dict=return_dict,
996
+ )
997
+
998
+ if not return_dict:
999
+ return decoder_outputs + encoder_outputs
1000
+
1001
+ return Seq2SeqModelOutput(
1002
+ last_hidden_state=decoder_outputs.last_hidden_state,
1003
+ past_key_values=decoder_outputs.past_key_values,
1004
+ decoder_hidden_states=decoder_outputs.hidden_states,
1005
+ decoder_attentions=decoder_outputs.attentions,
1006
+ cross_attentions=decoder_outputs.cross_attentions,
1007
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1008
+ encoder_hidden_states=encoder_outputs.hidden_states,
1009
+ encoder_attentions=encoder_outputs.attentions,
1010
+ )
1011
+
1012
+
1013
+ @auto_docstring(
1014
+ custom_intro="""
1015
+ The MVP Model with a language modeling head. Can be used for various text generation tasks.
1016
+ """
1017
+ )
1018
+ class MvpForConditionalGeneration(MvpPreTrainedModel, GenerationMixin):
1019
+ _tied_weights_keys = {
1020
+ "lm_head.weight": "model.shared.weight",
1021
+ }
1022
+
1023
+ def __init__(self, config: MvpConfig):
1024
+ super().__init__(config)
1025
+ self.model = MvpModel(config)
1026
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1027
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1028
+
1029
+ # Initialize weights and apply final processing
1030
+ self.post_init()
1031
+
1032
+ def resize_token_embeddings(
1033
+ self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
1034
+ ) -> nn.Embedding:
1035
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1036
+ self._resize_final_logits_bias(new_num_tokens)
1037
+ return new_embeddings
1038
+
1039
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1040
+ old_num_tokens = self.final_logits_bias.shape[-1]
1041
+ if new_num_tokens <= old_num_tokens:
1042
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1043
+ else:
1044
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1045
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1046
+ self.register_buffer("final_logits_bias", new_bias)
1047
+
1048
+ def set_lightweight_tuning(self):
1049
+ self.model.set_lightweight_tuning()
1050
+ self.lm_head.requires_grad_(False)
1051
+
1052
+ @auto_docstring
1053
+ def forward(
1054
+ self,
1055
+ input_ids: torch.LongTensor | None = None,
1056
+ attention_mask: torch.Tensor | None = None,
1057
+ decoder_input_ids: torch.LongTensor | None = None,
1058
+ decoder_attention_mask: torch.LongTensor | None = None,
1059
+ encoder_outputs: list[torch.FloatTensor] | None = None,
1060
+ past_key_values: Cache | None = None,
1061
+ inputs_embeds: torch.FloatTensor | None = None,
1062
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1063
+ labels: torch.LongTensor | None = None,
1064
+ use_cache: bool | None = None,
1065
+ output_attentions: bool | None = None,
1066
+ output_hidden_states: bool | None = None,
1067
+ return_dict: bool | None = None,
1068
+ **kwargs,
1069
+ ) -> tuple | Seq2SeqLMOutput:
1070
+ r"""
1071
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1072
+ Indices of decoder input sequence tokens in the vocabulary.
1073
+
1074
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1075
+ [`PreTrainedTokenizer.__call__`] for details.
1076
+
1077
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1078
+
1079
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1080
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1081
+
1082
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
1083
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
1084
+ for denoising pre-training following the paper.
1085
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1086
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1087
+ be used by default.
1088
+
1089
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
1090
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
1091
+ information on the default strategy.
1092
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1093
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1094
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1095
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1096
+
1097
+ Example of summarization:
1098
+
1099
+ Fine-tuning a model
1100
+ ```python
1101
+ >>> import torch
1102
+ >>> from transformers import AutoTokenizer, MvpForConditionalGeneration
1103
+
1104
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1105
+ >>> model = MvpForConditionalGeneration.from_pretrained("RUCAIBox/mvp")
1106
+
1107
+ >>> inputs = tokenizer(
1108
+ ... "Summarize: You may want to stick it to your boss and leave your job, but don't do it if these are your reasons.",
1109
+ ... return_tensors="pt",
1110
+ ... )
1111
+ >>> labels = tokenizer("Bad Reasons To Quit Your Job", return_tensors="pt")["input_ids"]
1112
+
1113
+ >>> loss = model(**inputs, labels=labels).loss
1114
+ >>> loss.backward()
1115
+ ```
1116
+
1117
+ Inference after the model fine-tuned
1118
+ ```python
1119
+ >>> with torch.no_grad():
1120
+ ... generated_ids = model.generate(**inputs)
1121
+
1122
+ >>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
1123
+ ```
1124
+ """
1125
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1126
+
1127
+ if labels is not None:
1128
+ if use_cache:
1129
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1130
+ use_cache = False
1131
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1132
+ decoder_input_ids = shift_tokens_right(
1133
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1134
+ )
1135
+
1136
+ outputs = self.model(
1137
+ input_ids,
1138
+ attention_mask=attention_mask,
1139
+ decoder_input_ids=decoder_input_ids,
1140
+ encoder_outputs=encoder_outputs,
1141
+ decoder_attention_mask=decoder_attention_mask,
1142
+ past_key_values=past_key_values,
1143
+ inputs_embeds=inputs_embeds,
1144
+ decoder_inputs_embeds=decoder_inputs_embeds,
1145
+ use_cache=use_cache,
1146
+ output_attentions=output_attentions,
1147
+ output_hidden_states=output_hidden_states,
1148
+ return_dict=return_dict,
1149
+ )
1150
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1151
+
1152
+ masked_lm_loss = None
1153
+ if labels is not None:
1154
+ loss_fct = CrossEntropyLoss()
1155
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1156
+
1157
+ if not return_dict:
1158
+ output = (lm_logits,) + outputs[1:]
1159
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1160
+
1161
+ return Seq2SeqLMOutput(
1162
+ loss=masked_lm_loss,
1163
+ logits=lm_logits,
1164
+ past_key_values=outputs.past_key_values,
1165
+ decoder_hidden_states=outputs.decoder_hidden_states,
1166
+ decoder_attentions=outputs.decoder_attentions,
1167
+ cross_attentions=outputs.cross_attentions,
1168
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1169
+ encoder_hidden_states=outputs.encoder_hidden_states,
1170
+ encoder_attentions=outputs.encoder_attentions,
1171
+ )
1172
+
1173
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1174
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1175
+
1176
+
1177
+ @auto_docstring(
1178
+ custom_intro="""
1179
+ Mvp model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1180
+ tasks.
1181
+ """
1182
+ )
1183
+ class MvpForSequenceClassification(MvpPreTrainedModel):
1184
+ def __init__(self, config: MvpConfig, **kwargs):
1185
+ super().__init__(config, **kwargs)
1186
+ self.model = MvpModel(config)
1187
+ self.classification_head = MvpClassificationHead(
1188
+ config.d_model,
1189
+ config.d_model,
1190
+ config.num_labels,
1191
+ config.classifier_dropout,
1192
+ )
1193
+
1194
+ # Initialize weights and apply final processing
1195
+ self.post_init()
1196
+
1197
+ def set_lightweight_tuning(self):
1198
+ self.model.set_lightweight_tuning()
1199
+ self.classification_head.requires_grad_(False)
1200
+
1201
+ @auto_docstring
1202
+ def forward(
1203
+ self,
1204
+ input_ids: torch.LongTensor | None = None,
1205
+ attention_mask: torch.Tensor | None = None,
1206
+ decoder_input_ids: torch.LongTensor | None = None,
1207
+ decoder_attention_mask: torch.LongTensor | None = None,
1208
+ encoder_outputs: list[torch.FloatTensor] | None = None,
1209
+ inputs_embeds: torch.FloatTensor | None = None,
1210
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1211
+ labels: torch.LongTensor | None = None,
1212
+ use_cache: bool | None = None,
1213
+ output_attentions: bool | None = None,
1214
+ output_hidden_states: bool | None = None,
1215
+ return_dict: bool | None = None,
1216
+ **kwargs,
1217
+ ) -> tuple | Seq2SeqSequenceClassifierOutput:
1218
+ r"""
1219
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1220
+ Indices of decoder input sequence tokens in the vocabulary.
1221
+
1222
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1223
+ [`PreTrainedTokenizer.__call__`] for details.
1224
+
1225
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1226
+
1227
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1228
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1229
+
1230
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
1231
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
1232
+ for denoising pre-training following the paper.
1233
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1234
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1235
+ be used by default.
1236
+
1237
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
1238
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
1239
+ information on the default strategy.
1240
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1241
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1242
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1243
+
1244
+ Example of single-label classification:
1245
+
1246
+ Fine-tuning a model on `num_labels` classes
1247
+ ```python
1248
+ >>> import torch
1249
+ >>> from transformers import AutoTokenizer, MvpForSequenceClassification
1250
+
1251
+ >>> num_labels = 2 # for example, this is a binary classification task
1252
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1253
+ >>> model = MvpForSequenceClassification.from_pretrained("RUCAIBox/mvp", num_labels=num_labels)
1254
+
1255
+ >>> inputs = tokenizer("Classify: Hello, my dog is cute", return_tensors="pt")
1256
+ >>> labels = torch.tensor(1) # the real label for inputs
1257
+
1258
+ >>> loss = model(**inputs, labels=labels).loss
1259
+ >>> loss.backward()
1260
+ ```
1261
+
1262
+ Inference after the model fine-tuned
1263
+ ```python
1264
+ >>> with torch.no_grad():
1265
+ ... logits = model(**inputs).logits
1266
+
1267
+ >>> predicted_class_id = logits.argmax()
1268
+ ```
1269
+ """
1270
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1271
+ if labels is not None:
1272
+ use_cache = False
1273
+
1274
+ if input_ids is None and inputs_embeds is not None:
1275
+ raise NotImplementedError(
1276
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1277
+ )
1278
+
1279
+ outputs = self.model(
1280
+ input_ids,
1281
+ attention_mask=attention_mask,
1282
+ decoder_input_ids=decoder_input_ids,
1283
+ decoder_attention_mask=decoder_attention_mask,
1284
+ encoder_outputs=encoder_outputs,
1285
+ inputs_embeds=inputs_embeds,
1286
+ decoder_inputs_embeds=decoder_inputs_embeds,
1287
+ use_cache=use_cache,
1288
+ output_attentions=output_attentions,
1289
+ output_hidden_states=output_hidden_states,
1290
+ return_dict=return_dict,
1291
+ )
1292
+ hidden_states = outputs[0] # last hidden state
1293
+
1294
+ eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
1295
+
1296
+ torch_compilable_check(
1297
+ torch.unique_consecutive(eos_mask.sum(1)).numel() == 1,
1298
+ "All examples must have the same number of <eos> tokens.",
1299
+ )
1300
+ sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
1301
+ :, -1, :
1302
+ ]
1303
+ logits = self.classification_head(sentence_representation)
1304
+
1305
+ loss = None
1306
+ if labels is not None:
1307
+ if self.config.problem_type is None:
1308
+ if self.config.num_labels == 1:
1309
+ self.config.problem_type = "regression"
1310
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1311
+ self.config.problem_type = "single_label_classification"
1312
+ else:
1313
+ self.config.problem_type = "multi_label_classification"
1314
+
1315
+ if self.config.problem_type == "regression":
1316
+ loss_fct = MSELoss()
1317
+ if self.config.num_labels == 1:
1318
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1319
+ else:
1320
+ loss = loss_fct(logits, labels)
1321
+ elif self.config.problem_type == "single_label_classification":
1322
+ loss_fct = CrossEntropyLoss()
1323
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1324
+ elif self.config.problem_type == "multi_label_classification":
1325
+ loss_fct = BCEWithLogitsLoss()
1326
+ loss = loss_fct(logits, labels)
1327
+ if not return_dict:
1328
+ output = (logits,) + outputs[1:]
1329
+ return ((loss,) + output) if loss is not None else output
1330
+
1331
+ return Seq2SeqSequenceClassifierOutput(
1332
+ loss=loss,
1333
+ logits=logits,
1334
+ past_key_values=outputs.past_key_values,
1335
+ decoder_hidden_states=outputs.decoder_hidden_states,
1336
+ decoder_attentions=outputs.decoder_attentions,
1337
+ cross_attentions=outputs.cross_attentions,
1338
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1339
+ encoder_hidden_states=outputs.encoder_hidden_states,
1340
+ encoder_attentions=outputs.encoder_attentions,
1341
+ )
1342
+
1343
+
1344
+ @auto_docstring
1345
+ class MvpForQuestionAnswering(MvpPreTrainedModel):
1346
+ def __init__(self, config):
1347
+ super().__init__(config)
1348
+
1349
+ config.num_labels = 2
1350
+ self.num_labels = config.num_labels
1351
+
1352
+ self.model = MvpModel(config)
1353
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1354
+
1355
+ # Initialize weights and apply final processing
1356
+ self.post_init()
1357
+
1358
+ def set_lightweight_tuning(self):
1359
+ self.model.set_lightweight_tuning()
1360
+ self.qa_outputs.requires_grad_(False)
1361
+
1362
+ @auto_docstring
1363
+ def forward(
1364
+ self,
1365
+ input_ids: torch.Tensor | None = None,
1366
+ attention_mask: torch.Tensor | None = None,
1367
+ decoder_input_ids: torch.LongTensor | None = None,
1368
+ decoder_attention_mask: torch.LongTensor | None = None,
1369
+ encoder_outputs: list[torch.FloatTensor] | None = None,
1370
+ start_positions: torch.LongTensor | None = None,
1371
+ end_positions: torch.LongTensor | None = None,
1372
+ inputs_embeds: torch.FloatTensor | None = None,
1373
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1374
+ use_cache: bool | None = None,
1375
+ output_attentions: bool | None = None,
1376
+ output_hidden_states: bool | None = None,
1377
+ return_dict: bool | None = None,
1378
+ **kwargs,
1379
+ ) -> tuple | Seq2SeqQuestionAnsweringModelOutput:
1380
+ r"""
1381
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1382
+ Indices of decoder input sequence tokens in the vocabulary.
1383
+
1384
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1385
+ [`PreTrainedTokenizer.__call__`] for details.
1386
+
1387
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1388
+
1389
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1390
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1391
+
1392
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
1393
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
1394
+ for denoising pre-training following the paper.
1395
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1396
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1397
+ be used by default.
1398
+
1399
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
1400
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
1401
+ information on the default strategy.
1402
+
1403
+ Example:
1404
+
1405
+ Fine-tuning a model for extrative question answering, and our model also supports generative question answering
1406
+ using `BartForConditionalGeneration`
1407
+ ```python
1408
+ >>> import torch
1409
+ >>> from transformers import AutoTokenizer, MvpForQuestionAnswering
1410
+
1411
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1412
+ >>> model = MvpForQuestionAnswering.from_pretrained("RUCAIBox/mvp")
1413
+
1414
+ >>> inputs = tokenizer(
1415
+ ... "Answer the following question: Who was Jim Henson? [SEP] Jim Henson was a nice puppet",
1416
+ ... return_tensors="pt",
1417
+ ... )
1418
+ >>> target_start_index = torch.tensor([18])
1419
+ >>> target_end_index = torch.tensor([19])
1420
+
1421
+ >>> loss = model(**inputs, start_positions=target_start_index, end_positions=target_end_index).loss
1422
+ >>> loss.backward()
1423
+ ```
1424
+
1425
+ Inference after the model fine-tuned
1426
+ ```python
1427
+ >>> with torch.no_grad():
1428
+ ... outputs = model(**inputs)
1429
+
1430
+ >>> answer_start_index = outputs.start_logits.argmax()
1431
+ >>> answer_end_index = outputs.end_logits.argmax()
1432
+
1433
+ >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
1434
+ >>> predict_answer = tokenizer.decode(predict_answer_tokens)
1435
+ ```
1436
+ """
1437
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1438
+ if start_positions is not None and end_positions is not None:
1439
+ use_cache = False
1440
+
1441
+ outputs = self.model(
1442
+ input_ids,
1443
+ attention_mask=attention_mask,
1444
+ decoder_input_ids=decoder_input_ids,
1445
+ decoder_attention_mask=decoder_attention_mask,
1446
+ encoder_outputs=encoder_outputs,
1447
+ inputs_embeds=inputs_embeds,
1448
+ decoder_inputs_embeds=decoder_inputs_embeds,
1449
+ use_cache=use_cache,
1450
+ output_attentions=output_attentions,
1451
+ output_hidden_states=output_hidden_states,
1452
+ return_dict=return_dict,
1453
+ )
1454
+
1455
+ sequence_output = outputs[0]
1456
+
1457
+ logits = self.qa_outputs(sequence_output)
1458
+ start_logits, end_logits = logits.split(1, dim=-1)
1459
+ start_logits = start_logits.squeeze(-1).contiguous()
1460
+ end_logits = end_logits.squeeze(-1).contiguous()
1461
+
1462
+ total_loss = None
1463
+ if start_positions is not None and end_positions is not None:
1464
+ # If we are on multi-GPU, split add a dimension
1465
+ if len(start_positions.size()) > 1:
1466
+ start_positions = start_positions.squeeze(-1)
1467
+ if len(end_positions.size()) > 1:
1468
+ end_positions = end_positions.squeeze(-1)
1469
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1470
+ ignored_index = start_logits.size(1)
1471
+ start_positions = start_positions.clamp(0, ignored_index)
1472
+ end_positions = end_positions.clamp(0, ignored_index)
1473
+
1474
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1475
+ start_loss = loss_fct(start_logits, start_positions)
1476
+ end_loss = loss_fct(end_logits, end_positions)
1477
+ total_loss = (start_loss + end_loss) / 2
1478
+
1479
+ if not return_dict:
1480
+ output = (
1481
+ start_logits,
1482
+ end_logits,
1483
+ ) + outputs[1:]
1484
+ return ((total_loss,) + output) if total_loss is not None else output
1485
+
1486
+ return Seq2SeqQuestionAnsweringModelOutput(
1487
+ loss=total_loss,
1488
+ start_logits=start_logits,
1489
+ end_logits=end_logits,
1490
+ past_key_values=outputs.past_key_values,
1491
+ decoder_hidden_states=outputs.decoder_hidden_states,
1492
+ decoder_attentions=outputs.decoder_attentions,
1493
+ cross_attentions=outputs.cross_attentions,
1494
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1495
+ encoder_hidden_states=outputs.encoder_hidden_states,
1496
+ encoder_attentions=outputs.encoder_attentions,
1497
+ )
1498
+
1499
+
1500
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Mvp
1501
+ class MvpDecoderWrapper(MvpPreTrainedModel):
1502
+ """
1503
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1504
+ used in combination with the [`EncoderDecoderModel`] framework.
1505
+ """
1506
+
1507
+ def __init__(self, config):
1508
+ super().__init__(config)
1509
+ self.decoder = MvpDecoder(config)
1510
+ self.post_init()
1511
+
1512
+ def forward(self, *args, **kwargs):
1513
+ return self.decoder(*args, **kwargs)
1514
+
1515
+
1516
+ class MvpForCausalLM(MvpPreTrainedModel, GenerationMixin):
1517
+ _tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
1518
+
1519
+ def __init__(self, config):
1520
+ config.is_decoder = True
1521
+ config.is_encoder_decoder = False
1522
+ super().__init__(config)
1523
+ self.model = MvpDecoderWrapper(config)
1524
+
1525
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1526
+
1527
+ # Initialize weights and apply final processing
1528
+ self.post_init()
1529
+
1530
+ def get_input_embeddings(self):
1531
+ return self.model.decoder.embed_tokens
1532
+
1533
+ def set_input_embeddings(self, value):
1534
+ self.model.decoder.embed_tokens = value
1535
+
1536
+ def set_lightweight_tuning(self):
1537
+ self.model.set_lightweight_tuning()
1538
+ self.lm_head.requires_grad_(False)
1539
+
1540
+ @auto_docstring
1541
+ def forward(
1542
+ self,
1543
+ input_ids: torch.LongTensor | None = None,
1544
+ attention_mask: torch.Tensor | None = None,
1545
+ encoder_hidden_states: torch.FloatTensor | None = None,
1546
+ encoder_attention_mask: torch.FloatTensor | None = None,
1547
+ past_key_values: Cache | None = None,
1548
+ inputs_embeds: torch.FloatTensor | None = None,
1549
+ labels: torch.LongTensor | None = None,
1550
+ use_cache: bool | None = None,
1551
+ output_attentions: bool | None = None,
1552
+ output_hidden_states: bool | None = None,
1553
+ return_dict: bool | None = None,
1554
+ logits_to_keep: int | torch.Tensor = 0,
1555
+ **kwargs,
1556
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
1557
+ r"""
1558
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1559
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1560
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1561
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1562
+
1563
+ Example:
1564
+
1565
+ ```python
1566
+ >>> from transformers import AutoTokenizer, MvpForCausalLM
1567
+
1568
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1569
+ >>> model = MvpForCausalLM.from_pretrained("RUCAIBox/mvp")
1570
+
1571
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1572
+ >>> outputs = model(**inputs)
1573
+
1574
+ >>> logits = outputs.logits
1575
+ >>> list(logits.shape)
1576
+ [1, 8, 50267]
1577
+ ```"""
1578
+
1579
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1580
+ output_hidden_states = (
1581
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1582
+ )
1583
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1584
+
1585
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1586
+ outputs = self.model.decoder(
1587
+ input_ids=input_ids,
1588
+ attention_mask=attention_mask,
1589
+ encoder_hidden_states=encoder_hidden_states,
1590
+ encoder_attention_mask=encoder_attention_mask,
1591
+ past_key_values=past_key_values,
1592
+ inputs_embeds=inputs_embeds,
1593
+ use_cache=use_cache,
1594
+ output_attentions=output_attentions,
1595
+ output_hidden_states=output_hidden_states,
1596
+ return_dict=return_dict,
1597
+ )
1598
+
1599
+ hidden_states = outputs[0]
1600
+ # Only compute necessary logits
1601
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1602
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1603
+
1604
+ loss = None
1605
+ if labels is not None:
1606
+ loss_fct = CrossEntropyLoss()
1607
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1608
+
1609
+ if not return_dict:
1610
+ output = (logits,) + outputs[1:]
1611
+ return (loss,) + output if loss is not None else output
1612
+
1613
+ return CausalLMOutputWithCrossAttentions(
1614
+ loss=loss,
1615
+ logits=logits,
1616
+ past_key_values=outputs.past_key_values,
1617
+ hidden_states=outputs.hidden_states,
1618
+ attentions=outputs.attentions,
1619
+ cross_attentions=outputs.cross_attentions,
1620
+ )
1621
+
1622
+
1623
+ __all__ = [
1624
+ "MvpForCausalLM",
1625
+ "MvpForConditionalGeneration",
1626
+ "MvpForQuestionAnswering",
1627
+ "MvpForSequenceClassification",
1628
+ "MvpModel",
1629
+ "MvpPreTrainedModel",
1630
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pvt_v2/__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_pvt_v2 import *
22
+ from .modeling_pvt_v2 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/pvt_v2/configuration_pvt_v2.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Authors: Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan,
2
+ # Kaitao Song, Ding Liang, Tong Lu, Ping Luo, Ling Shao and The HuggingFace Inc. team.
3
+ # All rights reserved.
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
+ """Pvt V2 model configuration"""
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...backbone_utils import BackboneConfigMixin
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...utils import auto_docstring
23
+
24
+
25
+ @auto_docstring(checkpoint="OpenGVLab/pvt_v2_b0")
26
+ @strict
27
+ class PvtV2Config(BackboneConfigMixin, PreTrainedConfig):
28
+ r"""
29
+ num_encoder_blocks (`[int]`, *optional*, defaults to 4):
30
+ The number of encoder blocks (i.e. stages in the Mix Transformer encoder).
31
+ sr_ratios (`list[int]`, *optional*, defaults to `[8, 4, 2, 1]`):
32
+ Spatial reduction ratios in each encoder block.
33
+ patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
34
+ Patch size for overlapping patch embedding before each encoder block.
35
+ strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
36
+ Stride for overlapping patch embedding before each encoder block.
37
+ num_attention_heads (`list[int]`, *optional*, defaults to `[1, 2, 5, 8]`):
38
+ Number of attention heads for each attention layer in each block of the Transformer encoder.
39
+ mlp_ratios (`list[int]`, *optional*, defaults to `[8, 8, 4, 4]`):
40
+ Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
41
+ encoder blocks.
42
+ linear_attention (`bool`, *optional*, defaults to `False`):
43
+ Use linear attention complexity. If set to True, `sr_ratio` is ignored and average pooling is used for
44
+ dimensionality reduction in the attention layers rather than strided convolution.
45
+
46
+ Example:
47
+
48
+ ```python
49
+ >>> from transformers import PvtV2Model, PvtV2Config
50
+
51
+ >>> # Initializing a pvt_v2_b0 style configuration
52
+ >>> configuration = PvtV2Config()
53
+
54
+ >>> # Initializing a model from the OpenGVLab/pvt_v2_b0 style configuration
55
+ >>> model = PvtV2Model(configuration)
56
+
57
+ >>> # Accessing the model configuration
58
+ >>> configuration = model.config
59
+ ```"""
60
+
61
+ model_type = "pvt_v2"
62
+
63
+ image_size: int | list[int] | tuple[int, int] | dict = 224
64
+ num_channels: int = 3
65
+ num_encoder_blocks: int = 4
66
+ depths: list[int] | tuple[int, ...] = (2, 2, 2, 2)
67
+ sr_ratios: list[int] | tuple[int, ...] = (8, 4, 2, 1)
68
+ hidden_sizes: list[int] | tuple[int, ...] = (32, 64, 160, 256)
69
+ patch_sizes: list[int] | tuple[int, ...] = (7, 3, 3, 3)
70
+ strides: list[int] | tuple[int, ...] = (4, 2, 2, 2)
71
+ num_attention_heads: list[int] | tuple[int, ...] = (1, 2, 5, 8)
72
+ mlp_ratios: list[int] | tuple[int, ...] = (8, 8, 4, 4)
73
+ hidden_act: str = "gelu"
74
+ hidden_dropout_prob: float | int = 0.0
75
+ attention_probs_dropout_prob: float | int = 0.0
76
+ initializer_range: float = 0.02
77
+ drop_path_rate: float | int = 0.0
78
+ layer_norm_eps: float = 1e-6
79
+ qkv_bias: bool = True
80
+ linear_attention: bool = False
81
+ _out_features: list[str] | None = None
82
+ _out_indices: list[int] | None = None
83
+
84
+ def __post_init__(self, **kwargs):
85
+ self.image_size = (self.image_size, self.image_size) if isinstance(self.image_size, int) else self.image_size
86
+ self.stage_names = [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
87
+ self.set_output_features_output_indices(
88
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
89
+ )
90
+ super().__post_init__(**kwargs)
91
+
92
+
93
+ __all__ = ["PvtV2Config"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pvt_v2/modeling_pvt_v2.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Authors: Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan,
2
+ # Kaitao Song, Ding Liang, Tong Lu, Ping Luo, Ling Shao and The HuggingFace Inc. team.
3
+ # All rights reserved.
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
+ """PyTorch PVTv2 model."""
17
+
18
+ import math
19
+
20
+ import torch
21
+ from torch import nn
22
+
23
+ from ... import initialization as init
24
+ from ...activations import ACT2FN
25
+ from ...backbone_utils import BackboneMixin, filter_output_hidden_states
26
+ from ...modeling_layers import GradientCheckpointingLayer
27
+ from ...modeling_outputs import BackboneOutput, BaseModelOutput, ImageClassifierOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import auto_docstring, logging
30
+ from ...utils.generic import can_return_tuple
31
+ from .configuration_pvt_v2 import PvtV2Config
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class PvtV2OverlapPatchEmbeddings(nn.Module):
38
+ """Image to Patch Embedding"""
39
+
40
+ def __init__(self, config: PvtV2Config, layer_idx: int):
41
+ super().__init__()
42
+ patch_size = config.patch_sizes[layer_idx]
43
+ patch_size = (patch_size, patch_size) if isinstance(patch_size, int) else patch_size
44
+ stride = config.strides[layer_idx]
45
+ num_channels = config.num_channels if layer_idx == 0 else config.hidden_sizes[layer_idx - 1]
46
+ hidden_size = config.hidden_sizes[layer_idx]
47
+ self.patch_size = patch_size
48
+ self.proj = nn.Conv2d(
49
+ num_channels,
50
+ hidden_size,
51
+ kernel_size=patch_size,
52
+ stride=stride,
53
+ padding=(patch_size[0] // 2, patch_size[1] // 2),
54
+ )
55
+ self.layer_norm = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
56
+
57
+ def forward(self, pixel_values):
58
+ embeddings = self.proj(pixel_values)
59
+ _, _, height, width = embeddings.shape
60
+ embeddings = embeddings.flatten(2).transpose(1, 2)
61
+ embeddings = self.layer_norm(embeddings)
62
+ return embeddings, height, width
63
+
64
+
65
+ class PvtV2DepthWiseConv(nn.Module):
66
+ """
67
+ Depth-wise (DW) convolution to infuse positional information using zero-padding. Depth-wise convolutions
68
+ have an equal number of groups to the number of input channels, meaning one filter per input channel. This
69
+ reduces the overall parameters and compute costs since the key purpose of this layer is position encoding.
70
+ """
71
+
72
+ def __init__(self, config: PvtV2Config, dim: int = 768):
73
+ super().__init__()
74
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
75
+
76
+ def forward(self, hidden_states, height, width):
77
+ batch_size, seq_len, num_channels = hidden_states.shape
78
+ hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width)
79
+ hidden_states = self.dwconv(hidden_states)
80
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
81
+
82
+ return hidden_states
83
+
84
+
85
+ class PvtV2SelfAttention(nn.Module):
86
+ """Efficient self-attention mechanism."""
87
+
88
+ def __init__(self, config: PvtV2Config, hidden_size: int, num_attention_heads: int, spatial_reduction_ratio: int):
89
+ super().__init__()
90
+ self.linear_attention = config.linear_attention
91
+
92
+ self.hidden_size = hidden_size
93
+ self.num_attention_heads = num_attention_heads
94
+
95
+ if self.hidden_size % self.num_attention_heads != 0:
96
+ raise ValueError(
97
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
98
+ f"heads ({self.num_attention_heads})"
99
+ )
100
+
101
+ self.attention_head_size = int(self.hidden_size / self.num_attention_heads)
102
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
103
+
104
+ self.query = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias)
105
+ self.key = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias)
106
+ self.value = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias)
107
+ self.attn_drop = nn.Dropout(config.attention_probs_dropout_prob)
108
+ self.proj = nn.Linear(self.hidden_size, self.hidden_size)
109
+ self.proj_drop = nn.Dropout(config.hidden_dropout_prob)
110
+
111
+ self.spatial_reduction_ratio = spatial_reduction_ratio
112
+ if self.linear_attention:
113
+ self.pool = nn.AdaptiveAvgPool2d(7)
114
+ self.spatial_reduction = nn.Conv2d(self.hidden_size, self.hidden_size, kernel_size=1, stride=1)
115
+ self.layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
116
+ self.act = nn.GELU()
117
+ elif spatial_reduction_ratio > 1:
118
+ self.spatial_reduction = nn.Conv2d(
119
+ self.hidden_size, self.hidden_size, kernel_size=spatial_reduction_ratio, stride=spatial_reduction_ratio
120
+ )
121
+ self.layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
122
+
123
+ def transpose_for_scores(self, hidden_states) -> torch.Tensor:
124
+ new_shape = hidden_states.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
125
+ hidden_states = hidden_states.view(new_shape)
126
+ return hidden_states.permute(0, 2, 1, 3)
127
+
128
+ def forward(
129
+ self,
130
+ hidden_states: torch.Tensor,
131
+ height: int,
132
+ width: int,
133
+ output_attentions: bool = False,
134
+ ) -> tuple[torch.Tensor]:
135
+ batch_size, seq_len, num_channels = hidden_states.shape
136
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
137
+
138
+ if self.linear_attention:
139
+ hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
140
+ hidden_states = (
141
+ self.spatial_reduction(self.pool(hidden_states)).reshape(batch_size, num_channels, -1).permute(0, 2, 1)
142
+ )
143
+ hidden_states = self.act(self.layer_norm(hidden_states))
144
+ elif self.spatial_reduction_ratio > 1:
145
+ hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
146
+ hidden_states = (
147
+ self.spatial_reduction(hidden_states).reshape(batch_size, num_channels, -1).permute(0, 2, 1)
148
+ )
149
+ hidden_states = self.layer_norm(hidden_states)
150
+
151
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
152
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
153
+
154
+ # Take the dot product between "query" and "key" to get the raw attention scores.
155
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
156
+
157
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
158
+
159
+ # Normalize the attention scores to probabilities.
160
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
161
+
162
+ # This is actually dropping out entire tokens to attend to, which might
163
+ # seem a bit unusual, but is taken from the original Transformer paper.
164
+ attention_probs = self.attn_drop(attention_probs)
165
+ context_layer = (attention_probs @ value_layer).transpose(1, 2).reshape(batch_size, seq_len, num_channels)
166
+ context_layer = self.proj(context_layer)
167
+ context_layer = self.proj_drop(context_layer)
168
+
169
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
170
+
171
+ return outputs
172
+
173
+
174
+ class PvtV2ConvFeedForwardNetwork(nn.Module):
175
+ def __init__(
176
+ self,
177
+ config: PvtV2Config,
178
+ in_features: int,
179
+ hidden_features: int | None = None,
180
+ out_features: int | None = None,
181
+ ):
182
+ super().__init__()
183
+ out_features = out_features if out_features is not None else in_features
184
+ self.dense1 = nn.Linear(in_features, hidden_features)
185
+ self.dwconv = PvtV2DepthWiseConv(config, hidden_features)
186
+ if isinstance(config.hidden_act, str):
187
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
188
+ else:
189
+ self.intermediate_act_fn = config.hidden_act
190
+ self.dense2 = nn.Linear(hidden_features, out_features)
191
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
192
+ self.relu = nn.ReLU() if config.linear_attention else nn.Identity()
193
+
194
+ def forward(self, hidden_states: torch.Tensor, height, width) -> torch.Tensor:
195
+ hidden_states = self.dense1(hidden_states)
196
+ hidden_states = self.relu(hidden_states)
197
+ hidden_states = self.dwconv(hidden_states, height, width)
198
+ hidden_states = self.intermediate_act_fn(hidden_states)
199
+ hidden_states = self.dropout(hidden_states)
200
+ hidden_states = self.dense2(hidden_states)
201
+ hidden_states = self.dropout(hidden_states)
202
+ return hidden_states
203
+
204
+
205
+ # Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->PvtV2DropPath
206
+ class PvtV2DropPath(nn.Module):
207
+ """Stochastic depth (DropPath) per sample, for residual blocks.
208
+
209
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
210
+ <https://arxiv.org/abs/1603.09382>`_.
211
+ """
212
+
213
+ def __init__(self, drop_prob: float = 0.0) -> None:
214
+ super().__init__()
215
+ self.drop_prob = drop_prob
216
+
217
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
218
+ if self.drop_prob == 0.0 or not self.training:
219
+ return hidden_states
220
+ keep_prob = 1 - self.drop_prob
221
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
222
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
223
+ random_tensor = torch.floor(random_tensor + keep_prob)
224
+ return hidden_states.div(keep_prob) * random_tensor
225
+
226
+ def extra_repr(self) -> str:
227
+ return f"p={self.drop_prob}"
228
+
229
+
230
+ class PvtV2BlockLayer(nn.Module):
231
+ def __init__(self, config: PvtV2Config, layer_idx: int, drop_path: float = 0.0):
232
+ super().__init__()
233
+ hidden_size: int = config.hidden_sizes[layer_idx]
234
+ num_attention_heads: int = config.num_attention_heads[layer_idx]
235
+ spatial_reduction_ratio: int = config.sr_ratios[layer_idx]
236
+ mlp_ratio: float = config.mlp_ratios[layer_idx]
237
+ self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
238
+ self.attention = PvtV2SelfAttention(
239
+ config=config,
240
+ hidden_size=hidden_size,
241
+ num_attention_heads=num_attention_heads,
242
+ spatial_reduction_ratio=spatial_reduction_ratio,
243
+ )
244
+ self.drop_path = PvtV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
245
+ self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
246
+ mlp_hidden_size = int(hidden_size * mlp_ratio)
247
+ self.mlp = PvtV2ConvFeedForwardNetwork(config=config, in_features=hidden_size, hidden_features=mlp_hidden_size)
248
+
249
+ def forward(self, hidden_states: torch.Tensor, height: int, width: int, output_attentions: bool = False):
250
+ self_attention_outputs = self.attention(
251
+ hidden_states=self.layer_norm_1(hidden_states),
252
+ height=height,
253
+ width=width,
254
+ output_attentions=output_attentions,
255
+ )
256
+ attention_output = self_attention_outputs[0]
257
+ outputs = self_attention_outputs[1:]
258
+
259
+ attention_output = self.drop_path(attention_output)
260
+ hidden_states = attention_output + hidden_states
261
+
262
+ mlp_output = self.mlp(self.layer_norm_2(hidden_states), height, width)
263
+
264
+ mlp_output = self.drop_path(mlp_output)
265
+ layer_output = hidden_states + mlp_output
266
+
267
+ outputs = (layer_output,) + outputs
268
+
269
+ return outputs
270
+
271
+
272
+ class PvtV2EncoderLayer(GradientCheckpointingLayer):
273
+ def __init__(self, config: PvtV2Config, layer_idx: int):
274
+ super().__init__()
275
+ self.patch_embedding = PvtV2OverlapPatchEmbeddings(
276
+ config=config,
277
+ layer_idx=layer_idx,
278
+ )
279
+ # Transformer block
280
+ # stochastic depth decay rule
281
+ drop_path_decays = torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").tolist()
282
+ block_layers = []
283
+ for block_idx in range(config.depths[layer_idx]):
284
+ block_layers.append(
285
+ PvtV2BlockLayer(
286
+ config=config,
287
+ layer_idx=layer_idx,
288
+ drop_path=drop_path_decays[sum(config.depths[:layer_idx]) + block_idx],
289
+ )
290
+ )
291
+ self.blocks = nn.ModuleList(block_layers)
292
+
293
+ # Layer norm
294
+ self.layer_norm = nn.LayerNorm(config.hidden_sizes[layer_idx], eps=config.layer_norm_eps)
295
+
296
+ def forward(self, hidden_states, output_attentions):
297
+ all_self_attentions = () if output_attentions else None
298
+ # first, obtain patch embeddings
299
+ hidden_states, height, width = self.patch_embedding(hidden_states)
300
+ # second, send embeddings through blocks
301
+ for block in self.blocks:
302
+ layer_outputs = block(hidden_states, height, width, output_attentions)
303
+ hidden_states = layer_outputs[0]
304
+ if output_attentions:
305
+ all_self_attentions += (layer_outputs[1],)
306
+ # third, apply layer norm
307
+ hidden_states = self.layer_norm(hidden_states)
308
+
309
+ outputs = (hidden_states,)
310
+
311
+ if output_attentions:
312
+ outputs += (all_self_attentions,)
313
+
314
+ return outputs, height, width
315
+
316
+
317
+ class PvtV2Encoder(nn.Module):
318
+ def __init__(self, config: PvtV2Config):
319
+ super().__init__()
320
+ self.config = config
321
+ self.gradient_checkpointing = False
322
+
323
+ # encoder layers
324
+ self.layers = nn.ModuleList([PvtV2EncoderLayer(config, i) for i in range(config.num_encoder_blocks)])
325
+
326
+ def forward(
327
+ self,
328
+ pixel_values: torch.FloatTensor,
329
+ output_attentions: bool | None = False,
330
+ output_hidden_states: bool | None = False,
331
+ return_dict: bool | None = True,
332
+ ) -> tuple | BaseModelOutput:
333
+ all_hidden_states = () if output_hidden_states else None
334
+ all_self_attentions = () if output_attentions else None
335
+
336
+ batch_size = pixel_values.shape[0]
337
+ hidden_states = pixel_values
338
+ for idx, layer in enumerate(self.layers):
339
+ layer_output = layer(hidden_states, output_attentions)
340
+ outputs, height, width = layer_output
341
+ hidden_states = outputs[0]
342
+ if output_attentions:
343
+ all_self_attentions = all_self_attentions + (outputs[1],)
344
+ # reshape back to (batch_size, num_channels, height, width)
345
+ hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
346
+ if output_hidden_states:
347
+ all_hidden_states = all_hidden_states + (hidden_states,)
348
+ if not return_dict:
349
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
350
+ return BaseModelOutput(
351
+ last_hidden_state=hidden_states,
352
+ hidden_states=all_hidden_states,
353
+ attentions=all_self_attentions,
354
+ )
355
+
356
+
357
+ @auto_docstring
358
+ class PvtV2PreTrainedModel(PreTrainedModel):
359
+ config: PvtV2Config
360
+ base_model_prefix = "pvt_v2"
361
+ main_input_name = "pixel_values"
362
+ input_modalities = ("image",)
363
+ supports_gradient_checkpointing = True
364
+
365
+ @torch.no_grad()
366
+ def _init_weights(self, module: nn.Linear | nn.Conv2d | nn.LayerNorm) -> None:
367
+ """Initialize the weights"""
368
+ if isinstance(module, nn.Linear):
369
+ init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_range)
370
+ if module.bias is not None:
371
+ init.zeros_(module.bias)
372
+ elif isinstance(module, nn.LayerNorm):
373
+ init.zeros_(module.bias)
374
+ init.ones_(module.weight)
375
+ elif isinstance(module, nn.Conv2d):
376
+ fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
377
+ fan_out //= module.groups
378
+ init.normal_(module.weight, 0, math.sqrt(2.0 / fan_out))
379
+ if module.bias is not None:
380
+ init.zeros_(module.bias)
381
+
382
+
383
+ @auto_docstring
384
+ class PvtV2Model(PvtV2PreTrainedModel):
385
+ def __init__(self, config: PvtV2Config):
386
+ super().__init__(config)
387
+ self.config = config
388
+
389
+ # hierarchical Transformer encoder
390
+ self.encoder = PvtV2Encoder(config)
391
+
392
+ # Initialize weights and apply final processing
393
+ self.post_init()
394
+
395
+ @auto_docstring
396
+ def forward(
397
+ self,
398
+ pixel_values: torch.FloatTensor,
399
+ output_attentions: bool | None = None,
400
+ output_hidden_states: bool | None = None,
401
+ return_dict: bool | None = None,
402
+ **kwargs,
403
+ ) -> tuple | BaseModelOutput:
404
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
405
+ output_hidden_states = (
406
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
407
+ )
408
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
409
+
410
+ encoder_outputs = self.encoder(
411
+ pixel_values=pixel_values,
412
+ output_attentions=output_attentions,
413
+ output_hidden_states=output_hidden_states,
414
+ return_dict=return_dict,
415
+ )
416
+ sequence_output = encoder_outputs[0]
417
+
418
+ if not return_dict:
419
+ return (sequence_output,) + encoder_outputs[1:]
420
+
421
+ return BaseModelOutput(
422
+ last_hidden_state=sequence_output,
423
+ hidden_states=encoder_outputs.hidden_states,
424
+ attentions=encoder_outputs.attentions,
425
+ )
426
+
427
+
428
+ @auto_docstring(
429
+ custom_intro="""
430
+ Pvt-v2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state
431
+ of the [CLS] token) e.g. for ImageNet.
432
+ """
433
+ )
434
+ class PvtV2ForImageClassification(PvtV2PreTrainedModel):
435
+ def __init__(self, config: PvtV2Config) -> None:
436
+ super().__init__(config)
437
+
438
+ self.num_labels = config.num_labels
439
+ self.pvt_v2 = PvtV2Model(config)
440
+
441
+ # Classifier head
442
+ self.classifier = (
443
+ nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
444
+ )
445
+
446
+ # Initialize weights and apply final processing
447
+ self.post_init()
448
+
449
+ @auto_docstring
450
+ def forward(
451
+ self,
452
+ pixel_values: torch.Tensor | None,
453
+ labels: torch.Tensor | None = None,
454
+ output_attentions: bool | None = None,
455
+ output_hidden_states: bool | None = None,
456
+ return_dict: bool | None = None,
457
+ **kwargs,
458
+ ) -> tuple | ImageClassifierOutput:
459
+ r"""
460
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
461
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
462
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
463
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
464
+ """
465
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
466
+
467
+ outputs = self.pvt_v2(
468
+ pixel_values=pixel_values,
469
+ output_attentions=output_attentions,
470
+ output_hidden_states=output_hidden_states,
471
+ return_dict=return_dict,
472
+ )
473
+
474
+ sequence_output = outputs[0]
475
+
476
+ # convert last hidden states to (batch_size, height*width, hidden_size)
477
+ batch_size = sequence_output.shape[0]
478
+ # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
479
+ sequence_output = sequence_output.permute(0, 2, 3, 1)
480
+ sequence_output = sequence_output.reshape(batch_size, -1, self.config.hidden_sizes[-1])
481
+
482
+ # global average pooling
483
+ sequence_output = sequence_output.mean(dim=1)
484
+
485
+ logits = self.classifier(sequence_output)
486
+
487
+ loss = None
488
+ if labels is not None:
489
+ loss = self.loss_function(labels, logits, self.config)
490
+
491
+ if not return_dict:
492
+ output = (logits,) + outputs[1:]
493
+ return ((loss,) + output) if loss is not None else output
494
+
495
+ return ImageClassifierOutput(
496
+ loss=loss,
497
+ logits=logits,
498
+ hidden_states=outputs.hidden_states,
499
+ attentions=outputs.attentions,
500
+ )
501
+
502
+
503
+ @auto_docstring(
504
+ custom_intro="""
505
+ PVTv2 backbone, to be used with frameworks like DETR and MaskFormer.
506
+ """
507
+ )
508
+ class PvtV2Backbone(BackboneMixin, PvtV2Model):
509
+ def __init__(self, config: PvtV2Config):
510
+ super().__init__(config)
511
+ self.num_features = config.hidden_sizes
512
+
513
+ @can_return_tuple
514
+ @filter_output_hidden_states
515
+ @auto_docstring
516
+ def forward(
517
+ self,
518
+ pixel_values: torch.FloatTensor,
519
+ output_attentions: bool | None = None,
520
+ output_hidden_states: bool | None = None,
521
+ return_dict: bool | None = None,
522
+ **kwargs,
523
+ ) -> BackboneOutput:
524
+ r"""
525
+ Examples:
526
+
527
+ ```python
528
+ >>> from transformers import AutoImageProcessor, AutoBackbone
529
+ >>> import torch
530
+ >>> from PIL import Image
531
+ >>> import httpx
532
+ >>> from io import BytesIO
533
+
534
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
535
+ >>> with httpx.stream("GET", url) as response:
536
+ ... image = Image.open(BytesIO(response.read()))
537
+
538
+ >>> processor = AutoImageProcessor.from_pretrained("OpenGVLab/pvt_v2_b0")
539
+ >>> model = AutoBackbone.from_pretrained(
540
+ ... "OpenGVLab/pvt_v2_b0", out_features=["stage1", "stage2", "stage3", "stage4"]
541
+ ... )
542
+
543
+ >>> inputs = processor(image, return_tensors="pt")
544
+
545
+ >>> outputs = model(**inputs)
546
+ >>> feature_maps = outputs.feature_maps
547
+ >>> list(feature_maps[-1].shape)
548
+ [1, 256, 7, 7]
549
+ ```"""
550
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
551
+ output_hidden_states = (
552
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
553
+ )
554
+
555
+ outputs = self.encoder(
556
+ pixel_values=pixel_values,
557
+ output_attentions=output_attentions,
558
+ output_hidden_states=True,
559
+ return_dict=return_dict,
560
+ )
561
+
562
+ hidden_states = outputs.hidden_states
563
+
564
+ feature_maps = ()
565
+ for idx, stage in enumerate(self.stage_names):
566
+ if stage in self.out_features:
567
+ feature_maps += (hidden_states[idx],)
568
+
569
+ if not return_dict:
570
+ output = (feature_maps,)
571
+ if output_hidden_states:
572
+ output += (outputs.hidden_states,)
573
+ return output
574
+
575
+ return BackboneOutput(
576
+ feature_maps=feature_maps,
577
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
578
+ attentions=None,
579
+ )
580
+
581
+
582
+ __all__ = ["PvtV2ForImageClassification", "PvtV2Model", "PvtV2PreTrainedModel", "PvtV2Backbone"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/xmod/__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_xmod import *
22
+ from .modeling_xmod 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/xmod/configuration_xmod.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The Meta AI Team Authors and The HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """X-MOD configuration"""
16
+
17
+ from huggingface_hub.dataclasses import strict
18
+
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ @auto_docstring(checkpoint="facebook/xmod-base")
24
+ @strict
25
+ class XmodConfig(PreTrainedConfig):
26
+ r"""
27
+ pre_norm (`bool`, *optional*, defaults to `False`):
28
+ Whether to apply layer normalization before each block.
29
+ adapter_reduction_factor (`int` or `float`, *optional*, defaults to 2):
30
+ The factor by which the dimensionality of the adapter is reduced relative to `hidden_size`.
31
+ adapter_layer_norm (`bool`, *optional*, defaults to `False`):
32
+ Whether to apply a new layer normalization before the adapter modules (shared across all adapters).
33
+ adapter_reuse_layer_norm (`bool`, *optional*, defaults to `True`):
34
+ Whether to reuse the second layer normalization and apply it before the adapter modules as well.
35
+ ln_before_adapter (`bool`, *optional*, defaults to `True`):
36
+ Whether to apply the layer normalization before the residual connection around the adapter module.
37
+ languages (`Iterable[str]`, *optional*, defaults to `["en_XX"]`):
38
+ An iterable of language codes for which adapter modules should be initialized.
39
+ default_language (`str`, *optional*):
40
+ Language code of a default language. It will be assumed that the input is in this language if no language
41
+ codes are explicitly passed to the forward method.
42
+
43
+ Examples:
44
+
45
+ ```python
46
+ >>> from transformers import XmodConfig, XmodModel
47
+
48
+ >>> # Initializing an X-MOD facebook/xmod-base style configuration
49
+ >>> configuration = XmodConfig()
50
+
51
+ >>> # Initializing a model (with random weights) from the facebook/xmod-base style configuration
52
+ >>> model = XmodModel(configuration)
53
+
54
+ >>> # Accessing the model configuration
55
+ >>> configuration = model.config
56
+ ```"""
57
+
58
+ model_type = "xmod"
59
+
60
+ vocab_size: int = 30522
61
+ hidden_size: int = 768
62
+ num_hidden_layers: int = 12
63
+ num_attention_heads: int = 12
64
+ intermediate_size: int = 3072
65
+ hidden_act: str = "gelu"
66
+ hidden_dropout_prob: float | int = 0.1
67
+ attention_probs_dropout_prob: float | int = 0.1
68
+ max_position_embeddings: int = 512
69
+ type_vocab_size: int = 2
70
+ initializer_range: float = 0.02
71
+ layer_norm_eps: float = 1e-12
72
+ pad_token_id: int | None = 1
73
+ bos_token_id: int | None = 0
74
+ eos_token_id: int | list[int] | None = 2
75
+ use_cache: bool = True
76
+ classifier_dropout: float | int | None = None
77
+ pre_norm: bool = False
78
+ adapter_reduction_factor: int = 2
79
+ adapter_layer_norm: bool = False
80
+ adapter_reuse_layer_norm: bool = True
81
+ ln_before_adapter: bool = True
82
+ languages: list[str] | tuple[str, ...] = ("en_XX",)
83
+ default_language: str | None = None
84
+ is_decoder: bool = False
85
+ add_cross_attention: bool = False
86
+ tie_word_embeddings: bool = True
87
+
88
+
89
+ __all__ = ["XmodConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py ADDED
@@ -0,0 +1,1390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Meta AI Team and the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch X-MOD model."""
15
+
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN, gelu
24
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
25
+ from ...generation import GenerationMixin
26
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutput,
36
+ TokenClassifierOutput,
37
+ )
38
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from ...processing_utils import Unpack
40
+ from ...pytorch_utils import apply_chunking_to_forward
41
+ from ...utils import TransformersKwargs, auto_docstring, logging
42
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
43
+ from ...utils.output_capturing import capture_outputs
44
+ from .configuration_xmod import XmodConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Xmod
51
+ class XmodEmbeddings(nn.Module):
52
+ """Construct the embeddings from word, position and token_type embeddings."""
53
+
54
+ def __init__(self, config):
55
+ super().__init__()
56
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
57
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
58
+
59
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
60
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
61
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
62
+ self.register_buffer(
63
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
64
+ )
65
+ self.register_buffer(
66
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
67
+ )
68
+
69
+ self.padding_idx = config.pad_token_id
70
+ self.position_embeddings = nn.Embedding(
71
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
72
+ )
73
+
74
+ def forward(
75
+ self,
76
+ input_ids: torch.LongTensor | None = None,
77
+ token_type_ids: torch.LongTensor | None = None,
78
+ position_ids: torch.LongTensor | None = None,
79
+ inputs_embeds: torch.FloatTensor | None = None,
80
+ past_key_values_length: int = 0,
81
+ ) -> torch.Tensor:
82
+ if position_ids is None:
83
+ if input_ids is not None:
84
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
85
+ position_ids = self.create_position_ids_from_input_ids(
86
+ input_ids, self.padding_idx, past_key_values_length
87
+ )
88
+ else:
89
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
90
+
91
+ if input_ids is not None:
92
+ input_shape = input_ids.size()
93
+ else:
94
+ input_shape = inputs_embeds.size()[:-1]
95
+
96
+ batch_size, seq_length = input_shape
97
+
98
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
99
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
100
+ # issue #5664
101
+ if token_type_ids is None:
102
+ if hasattr(self, "token_type_ids"):
103
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
104
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
105
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
106
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
107
+ else:
108
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
109
+
110
+ if inputs_embeds is None:
111
+ inputs_embeds = self.word_embeddings(input_ids)
112
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
113
+ embeddings = inputs_embeds + token_type_embeddings
114
+
115
+ position_embeddings = self.position_embeddings(position_ids)
116
+ embeddings = embeddings + position_embeddings
117
+
118
+ embeddings = self.LayerNorm(embeddings)
119
+ embeddings = self.dropout(embeddings)
120
+ return embeddings
121
+
122
+ @staticmethod
123
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
124
+ """
125
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
126
+
127
+ Args:
128
+ inputs_embeds: torch.Tensor
129
+
130
+ Returns: torch.Tensor
131
+ """
132
+ input_shape = inputs_embeds.size()[:-1]
133
+ sequence_length = input_shape[1]
134
+
135
+ position_ids = torch.arange(
136
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
137
+ )
138
+ return position_ids.unsqueeze(0).expand(input_shape)
139
+
140
+ @staticmethod
141
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
142
+ """
143
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
144
+ are ignored. This is modified from fairseq's `utils.make_positions`.
145
+
146
+ Args:
147
+ x: torch.Tensor x:
148
+
149
+ Returns: torch.Tensor
150
+ """
151
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
152
+ mask = input_ids.ne(padding_idx).int()
153
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
154
+ return incremental_indices.long() + padding_idx
155
+
156
+
157
+ # Copied from transformers.models.bert.modeling_bert.eager_attention_forward
158
+ def eager_attention_forward(
159
+ module: nn.Module,
160
+ query: torch.Tensor,
161
+ key: torch.Tensor,
162
+ value: torch.Tensor,
163
+ attention_mask: torch.Tensor | None,
164
+ scaling: float | None = None,
165
+ dropout: float = 0.0,
166
+ **kwargs: Unpack[TransformersKwargs],
167
+ ):
168
+ if scaling is None:
169
+ scaling = query.size(-1) ** -0.5
170
+
171
+ # Take the dot product between "query" and "key" to get the raw attention scores.
172
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
173
+
174
+ if attention_mask is not None:
175
+ attn_weights = attn_weights + attention_mask
176
+
177
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
178
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
179
+
180
+ attn_output = torch.matmul(attn_weights, value)
181
+ attn_output = attn_output.transpose(1, 2).contiguous()
182
+
183
+ return attn_output, attn_weights
184
+
185
+
186
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Xmod
187
+ class XmodSelfAttention(nn.Module):
188
+ def __init__(self, config, is_causal=False, layer_idx=None):
189
+ super().__init__()
190
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
191
+ raise ValueError(
192
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
193
+ f"heads ({config.num_attention_heads})"
194
+ )
195
+ self.config = config
196
+
197
+ self.num_attention_heads = config.num_attention_heads
198
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
199
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
200
+ self.scaling = self.attention_head_size**-0.5
201
+
202
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
203
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
204
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
205
+
206
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
207
+
208
+ self.is_decoder = config.is_decoder
209
+ self.is_causal = is_causal
210
+ self.layer_idx = layer_idx
211
+
212
+ def forward(
213
+ self,
214
+ hidden_states: torch.Tensor,
215
+ attention_mask: torch.FloatTensor | None = None,
216
+ past_key_values: Cache | None = None,
217
+ **kwargs: Unpack[TransformersKwargs],
218
+ ) -> tuple[torch.Tensor]:
219
+ input_shape = hidden_states.shape[:-1]
220
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
221
+
222
+ # get all proj
223
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
224
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
225
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
226
+
227
+ if past_key_values is not None:
228
+ # decoder-only roberta can have a simple dynamic cache for example
229
+ current_past_key_values = past_key_values
230
+ if isinstance(past_key_values, EncoderDecoderCache):
231
+ current_past_key_values = past_key_values.self_attention_cache
232
+
233
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
234
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
235
+
236
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
237
+ self.config._attn_implementation, eager_attention_forward
238
+ )
239
+
240
+ attn_output, attn_weights = attention_interface(
241
+ self,
242
+ query_layer,
243
+ key_layer,
244
+ value_layer,
245
+ attention_mask,
246
+ dropout=0.0 if not self.training else self.dropout.p,
247
+ scaling=self.scaling,
248
+ **kwargs,
249
+ )
250
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
251
+ return attn_output, attn_weights
252
+
253
+
254
+ # Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->Xmod
255
+ class XmodCrossAttention(nn.Module):
256
+ def __init__(self, config, is_causal=False, layer_idx=None):
257
+ super().__init__()
258
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
259
+ raise ValueError(
260
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
261
+ f"heads ({config.num_attention_heads})"
262
+ )
263
+ self.config = config
264
+
265
+ self.num_attention_heads = config.num_attention_heads
266
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
267
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
268
+ self.scaling = self.attention_head_size**-0.5
269
+
270
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
271
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
272
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
273
+
274
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
275
+
276
+ self.is_causal = is_causal
277
+ self.layer_idx = layer_idx
278
+
279
+ def forward(
280
+ self,
281
+ hidden_states: torch.Tensor,
282
+ encoder_hidden_states: torch.FloatTensor | None = None,
283
+ attention_mask: torch.FloatTensor | None = None,
284
+ past_key_values: EncoderDecoderCache | None = None,
285
+ **kwargs: Unpack[TransformersKwargs],
286
+ ) -> tuple[torch.Tensor]:
287
+ # determine input shapes
288
+ input_shape = hidden_states.shape[:-1]
289
+
290
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
291
+
292
+ # get query proj
293
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
294
+
295
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
296
+ if past_key_values is not None and is_updated:
297
+ # reuse k,v, cross_attentions
298
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
299
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
300
+ else:
301
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
302
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
303
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
304
+
305
+ if past_key_values is not None:
306
+ # save all states to the cache
307
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
308
+ key_layer, value_layer, self.layer_idx
309
+ )
310
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
311
+ past_key_values.is_updated[self.layer_idx] = True
312
+
313
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
314
+ self.config._attn_implementation, eager_attention_forward
315
+ )
316
+
317
+ attn_output, attn_weights = attention_interface(
318
+ self,
319
+ query_layer,
320
+ key_layer,
321
+ value_layer,
322
+ attention_mask,
323
+ dropout=0.0 if not self.training else self.dropout.p,
324
+ scaling=self.scaling,
325
+ **kwargs,
326
+ )
327
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
328
+ return attn_output, attn_weights
329
+
330
+
331
+ class XmodSelfOutput(nn.Module):
332
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput.__init__
333
+ def __init__(self, config):
334
+ super().__init__()
335
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
336
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
337
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
338
+
339
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
340
+ hidden_states = self.dense(hidden_states)
341
+ hidden_states = self.dropout(hidden_states)
342
+ hidden_states = hidden_states + input_tensor
343
+ return hidden_states
344
+
345
+
346
+ class XmodAttention(nn.Module):
347
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
348
+ super().__init__()
349
+ self.is_cross_attention = is_cross_attention
350
+ attention_class = XmodCrossAttention if is_cross_attention else XmodSelfAttention
351
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
352
+ self.output = XmodSelfOutput(config)
353
+
354
+ self.pre_norm = config.pre_norm
355
+
356
+ def forward(
357
+ self,
358
+ hidden_states: torch.Tensor,
359
+ attention_mask: torch.FloatTensor | None = None,
360
+ encoder_hidden_states: torch.FloatTensor | None = None,
361
+ encoder_attention_mask: torch.FloatTensor | None = None,
362
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
363
+ **kwargs: Unpack[TransformersKwargs],
364
+ ) -> tuple[torch.Tensor]:
365
+ residual = hidden_states
366
+ if self.pre_norm:
367
+ hidden_states = self.output.LayerNorm(hidden_states)
368
+
369
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
370
+ attention_output, attn_weights = self.self(
371
+ hidden_states,
372
+ encoder_hidden_states=encoder_hidden_states,
373
+ attention_mask=attention_mask,
374
+ past_key_values=past_key_values,
375
+ **kwargs,
376
+ )
377
+ attention_output = self.output(attention_output, residual)
378
+
379
+ if not self.pre_norm:
380
+ attention_output = self.output.LayerNorm(attention_output)
381
+
382
+ return attention_output, attn_weights
383
+
384
+
385
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate
386
+ class XmodIntermediate(nn.Module):
387
+ def __init__(self, config):
388
+ super().__init__()
389
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
390
+ if isinstance(config.hidden_act, str):
391
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
392
+ else:
393
+ self.intermediate_act_fn = config.hidden_act
394
+
395
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
396
+ hidden_states = self.dense(hidden_states)
397
+ hidden_states = self.intermediate_act_fn(hidden_states)
398
+ return hidden_states
399
+
400
+
401
+ class XmodAdapter(nn.Module):
402
+ def __init__(self, config):
403
+ super().__init__()
404
+ self.bottleneck_size = config.hidden_size // config.adapter_reduction_factor
405
+ self.dense1 = nn.Linear(config.hidden_size, self.bottleneck_size)
406
+ self.dense2 = nn.Linear(self.bottleneck_size, config.hidden_size)
407
+ if isinstance(config.hidden_act, str):
408
+ self.adapter_act_fn = ACT2FN[config.hidden_act]
409
+ else:
410
+ self.adapter_act_fn = config.hidden_act
411
+
412
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
413
+ hidden_states = self.dense1(hidden_states)
414
+ hidden_states = self.adapter_act_fn(hidden_states)
415
+ hidden_states = self.dense2(hidden_states)
416
+ return hidden_states
417
+
418
+
419
+ class XmodOutput(nn.Module):
420
+ def __init__(self, config):
421
+ super().__init__()
422
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
423
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
424
+ self.ln_before_adapter = config.ln_before_adapter
425
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
426
+ if config.adapter_layer_norm:
427
+ self.adapter_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
428
+ else:
429
+ self.adapter_layer_norm = None
430
+ self.adapter_reuse_layer_norm = config.adapter_reuse_layer_norm
431
+ self.adapter_modules = nn.ModuleDict({})
432
+ for language in config.languages:
433
+ self.adapter_modules[str(language)] = XmodAdapter(config)
434
+
435
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, lang_ids: torch.Tensor) -> torch.Tensor:
436
+ hidden_states = self.dense(hidden_states)
437
+ hidden_states = self.dropout(hidden_states)
438
+ hidden_states = hidden_states + input_tensor
439
+ hidden_states = self.lang_adapter(lang_ids, hidden_states)
440
+ return hidden_states
441
+
442
+ def lang_adapter(self, lang_ids: torch.Tensor, hidden_states: torch.Tensor):
443
+ if not self.ln_before_adapter:
444
+ residual = hidden_states
445
+
446
+ if self.adapter_layer_norm is not None:
447
+ hidden_states = self.adapter_layer_norm(hidden_states)
448
+ elif self.adapter_reuse_layer_norm:
449
+ hidden_states = self.LayerNorm(hidden_states)
450
+
451
+ if self.ln_before_adapter:
452
+ residual = hidden_states
453
+
454
+ new_hidden_states = torch.zeros_like(hidden_states)
455
+ for adapter_idx, lang_key in enumerate(self.adapter_modules.keys()):
456
+ lang_mask = lang_ids == adapter_idx
457
+ lang_hidden_states = hidden_states[lang_mask]
458
+ adapted_lang_hidden_states = self.adapter_modules[lang_key](lang_hidden_states)
459
+ new_hidden_states[lang_mask] = adapted_lang_hidden_states
460
+
461
+ hidden_states = self.dropout(new_hidden_states)
462
+ hidden_states += residual
463
+ return hidden_states
464
+
465
+
466
+ class XmodLayer(GradientCheckpointingLayer):
467
+ def __init__(self, config, layer_idx=None):
468
+ super().__init__()
469
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
470
+ self.seq_len_dim = 1
471
+ self.attention = XmodAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
472
+ self.is_decoder = config.is_decoder
473
+ self.add_cross_attention = config.add_cross_attention
474
+ if self.add_cross_attention:
475
+ if not self.is_decoder:
476
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
477
+ self.crossattention = XmodAttention(
478
+ config,
479
+ is_causal=False,
480
+ layer_idx=layer_idx,
481
+ is_cross_attention=True,
482
+ )
483
+ self.intermediate = XmodIntermediate(config)
484
+ self.output = XmodOutput(config)
485
+ self.pre_norm = config.pre_norm
486
+
487
+ def forward(
488
+ self,
489
+ hidden_states: torch.Tensor,
490
+ lang_ids: torch.Tensor,
491
+ attention_mask: torch.FloatTensor | None = None,
492
+ encoder_hidden_states: torch.FloatTensor | None = None,
493
+ encoder_attention_mask: torch.FloatTensor | None = None,
494
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
495
+ **kwargs: Unpack[TransformersKwargs],
496
+ ) -> torch.Tensor:
497
+ self_attention_output, _ = self.attention(
498
+ hidden_states,
499
+ attention_mask,
500
+ past_key_values=past_key_values,
501
+ **kwargs,
502
+ )
503
+ attention_output = self_attention_output
504
+
505
+ if self.is_decoder and encoder_hidden_states is not None:
506
+ if not hasattr(self, "crossattention"):
507
+ raise ValueError(
508
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
509
+ " by setting `config.add_cross_attention=True`"
510
+ )
511
+
512
+ cross_attention_output, _ = self.crossattention(
513
+ attention_output,
514
+ None, # attention_mask
515
+ encoder_hidden_states,
516
+ encoder_attention_mask,
517
+ past_key_values=past_key_values,
518
+ **kwargs,
519
+ )
520
+ attention_output = cross_attention_output
521
+
522
+ residual = attention_output
523
+ if self.pre_norm:
524
+ attention_output = self.output.LayerNorm(attention_output)
525
+ intermediate_output = apply_chunking_to_forward(
526
+ self.feed_forward_chunk,
527
+ self.chunk_size_feed_forward,
528
+ self.seq_len_dim,
529
+ attention_output,
530
+ )
531
+ layer_output = self.output(intermediate_output, residual, lang_ids)
532
+ if not self.pre_norm:
533
+ layer_output = self.output.LayerNorm(layer_output)
534
+
535
+ return layer_output
536
+
537
+ def feed_forward_chunk(self, attention_output):
538
+ return self.intermediate(attention_output)
539
+
540
+
541
+ class XmodEncoder(nn.Module):
542
+ def __init__(self, config):
543
+ super().__init__()
544
+ self.config = config
545
+ self.layer = nn.ModuleList([XmodLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
546
+ self.is_pre_norm = config.pre_norm
547
+ if self.is_pre_norm:
548
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
549
+
550
+ def forward(
551
+ self,
552
+ hidden_states: torch.Tensor,
553
+ lang_ids: torch.Tensor,
554
+ attention_mask: torch.FloatTensor | None = None,
555
+ encoder_hidden_states: torch.FloatTensor | None = None,
556
+ encoder_attention_mask: torch.FloatTensor | None = None,
557
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
558
+ use_cache: bool | None = None,
559
+ **kwargs: Unpack[TransformersKwargs],
560
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
561
+ for i, layer_module in enumerate(self.layer):
562
+ hidden_states = layer_module(
563
+ hidden_states,
564
+ lang_ids,
565
+ attention_mask,
566
+ encoder_hidden_states,
567
+ encoder_attention_mask,
568
+ past_key_values,
569
+ **kwargs,
570
+ )
571
+
572
+ if self.is_pre_norm:
573
+ hidden_states = self.LayerNorm(hidden_states)
574
+
575
+ return BaseModelOutputWithPastAndCrossAttentions(
576
+ last_hidden_state=hidden_states,
577
+ past_key_values=past_key_values if use_cache else None,
578
+ )
579
+
580
+
581
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
582
+ class XmodPooler(nn.Module):
583
+ def __init__(self, config):
584
+ super().__init__()
585
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
586
+ self.activation = nn.Tanh()
587
+
588
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
589
+ # We "pool" the model by simply taking the hidden state corresponding
590
+ # to the first token.
591
+ first_token_tensor = hidden_states[:, 0]
592
+ pooled_output = self.dense(first_token_tensor)
593
+ pooled_output = self.activation(pooled_output)
594
+ return pooled_output
595
+
596
+
597
+ @auto_docstring
598
+ class XmodPreTrainedModel(PreTrainedModel):
599
+ config_class = XmodConfig
600
+ base_model_prefix = "roberta"
601
+ supports_gradient_checkpointing = True
602
+ no_split_modules = ["XmodEmbeddings", "XmodSelfAttention", "XmodCrossAttention"]
603
+ _supports_flash_attn = True
604
+ _supports_sdpa = True
605
+ _supports_flex_attn = True
606
+ _supports_attention_backend = True
607
+ _can_record_outputs = {
608
+ "hidden_states": XmodLayer,
609
+ "attentions": XmodSelfAttention,
610
+ "cross_attentions": XmodCrossAttention,
611
+ }
612
+
613
+ @torch.no_grad()
614
+ def _init_weights(self, module):
615
+ """Initialize the weights"""
616
+ super()._init_weights(module)
617
+ if isinstance(module, XmodLMHead):
618
+ init.zeros_(module.bias)
619
+ elif isinstance(module, XmodEmbeddings):
620
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
621
+ init.zeros_(module.token_type_ids)
622
+
623
+ def set_default_language(self, language: str):
624
+ """
625
+ Set the default language code for the model. This is used when the language is not specified in the input.
626
+
627
+ Args:
628
+ language (`str`): The language code, such as `"en_XX"` or `"de_DE"`.
629
+ """
630
+ if language not in self.config.languages:
631
+ raise ValueError(
632
+ f"{self} does not have an adapter for {language}. Supported languages: {list(self.config.languages)}"
633
+ )
634
+ self.config.default_language = language
635
+
636
+ def freeze_embeddings_and_language_adapters(self):
637
+ """
638
+ Freeze the embeddings and language adapters of the model. Usually, this is applied before the model is
639
+ fine-tuned on a downstream task.
640
+ """
641
+ logger.info("Freezing embeddings")
642
+ for parameter in self.roberta.embeddings.parameters():
643
+ parameter.requires_grad = False
644
+ logger.info("Freezing adapters")
645
+ for layer in self.roberta.encoder.layer:
646
+ if layer.output.adapter_layer_norm is not None:
647
+ for parameter in layer.output.adapter_layer_norm.parameters():
648
+ parameter.requires_grad = False
649
+ for parameter in layer.output.adapter_modules.parameters():
650
+ parameter.requires_grad = False
651
+
652
+
653
+ @auto_docstring(
654
+ custom_intro="""
655
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
656
+ cross-attention is added between the self-attention layers, following the architecture described in *Attention is
657
+ all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
658
+ Kaiser and Illia Polosukhin.
659
+
660
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
661
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
662
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
663
+
664
+ .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
665
+ """
666
+ )
667
+ class XmodModel(XmodPreTrainedModel):
668
+ def __init__(self, config, add_pooling_layer=True):
669
+ r"""
670
+ add_pooling_layer (bool, *optional*, defaults to `True`):
671
+ Whether to add a pooling layer
672
+ """
673
+ super().__init__(config)
674
+ self.config = config
675
+ self.gradient_checkpointing = False
676
+
677
+ self.embeddings = XmodEmbeddings(config)
678
+ self.encoder = XmodEncoder(config)
679
+
680
+ self.pooler = XmodPooler(config) if add_pooling_layer else None
681
+
682
+ # Initialize weights and apply final processing
683
+ self.post_init()
684
+
685
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel.get_input_embeddings
686
+ def get_input_embeddings(self):
687
+ return self.embeddings.word_embeddings
688
+
689
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel.set_input_embeddings
690
+ def set_input_embeddings(self, value):
691
+ self.embeddings.word_embeddings = value
692
+
693
+ @merge_with_config_defaults
694
+ @capture_outputs
695
+ @auto_docstring
696
+ def forward(
697
+ self,
698
+ input_ids: torch.Tensor | None = None,
699
+ lang_ids: torch.LongTensor | None = None,
700
+ attention_mask: torch.Tensor | None = None,
701
+ token_type_ids: torch.Tensor | None = None,
702
+ position_ids: torch.Tensor | None = None,
703
+ inputs_embeds: torch.Tensor | None = None,
704
+ encoder_hidden_states: torch.Tensor | None = None,
705
+ encoder_attention_mask: torch.Tensor | None = None,
706
+ past_key_values: list[torch.FloatTensor] | None = None,
707
+ use_cache: bool | None = None,
708
+ **kwargs: Unpack[TransformersKwargs],
709
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
710
+ r"""
711
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
712
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
713
+ that corresponds to `self.config.default_language`.
714
+ """
715
+ if (input_ids is None) ^ (inputs_embeds is not None):
716
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
717
+
718
+ if self.config.is_decoder:
719
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
720
+ else:
721
+ use_cache = False
722
+
723
+ if use_cache and past_key_values is None:
724
+ past_key_values = (
725
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
726
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
727
+ else DynamicCache(config=self.config)
728
+ )
729
+
730
+ batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
731
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
732
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
733
+
734
+ if lang_ids is None:
735
+ if self.config.default_language is None:
736
+ raise ValueError("Input language unknown. Please call `XmodPreTrainedModel.set_default_language()`")
737
+ adapter_languages = list(self.encoder.layer[0].output.adapter_modules.keys())
738
+ default_lang_id = adapter_languages.index(self.config.default_language)
739
+ lang_ids = default_lang_id * torch.ones(batch_size, device=device)
740
+
741
+ embedding_output = self.embeddings(
742
+ input_ids=input_ids,
743
+ position_ids=position_ids,
744
+ token_type_ids=token_type_ids,
745
+ inputs_embeds=inputs_embeds,
746
+ past_key_values_length=past_key_values_length,
747
+ )
748
+
749
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
750
+ attention_mask=attention_mask,
751
+ encoder_attention_mask=encoder_attention_mask,
752
+ embedding_output=embedding_output,
753
+ encoder_hidden_states=encoder_hidden_states,
754
+ past_key_values=past_key_values,
755
+ )
756
+
757
+ encoder_outputs = self.encoder(
758
+ embedding_output,
759
+ lang_ids=lang_ids,
760
+ attention_mask=attention_mask,
761
+ encoder_hidden_states=encoder_hidden_states,
762
+ encoder_attention_mask=encoder_attention_mask,
763
+ past_key_values=past_key_values,
764
+ use_cache=use_cache,
765
+ position_ids=position_ids,
766
+ **kwargs,
767
+ )
768
+ sequence_output = encoder_outputs[0]
769
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
770
+
771
+ return BaseModelOutputWithPoolingAndCrossAttentions(
772
+ last_hidden_state=sequence_output,
773
+ pooler_output=pooled_output,
774
+ past_key_values=encoder_outputs.past_key_values,
775
+ )
776
+
777
+ # Copied from transformers.models.bert.modeling_bert.BertModel._create_attention_masks
778
+ def _create_attention_masks(
779
+ self,
780
+ attention_mask,
781
+ encoder_attention_mask,
782
+ embedding_output,
783
+ encoder_hidden_states,
784
+ past_key_values,
785
+ ):
786
+ if self.config.is_decoder:
787
+ attention_mask = create_causal_mask(
788
+ config=self.config,
789
+ inputs_embeds=embedding_output,
790
+ attention_mask=attention_mask,
791
+ past_key_values=past_key_values,
792
+ )
793
+ else:
794
+ attention_mask = create_bidirectional_mask(
795
+ config=self.config,
796
+ inputs_embeds=embedding_output,
797
+ attention_mask=attention_mask,
798
+ )
799
+
800
+ if encoder_attention_mask is not None:
801
+ encoder_attention_mask = create_bidirectional_mask(
802
+ config=self.config,
803
+ inputs_embeds=embedding_output,
804
+ attention_mask=encoder_attention_mask,
805
+ encoder_hidden_states=encoder_hidden_states,
806
+ )
807
+
808
+ return attention_mask, encoder_attention_mask
809
+
810
+
811
+ @auto_docstring(
812
+ custom_intro="""
813
+ X-MOD Model with a `language modeling` head on top for CLM fine-tuning.
814
+ """
815
+ )
816
+ class XmodForCausalLM(XmodPreTrainedModel, GenerationMixin):
817
+ _tied_weights_keys = {
818
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
819
+ "lm_head.decoder.bias": "lm_head.bias",
820
+ }
821
+
822
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.__init__ with Roberta->Xmod
823
+ def __init__(self, config):
824
+ super().__init__(config)
825
+
826
+ if not config.is_decoder:
827
+ logger.warning("If you want to use `XmodLMHeadModel` as a standalone, add `is_decoder=True.`")
828
+
829
+ self.roberta = XmodModel(config, add_pooling_layer=False)
830
+ self.lm_head = XmodLMHead(config)
831
+
832
+ # Initialize weights and apply final processing
833
+ self.post_init()
834
+
835
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.get_output_embeddings
836
+ def get_output_embeddings(self):
837
+ return self.lm_head.decoder
838
+
839
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.set_output_embeddings
840
+ def set_output_embeddings(self, new_embeddings):
841
+ self.lm_head.decoder = new_embeddings
842
+
843
+ @can_return_tuple
844
+ @auto_docstring
845
+ def forward(
846
+ self,
847
+ input_ids: torch.LongTensor | None = None,
848
+ lang_ids: torch.LongTensor | None = None,
849
+ attention_mask: torch.FloatTensor | None = None,
850
+ token_type_ids: torch.LongTensor | None = None,
851
+ position_ids: torch.LongTensor | None = None,
852
+ inputs_embeds: torch.FloatTensor | None = None,
853
+ encoder_hidden_states: torch.FloatTensor | None = None,
854
+ encoder_attention_mask: torch.FloatTensor | None = None,
855
+ labels: torch.LongTensor | None = None,
856
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
857
+ use_cache: bool | None = None,
858
+ logits_to_keep: int | torch.Tensor = 0,
859
+ **kwargs: Unpack[TransformersKwargs],
860
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
861
+ r"""
862
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
863
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
864
+ that corresponds to `self.config.default_language`.
865
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
866
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
867
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
868
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
869
+
870
+ Example:
871
+
872
+ ```python
873
+ >>> from transformers import AutoTokenizer, XmodForCausalLM, AutoConfig
874
+ >>> import torch
875
+
876
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-roberta-base")
877
+ >>> config = AutoConfig.from_pretrained("facebook/xmod-base")
878
+ >>> config.is_decoder = True
879
+ >>> model = XmodForCausalLM.from_pretrained("facebook/xmod-base", config=config)
880
+ >>> model.set_default_language("en_XX")
881
+
882
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
883
+ >>> outputs = model(**inputs)
884
+
885
+ >>> prediction_logits = outputs.logits
886
+ ```"""
887
+ if labels is not None:
888
+ use_cache = False
889
+
890
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
891
+ input_ids,
892
+ lang_ids=lang_ids,
893
+ attention_mask=attention_mask,
894
+ token_type_ids=token_type_ids,
895
+ position_ids=position_ids,
896
+ inputs_embeds=inputs_embeds,
897
+ encoder_hidden_states=encoder_hidden_states,
898
+ encoder_attention_mask=encoder_attention_mask,
899
+ past_key_values=past_key_values,
900
+ use_cache=use_cache,
901
+ return_dict=True,
902
+ **kwargs,
903
+ )
904
+
905
+ hidden_states = outputs.last_hidden_state
906
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
907
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
908
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
909
+
910
+ loss = None
911
+ if labels is not None:
912
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
913
+
914
+ return CausalLMOutputWithCrossAttentions(
915
+ loss=loss,
916
+ logits=logits,
917
+ past_key_values=outputs.past_key_values,
918
+ hidden_states=outputs.hidden_states,
919
+ attentions=outputs.attentions,
920
+ cross_attentions=outputs.cross_attentions,
921
+ )
922
+
923
+
924
+ @auto_docstring
925
+ class XmodForMaskedLM(XmodPreTrainedModel):
926
+ _tied_weights_keys = {
927
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
928
+ "lm_head.decoder.bias": "lm_head.bias",
929
+ }
930
+
931
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.__init__ with Roberta->Xmod
932
+ def __init__(self, config):
933
+ super().__init__(config)
934
+
935
+ if config.is_decoder:
936
+ logger.warning(
937
+ "If you want to use `XmodForMaskedLM` make sure `config.is_decoder=False` for "
938
+ "bi-directional self-attention."
939
+ )
940
+
941
+ self.roberta = XmodModel(config, add_pooling_layer=False)
942
+ self.lm_head = XmodLMHead(config)
943
+
944
+ # Initialize weights and apply final processing
945
+ self.post_init()
946
+
947
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.get_output_embeddings
948
+ def get_output_embeddings(self):
949
+ return self.lm_head.decoder
950
+
951
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.set_output_embeddings
952
+ def set_output_embeddings(self, new_embeddings):
953
+ self.lm_head.decoder = new_embeddings
954
+
955
+ @can_return_tuple
956
+ @auto_docstring
957
+ def forward(
958
+ self,
959
+ input_ids: torch.LongTensor | None = None,
960
+ lang_ids: torch.LongTensor | None = None,
961
+ attention_mask: torch.FloatTensor | None = None,
962
+ token_type_ids: torch.LongTensor | None = None,
963
+ position_ids: torch.LongTensor | None = None,
964
+ inputs_embeds: torch.FloatTensor | None = None,
965
+ encoder_hidden_states: torch.FloatTensor | None = None,
966
+ encoder_attention_mask: torch.FloatTensor | None = None,
967
+ labels: torch.LongTensor | None = None,
968
+ **kwargs: Unpack[TransformersKwargs],
969
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
970
+ r"""
971
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
972
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
973
+ that corresponds to `self.config.default_language`.
974
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
975
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
976
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
977
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
978
+ """
979
+ outputs = self.roberta(
980
+ input_ids,
981
+ lang_ids=lang_ids,
982
+ attention_mask=attention_mask,
983
+ token_type_ids=token_type_ids,
984
+ position_ids=position_ids,
985
+ inputs_embeds=inputs_embeds,
986
+ encoder_hidden_states=encoder_hidden_states,
987
+ encoder_attention_mask=encoder_attention_mask,
988
+ return_dict=True,
989
+ **kwargs,
990
+ )
991
+ sequence_output = outputs[0]
992
+ prediction_scores = self.lm_head(sequence_output)
993
+
994
+ masked_lm_loss = None
995
+ if labels is not None:
996
+ loss_fct = CrossEntropyLoss()
997
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
998
+
999
+ return MaskedLMOutput(
1000
+ loss=masked_lm_loss,
1001
+ logits=prediction_scores,
1002
+ hidden_states=outputs.hidden_states,
1003
+ attentions=outputs.attentions,
1004
+ )
1005
+
1006
+
1007
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead
1008
+ class XmodLMHead(nn.Module):
1009
+ """Roberta Head for masked language modeling."""
1010
+
1011
+ def __init__(self, config):
1012
+ super().__init__()
1013
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1014
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1015
+
1016
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
1017
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
1018
+
1019
+ def forward(self, features, **kwargs):
1020
+ x = self.dense(features)
1021
+ x = gelu(x)
1022
+ x = self.layer_norm(x)
1023
+
1024
+ # project back to size of vocabulary with bias
1025
+ x = self.decoder(x)
1026
+
1027
+ return x
1028
+
1029
+
1030
+ @auto_docstring(
1031
+ custom_intro="""
1032
+ X-MOD Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1033
+ output) e.g. for GLUE tasks.
1034
+ """
1035
+ )
1036
+ class XmodForSequenceClassification(XmodPreTrainedModel):
1037
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification.__init__ with Roberta->Xmod
1038
+ def __init__(self, config):
1039
+ super().__init__(config)
1040
+ self.num_labels = config.num_labels
1041
+ self.config = config
1042
+
1043
+ self.roberta = XmodModel(config, add_pooling_layer=False)
1044
+ self.classifier = XmodClassificationHead(config)
1045
+
1046
+ # Initialize weights and apply final processing
1047
+ self.post_init()
1048
+
1049
+ @can_return_tuple
1050
+ @auto_docstring
1051
+ def forward(
1052
+ self,
1053
+ input_ids: torch.LongTensor | None = None,
1054
+ lang_ids: torch.LongTensor | None = None,
1055
+ attention_mask: torch.FloatTensor | None = None,
1056
+ token_type_ids: torch.LongTensor | None = None,
1057
+ position_ids: torch.LongTensor | None = None,
1058
+ inputs_embeds: torch.FloatTensor | None = None,
1059
+ labels: torch.LongTensor | None = None,
1060
+ **kwargs: Unpack[TransformersKwargs],
1061
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
1062
+ r"""
1063
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1064
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
1065
+ that corresponds to `self.config.default_language`.
1066
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1067
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1068
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1069
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1070
+ """
1071
+ outputs = self.roberta(
1072
+ input_ids,
1073
+ lang_ids=lang_ids,
1074
+ attention_mask=attention_mask,
1075
+ token_type_ids=token_type_ids,
1076
+ position_ids=position_ids,
1077
+ inputs_embeds=inputs_embeds,
1078
+ return_dict=True,
1079
+ **kwargs,
1080
+ )
1081
+ sequence_output = outputs[0]
1082
+ logits = self.classifier(sequence_output)
1083
+
1084
+ loss = None
1085
+ if labels is not None:
1086
+ if self.config.problem_type is None:
1087
+ if self.num_labels == 1:
1088
+ self.config.problem_type = "regression"
1089
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1090
+ self.config.problem_type = "single_label_classification"
1091
+ else:
1092
+ self.config.problem_type = "multi_label_classification"
1093
+
1094
+ if self.config.problem_type == "regression":
1095
+ loss_fct = MSELoss()
1096
+ if self.num_labels == 1:
1097
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1098
+ else:
1099
+ loss = loss_fct(logits, labels)
1100
+ elif self.config.problem_type == "single_label_classification":
1101
+ loss_fct = CrossEntropyLoss()
1102
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1103
+ elif self.config.problem_type == "multi_label_classification":
1104
+ loss_fct = BCEWithLogitsLoss()
1105
+ loss = loss_fct(logits, labels)
1106
+
1107
+ return SequenceClassifierOutput(
1108
+ loss=loss,
1109
+ logits=logits,
1110
+ hidden_states=outputs.hidden_states,
1111
+ attentions=outputs.attentions,
1112
+ )
1113
+
1114
+
1115
+ @auto_docstring
1116
+ class XmodForMultipleChoice(XmodPreTrainedModel):
1117
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice.__init__ with Roberta->Xmod
1118
+ def __init__(self, config):
1119
+ super().__init__(config)
1120
+
1121
+ self.roberta = XmodModel(config)
1122
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1123
+ self.classifier = nn.Linear(config.hidden_size, 1)
1124
+
1125
+ # Initialize weights and apply final processing
1126
+ self.post_init()
1127
+
1128
+ @can_return_tuple
1129
+ @auto_docstring
1130
+ def forward(
1131
+ self,
1132
+ input_ids: torch.LongTensor | None = None,
1133
+ lang_ids: torch.LongTensor | None = None,
1134
+ token_type_ids: torch.LongTensor | None = None,
1135
+ attention_mask: torch.FloatTensor | None = None,
1136
+ labels: torch.LongTensor | None = None,
1137
+ position_ids: torch.LongTensor | None = None,
1138
+ inputs_embeds: torch.FloatTensor | None = None,
1139
+ **kwargs: Unpack[TransformersKwargs],
1140
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
1141
+ r"""
1142
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
1143
+ Indices of input sequence tokens in the vocabulary.
1144
+
1145
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1146
+ [`PreTrainedTokenizer.__call__`] for details.
1147
+
1148
+ [What are input IDs?](../glossary#input-ids)
1149
+ lang_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1150
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
1151
+ that corresponds to `self.config.default_language`.
1152
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1153
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1154
+ 1]`:
1155
+
1156
+ - 0 corresponds to a *sentence A* token,
1157
+ - 1 corresponds to a *sentence B* token.
1158
+
1159
+ [What are token type IDs?](../glossary#token-type-ids)
1160
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1161
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1162
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1163
+ `input_ids` above)
1164
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1165
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1166
+ config.max_position_embeddings - 1]`.
1167
+
1168
+ [What are position IDs?](../glossary#position-ids)
1169
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
1170
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1171
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1172
+ model's internal embedding lookup matrix.
1173
+ """
1174
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1175
+
1176
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1177
+ flat_lang_ids = lang_ids.repeat(input_ids.size(0) * input_ids.size(1)) if lang_ids is not None else None
1178
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1179
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1180
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1181
+ flat_inputs_embeds = (
1182
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1183
+ if inputs_embeds is not None
1184
+ else None
1185
+ )
1186
+
1187
+ outputs = self.roberta(
1188
+ flat_input_ids,
1189
+ lang_ids=flat_lang_ids,
1190
+ position_ids=flat_position_ids,
1191
+ token_type_ids=flat_token_type_ids,
1192
+ attention_mask=flat_attention_mask,
1193
+ inputs_embeds=flat_inputs_embeds,
1194
+ return_dict=True,
1195
+ **kwargs,
1196
+ )
1197
+ pooled_output = outputs[1]
1198
+
1199
+ pooled_output = self.dropout(pooled_output)
1200
+ logits = self.classifier(pooled_output)
1201
+ reshaped_logits = logits.view(-1, num_choices)
1202
+
1203
+ loss = None
1204
+ if labels is not None:
1205
+ loss_fct = CrossEntropyLoss()
1206
+ loss = loss_fct(reshaped_logits, labels)
1207
+
1208
+ return MultipleChoiceModelOutput(
1209
+ loss=loss,
1210
+ logits=reshaped_logits,
1211
+ hidden_states=outputs.hidden_states,
1212
+ attentions=outputs.attentions,
1213
+ )
1214
+
1215
+
1216
+ @auto_docstring
1217
+ class XmodForTokenClassification(XmodPreTrainedModel):
1218
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification.__init__ with Roberta->Xmod
1219
+ def __init__(self, config):
1220
+ super().__init__(config)
1221
+ self.num_labels = config.num_labels
1222
+
1223
+ self.roberta = XmodModel(config, add_pooling_layer=False)
1224
+ classifier_dropout = (
1225
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1226
+ )
1227
+ self.dropout = nn.Dropout(classifier_dropout)
1228
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1229
+
1230
+ # Initialize weights and apply final processing
1231
+ self.post_init()
1232
+
1233
+ @can_return_tuple
1234
+ @auto_docstring
1235
+ def forward(
1236
+ self,
1237
+ input_ids: torch.LongTensor | None = None,
1238
+ lang_ids: torch.LongTensor | None = None,
1239
+ attention_mask: torch.FloatTensor | None = None,
1240
+ token_type_ids: torch.LongTensor | None = None,
1241
+ position_ids: torch.LongTensor | None = None,
1242
+ inputs_embeds: torch.FloatTensor | None = None,
1243
+ labels: torch.LongTensor | None = None,
1244
+ **kwargs: Unpack[TransformersKwargs],
1245
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
1246
+ r"""
1247
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1248
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
1249
+ that corresponds to `self.config.default_language`.
1250
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1251
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1252
+ """
1253
+ outputs = self.roberta(
1254
+ input_ids,
1255
+ lang_ids=lang_ids,
1256
+ attention_mask=attention_mask,
1257
+ token_type_ids=token_type_ids,
1258
+ position_ids=position_ids,
1259
+ inputs_embeds=inputs_embeds,
1260
+ return_dict=True,
1261
+ **kwargs,
1262
+ )
1263
+
1264
+ sequence_output = outputs[0]
1265
+
1266
+ sequence_output = self.dropout(sequence_output)
1267
+ logits = self.classifier(sequence_output)
1268
+
1269
+ loss = None
1270
+ if labels is not None:
1271
+ loss_fct = CrossEntropyLoss()
1272
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1273
+
1274
+ return TokenClassifierOutput(
1275
+ loss=loss,
1276
+ logits=logits,
1277
+ hidden_states=outputs.hidden_states,
1278
+ attentions=outputs.attentions,
1279
+ )
1280
+
1281
+
1282
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead
1283
+ class XmodClassificationHead(nn.Module):
1284
+ """Head for sentence-level classification tasks."""
1285
+
1286
+ def __init__(self, config):
1287
+ super().__init__()
1288
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1289
+ classifier_dropout = (
1290
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1291
+ )
1292
+ self.dropout = nn.Dropout(classifier_dropout)
1293
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1294
+
1295
+ def forward(self, features, **kwargs):
1296
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
1297
+ x = self.dropout(x)
1298
+ x = self.dense(x)
1299
+ x = torch.tanh(x)
1300
+ x = self.dropout(x)
1301
+ x = self.out_proj(x)
1302
+ return x
1303
+
1304
+
1305
+ @auto_docstring
1306
+ class XmodForQuestionAnswering(XmodPreTrainedModel):
1307
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering.__init__ with Roberta->Xmod
1308
+ def __init__(self, config):
1309
+ super().__init__(config)
1310
+ self.num_labels = config.num_labels
1311
+
1312
+ self.roberta = XmodModel(config, add_pooling_layer=False)
1313
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1314
+
1315
+ # Initialize weights and apply final processing
1316
+ self.post_init()
1317
+
1318
+ @can_return_tuple
1319
+ @auto_docstring
1320
+ def forward(
1321
+ self,
1322
+ input_ids: torch.LongTensor | None = None,
1323
+ lang_ids: torch.LongTensor | None = None,
1324
+ attention_mask: torch.FloatTensor | None = None,
1325
+ token_type_ids: torch.LongTensor | None = None,
1326
+ position_ids: torch.LongTensor | None = None,
1327
+ inputs_embeds: torch.FloatTensor | None = None,
1328
+ start_positions: torch.LongTensor | None = None,
1329
+ end_positions: torch.LongTensor | None = None,
1330
+ **kwargs: Unpack[TransformersKwargs],
1331
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
1332
+ r"""
1333
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1334
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
1335
+ that corresponds to `self.config.default_language`.
1336
+ """
1337
+ outputs = self.roberta(
1338
+ input_ids,
1339
+ lang_ids=lang_ids,
1340
+ attention_mask=attention_mask,
1341
+ token_type_ids=token_type_ids,
1342
+ position_ids=position_ids,
1343
+ inputs_embeds=inputs_embeds,
1344
+ return_dict=True,
1345
+ **kwargs,
1346
+ )
1347
+
1348
+ sequence_output = outputs[0]
1349
+
1350
+ logits = self.qa_outputs(sequence_output)
1351
+ start_logits, end_logits = logits.split(1, dim=-1)
1352
+ start_logits = start_logits.squeeze(-1).contiguous()
1353
+ end_logits = end_logits.squeeze(-1).contiguous()
1354
+
1355
+ total_loss = None
1356
+ if start_positions is not None and end_positions is not None:
1357
+ # If we are on multi-GPU, split add a dimension
1358
+ if len(start_positions.size()) > 1:
1359
+ start_positions = start_positions.squeeze(-1)
1360
+ if len(end_positions.size()) > 1:
1361
+ end_positions = end_positions.squeeze(-1)
1362
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1363
+ ignored_index = start_logits.size(1)
1364
+ start_positions = start_positions.clamp(0, ignored_index)
1365
+ end_positions = end_positions.clamp(0, ignored_index)
1366
+
1367
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1368
+ start_loss = loss_fct(start_logits, start_positions)
1369
+ end_loss = loss_fct(end_logits, end_positions)
1370
+ total_loss = (start_loss + end_loss) / 2
1371
+
1372
+ return QuestionAnsweringModelOutput(
1373
+ loss=total_loss,
1374
+ start_logits=start_logits,
1375
+ end_logits=end_logits,
1376
+ hidden_states=outputs.hidden_states,
1377
+ attentions=outputs.attentions,
1378
+ )
1379
+
1380
+
1381
+ __all__ = [
1382
+ "XmodForCausalLM",
1383
+ "XmodForMaskedLM",
1384
+ "XmodForMultipleChoice",
1385
+ "XmodForQuestionAnswering",
1386
+ "XmodForSequenceClassification",
1387
+ "XmodForTokenClassification",
1388
+ "XmodModel",
1389
+ "XmodPreTrainedModel",
1390
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_086000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30a1b44d5c19fe6c9329a3bd93c18834500bddfd130703b6b3463cff4c069378
3
+ size 897562466
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_288000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9c36dd2652ea6a08957b515b29942e2bf66ddd88a671e39cae220d5b69059c2
3
+ size 897562466
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_473000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c16dbc9d229d25bdc6767ec1dc6e18ebb6d4aef323bbafedea09d943505aa572
3
+ size 897562466