JinghuiLuAstronaut commited on
Commit
f6fae86
·
verified ·
1 Parent(s): 8b31547

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0009000_logistic_normal_t1p45.log +74 -0
  2. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0014000_logistic_normal_t1p45.log +76 -0
  3. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0020000_logistic_normal_t1p45.log +76 -0
  4. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0028000_logistic_normal_t1p45.log +76 -0
  5. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0065000_logistic_normal_t1p45.log +76 -0
  6. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0069000_logistic_normal_t1p45.log +76 -0
  7. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0085000_logistic_normal_t1p45.log +76 -0
  8. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0106000_logistic_normal_t1p45.log +76 -0
  9. LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0113000_logistic_normal_t1p45.log +76 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/__init__.py +29 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/configuration_higgs_audio_v2.py +131 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py +796 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/modular_higgs_audio_v2.py +577 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/processing_higgs_audio_v2.py +366 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/__init__.py +30 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/configuration_pixtral.py +60 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/image_processing_pil_pixtral.py +227 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/image_processing_pixtral.py +238 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/modeling_pixtral.py +485 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/processing_pixtral.py +221 -0
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0009000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-22_22:47:49 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0009000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0009000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0009000.pt
3
+ [ckpt] step=9000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0009000.pt",
24
+ "step": 9000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "concentration_min": 1.0,
30
+ "concentration_max": 1024.0,
31
+ "endpoint_temp": 1.45,
32
+ "support_power": 1.0,
33
+ "semantic_power": 1.0,
34
+ "noise_init": "logistic_normal",
35
+ "noise_sigma": 3.0,
36
+ "noise_dirichlet_concentration": 1.0,
37
+ "sde_resample": "logistic_normal",
38
+ "logistic_normal_sigma_min": 0.18,
39
+ "logistic_normal_sigma_max": 3.0,
40
+ "logistic_normal_tau_min": 0.65,
41
+ "logistic_normal_tau_max": 1.0,
42
+ "final_from": "blend_0.5",
43
+ "n_samples": 256,
44
+ "seed": 20260522
45
+ },
46
+ "raw_genppl": {
47
+ "ppl": 35.86012933009373,
48
+ "nll_per_token": 3.5796260746984734,
49
+ "tokens": 32978,
50
+ "kept_samples": 256,
51
+ "total_samples": 256,
52
+ "empty_rate": 0.0,
53
+ "skipped_samples": 0
54
+ },
55
+ "stripped_genppl": {
56
+ "ppl": 45.17031616105308,
57
+ "nll_per_token": 3.8104401490011734,
58
+ "tokens": 28011,
59
+ "kept_samples": 256,
60
+ "total_samples": 256,
61
+ "empty_rate": 0.0,
62
+ "skipped_samples": 0
63
+ },
64
+ "diversity": {
65
+ "sample_entropy": 3.392318717305,
66
+ "unique_tokens": 1147,
67
+ "token_count": 32768,
68
+ "distinct_1": 0.035003662109375,
69
+ "distinct_2": 0.1977423720472441,
70
+ "top_token_mass": 0.15338134765625
71
+ }
72
+ }
73
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0009000/sde_steps128_samples256_scored.jsonl
74
+ [watch-lognormal-sde] 2026-05-22_22:50:08 done step_0009000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0014000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-22_23:47:30 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0014000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0014000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0014000.pt
3
+ [ckpt] step=14000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0014000.pt",
24
+ "step": 14000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 30.72806126096847,
50
+ "nll_per_token": 3.4251762846945866,
51
+ "tokens": 35808,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 43.579851912451694,
59
+ "nll_per_token": 3.7745949314485547,
60
+ "tokens": 29337,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.6612091153295747,
68
+ "unique_tokens": 1370,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.04180908203125,
71
+ "distinct_2": 0.2346825787401575,
72
+ "top_token_mass": 0.10333251953125
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0014000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-22_23:48:58 done step_0014000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0020000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_00:25:39 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0020000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0020000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0020000.pt
3
+ [ckpt] step=20000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0020000.pt",
24
+ "step": 20000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 38.55350467469302,
50
+ "nll_per_token": 3.6520470083204515,
51
+ "tokens": 34852,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 49.13615827041425,
59
+ "nll_per_token": 3.894595184761625,
60
+ "tokens": 29785,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.5280256539838124,
68
+ "unique_tokens": 2229,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.068023681640625,
71
+ "distinct_2": 0.32495693897637795,
72
+ "top_token_mass": 0.11724853515625
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0020000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_00:27:06 done step_0020000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0028000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_01:10:22 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0028000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0028000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0028000.pt
3
+ [ckpt] step=28000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0028000.pt",
24
+ "step": 28000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 33.04265292746846,
50
+ "nll_per_token": 3.4977992398442583,
51
+ "tokens": 35351,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 44.64582103928473,
59
+ "nll_per_token": 3.7987607091973175,
60
+ "tokens": 29424,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.506037820762122,
68
+ "unique_tokens": 1983,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.060516357421875,
71
+ "distinct_2": 0.2909079724409449,
72
+ "top_token_mass": 0.14129638671875
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0028000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_01:11:49 done step_0028000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0065000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_04:37:00 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0065000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0065000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0065000.pt
3
+ [ckpt] step=65000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0065000.pt",
24
+ "step": 65000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 32.89843000506491,
50
+ "nll_per_token": 3.4934249364218877,
51
+ "tokens": 34812,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 46.27597978946276,
59
+ "nll_per_token": 3.8346230314274763,
60
+ "tokens": 28701,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.5270455524010886,
68
+ "unique_tokens": 1962,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.05987548828125,
71
+ "distinct_2": 0.30447219488188976,
72
+ "top_token_mass": 0.14471435546875
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0065000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_04:38:28 done step_0065000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0069000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_04:58:38 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0069000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0069000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0069000.pt
3
+ [ckpt] step=69000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0069000.pt",
24
+ "step": 69000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 36.62032651736329,
50
+ "nll_per_token": 3.6006034555737165,
51
+ "tokens": 26117,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 47.58958758883215,
59
+ "nll_per_token": 3.8626139891747333,
60
+ "tokens": 21746,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 2.7032731348590184,
68
+ "unique_tokens": 1394,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.04254150390625,
71
+ "distinct_2": 0.21342888779527558,
72
+ "top_token_mass": 0.370330810546875
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0069000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_05:00:06 done step_0069000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0085000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_06:28:15 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0085000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0085000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0085000.pt
3
+ [ckpt] step=85000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0085000.pt",
24
+ "step": 85000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 31.782665476852156,
50
+ "nll_per_token": 3.458921030368417,
51
+ "tokens": 35678,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 39.792225275658964,
59
+ "nll_per_token": 3.6836715483754157,
60
+ "tokens": 30377,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.656928952001589,
68
+ "unique_tokens": 1842,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.05621337890625,
71
+ "distinct_2": 0.2951525590551181,
72
+ "top_token_mass": 0.0826416015625
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0085000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_06:29:42 done step_0085000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0106000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_08:25:33 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0106000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0106000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0106000.pt
3
+ [ckpt] step=106000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0106000.pt",
24
+ "step": 106000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 29.636316089088528,
50
+ "nll_per_token": 3.3890005042111415,
51
+ "tokens": 37334,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 38.801872919075215,
59
+ "nll_per_token": 3.658468516574401,
60
+ "tokens": 31352,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.6470654090070553,
68
+ "unique_tokens": 2439,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.074432373046875,
71
+ "distinct_2": 0.3699557086614173,
72
+ "top_token_mass": 0.08697509765625
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0106000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_08:27:02 done step_0106000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0113000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_09:04:29 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0113000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0113000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0113000.pt
3
+ [ckpt] step=113000
4
+ [sde] generated 16/256
5
+ [sde] generated 32/256
6
+ [sde] generated 48/256
7
+ [sde] generated 64/256
8
+ [sde] generated 80/256
9
+ [sde] generated 96/256
10
+ [sde] generated 112/256
11
+ [sde] generated 128/256
12
+ [sde] generated 144/256
13
+ [sde] generated 160/256
14
+ [sde] generated 176/256
15
+ [sde] generated 192/256
16
+ [sde] generated 208/256
17
+ [sde] generated 224/256
18
+ [sde] generated 240/256
19
+ [sde] generated 256/256
20
+ [score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
21
+ [summary] {
22
+ "type": "summary",
23
+ "checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0113000.pt",
24
+ "step": 113000,
25
+ "decode": {
26
+ "decode_rule": "logistic_normal_resample_sde",
27
+ "steps": 128,
28
+ "model_t_mode": "const0.5",
29
+ "mean_mode": "anchor_semantic",
30
+ "endpoint_floor": 0.0,
31
+ "concentration_min": 1.0,
32
+ "concentration_max": 1024.0,
33
+ "endpoint_temp": 1.45,
34
+ "support_power": 1.0,
35
+ "semantic_power": 1.0,
36
+ "noise_init": "logistic_normal",
37
+ "noise_sigma": 3.0,
38
+ "noise_dirichlet_concentration": 1.0,
39
+ "sde_resample": "logistic_normal",
40
+ "logistic_normal_sigma_min": 0.18,
41
+ "logistic_normal_sigma_max": 3.0,
42
+ "logistic_normal_tau_min": 0.65,
43
+ "logistic_normal_tau_max": 1.0,
44
+ "final_from": "blend_0.5",
45
+ "n_samples": 256,
46
+ "seed": 20260522
47
+ },
48
+ "raw_genppl": {
49
+ "ppl": 31.083597717912934,
50
+ "nll_per_token": 3.4366802754897634,
51
+ "tokens": 35974,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 41.42877739822764,
59
+ "nll_per_token": 3.7239757455942044,
60
+ "tokens": 29996,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.541817922504287,
68
+ "unique_tokens": 2168,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.066162109375,
71
+ "distinct_2": 0.33366141732283466,
72
+ "top_token_mass": 0.116668701171875
73
+ }
74
+ }
75
+ [done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0113000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_09:05:57 done step_0113000
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Boson AI and 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_higgs_audio_v2 import *
22
+ from .generation_higgs_audio_v2 import *
23
+ from .modeling_higgs_audio_v2 import *
24
+ from .processing_higgs_audio_v2 import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/configuration_higgs_audio_v2.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/higgs_audio_v2/modular_higgs_audio_v2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_higgs_audio_v2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 the HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from huggingface_hub.dataclasses import strict
23
+
24
+ from ...configuration_utils import PreTrainedConfig
25
+ from ...modeling_rope_utils import RopeParameters
26
+ from ...utils import auto_docstring
27
+ from ...utils.type_validators import interval
28
+
29
+
30
+ @auto_docstring(checkpoint="bosonai/higgs-audio-v2-generation-3B-base")
31
+ @strict
32
+ class HiggsAudioV2Config(PreTrainedConfig):
33
+ r"""
34
+ audio_bos_token_id (`int`, *optional*, defaults to 128013):
35
+ The token ID for the beginning-of-sequence token for audio output.
36
+ audio_delay_token_id (`int`, *optional*, defaults to 128014):
37
+ The token ID used for audio delay pattern in multi-codebook generation.
38
+ audio_stream_bos_id (`int`, *optional*, defaults to 1024):
39
+ The ID for the beginning-of-stream token in audio sequences.
40
+ audio_stream_eos_id (`int`, *optional*, defaults to 1025):
41
+ The ID for the end-of-stream token in audio sequences.
42
+
43
+ Example:
44
+
45
+ ```python
46
+ >>> from transformers import HiggsAudioV2Model, HiggsAudioV2Config
47
+
48
+ >>> # Initializing a HiggsAudioV2 style configuration
49
+ >>> configuration = HiggsAudioV2Config()
50
+
51
+ >>> # Initializing a model from the configuration
52
+ >>> model = HiggsAudioV2Model(configuration)
53
+
54
+ >>> # Accessing the model configuration
55
+ >>> configuration = model.config
56
+ ```"""
57
+
58
+ model_type = "higgs_audio_v2"
59
+ keys_to_ignore_at_inference = ["past_key_values"]
60
+ # Default tensor parallel plan for base model `HiggsAudioV2Model`
61
+ base_model_tp_plan = {
62
+ "layers.*.self_attn.q_proj": "colwise",
63
+ "layers.*.self_attn.k_proj": "colwise",
64
+ "layers.*.self_attn.v_proj": "colwise",
65
+ "layers.*.self_attn.o_proj": "rowwise",
66
+ "layers.*.mlp.gate_proj": "colwise",
67
+ "layers.*.mlp.up_proj": "colwise",
68
+ "layers.*.mlp.down_proj": "rowwise",
69
+ }
70
+ base_model_pp_plan = {
71
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
72
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
73
+ "norm": (["hidden_states"], ["hidden_states"]),
74
+ }
75
+
76
+ vocab_size: int = 128256
77
+ hidden_size: int = 3072
78
+ intermediate_size: int = 8192
79
+ num_hidden_layers: int = 28
80
+ num_attention_heads: int = 24
81
+ num_key_value_heads: int = 8
82
+ hidden_act: str = "silu"
83
+ max_position_embeddings: int = 2048
84
+ initializer_range: float = interval(min=0.0, max=1.0)(default=0.02)
85
+ rms_norm_eps: float = 1e-5
86
+ use_cache: bool = True
87
+ pad_token_id: int | None = 128001
88
+ bos_token_id: int | None = 1
89
+ eos_token_id: int | list[int] | None = 128009
90
+ pretraining_tp: int | None = 1
91
+ tie_word_embeddings: bool = False
92
+ rope_parameters: RopeParameters | dict | None = None
93
+ attention_bias: bool = False
94
+ attention_dropout: int | float | None = 0.0
95
+ mlp_bias: bool = False
96
+ head_dim: int | None = 128
97
+ num_codebooks: int = 8
98
+ codebook_size: int = 1024
99
+ audio_token_id: int = 128016
100
+ audio_bos_token_id: int = 128013
101
+ audio_delay_token_id: int = 128014
102
+ audio_stream_bos_id: int = 1024
103
+ audio_stream_eos_id: int = 1025
104
+
105
+ def __post_init__(self, **kwargs):
106
+ if self.rope_parameters is None:
107
+ self.rope_parameters = {
108
+ "factor": 32.0,
109
+ "rope_theta": 500000.0,
110
+ "high_freq_factor": 0.5,
111
+ "low_freq_factor": 0.125,
112
+ "original_max_position_embeddings": 1024,
113
+ "rope_type": "llama3",
114
+ }
115
+ if self.head_dim is None:
116
+ self.head_dim = self.hidden_size // self.num_attention_heads
117
+ if self.num_key_value_heads is None:
118
+ self.num_key_value_heads = self.num_attention_heads
119
+
120
+ super().__post_init__(**kwargs)
121
+
122
+ def validate_architecture(self):
123
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
124
+ if self.hidden_size % self.num_attention_heads != 0:
125
+ raise ValueError(
126
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
127
+ f"heads ({self.num_attention_heads})."
128
+ )
129
+
130
+
131
+ __all__ = ["HiggsAudioV2Config"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/higgs_audio_v2/modular_higgs_audio_v2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_higgs_audio_v2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 the HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from collections.abc import Callable
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+
28
+ from ... import initialization as init
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache, DynamicCache
31
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
32
+ from ...masking_utils import create_causal_mask
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
35
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from ...processing_utils import Unpack
38
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
39
+ from ...utils.generic import maybe_autocast
40
+ from ...utils.output_capturing import capture_outputs
41
+ from .configuration_higgs_audio_v2 import HiggsAudioV2Config
42
+ from .generation_higgs_audio_v2 import HiggsAudioV2GenerationMixin
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ class HiggsAudioV2MLP(nn.Module):
49
+ def __init__(self, config):
50
+ super().__init__()
51
+ self.config = config
52
+ self.hidden_size = config.hidden_size
53
+ self.intermediate_size = config.intermediate_size
54
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
55
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
56
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
57
+ self.act_fn = ACT2FN[config.hidden_act]
58
+
59
+ def forward(self, x):
60
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
61
+ return down_proj
62
+
63
+
64
+ @use_kernel_forward_from_hub("RMSNorm")
65
+ class HiggsAudioV2RMSNorm(nn.Module):
66
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
67
+ """
68
+ HiggsAudioV2RMSNorm is equivalent to T5LayerNorm
69
+ """
70
+ super().__init__()
71
+ self.weight = nn.Parameter(torch.ones(hidden_size))
72
+ self.variance_epsilon = eps
73
+
74
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
75
+ input_dtype = hidden_states.dtype
76
+ hidden_states = hidden_states.to(torch.float32)
77
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
78
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
79
+ return self.weight * hidden_states.to(input_dtype)
80
+
81
+ def extra_repr(self):
82
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
83
+
84
+
85
+ def rotate_half(x):
86
+ """Rotates half the hidden dims of the input."""
87
+ x1 = x[..., : x.shape[-1] // 2]
88
+ x2 = x[..., x.shape[-1] // 2 :]
89
+ return torch.cat((-x2, x1), dim=-1)
90
+
91
+
92
+ @use_kernel_func_from_hub("rotary_pos_emb")
93
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
94
+ """Applies Rotary Position Embedding to the query and key tensors.
95
+
96
+ Args:
97
+ q (`torch.Tensor`): The query tensor.
98
+ k (`torch.Tensor`): The key tensor.
99
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
100
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
101
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
102
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
103
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
104
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
105
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
106
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
107
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
108
+ Returns:
109
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
110
+ """
111
+ cos = cos.unsqueeze(unsqueeze_dim)
112
+ sin = sin.unsqueeze(unsqueeze_dim)
113
+ q_embed = (q * cos) + (rotate_half(q) * sin)
114
+ k_embed = (k * cos) + (rotate_half(k) * sin)
115
+ return q_embed, k_embed
116
+
117
+
118
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
119
+ """
120
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
121
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
122
+ """
123
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
124
+ if n_rep == 1:
125
+ return hidden_states
126
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
127
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
128
+
129
+
130
+ def eager_attention_forward(
131
+ module: nn.Module,
132
+ query: torch.Tensor,
133
+ key: torch.Tensor,
134
+ value: torch.Tensor,
135
+ attention_mask: torch.Tensor | None,
136
+ scaling: float,
137
+ dropout: float = 0.0,
138
+ **kwargs: Unpack[TransformersKwargs],
139
+ ):
140
+ key_states = repeat_kv(key, module.num_key_value_groups)
141
+ value_states = repeat_kv(value, module.num_key_value_groups)
142
+
143
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
144
+ if attention_mask is not None:
145
+ attn_weights = attn_weights + attention_mask
146
+
147
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
148
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
149
+ attn_output = torch.matmul(attn_weights, value_states)
150
+ attn_output = attn_output.transpose(1, 2).contiguous()
151
+
152
+ return attn_output, attn_weights
153
+
154
+
155
+ @use_kernelized_func(apply_rotary_pos_emb)
156
+ class HiggsAudioV2Attention(nn.Module):
157
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
158
+
159
+ def __init__(self, config: HiggsAudioV2Config, layer_idx: int):
160
+ super().__init__()
161
+ self.config = config
162
+ self.layer_idx = layer_idx
163
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
164
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
165
+ self.scaling = self.head_dim**-0.5
166
+ self.attention_dropout = config.attention_dropout
167
+ self.is_causal = True
168
+
169
+ self.q_proj = nn.Linear(
170
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
171
+ )
172
+ self.k_proj = nn.Linear(
173
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
174
+ )
175
+ self.v_proj = nn.Linear(
176
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
177
+ )
178
+ self.o_proj = nn.Linear(
179
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
180
+ )
181
+
182
+ def forward(
183
+ self,
184
+ hidden_states: torch.Tensor,
185
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
186
+ attention_mask: torch.Tensor | None = None,
187
+ past_key_values: Cache | None = None,
188
+ **kwargs: Unpack[TransformersKwargs],
189
+ ) -> tuple[torch.Tensor, torch.Tensor]:
190
+ input_shape = hidden_states.shape[:-1]
191
+ hidden_shape = (*input_shape, -1, self.head_dim)
192
+
193
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
194
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
195
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
196
+
197
+ cos, sin = position_embeddings
198
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
199
+
200
+ if past_key_values is not None:
201
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
202
+
203
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
204
+ self.config._attn_implementation, eager_attention_forward
205
+ )
206
+
207
+ attn_output, attn_weights = attention_interface(
208
+ self,
209
+ query_states,
210
+ key_states,
211
+ value_states,
212
+ attention_mask,
213
+ dropout=0.0 if not self.training else self.attention_dropout,
214
+ scaling=self.scaling,
215
+ **kwargs,
216
+ )
217
+
218
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
219
+ attn_output = self.o_proj(attn_output)
220
+ return attn_output, attn_weights
221
+
222
+
223
+ class HiggsAudioV2DecoderLayer(GradientCheckpointingLayer):
224
+ def __init__(self, config: HiggsAudioV2Config, layer_idx: int):
225
+ super().__init__()
226
+ self.hidden_size = config.hidden_size
227
+
228
+ self.self_attn = HiggsAudioV2Attention(config=config, layer_idx=layer_idx)
229
+
230
+ self.mlp = HiggsAudioV2MLP(config)
231
+ self.input_layernorm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
232
+ self.post_attention_layernorm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
233
+
234
+ self.audio_mlp = HiggsAudioV2MLP(config)
235
+ self.audio_input_layernorm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
236
+ self.audio_post_attention_layernorm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
237
+
238
+ def forward(
239
+ self,
240
+ hidden_states: torch.Tensor,
241
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
242
+ attention_mask: torch.Tensor | None = None,
243
+ audio_token_mask: torch.BoolTensor | None = None,
244
+ position_ids: torch.LongTensor | None = None,
245
+ past_key_values: Cache | None = None,
246
+ use_cache: bool | None = False,
247
+ **kwargs: Unpack[TransformersKwargs],
248
+ ) -> torch.Tensor:
249
+ residual = hidden_states
250
+
251
+ if audio_token_mask is None:
252
+ hidden_states = self.audio_input_layernorm(hidden_states)
253
+ else:
254
+ audio_token_mask = audio_token_mask.to(hidden_states.device)
255
+ hidden_states = hidden_states.masked_scatter(
256
+ audio_token_mask.unsqueeze(-1),
257
+ self.audio_input_layernorm(hidden_states[audio_token_mask]).to(hidden_states.device),
258
+ )
259
+ hidden_states = hidden_states.masked_scatter(
260
+ ~audio_token_mask.unsqueeze(-1),
261
+ self.input_layernorm(hidden_states[~audio_token_mask]).to(hidden_states.device),
262
+ )
263
+
264
+ # Self Attention
265
+ hidden_states, _ = self.self_attn(
266
+ hidden_states=hidden_states,
267
+ attention_mask=attention_mask,
268
+ position_ids=position_ids,
269
+ past_key_values=past_key_values,
270
+ use_cache=use_cache,
271
+ position_embeddings=position_embeddings,
272
+ **kwargs,
273
+ )
274
+ hidden_states = residual + hidden_states
275
+
276
+ if audio_token_mask is None:
277
+ audio_hidden_states = self.audio_post_attention_layernorm(hidden_states)
278
+ audio_hidden_states = self.audio_mlp(audio_hidden_states)
279
+ hidden_states = hidden_states + audio_hidden_states.to(hidden_states.device)
280
+ else:
281
+ text_hidden_states = self.post_attention_layernorm(hidden_states[~audio_token_mask])
282
+ audio_hidden_states = self.audio_post_attention_layernorm(hidden_states[audio_token_mask])
283
+
284
+ text_hidden_states = self.mlp(text_hidden_states)
285
+ hidden_states[~audio_token_mask] += text_hidden_states.to(hidden_states.device)
286
+
287
+ audio_hidden_states = self.audio_mlp(audio_hidden_states)
288
+ hidden_states[audio_token_mask] += audio_hidden_states.to(hidden_states.device)
289
+
290
+ return hidden_states
291
+
292
+
293
+ class HiggsAudioV2Embeddings(nn.Module):
294
+ def __init__(self, config):
295
+ super().__init__()
296
+ self.embed_audio_tokens = nn.Embedding((config.num_codebooks * config.codebook_size), config.hidden_size)
297
+ self.register_buffer(
298
+ "audio_tokens_offsets", torch.arange(config.num_codebooks) * config.codebook_size, persistent=False
299
+ )
300
+
301
+ def forward(self, input_ids):
302
+ inputs_embeds = self.embed_audio_tokens(input_ids + self.audio_tokens_offsets)
303
+ inputs_embeds = inputs_embeds.sum(dim=-2)
304
+ return inputs_embeds
305
+
306
+
307
+ @auto_docstring
308
+ class HiggsAudioV2PreTrainedModel(PreTrainedModel):
309
+ config: HiggsAudioV2Config
310
+ base_model_prefix = "model"
311
+ supports_gradient_checkpointing = True
312
+ _no_split_modules = ["HiggsAudioV2DecoderLayer"]
313
+ _skip_keys_device_placement = ["past_key_values"]
314
+ _supports_flash_attn = True
315
+ _supports_sdpa = True
316
+ _supports_flex_attn = True
317
+
318
+ _can_compile_fullgraph = True
319
+ _supports_attention_backend = True
320
+ _can_record_outputs = {
321
+ "hidden_states": HiggsAudioV2DecoderLayer,
322
+ "attentions": HiggsAudioV2Attention,
323
+ }
324
+
325
+ @torch.no_grad()
326
+ def _init_weights(self, module):
327
+ super()._init_weights(module)
328
+
329
+ if isinstance(module, HiggsAudioV2Embeddings):
330
+ init.copy_(
331
+ module.audio_tokens_offsets, torch.arange(self.config.num_codebooks) * self.config.codebook_size
332
+ )
333
+
334
+
335
+ class HiggsAudioV2RotaryEmbedding(nn.Module):
336
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
337
+
338
+ def __init__(self, config: HiggsAudioV2Config, device=None):
339
+ super().__init__()
340
+ self.max_seq_len_cached = config.max_position_embeddings
341
+ self.original_max_seq_len = config.max_position_embeddings
342
+
343
+ self.config = config
344
+
345
+ self.rope_type = self.config.rope_parameters["rope_type"]
346
+ rope_init_fn: Callable = self.compute_default_rope_parameters
347
+ if self.rope_type != "default":
348
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
349
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
350
+
351
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
352
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
353
+
354
+ @staticmethod
355
+ def compute_default_rope_parameters(
356
+ config: HiggsAudioV2Config | None = None,
357
+ device: Optional["torch.device"] = None,
358
+ seq_len: int | None = None,
359
+ ) -> tuple["torch.Tensor", float]:
360
+ """
361
+ Computes the inverse frequencies according to the original RoPE implementation
362
+ Args:
363
+ config ([`~transformers.PreTrainedConfig`]):
364
+ The model configuration.
365
+ device (`torch.device`):
366
+ The device to use for initialization of the inverse frequencies.
367
+ seq_len (`int`, *optional*):
368
+ The current sequence length. Unused for this type of RoPE.
369
+ Returns:
370
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
371
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
372
+ """
373
+ base = config.rope_parameters["rope_theta"]
374
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
375
+
376
+ attention_factor = 1.0 # Unused in this type of RoPE
377
+
378
+ # Compute the inverse frequencies
379
+ inv_freq = 1.0 / (
380
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
381
+ )
382
+ return inv_freq, attention_factor
383
+
384
+ @torch.no_grad()
385
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
386
+ def forward(self, x, position_ids):
387
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
388
+ position_ids_expanded = position_ids[:, None, :].float()
389
+
390
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
391
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
392
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
393
+ emb = torch.cat((freqs, freqs), dim=-1)
394
+ cos = emb.cos() * self.attention_scaling
395
+ sin = emb.sin() * self.attention_scaling
396
+
397
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
398
+
399
+
400
+ @auto_docstring
401
+ class HiggsAudioV2Model(HiggsAudioV2PreTrainedModel):
402
+ def __init__(self, config: HiggsAudioV2Config):
403
+ super().__init__(config)
404
+ self.padding_idx = config.pad_token_id
405
+ self.vocab_size = config.vocab_size
406
+
407
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
408
+ self.layers = nn.ModuleList(
409
+ [HiggsAudioV2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
410
+ )
411
+ self.norm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
412
+ self.rotary_emb = HiggsAudioV2RotaryEmbedding(config=config)
413
+ self.gradient_checkpointing = False
414
+ self.embed_audio_tokens = HiggsAudioV2Embeddings(config)
415
+
416
+ # Initialize weights and apply final processing
417
+ self.post_init()
418
+
419
+ @capture_outputs
420
+ @auto_docstring
421
+ def forward(
422
+ self,
423
+ input_ids: torch.LongTensor | None = None,
424
+ audio_input_ids: torch.LongTensor | None = None,
425
+ attention_mask: torch.LongTensor | None = None,
426
+ audio_input_ids_mask: torch.BoolTensor | None = None,
427
+ position_ids: torch.LongTensor | None = None,
428
+ past_key_values: Cache | None = None,
429
+ inputs_embeds: torch.FloatTensor | None = None,
430
+ use_cache: bool | None = None,
431
+ **kwargs: Unpack[TransformersKwargs],
432
+ ) -> BaseModelOutputWithPast:
433
+ r"""
434
+ audio_input_ids (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*):
435
+ Indices of audio codebook tokens.
436
+
437
+ Indices can be obtained using [`HiggsAudioV2TokenizerModel.encode`].
438
+ audio_input_ids_mask (`torch.BoolTensor` of shape `(batch_size, num_audio_frames)`, *optional*):
439
+ Indicates which audio frames in `audio_input_ids` are valid.
440
+
441
+ Returns:
442
+ [`~models.modeling_outputs.BaseModelOutputWithPast`]:
443
+ Usual decoder outputs with the placeholder positions already substituted by their corresponding
444
+ audio embeddings.
445
+
446
+ Example:
447
+
448
+ ```python
449
+ >>> from transformers import AutoProcessor, HiggsAudioV2Model
450
+ >>> import torch
451
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
452
+ >>> processor = AutoProcessor.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
453
+ >>> model = HiggsAudioV2Model.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
454
+ >>> conversation = [
455
+ ... {
456
+ ... "role": "system",
457
+ ... "content": [
458
+ ... {
459
+ ... "type": "text",
460
+ ... "text": "Generate audio following instruction."
461
+ ... }
462
+ ... ]
463
+ ... },
464
+ ... {
465
+ ... "role": "scene",
466
+ ... "content": [
467
+ ... {
468
+ ... "type": "text",
469
+ ... "text": "Audio is recorded from a quiet room."
470
+ ... }
471
+ ... ]
472
+ ... },
473
+ ... {
474
+ ... "role": "user",
475
+ ... "content": [
476
+ ... {
477
+ ... "type": "text",
478
+ ... "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
479
+ ... }
480
+ ... ]
481
+ ... },
482
+ ... {
483
+ ... "role": "assistant",
484
+ ... "content": [
485
+ ... {
486
+ ... "type": "audio",
487
+ ... "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
488
+ ... }
489
+ ... ]
490
+ ... },
491
+ ... {
492
+ ... "role": "user",
493
+ ... "content": [
494
+ ... {
495
+ ... "type": "text",
496
+ ... "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
497
+ ... }
498
+ ... ]
499
+ ... }
500
+ ... ]
501
+ >>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
502
+ >>> inputs = inputs.to(model.device)
503
+ >>> outputs = model(**inputs)
504
+ ```
505
+ """
506
+ if (input_ids is None) and (inputs_embeds is None) and (audio_input_ids is None):
507
+ raise ValueError("You must specify at least one of input_ids, inputs_embeds, or audio_input_ids")
508
+
509
+ if (input_ids is not None) and (inputs_embeds is not None):
510
+ raise ValueError("Only one of input_ids or inputs_embeds can be provided")
511
+
512
+ audio_token_mask = self.get_placeholder_mask(input_ids, inputs_embeds, audio_input_ids_mask)
513
+
514
+ if input_ids is not None:
515
+ inputs_embeds = self.embed_tokens(input_ids)
516
+
517
+ if audio_input_ids is not None:
518
+ audio_embeds = self.embed_audio_tokens(audio_input_ids)
519
+
520
+ if inputs_embeds is not None and audio_input_ids is not None:
521
+ audio_embeds = (
522
+ audio_embeds[audio_input_ids_mask.to(audio_embeds.device)]
523
+ if audio_input_ids_mask is not None
524
+ else audio_embeds
525
+ )
526
+ inputs_embeds = inputs_embeds.masked_scatter(
527
+ audio_token_mask[..., None].expand_as(inputs_embeds), audio_embeds.to(inputs_embeds.device)
528
+ )
529
+ elif audio_input_ids is not None:
530
+ inputs_embeds = audio_embeds
531
+
532
+ if use_cache and past_key_values is None:
533
+ past_key_values = DynamicCache(config=self.config)
534
+
535
+ if position_ids is None:
536
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
537
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
538
+ position_ids = position_ids.unsqueeze(0)
539
+
540
+ causal_mask = create_causal_mask(
541
+ config=self.config,
542
+ inputs_embeds=inputs_embeds,
543
+ attention_mask=attention_mask,
544
+ past_key_values=past_key_values,
545
+ position_ids=position_ids,
546
+ )
547
+
548
+ hidden_states = inputs_embeds
549
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
550
+
551
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
552
+ hidden_states = decoder_layer(
553
+ hidden_states,
554
+ attention_mask=causal_mask,
555
+ audio_token_mask=audio_token_mask,
556
+ position_ids=position_ids,
557
+ past_key_values=past_key_values,
558
+ position_embeddings=position_embeddings,
559
+ **kwargs,
560
+ )
561
+
562
+ hidden_states = self.norm(hidden_states)
563
+ return BaseModelOutputWithPast(
564
+ last_hidden_state=hidden_states,
565
+ past_key_values=past_key_values,
566
+ )
567
+
568
+ def get_placeholder_mask(
569
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, audio_input_ids_mask: torch.LongTensor
570
+ ):
571
+ """
572
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
573
+ equal to the length of audio_input_ids. If the lengths are different, an error is raised.
574
+
575
+ If input_ids and inputs_embeds are None, we return None.
576
+ Indeed this means we cannot determine the placeholder mask, the model is to be used in a audio-only mode, hence we return None.
577
+ """
578
+ if input_ids is None and inputs_embeds is None:
579
+ return None
580
+
581
+ elif input_ids is None:
582
+ special_audio_mask = inputs_embeds == self.embed_tokens(
583
+ torch.tensor(self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
584
+ )
585
+ special_audio_mask = special_audio_mask.all(-1)
586
+
587
+ else:
588
+ special_audio_mask = (input_ids == self.config.audio_token_id) | (
589
+ input_ids == self.config.audio_delay_token_id
590
+ )
591
+
592
+ return special_audio_mask
593
+
594
+
595
+ @auto_docstring(
596
+ custom_intro="""
597
+ The Higgs Audio model, a llama-like auto-regressive transformer model with dual-FFN.
598
+ """
599
+ )
600
+ class HiggsAudioV2ForConditionalGeneration(HiggsAudioV2PreTrainedModel, HiggsAudioV2GenerationMixin):
601
+ base_model_prefix = "model"
602
+ _keys_to_ignore_on_load_unexpected = ["text_lm_head.weight"]
603
+
604
+ def __init__(self, config: HiggsAudioV2Config, use_text_head: bool = False):
605
+ r"""
606
+ use_text_head (`bool`, *optional*, defaults to False):
607
+ Whether to use a text language model head. Such head is not required for generation,
608
+ but can be used to compute the text loss when training.
609
+ """
610
+ super().__init__(config)
611
+ self.model = HiggsAudioV2Model(config)
612
+ self.audio_lm_head = nn.Linear(config.hidden_size, config.num_codebooks * config.codebook_size, bias=False)
613
+ self.text_lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) if use_text_head else None
614
+
615
+ self.post_init()
616
+
617
+ def prepare_inputs_for_generation(
618
+ self,
619
+ input_ids: torch.LongTensor,
620
+ audio_input_ids: torch.LongTensor | None = None,
621
+ audio_input_ids_mask: torch.LongTensor | None = None,
622
+ **kwargs,
623
+ ):
624
+ model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs)
625
+
626
+ if audio_input_ids is not None and model_inputs.get("past_key_values") is not None:
627
+ current_cache_length = model_inputs.get("past_key_values").get_seq_length()
628
+ audio_token_mask = (input_ids == self.config.audio_token_id) | (
629
+ input_ids == self.config.audio_delay_token_id
630
+ )
631
+ in_cache_num_audio_input_ids = audio_token_mask[:, :current_cache_length].sum(dim=-1)
632
+
633
+ # already cached audio_input_ids should be masked
634
+ # this surmise that audio_input_ids are right padded!
635
+ valid_audio_input_ids = audio_input_ids_mask.cumsum(dim=-1) > in_cache_num_audio_input_ids[:, None]
636
+ audio_input_ids_mask = audio_input_ids_mask & valid_audio_input_ids
637
+
638
+ if audio_input_ids_mask is not None and (~audio_input_ids_mask[:, :-1]).all():
639
+ # in decoding mode, we only pass audio_input_ids
640
+ audio_input_ids = audio_input_ids[:, -1:, :].clone(memory_format=torch.contiguous_format)
641
+ model_inputs.pop("input_ids", None)
642
+ audio_input_ids_mask = None
643
+
644
+ model_inputs["audio_input_ids"] = audio_input_ids
645
+ model_inputs["audio_input_ids_mask"] = audio_input_ids_mask
646
+
647
+ return model_inputs
648
+
649
+ @auto_docstring
650
+ @can_return_tuple
651
+ def forward(
652
+ self,
653
+ input_ids: torch.LongTensor | None = None,
654
+ attention_mask: torch.BoolTensor | None = None,
655
+ audio_input_ids: torch.LongTensor | None = None,
656
+ audio_input_ids_mask: torch.LongTensor | None = None,
657
+ position_ids: torch.LongTensor | None = None,
658
+ past_key_values: Cache | None = None,
659
+ inputs_embeds: torch.FloatTensor | None = None,
660
+ labels: torch.LongTensor | None = None,
661
+ audio_labels: torch.LongTensor | None = None,
662
+ use_cache: bool | None = None,
663
+ logits_to_keep: int | torch.Tensor = 0,
664
+ **kwargs: Unpack[TransformersKwargs],
665
+ ):
666
+ r"""
667
+ audio_input_ids (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*):
668
+ Indices of audio codebook tokens.
669
+
670
+ Indices can be obtained using [`HiggsAudioV2TokenizerModel.encode`].
671
+ audio_input_ids_mask (`torch.BoolTensor` of shape `(batch_size, num_audio_frames)`, *optional*):
672
+ Indicates which audio frames in `audio_input_ids` are valid.
673
+ audio_labels (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*):
674
+ Labels for the audio codebook tokens for computing the masked language modeling loss. Indices should either be in `[0, ...,
675
+ config.codebook_size]. Token with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.codebook_size]`.
676
+ Can be obtained using `output_labels=True` when calling [`HiggsAudioV2Processor`].
677
+
678
+ Returns:
679
+ [`~models.modeling_outputs.CausalLMOutputWithPast`]:
680
+ A [`~models.modeling_outputs.CausalLMOutputWithPast`] containing the logits, loss (if labels are provided),
681
+ and other outputs from the model.
682
+
683
+ Example:
684
+
685
+ ```python
686
+ >>> from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
687
+ >>> model_id = "eustlb/higgs-audio-v2-generation-3B-base"
688
+ >>> processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
689
+ >>> model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
690
+ >>> conversation = [
691
+ ... {
692
+ ... "role": "system",
693
+ ... "content": [
694
+ ... {
695
+ ... "type": "text",
696
+ ... "text": "Generate audio following instruction."
697
+ ... }
698
+ ... ]
699
+ ... },
700
+ ... {
701
+ ... "role": "scene",
702
+ ... "content": [
703
+ ... {
704
+ ... "type": "text",
705
+ ... "text": "Audio is recorded from a quiet room."
706
+ ... }
707
+ ... ]
708
+ ... },
709
+ ... {
710
+ ... "role": "user",
711
+ ... "content": [
712
+ ... {
713
+ ... "type": "text",
714
+ ... "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
715
+ ... }
716
+ ... ]
717
+ ... },
718
+ ... {
719
+ ... "role": "assistant",
720
+ ... "content": [
721
+ ... {
722
+ ... "type": "audio",
723
+ ... "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
724
+ ... }
725
+ ... ]
726
+ ... },
727
+ ... {
728
+ ... "role": "user",
729
+ ... "content": [
730
+ ... {
731
+ ... "type": "text",
732
+ ... "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
733
+ ... }
734
+ ... ]
735
+ ... }
736
+ ... ]
737
+ >>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
738
+ >>> inputs = inputs.to(model.device)
739
+ >>> outputs = model(**inputs)
740
+ ```
741
+ """
742
+ outputs = self.model(
743
+ input_ids=input_ids,
744
+ attention_mask=attention_mask,
745
+ audio_input_ids=audio_input_ids,
746
+ audio_input_ids_mask=audio_input_ids_mask,
747
+ position_ids=position_ids,
748
+ past_key_values=past_key_values,
749
+ inputs_embeds=inputs_embeds,
750
+ use_cache=use_cache,
751
+ **kwargs,
752
+ )
753
+
754
+ hidden_states = outputs.last_hidden_state
755
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
756
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
757
+ logits = self.audio_lm_head(hidden_states[:, slice_indices, :])
758
+
759
+ loss = None
760
+ if audio_labels is not None:
761
+ audio_logits = logits.reshape(*logits.shape[:2], self.config.num_codebooks, self.config.codebook_size)
762
+ audio_labels_expanded = input_ids.new_ones((*input_ids.shape[:2], 8)) * -100
763
+ audio_token_mask = self.model.get_placeholder_mask(input_ids, inputs_embeds, audio_input_ids_mask)
764
+ audio_labels_expanded[audio_token_mask] = audio_labels[audio_input_ids_mask]
765
+
766
+ codebook_losses = []
767
+ for codebook_idx in range(self.config.num_codebooks):
768
+ codebook_logits = audio_logits[:, :, codebook_idx, :]
769
+ codebook_labels = audio_labels_expanded[:, :, codebook_idx]
770
+ codebook_losses.append(
771
+ self.loss_function(codebook_logits, codebook_labels, self.config.codebook_size, **kwargs)
772
+ )
773
+
774
+ loss = sum(codebook_losses)
775
+
776
+ if labels is not None:
777
+ if self.text_lm_head is not None:
778
+ text_logits = self.text_lm_head(hidden_states[:, slice_indices, :])
779
+ text_loss = self.loss_function(text_logits, labels, self.config.vocab_size, **kwargs)
780
+ loss = text_loss if loss is None else loss + text_loss
781
+ else:
782
+ logger.warning_once(
783
+ f"`labels` provided to {self.__class__.__name__} but `text_lm_head` is disabled. "
784
+ f"Text labels ignored. Set `use_text_head=True` in model init to enable text loss."
785
+ )
786
+
787
+ return CausalLMOutputWithPast(
788
+ loss=loss,
789
+ logits=logits,
790
+ past_key_values=outputs.past_key_values,
791
+ hidden_states=outputs.hidden_states,
792
+ attentions=outputs.attentions,
793
+ )
794
+
795
+
796
+ __all__ = ["HiggsAudioV2ForConditionalGeneration", "HiggsAudioV2PreTrainedModel", "HiggsAudioV2Model"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/modular_higgs_audio_v2.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ... import initialization as init
21
+ from ...cache_utils import Cache, DynamicCache
22
+ from ...masking_utils import create_causal_mask
23
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
24
+ from ...modeling_utils import PreTrainedModel
25
+ from ...processing_utils import Unpack
26
+ from ...utils import (
27
+ TransformersKwargs,
28
+ auto_docstring,
29
+ can_return_tuple,
30
+ logging,
31
+ )
32
+ from ...utils.output_capturing import capture_outputs
33
+ from ..csm.modeling_csm import CsmBackboneModelEmbeddings
34
+ from ..llama.configuration_llama import LlamaConfig
35
+ from ..llama.modeling_llama import LlamaDecoderLayer, LlamaMLP, LlamaModel, LlamaPreTrainedModel, LlamaRMSNorm
36
+ from .generation_higgs_audio_v2 import HiggsAudioV2GenerationMixin
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ @auto_docstring(checkpoint="bosonai/higgs-audio-v2-generation-3B-base")
43
+ @strict
44
+ class HiggsAudioV2Config(LlamaConfig):
45
+ r"""
46
+ audio_bos_token_id (`int`, *optional*, defaults to 128013):
47
+ The token ID for the beginning-of-sequence token for audio output.
48
+ audio_delay_token_id (`int`, *optional*, defaults to 128014):
49
+ The token ID used for audio delay pattern in multi-codebook generation.
50
+ audio_stream_bos_id (`int`, *optional*, defaults to 1024):
51
+ The ID for the beginning-of-stream token in audio sequences.
52
+ audio_stream_eos_id (`int`, *optional*, defaults to 1025):
53
+ The ID for the end-of-stream token in audio sequences.
54
+
55
+ Example:
56
+
57
+ ```python
58
+ >>> from transformers import HiggsAudioV2Model, HiggsAudioV2Config
59
+
60
+ >>> # Initializing a HiggsAudioV2 style configuration
61
+ >>> configuration = HiggsAudioV2Config()
62
+
63
+ >>> # Initializing a model from the configuration
64
+ >>> model = HiggsAudioV2Model(configuration)
65
+
66
+ >>> # Accessing the model configuration
67
+ >>> configuration = model.config
68
+ ```"""
69
+
70
+ vocab_size: int = 128256
71
+ rms_norm_eps: float = 1e-5
72
+ hidden_size: int = 3072
73
+ intermediate_size: int = 8192
74
+ num_hidden_layers: int = 28
75
+ num_attention_heads: int = 24
76
+ num_key_value_heads: int = 8
77
+ pad_token_id: int | None = 128001
78
+ eos_token_id: int | list[int] | None = 128009
79
+ head_dim: int | None = 128
80
+ num_codebooks: int = 8
81
+ codebook_size: int = 1024
82
+ audio_token_id: int = 128016
83
+ audio_bos_token_id: int = 128013
84
+ audio_delay_token_id: int = 128014
85
+ audio_stream_bos_id: int = 1024
86
+ audio_stream_eos_id: int = 1025
87
+
88
+ def __post_init__(self, **kwargs):
89
+ if self.rope_parameters is None:
90
+ self.rope_parameters = {
91
+ "factor": 32.0,
92
+ "rope_theta": 500000.0,
93
+ "high_freq_factor": 0.5,
94
+ "low_freq_factor": 0.125,
95
+ "original_max_position_embeddings": 1024,
96
+ "rope_type": "llama3",
97
+ }
98
+ super().__post_init__(**kwargs)
99
+
100
+
101
+ class HiggsAudioV2MLP(LlamaMLP):
102
+ pass
103
+
104
+
105
+ class HiggsAudioV2RMSNorm(LlamaRMSNorm):
106
+ pass
107
+
108
+
109
+ class HiggsAudioV2DecoderLayer(LlamaDecoderLayer):
110
+ def __init__(self, config: HiggsAudioV2Config, layer_idx: int):
111
+ super().__init__(config, layer_idx)
112
+
113
+ self.audio_mlp = HiggsAudioV2MLP(config)
114
+ self.audio_input_layernorm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
115
+ self.audio_post_attention_layernorm = HiggsAudioV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
116
+
117
+ def forward(
118
+ self,
119
+ hidden_states: torch.Tensor,
120
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
121
+ attention_mask: torch.Tensor | None = None,
122
+ audio_token_mask: torch.BoolTensor | None = None,
123
+ position_ids: torch.LongTensor | None = None,
124
+ past_key_values: Cache | None = None,
125
+ use_cache: bool | None = False,
126
+ **kwargs: Unpack[TransformersKwargs],
127
+ ) -> torch.Tensor:
128
+ residual = hidden_states
129
+
130
+ if audio_token_mask is None:
131
+ hidden_states = self.audio_input_layernorm(hidden_states)
132
+ else:
133
+ audio_token_mask = audio_token_mask.to(hidden_states.device)
134
+ hidden_states = hidden_states.masked_scatter(
135
+ audio_token_mask.unsqueeze(-1),
136
+ self.audio_input_layernorm(hidden_states[audio_token_mask]).to(hidden_states.device),
137
+ )
138
+ hidden_states = hidden_states.masked_scatter(
139
+ ~audio_token_mask.unsqueeze(-1),
140
+ self.input_layernorm(hidden_states[~audio_token_mask]).to(hidden_states.device),
141
+ )
142
+
143
+ # Self Attention
144
+ hidden_states, _ = self.self_attn(
145
+ hidden_states=hidden_states,
146
+ attention_mask=attention_mask,
147
+ position_ids=position_ids,
148
+ past_key_values=past_key_values,
149
+ use_cache=use_cache,
150
+ position_embeddings=position_embeddings,
151
+ **kwargs,
152
+ )
153
+ hidden_states = residual + hidden_states
154
+
155
+ if audio_token_mask is None:
156
+ audio_hidden_states = self.audio_post_attention_layernorm(hidden_states)
157
+ audio_hidden_states = self.audio_mlp(audio_hidden_states)
158
+ hidden_states = hidden_states + audio_hidden_states.to(hidden_states.device)
159
+ else:
160
+ text_hidden_states = self.post_attention_layernorm(hidden_states[~audio_token_mask])
161
+ audio_hidden_states = self.audio_post_attention_layernorm(hidden_states[audio_token_mask])
162
+
163
+ text_hidden_states = self.mlp(text_hidden_states)
164
+ hidden_states[~audio_token_mask] += text_hidden_states.to(hidden_states.device)
165
+
166
+ audio_hidden_states = self.audio_mlp(audio_hidden_states)
167
+ hidden_states[audio_token_mask] += audio_hidden_states.to(hidden_states.device)
168
+
169
+ return hidden_states
170
+
171
+
172
+ class HiggsAudioV2Embeddings(CsmBackboneModelEmbeddings):
173
+ def forward(self, input_ids):
174
+ inputs_embeds = self.embed_audio_tokens(input_ids + self.audio_tokens_offsets)
175
+ inputs_embeds = inputs_embeds.sum(dim=-2)
176
+ return inputs_embeds
177
+
178
+
179
+ class HiggsAudioV2PreTrainedModel(LlamaPreTrainedModel, PreTrainedModel):
180
+ @torch.no_grad()
181
+ def _init_weights(self, module):
182
+ PreTrainedModel._init_weights(module)
183
+
184
+ if isinstance(module, HiggsAudioV2Embeddings):
185
+ init.copy_(
186
+ module.audio_tokens_offsets, torch.arange(self.config.num_codebooks) * self.config.codebook_size
187
+ )
188
+
189
+
190
+ class HiggsAudioV2Model(LlamaModel):
191
+ def __init__(self, config: HiggsAudioV2Config):
192
+ super().__init__(config)
193
+ self.embed_audio_tokens = HiggsAudioV2Embeddings(config)
194
+
195
+ def get_placeholder_mask(
196
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, audio_input_ids_mask: torch.LongTensor
197
+ ):
198
+ """
199
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
200
+ equal to the length of audio_input_ids. If the lengths are different, an error is raised.
201
+
202
+ If input_ids and inputs_embeds are None, we return None.
203
+ Indeed this means we cannot determine the placeholder mask, the model is to be used in a audio-only mode, hence we return None.
204
+ """
205
+ if input_ids is None and inputs_embeds is None:
206
+ return None
207
+
208
+ elif input_ids is None:
209
+ special_audio_mask = inputs_embeds == self.embed_tokens(
210
+ torch.tensor(self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
211
+ )
212
+ special_audio_mask = special_audio_mask.all(-1)
213
+
214
+ else:
215
+ special_audio_mask = (input_ids == self.config.audio_token_id) | (
216
+ input_ids == self.config.audio_delay_token_id
217
+ )
218
+
219
+ return special_audio_mask
220
+
221
+ @capture_outputs
222
+ @auto_docstring
223
+ def forward(
224
+ self,
225
+ input_ids: torch.LongTensor | None = None,
226
+ audio_input_ids: torch.LongTensor | None = None,
227
+ attention_mask: torch.LongTensor | None = None,
228
+ audio_input_ids_mask: torch.BoolTensor | None = None,
229
+ position_ids: torch.LongTensor | None = None,
230
+ past_key_values: Cache | None = None,
231
+ inputs_embeds: torch.FloatTensor | None = None,
232
+ use_cache: bool | None = None,
233
+ **kwargs: Unpack[TransformersKwargs],
234
+ ) -> BaseModelOutputWithPast:
235
+ r"""
236
+ audio_input_ids (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*):
237
+ Indices of audio codebook tokens.
238
+
239
+ Indices can be obtained using [`HiggsAudioV2TokenizerModel.encode`].
240
+ audio_input_ids_mask (`torch.BoolTensor` of shape `(batch_size, num_audio_frames)`, *optional*):
241
+ Indicates which audio frames in `audio_input_ids` are valid.
242
+
243
+ Returns:
244
+ [`~models.modeling_outputs.BaseModelOutputWithPast`]:
245
+ Usual decoder outputs with the placeholder positions already substituted by their corresponding
246
+ audio embeddings.
247
+
248
+ Example:
249
+
250
+ ```python
251
+ >>> from transformers import AutoProcessor, HiggsAudioV2Model
252
+ >>> import torch
253
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
254
+ >>> processor = AutoProcessor.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
255
+ >>> model = HiggsAudioV2Model.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
256
+ >>> conversation = [
257
+ ... {
258
+ ... "role": "system",
259
+ ... "content": [
260
+ ... {
261
+ ... "type": "text",
262
+ ... "text": "Generate audio following instruction."
263
+ ... }
264
+ ... ]
265
+ ... },
266
+ ... {
267
+ ... "role": "scene",
268
+ ... "content": [
269
+ ... {
270
+ ... "type": "text",
271
+ ... "text": "Audio is recorded from a quiet room."
272
+ ... }
273
+ ... ]
274
+ ... },
275
+ ... {
276
+ ... "role": "user",
277
+ ... "content": [
278
+ ... {
279
+ ... "type": "text",
280
+ ... "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
281
+ ... }
282
+ ... ]
283
+ ... },
284
+ ... {
285
+ ... "role": "assistant",
286
+ ... "content": [
287
+ ... {
288
+ ... "type": "audio",
289
+ ... "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
290
+ ... }
291
+ ... ]
292
+ ... },
293
+ ... {
294
+ ... "role": "user",
295
+ ... "content": [
296
+ ... {
297
+ ... "type": "text",
298
+ ... "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
299
+ ... }
300
+ ... ]
301
+ ... }
302
+ ... ]
303
+ >>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
304
+ >>> inputs = inputs.to(model.device)
305
+ >>> outputs = model(**inputs)
306
+ ```
307
+ """
308
+ if (input_ids is None) and (inputs_embeds is None) and (audio_input_ids is None):
309
+ raise ValueError("You must specify at least one of input_ids, inputs_embeds, or audio_input_ids")
310
+
311
+ if (input_ids is not None) and (inputs_embeds is not None):
312
+ raise ValueError("Only one of input_ids or inputs_embeds can be provided")
313
+
314
+ audio_token_mask = self.get_placeholder_mask(input_ids, inputs_embeds, audio_input_ids_mask)
315
+
316
+ if input_ids is not None:
317
+ inputs_embeds = self.embed_tokens(input_ids)
318
+
319
+ if audio_input_ids is not None:
320
+ audio_embeds = self.embed_audio_tokens(audio_input_ids)
321
+
322
+ if inputs_embeds is not None and audio_input_ids is not None:
323
+ audio_embeds = (
324
+ audio_embeds[audio_input_ids_mask.to(audio_embeds.device)]
325
+ if audio_input_ids_mask is not None
326
+ else audio_embeds
327
+ )
328
+ inputs_embeds = inputs_embeds.masked_scatter(
329
+ audio_token_mask[..., None].expand_as(inputs_embeds), audio_embeds.to(inputs_embeds.device)
330
+ )
331
+ elif audio_input_ids is not None:
332
+ inputs_embeds = audio_embeds
333
+
334
+ if use_cache and past_key_values is None:
335
+ past_key_values = DynamicCache(config=self.config)
336
+
337
+ if position_ids is None:
338
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
339
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
340
+ position_ids = position_ids.unsqueeze(0)
341
+
342
+ causal_mask = create_causal_mask(
343
+ config=self.config,
344
+ inputs_embeds=inputs_embeds,
345
+ attention_mask=attention_mask,
346
+ past_key_values=past_key_values,
347
+ position_ids=position_ids,
348
+ )
349
+
350
+ hidden_states = inputs_embeds
351
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
352
+
353
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
354
+ hidden_states = decoder_layer(
355
+ hidden_states,
356
+ attention_mask=causal_mask,
357
+ audio_token_mask=audio_token_mask,
358
+ position_ids=position_ids,
359
+ past_key_values=past_key_values,
360
+ position_embeddings=position_embeddings,
361
+ **kwargs,
362
+ )
363
+
364
+ hidden_states = self.norm(hidden_states)
365
+ return BaseModelOutputWithPast(
366
+ last_hidden_state=hidden_states,
367
+ past_key_values=past_key_values,
368
+ )
369
+
370
+
371
+ @auto_docstring(
372
+ custom_intro="""
373
+ The Higgs Audio model, a llama-like auto-regressive transformer model with dual-FFN.
374
+ """
375
+ )
376
+ class HiggsAudioV2ForConditionalGeneration(HiggsAudioV2PreTrainedModel, HiggsAudioV2GenerationMixin):
377
+ base_model_prefix = "model"
378
+ _keys_to_ignore_on_load_unexpected = ["text_lm_head.weight"]
379
+
380
+ def __init__(self, config: HiggsAudioV2Config, use_text_head: bool = False):
381
+ r"""
382
+ use_text_head (`bool`, *optional*, defaults to False):
383
+ Whether to use a text language model head. Such head is not required for generation,
384
+ but can be used to compute the text loss when training.
385
+ """
386
+ super().__init__(config)
387
+ self.model = HiggsAudioV2Model(config)
388
+ self.audio_lm_head = nn.Linear(config.hidden_size, config.num_codebooks * config.codebook_size, bias=False)
389
+ self.text_lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) if use_text_head else None
390
+
391
+ self.post_init()
392
+
393
+ def prepare_inputs_for_generation(
394
+ self,
395
+ input_ids: torch.LongTensor,
396
+ audio_input_ids: torch.LongTensor | None = None,
397
+ audio_input_ids_mask: torch.LongTensor | None = None,
398
+ **kwargs,
399
+ ):
400
+ model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs)
401
+
402
+ if audio_input_ids is not None and model_inputs.get("past_key_values") is not None:
403
+ current_cache_length = model_inputs.get("past_key_values").get_seq_length()
404
+ audio_token_mask = (input_ids == self.config.audio_token_id) | (
405
+ input_ids == self.config.audio_delay_token_id
406
+ )
407
+ in_cache_num_audio_input_ids = audio_token_mask[:, :current_cache_length].sum(dim=-1)
408
+
409
+ # already cached audio_input_ids should be masked
410
+ # this surmise that audio_input_ids are right padded!
411
+ valid_audio_input_ids = audio_input_ids_mask.cumsum(dim=-1) > in_cache_num_audio_input_ids[:, None]
412
+ audio_input_ids_mask = audio_input_ids_mask & valid_audio_input_ids
413
+
414
+ if audio_input_ids_mask is not None and (~audio_input_ids_mask[:, :-1]).all():
415
+ # in decoding mode, we only pass audio_input_ids
416
+ audio_input_ids = audio_input_ids[:, -1:, :].clone(memory_format=torch.contiguous_format)
417
+ model_inputs.pop("input_ids", None)
418
+ audio_input_ids_mask = None
419
+
420
+ model_inputs["audio_input_ids"] = audio_input_ids
421
+ model_inputs["audio_input_ids_mask"] = audio_input_ids_mask
422
+
423
+ return model_inputs
424
+
425
+ @auto_docstring
426
+ @can_return_tuple
427
+ def forward(
428
+ self,
429
+ input_ids: torch.LongTensor | None = None,
430
+ attention_mask: torch.BoolTensor | None = None,
431
+ audio_input_ids: torch.LongTensor | None = None,
432
+ audio_input_ids_mask: torch.LongTensor | None = None,
433
+ position_ids: torch.LongTensor | None = None,
434
+ past_key_values: Cache | None = None,
435
+ inputs_embeds: torch.FloatTensor | None = None,
436
+ labels: torch.LongTensor | None = None,
437
+ audio_labels: torch.LongTensor | None = None,
438
+ use_cache: bool | None = None,
439
+ logits_to_keep: int | torch.Tensor = 0,
440
+ **kwargs: Unpack[TransformersKwargs],
441
+ ):
442
+ r"""
443
+ audio_input_ids (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*):
444
+ Indices of audio codebook tokens.
445
+
446
+ Indices can be obtained using [`HiggsAudioV2TokenizerModel.encode`].
447
+ audio_input_ids_mask (`torch.BoolTensor` of shape `(batch_size, num_audio_frames)`, *optional*):
448
+ Indicates which audio frames in `audio_input_ids` are valid.
449
+ audio_labels (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*):
450
+ Labels for the audio codebook tokens for computing the masked language modeling loss. Indices should either be in `[0, ...,
451
+ config.codebook_size]. Token with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.codebook_size]`.
452
+ Can be obtained using `output_labels=True` when calling [`HiggsAudioV2Processor`].
453
+
454
+ Returns:
455
+ [`~models.modeling_outputs.CausalLMOutputWithPast`]:
456
+ A [`~models.modeling_outputs.CausalLMOutputWithPast`] containing the logits, loss (if labels are provided),
457
+ and other outputs from the model.
458
+
459
+ Example:
460
+
461
+ ```python
462
+ >>> from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
463
+ >>> model_id = "eustlb/higgs-audio-v2-generation-3B-base"
464
+ >>> processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
465
+ >>> model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
466
+ >>> conversation = [
467
+ ... {
468
+ ... "role": "system",
469
+ ... "content": [
470
+ ... {
471
+ ... "type": "text",
472
+ ... "text": "Generate audio following instruction."
473
+ ... }
474
+ ... ]
475
+ ... },
476
+ ... {
477
+ ... "role": "scene",
478
+ ... "content": [
479
+ ... {
480
+ ... "type": "text",
481
+ ... "text": "Audio is recorded from a quiet room."
482
+ ... }
483
+ ... ]
484
+ ... },
485
+ ... {
486
+ ... "role": "user",
487
+ ... "content": [
488
+ ... {
489
+ ... "type": "text",
490
+ ... "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
491
+ ... }
492
+ ... ]
493
+ ... },
494
+ ... {
495
+ ... "role": "assistant",
496
+ ... "content": [
497
+ ... {
498
+ ... "type": "audio",
499
+ ... "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
500
+ ... }
501
+ ... ]
502
+ ... },
503
+ ... {
504
+ ... "role": "user",
505
+ ... "content": [
506
+ ... {
507
+ ... "type": "text",
508
+ ... "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
509
+ ... }
510
+ ... ]
511
+ ... }
512
+ ... ]
513
+ >>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
514
+ >>> inputs = inputs.to(model.device)
515
+ >>> outputs = model(**inputs)
516
+ ```
517
+ """
518
+ outputs = self.model(
519
+ input_ids=input_ids,
520
+ attention_mask=attention_mask,
521
+ audio_input_ids=audio_input_ids,
522
+ audio_input_ids_mask=audio_input_ids_mask,
523
+ position_ids=position_ids,
524
+ past_key_values=past_key_values,
525
+ inputs_embeds=inputs_embeds,
526
+ use_cache=use_cache,
527
+ **kwargs,
528
+ )
529
+
530
+ hidden_states = outputs.last_hidden_state
531
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
532
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
533
+ logits = self.audio_lm_head(hidden_states[:, slice_indices, :])
534
+
535
+ loss = None
536
+ if audio_labels is not None:
537
+ audio_logits = logits.reshape(*logits.shape[:2], self.config.num_codebooks, self.config.codebook_size)
538
+ audio_labels_expanded = input_ids.new_ones((*input_ids.shape[:2], 8)) * -100
539
+ audio_token_mask = self.model.get_placeholder_mask(input_ids, inputs_embeds, audio_input_ids_mask)
540
+ audio_labels_expanded[audio_token_mask] = audio_labels[audio_input_ids_mask]
541
+
542
+ codebook_losses = []
543
+ for codebook_idx in range(self.config.num_codebooks):
544
+ codebook_logits = audio_logits[:, :, codebook_idx, :]
545
+ codebook_labels = audio_labels_expanded[:, :, codebook_idx]
546
+ codebook_losses.append(
547
+ self.loss_function(codebook_logits, codebook_labels, self.config.codebook_size, **kwargs)
548
+ )
549
+
550
+ loss = sum(codebook_losses)
551
+
552
+ if labels is not None:
553
+ if self.text_lm_head is not None:
554
+ text_logits = self.text_lm_head(hidden_states[:, slice_indices, :])
555
+ text_loss = self.loss_function(text_logits, labels, self.config.vocab_size, **kwargs)
556
+ loss = text_loss if loss is None else loss + text_loss
557
+ else:
558
+ logger.warning_once(
559
+ f"`labels` provided to {self.__class__.__name__} but `text_lm_head` is disabled. "
560
+ f"Text labels ignored. Set `use_text_head=True` in model init to enable text loss."
561
+ )
562
+
563
+ return CausalLMOutputWithPast(
564
+ loss=loss,
565
+ logits=logits,
566
+ past_key_values=outputs.past_key_values,
567
+ hidden_states=outputs.hidden_states,
568
+ attentions=outputs.attentions,
569
+ )
570
+
571
+
572
+ __all__ = [
573
+ "HiggsAudioV2ForConditionalGeneration",
574
+ "HiggsAudioV2PreTrainedModel",
575
+ "HiggsAudioV2Model",
576
+ "HiggsAudioV2Config",
577
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/higgs_audio_v2/processing_higgs_audio_v2.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ from itertools import islice
17
+ from pathlib import Path
18
+
19
+ from ...audio_utils import AudioInput, make_list_of_audio
20
+ from ...feature_extraction_utils import BatchFeature
21
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
22
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
23
+ from ...utils import is_soundfile_available, is_torch_available, logging
24
+
25
+
26
+ if is_torch_available():
27
+ import torch
28
+ import torch.nn.functional as F
29
+
30
+
31
+ if is_soundfile_available():
32
+ import soundfile as sf
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class HiggsAudioV2ProcessorKwargs(ProcessingKwargs, total=False):
39
+ _defaults = {
40
+ "text_kwargs": {
41
+ "padding": True,
42
+ "padding_side": "left",
43
+ },
44
+ "audio_kwargs": {
45
+ "padding": False,
46
+ "sampling_rate": 24000,
47
+ },
48
+ }
49
+
50
+
51
+ class HiggsAudioV2Processor(ProcessorMixin):
52
+ r"""
53
+ Constructs a Higgs Audio processor which wraps a [`DacFeatureExtractor`], a [`AutoTokenizer`],
54
+ and a [`HiggsAudioV2TokenizerModel`] into a single processor. It inherits, the audio feature extraction, tokenizer,
55
+ and audio encode/decode functionalities.
56
+ See [`~HiggsAudioV2Processor.__call__`] and [`~HiggsAudioV2Processor.decode`] for more information.
57
+
58
+ Args:
59
+ feature_extractor (`DacFeatureExtractor`):
60
+ An instance of [`DacFeatureExtractor`]. The feature extractor is a required input.
61
+ tokenizer (`AutoTokenizer`):
62
+ An instance of [`AutoTokenizer`]. The tokenizer is a required input.
63
+ audio_tokenizer (`HiggsAudioV2TokenizerModel`):
64
+ An instance of [`HiggsAudioV2TokenizerModel`]. The audio tokenizer is a required input.
65
+ chat_template (`str`, *optional*):
66
+ A template string for chat formatting when combining text and audio interactions.
67
+ audio_token (`str`, *optional*, defaults to `"<|AUDIO_OUT|>"`):
68
+ The token used to represent audio output in the text sequence.
69
+ audio_bos_token (`str`, *optional*, defaults to `"<|audio_out_bos|>"`):
70
+ The beginning-of-sequence token for audio output.
71
+ audio_eos_token (`str`, *optional*, defaults to `"<|audio_eos|>"`):
72
+ The end-of-sequence token for audio output.
73
+ audio_delay_token (`str`, *optional*, defaults to `"<|reserved_special_token_6|>"`):
74
+ The token used for audio delay pattern in multi-codebook generation.
75
+ audio_stream_bos_id (`int`, *optional*, defaults to 1024):
76
+ The ID for the beginning-of-stream token in audio sequences.
77
+ audio_stream_eos_id (`int`, *optional*, defaults to 1025):
78
+ The ID for the end-of-stream token in audio sequences.
79
+ """
80
+
81
+ feature_extractor_class = "DacFeatureExtractor"
82
+ tokenizer_class = "AutoTokenizer"
83
+ audio_tokenizer_class = "HiggsAudioV2TokenizerModel"
84
+
85
+ def __init__(
86
+ self,
87
+ feature_extractor,
88
+ tokenizer,
89
+ audio_tokenizer,
90
+ chat_template=None,
91
+ audio_token="<|AUDIO_OUT|>",
92
+ audio_bos_token="<|audio_out_bos|>",
93
+ audio_eos_token="<|audio_eos|>",
94
+ audio_delay_token="<|reserved_special_token_6|>",
95
+ audio_stream_bos_id=1024,
96
+ audio_stream_eos_id=1025,
97
+ ):
98
+ self.audio_token = tokenizer.audio_token if hasattr(tokenizer, "audio_token") else audio_token
99
+ self.audio_bos_token = tokenizer.audio_bos_token if hasattr(tokenizer, "audio_bos_token") else audio_bos_token
100
+ self.audio_eos_token = tokenizer.audio_eos_token if hasattr(tokenizer, "audio_eos_token") else audio_eos_token
101
+ self.audio_delay_token = (
102
+ tokenizer.audio_delay_token if hasattr(tokenizer, "audio_delay_token") else audio_delay_token
103
+ )
104
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
105
+ self.audio_bos_token_id = tokenizer.convert_tokens_to_ids(self.audio_bos_token)
106
+ self.audio_eos_token_id = tokenizer.convert_tokens_to_ids(self.audio_eos_token)
107
+ self.audio_delay_token_id = tokenizer.convert_tokens_to_ids(self.audio_delay_token)
108
+ self.audio_stream_bos_id = audio_stream_bos_id
109
+ self.audio_stream_eos_id = audio_stream_eos_id
110
+
111
+ super().__init__(
112
+ feature_extractor,
113
+ tokenizer,
114
+ audio_tokenizer=audio_tokenizer,
115
+ chat_template=chat_template,
116
+ )
117
+
118
+ def get_audio_tokens(self, num_audio_tokens):
119
+ """
120
+ Returns the audio tokens for a given number of audio tokens.
121
+ """
122
+ num_codebooks = self.audio_tokenizer.config.num_quantizers
123
+ return self.audio_token * (num_audio_tokens - (num_codebooks - 1)) + self.audio_delay_token * (
124
+ num_codebooks - 1
125
+ )
126
+
127
+ def __call__(
128
+ self,
129
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
130
+ audio: AudioInput | None = None,
131
+ output_labels: bool | None = False,
132
+ **kwargs: Unpack[HiggsAudioV2ProcessorKwargs],
133
+ ):
134
+ output_kwargs = self._merge_kwargs(
135
+ HiggsAudioV2ProcessorKwargs,
136
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
137
+ **kwargs,
138
+ )
139
+
140
+ text_kwargs = output_kwargs["text_kwargs"]
141
+ audio_kwargs = output_kwargs["audio_kwargs"]
142
+ return_tensors = text_kwargs.get("return_tensors", None)
143
+ if return_tensors != "pt":
144
+ raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
145
+
146
+ if isinstance(text, str):
147
+ text = [text]
148
+ elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
149
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
150
+ n_audio_in_text = [t.count(self.audio_token) for t in text]
151
+
152
+ n_audio = 0
153
+ if audio is not None:
154
+ audio = make_list_of_audio(audio)
155
+ n_audio = len(audio)
156
+
157
+ if sum(n_audio_in_text) > 0 and n_audio != sum(n_audio_in_text):
158
+ if audio is None:
159
+ raise ValueError("No audio were provided, but there are audio tokens in the prompt")
160
+ else:
161
+ raise ValueError(
162
+ f"The number of audio tokens in each text ({n_audio_in_text}) should be the same as the "
163
+ f"number of provided audios ({n_audio})."
164
+ )
165
+ elif sum(n_audio_in_text) == 0 and n_audio > 0:
166
+ raise ValueError("Audio were provided, but there are no audio tokens in the prompt")
167
+
168
+ if audio is not None:
169
+ # tokenize audio
170
+ audio_input_ids_list = []
171
+ for audio_el in audio:
172
+ # TODO: @eustlb, this should be batched !!!
173
+ audio_inputs = self.feature_extractor(audio_el, **audio_kwargs)
174
+
175
+ # TODO: @eustlb, padding_mask should be supported...
176
+ audio_inputs.pop("padding_mask", None)
177
+ audio_inputs.to(self.audio_tokenizer.device)
178
+ audio_input_ids = self.audio_tokenizer.encode(**audio_inputs).audio_codes
179
+
180
+ # add audio eos and bos
181
+ bos_codes = audio_input_ids.new_full((*audio_input_ids.shape[:2], 1), self.audio_stream_bos_id)
182
+ eos_codes = audio_input_ids.new_full((*audio_input_ids.shape[:2], 1), self.audio_stream_eos_id)
183
+ audio_input_ids = torch.cat([bos_codes, audio_input_ids, eos_codes], dim=2)
184
+
185
+ audio_input_ids = self.build_delay_pattern(audio_input_ids)
186
+ audio_input_ids_list.append(audio_input_ids[0].transpose(0, 1))
187
+
188
+ # expand audio tokens in text
189
+ num_audio_tokens_iter = iter(len(audio_input_ids) for audio_input_ids in audio_input_ids_list)
190
+ for i in range(len(text)):
191
+ expanded = re.sub(
192
+ re.escape(self.audio_token), lambda _: self.get_audio_tokens(next(num_audio_tokens_iter)), text[i]
193
+ )
194
+ text[i] = expanded
195
+
196
+ # convert to nested list according to n_audio_in_text
197
+ # [audio_1, audio_2, ...] -> [[audio_1_1, audio_1_2, ...], [audio_2_1, audio_2_2, ...], ...]
198
+ audio_input_ids_iter = iter(audio_input_ids_list)
199
+ audio_input_ids_list = [list(islice(audio_input_ids_iter, l)) for l in n_audio_in_text]
200
+ audio_input_ids_list = [torch.cat(batch_el, dim=0) for batch_el in audio_input_ids_list]
201
+
202
+ # pad and stack
203
+ lenghts = [ids.shape[0] for ids in audio_input_ids_list]
204
+ max_length = max(lenghts)
205
+ audio_input_ids_list = [
206
+ F.pad(ids, (0, 0, 0, max_length - ids.shape[0]), value=self.audio_stream_eos_id)
207
+ for ids in audio_input_ids_list
208
+ ]
209
+ audio_input_ids = torch.stack(audio_input_ids_list, dim=0)
210
+ audio_input_ids_mask = torch.arange(max_length)[None, :] < torch.tensor(lenghts)[:, None]
211
+
212
+ # tokenize text
213
+ data = self.tokenizer(text, **text_kwargs)
214
+ if audio is not None:
215
+ data.update(
216
+ {
217
+ "audio_input_ids": audio_input_ids,
218
+ "audio_input_ids_mask": audio_input_ids_mask,
219
+ }
220
+ )
221
+
222
+ if output_labels:
223
+ labels = data["input_ids"].clone()
224
+ labels[labels == self.audio_token_id] = -100
225
+ labels[labels == self.tokenizer.pad_token_id] = -100
226
+ labels[labels == self.audio_bos_token_id] = -100
227
+ data["labels"] = labels
228
+
229
+ if audio is not None:
230
+ audio_labels = audio_input_ids.clone()
231
+ audio_labels[audio_labels == self.audio_stream_bos_id] = -100
232
+ audio_labels[audio_labels == self.audio_stream_eos_id] = -100
233
+ data.update({"audio_labels": audio_labels})
234
+
235
+ return BatchFeature(data=data, tensor_type="pt")
236
+
237
+ def batch_decode(self, audio_input_ids):
238
+ """
239
+ Decode a batch of audio token sequences into audio waveforms.
240
+
241
+ This method processes audio token sequences generated by the model, extracting the actual audio tokens
242
+ between the beginning-of-stream (BOS) and end-of-stream (EOS) markers, reverting the delay pattern
243
+ used during generation, and decoding them into audio waveforms using the audio tokenizer.
244
+
245
+ Args:
246
+ audio_input_ids (`torch.LongTensor`):
247
+ Shape `(batch_size, sequence_length, num_codebooks)`
248
+ The audio token sequences to decode. These should contain audio tokens with BOS and EOS markers
249
+ in a delay pattern format as generated by the model.
250
+
251
+ Returns:
252
+ `list[torch.Tensor]`: A list of decoded audio waveforms, one for each batch element. Each waveform
253
+ is a 1D tensor containing the audio samples.
254
+ """
255
+ # start idx should be the last sequence index of the audio bos tokens
256
+ audio_bos_token_idxs = (audio_input_ids == self.audio_stream_bos_id).all(-1).nonzero()
257
+ start_of_generation_idx = audio_bos_token_idxs[-1, -1].item()
258
+
259
+ audio_input_ids = audio_input_ids[:, start_of_generation_idx:]
260
+
261
+ # end idx for each batch idx should be the first sequence index of the audio eos tokens
262
+ audio_eos_token_idxs = (audio_input_ids == self.audio_stream_eos_id).all(-1).nonzero()
263
+ end_of_generation_idxs = [
264
+ audio_eos_token_idxs[audio_eos_token_idxs[:, 0] == batch_idx, 1].min().item()
265
+ if len(audio_eos_token_idxs[audio_eos_token_idxs[:, 0] == batch_idx]) > 0
266
+ else audio_input_ids.shape[1]
267
+ for batch_idx in range(audio_input_ids.shape[0])
268
+ ]
269
+
270
+ audios = []
271
+ with torch.no_grad():
272
+ # TODO: @eustlb, this should be batched !!!
273
+ for batch_idx in range(audio_input_ids.shape[0]):
274
+ audio_token_ids = audio_input_ids[batch_idx, 1 : end_of_generation_idxs[batch_idx]]
275
+ audio_token_ids = self.revert_delay_pattern(audio_token_ids).clip(0, self.audio_stream_bos_id - 1)
276
+ audio_i = (
277
+ self.audio_tokenizer.decode(audio_token_ids.transpose(0, 1).unsqueeze(0))
278
+ .audio_values.cpu()
279
+ .squeeze()
280
+ )
281
+ audios.append(audio_i)
282
+
283
+ return audios
284
+
285
+ def decode(self, audio_input_ids):
286
+ if audio_input_ids.shape[0] != 1:
287
+ raise ValueError(
288
+ f"Expecting a single output to be decoded but received {audio_input_ids.shape[0]} samples instead."
289
+ )
290
+
291
+ return self.batch_decode(audio_input_ids)[0]
292
+
293
+ def build_delay_pattern(self, input_ids):
294
+ bsz, num_codebooks, seq_len = input_ids.shape
295
+ new_seq_len = seq_len + num_codebooks - 1
296
+
297
+ # Create output tensor with delay pattern
298
+ output = torch.ones((bsz, num_codebooks, new_seq_len), dtype=torch.long, device=input_ids.device)
299
+
300
+ # Create masks for different regions
301
+ bos_mask = torch.tril(output, -1) > 0
302
+ eos_mask = torch.triu(output, seq_len) > 0
303
+ data_mask = ~(bos_mask | eos_mask)
304
+
305
+ # Fill the tensor
306
+ output[bos_mask] = self.audio_stream_bos_id
307
+ output[data_mask] = input_ids.reshape(-1)
308
+ output[eos_mask] = self.audio_stream_eos_id
309
+
310
+ return output
311
+
312
+ def revert_delay_pattern(self, input_ids):
313
+ seq_len, num_codebooks = input_ids.shape
314
+ # Extract diagonal slices from the delay pattern
315
+ slices = []
316
+ for i in range(num_codebooks):
317
+ end_idx = seq_len - num_codebooks + 1 + i
318
+ slices.append(input_ids[i:end_idx, i : i + 1])
319
+
320
+ return torch.cat(slices, dim=1)
321
+
322
+ # Copied from transformers.models.csm.processing_csm.CsmProcessor.save_audio with Csm->HiggsAudioV2
323
+ def save_audio(
324
+ self,
325
+ audio: AudioInput,
326
+ saving_path: str | Path | list[str | Path],
327
+ **kwargs: Unpack[HiggsAudioV2ProcessorKwargs],
328
+ ):
329
+ # TODO: @eustlb, this should be in AudioProcessor
330
+ if not is_soundfile_available():
331
+ raise ImportError("Please install `soundfile` to save audio files.")
332
+
333
+ # ensure correct audio input
334
+ audio = make_list_of_audio(audio)
335
+
336
+ # ensure correct saving path
337
+ if isinstance(saving_path, (str, Path)):
338
+ saving_path = [saving_path]
339
+ elif not (isinstance(saving_path, (list, tuple)) and all(isinstance(p, (str, Path)) for p in saving_path)):
340
+ raise ValueError("Invalid input path. Please provide a string, or a list of strings")
341
+
342
+ if len(audio) != len(saving_path):
343
+ raise ValueError("The number of audio and saving paths must be the same")
344
+
345
+ output_kwargs = self._merge_kwargs(
346
+ HiggsAudioV2ProcessorKwargs,
347
+ **kwargs,
348
+ )
349
+ audio_kwargs = output_kwargs["audio_kwargs"]
350
+ sampling_rate = audio_kwargs["sampling_rate"]
351
+
352
+ for audio_value, p in zip(audio, saving_path):
353
+ if isinstance(audio_value, torch.Tensor):
354
+ audio_value = audio_value.cpu().float().numpy()
355
+ sf.write(p, audio_value, sampling_rate)
356
+
357
+ @property
358
+ def model_input_names(self):
359
+ tokenizer_input_names = self.tokenizer.model_input_names
360
+
361
+ # TODO: @eustlb, to be standardized!!
362
+ audio_tokenizer_input_names = ["audio_input_ids", "audio_input_ids_mask"]
363
+ return tokenizer_input_names + audio_tokenizer_input_names
364
+
365
+
366
+ __all__ = ["HiggsAudioV2Processor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_pixtral import *
22
+ from .image_processing_pil_pixtral import *
23
+ from .image_processing_pixtral import *
24
+ from .modeling_pixtral import *
25
+ from .processing_pixtral import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ 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/pixtral/configuration_pixtral.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """Pixtral model configuration"""
14
+
15
+ from huggingface_hub.dataclasses import strict
16
+
17
+ from ...configuration_utils import PreTrainedConfig
18
+ from ...modeling_rope_utils import RopeParameters
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="mistral-labs/pixtral-12b")
23
+ @strict
24
+ class PixtralVisionConfig(PreTrainedConfig):
25
+ r"""
26
+ Example:
27
+
28
+ ```python
29
+ >>> from transformers import PixtralVisionModel, PixtralVisionConfig
30
+
31
+ >>> # Initializing a Pixtral-12B style configuration
32
+ >>> config = PixtralVisionConfig()
33
+
34
+ >>> # Initializing a model (with randomly initialized weights) from the configuration
35
+ >>> model = PixtralVisionModel(configuration)
36
+
37
+ >>> # Accessing the model configuration
38
+ >>> configuration = model.config
39
+ ```"""
40
+
41
+ model_type = "pixtral"
42
+
43
+ hidden_size: int = 1024
44
+ intermediate_size: int = 4096
45
+ num_hidden_layers: int = 24
46
+ num_attention_heads: int = 16
47
+ num_channels: int = 3
48
+ image_size: int | list[int] | tuple[int, int] = 1024
49
+ patch_size: int | list[int] | tuple[int, int] = 16
50
+ hidden_act: str = "gelu"
51
+ attention_dropout: float | int = 0.0
52
+ rope_parameters: RopeParameters | dict | None = None
53
+ initializer_range: float = 0.02
54
+
55
+ def __post_init__(self, **kwargs):
56
+ self.head_dim = self.hidden_size // self.num_attention_heads
57
+ super().__post_init__(**kwargs)
58
+
59
+
60
+ __all__ = ["PixtralVisionConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/image_processing_pil_pixtral.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for Pixtral."""
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+
20
+ from ...image_processing_backends import PilBackend
21
+ from ...image_processing_utils import BatchFeature, get_size_dict
22
+ from ...image_transforms import PaddingMode, pad
23
+ from ...image_utils import (
24
+ ChannelDimension,
25
+ ImageInput,
26
+ PILImageResampling,
27
+ SizeDict,
28
+ get_image_size,
29
+ )
30
+ from ...processing_utils import ImagesKwargs, Unpack
31
+ from ...utils import TensorType, auto_docstring
32
+
33
+
34
+ # Adapted from transformers.models.pixtral.image_processing_pixtral.PixtralImageProcessorKwargs
35
+ class PixtralImageProcessorKwargs(ImagesKwargs, total=False):
36
+ """
37
+ patch_size (`Union[dict[str, int], int]` *optional*, defaults to `{"height": 16, "width": 16}`):
38
+ Size of the patches in the model, used to calculate the output image size.
39
+ """
40
+
41
+ patch_size: dict[str, int] | int
42
+
43
+
44
+ # Adapted from transformers.models.pixtral.image_processing_pixtral._num_image_tokens
45
+ def _num_image_tokens(image_size: tuple[int, int], patch_size: tuple[int, int]) -> int:
46
+ """
47
+ Calculate the number of image tokens given the image size and patch size.
48
+
49
+ Args:
50
+ image_size (`tuple[int, int]`):
51
+ The size of the image as `(height, width)`.
52
+ patch_size (`tuple[int, int]`):
53
+ The patch size as `(height, width)`.
54
+
55
+ Returns:
56
+ `int`: The number of image tokens.
57
+ """
58
+ height, width = image_size
59
+ patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)
60
+ num_width_tokens = (width - 1) // patch_width + 1
61
+ num_height_tokens = (height - 1) // patch_height + 1
62
+ return num_height_tokens, num_width_tokens
63
+
64
+
65
+ # Adapted from transformers.models.pixtral.image_processing_pixtral.get_resize_output_image_size
66
+ def get_resize_output_image_size(
67
+ input_image: ImageInput,
68
+ size: int | tuple[int, int] | list[int] | tuple[int],
69
+ patch_size: int | tuple[int, int] | list[int] | tuple[int],
70
+ input_data_format: str | ChannelDimension | None = None,
71
+ ) -> tuple:
72
+ """
73
+ Find the target (height, width) dimension of the output image after resizing given the input image and the desired
74
+ size.
75
+
76
+ Args:
77
+ input_image (`ImageInput`):
78
+ The image to resize.
79
+ size (`int` or `tuple[int, int]`):
80
+ Max image size an input image can be. Must be a dictionary with the key "longest_edge".
81
+ patch_size (`int` or `tuple[int, int]`):
82
+ The patch_size as `(height, width)` to use for resizing the image. If patch_size is an integer, `(patch_size, patch_size)`
83
+ will be used
84
+ input_data_format (`ChannelDimension`, *optional*):
85
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
86
+
87
+ Returns:
88
+ `tuple`: The target (height, width) dimension of the output image after resizing.
89
+ """
90
+ max_height, max_width = size if isinstance(size, (tuple, list)) else (size, size)
91
+ patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)
92
+ height, width = get_image_size(input_image, input_data_format)
93
+
94
+ ratio = max(height / max_height, width / max_width)
95
+
96
+ if ratio > 1:
97
+ # Original implementation uses `round` which utilises bankers rounding, which can lead to surprising results
98
+ # Here we use floor to ensure the image is always smaller than the given "longest_edge"
99
+ height = int(math.floor(height / ratio))
100
+ width = int(math.floor(width / ratio))
101
+
102
+ num_height_tokens, num_width_tokens = _num_image_tokens((height, width), (patch_height, patch_width))
103
+ return num_height_tokens * patch_height, num_width_tokens * patch_width
104
+
105
+
106
+ @auto_docstring
107
+ class PixtralImageProcessorPil(PilBackend):
108
+ resample = PILImageResampling.BICUBIC
109
+ image_mean = [0.48145466, 0.4578275, 0.40821073]
110
+ image_std = [0.26862954, 0.26130258, 0.27577711]
111
+ patch_size = {"height": 16, "width": 16}
112
+ size = {"longest_edge": 1024}
113
+ default_to_square = True
114
+ do_resize = True
115
+ do_rescale = True
116
+ do_normalize = True
117
+ do_convert_rgb = True
118
+ valid_kwargs = PixtralImageProcessorKwargs
119
+
120
+ model_input_names = ["pixel_values", "image_sizes"]
121
+
122
+ def __init__(self, **kwargs: Unpack[PixtralImageProcessorKwargs]):
123
+ super().__init__(**kwargs)
124
+
125
+ @auto_docstring
126
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[PixtralImageProcessorKwargs]) -> BatchFeature:
127
+ return super().preprocess(images, **kwargs)
128
+
129
+ def resize(
130
+ self,
131
+ image: np.ndarray,
132
+ size: SizeDict,
133
+ patch_size: SizeDict,
134
+ resample: "PILImageResampling | None" = None,
135
+ **kwargs,
136
+ ) -> np.ndarray:
137
+ """
138
+ Resize an image. The longest edge is resized to size["longest_edge"], with aspect ratio preserved.
139
+ Output dimensions are aligned to patch_size.
140
+ """
141
+ if size.longest_edge:
142
+ size_tuple = (size.longest_edge, size.longest_edge)
143
+ elif size.height and size.width:
144
+ size_tuple = (size.height, size.width)
145
+ else:
146
+ raise ValueError("size must contain either 'longest_edge' or 'height' and 'width'.")
147
+
148
+ if patch_size.height and patch_size.width:
149
+ patch_size_tuple = (patch_size.height, patch_size.width)
150
+ else:
151
+ raise ValueError("patch_size must contain 'height' and 'width'.")
152
+
153
+ output_size = get_resize_output_image_size(
154
+ image, size=size_tuple, patch_size=patch_size_tuple, input_data_format=ChannelDimension.FIRST
155
+ )
156
+ return super().resize(
157
+ image, size=SizeDict(height=output_size[0], width=output_size[1]), resample=resample, **kwargs
158
+ )
159
+
160
+ def _pad_for_batching(
161
+ self,
162
+ pixel_values: list[np.ndarray],
163
+ image_sizes: list[tuple[int, int]],
164
+ ) -> np.ndarray:
165
+ """Pad images to form a batch of same shape."""
166
+ max_shape = (max(s[0] for s in image_sizes), max(s[1] for s in image_sizes))
167
+ padded = []
168
+ for img, size in zip(pixel_values, image_sizes):
169
+ pad_h = max_shape[0] - size[0]
170
+ pad_w = max_shape[1] - size[1]
171
+ padded_img = pad(
172
+ img,
173
+ padding=((0, pad_h), (0, pad_w)),
174
+ mode=PaddingMode.CONSTANT,
175
+ constant_values=0,
176
+ input_data_format=ChannelDimension.FIRST,
177
+ )
178
+ padded.append(padded_img)
179
+ return np.stack(padded)
180
+
181
+ def _preprocess(
182
+ self,
183
+ images: list[np.ndarray],
184
+ do_resize: bool,
185
+ size: SizeDict,
186
+ resample: "PILImageResampling | None",
187
+ do_center_crop: bool,
188
+ crop_size: SizeDict,
189
+ do_rescale: bool,
190
+ rescale_factor: float,
191
+ do_normalize: bool,
192
+ image_mean: float | list[float] | None,
193
+ image_std: float | list[float] | None,
194
+ return_tensors: str | TensorType | None,
195
+ patch_size: dict[str, int] | SizeDict | None = None,
196
+ **kwargs,
197
+ ) -> BatchFeature:
198
+ patch_size = get_size_dict(patch_size or self.patch_size, default_to_square=True)
199
+ patch_size_sd = SizeDict(**patch_size)
200
+
201
+ processed_images = []
202
+ batch_image_sizes = []
203
+
204
+ for image in images:
205
+ if do_resize:
206
+ image = self.resize(image, size=size, patch_size=patch_size_sd, resample=resample)
207
+ if do_center_crop:
208
+ image = self.center_crop(image, crop_size)
209
+ if do_rescale:
210
+ image = self.rescale(image, rescale_factor)
211
+ if do_normalize:
212
+ image = self.normalize(image, image_mean, image_std)
213
+
214
+ processed_images.append(image)
215
+ batch_image_sizes.append(get_image_size(image, channel_dim=ChannelDimension.FIRST))
216
+
217
+ padded_images = self._pad_for_batching(
218
+ pixel_values=processed_images,
219
+ image_sizes=batch_image_sizes,
220
+ )
221
+
222
+ return BatchFeature(
223
+ data={"pixel_values": padded_images, "image_sizes": batch_image_sizes}, tensor_type=return_tensors
224
+ )
225
+
226
+
227
+ __all__ = ["PixtralImageProcessorPil"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/image_processing_pixtral.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for Pixtral."""
15
+
16
+ import math
17
+
18
+ import torch
19
+ from torchvision.transforms.v2 import functional as tvF
20
+
21
+ from ...image_processing_backends import TorchvisionBackend
22
+ from ...image_processing_utils import BatchFeature, get_size_dict
23
+ from ...image_transforms import group_images_by_shape, reorder_images
24
+ from ...image_utils import ChannelDimension, ImageInput, PILImageResampling, SizeDict, get_image_size
25
+ from ...processing_utils import ImagesKwargs, Unpack
26
+ from ...utils import TensorType, auto_docstring
27
+
28
+
29
+ def _num_image_tokens(image_size: tuple[int, int], patch_size: tuple[int, int]) -> int:
30
+ """
31
+ Calculate the number of image tokens given the image size and patch size.
32
+
33
+ Args:
34
+ image_size (`tuple[int, int]`):
35
+ The size of the image as `(height, width)`.
36
+ patch_size (`tuple[int, int]`):
37
+ The patch size as `(height, width)`.
38
+
39
+ Returns:
40
+ `int`: The number of image tokens.
41
+ """
42
+ height, width = image_size
43
+ patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)
44
+ num_width_tokens = (width - 1) // patch_width + 1
45
+ num_height_tokens = (height - 1) // patch_height + 1
46
+ return num_height_tokens, num_width_tokens
47
+
48
+
49
+ def get_resize_output_image_size(
50
+ input_image: ImageInput,
51
+ size: int | tuple[int, int] | list[int] | tuple[int],
52
+ patch_size: int | tuple[int, int] | list[int] | tuple[int],
53
+ input_data_format: str | ChannelDimension | None = None,
54
+ ) -> tuple:
55
+ """
56
+ Find the target (height, width) dimension of the output image after resizing given the input image and the desired
57
+ size.
58
+
59
+ Args:
60
+ input_image (`ImageInput`):
61
+ The image to resize.
62
+ size (`int` or `tuple[int, int]`):
63
+ Max image size an input image can be. Must be a dictionary with the key "longest_edge".
64
+ patch_size (`int` or `tuple[int, int]`):
65
+ The patch_size as `(height, width)` to use for resizing the image. If patch_size is an integer, `(patch_size, patch_size)`
66
+ will be used
67
+ input_data_format (`ChannelDimension`, *optional*):
68
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
69
+
70
+ Returns:
71
+ `tuple`: The target (height, width) dimension of the output image after resizing.
72
+ """
73
+ max_height, max_width = size if isinstance(size, (tuple, list)) else (size, size)
74
+ patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)
75
+ height, width = get_image_size(input_image, input_data_format)
76
+
77
+ ratio = max(height / max_height, width / max_width)
78
+
79
+ if ratio > 1:
80
+ # Original implementation uses `round` which utilises bankers rounding, which can lead to surprising results
81
+ # Here we use floor to ensure the image is always smaller than the given "longest_edge"
82
+ height = int(math.floor(height / ratio))
83
+ width = int(math.floor(width / ratio))
84
+
85
+ num_height_tokens, num_width_tokens = _num_image_tokens((height, width), (patch_height, patch_width))
86
+ return num_height_tokens * patch_height, num_width_tokens * patch_width
87
+
88
+
89
+ class PixtralImageProcessorKwargs(ImagesKwargs, total=False):
90
+ """
91
+ patch_size (`Union[dict[str, int], int]` *optional*, defaults to `{"height": 16, "width": 16}`):
92
+ Size of the patches in the model, used to calculate the output image size.
93
+ """
94
+
95
+ patch_size: dict[str, int] | int
96
+
97
+
98
+ @auto_docstring
99
+ class PixtralImageProcessor(TorchvisionBackend):
100
+ resample = PILImageResampling.BICUBIC
101
+ image_mean = [0.48145466, 0.4578275, 0.40821073]
102
+ image_std = [0.26862954, 0.26130258, 0.27577711]
103
+ patch_size = {"height": 16, "width": 16}
104
+ size = {"longest_edge": 1024}
105
+ default_to_square = True
106
+ do_resize = True
107
+ do_rescale = True
108
+ do_normalize = True
109
+ do_convert_rgb = True
110
+ valid_kwargs = PixtralImageProcessorKwargs
111
+
112
+ model_input_names = ["pixel_values", "image_sizes"]
113
+
114
+ def __init__(self, **kwargs: Unpack[PixtralImageProcessorKwargs]):
115
+ super().__init__(**kwargs)
116
+
117
+ @auto_docstring
118
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[PixtralImageProcessorKwargs]) -> BatchFeature:
119
+ return super().preprocess(images, **kwargs)
120
+
121
+ def resize(
122
+ self,
123
+ image: "torch.Tensor",
124
+ size: SizeDict,
125
+ patch_size: SizeDict,
126
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
127
+ **kwargs,
128
+ ) -> "torch.Tensor":
129
+ """
130
+ Resize an image. The longest edge of the image is resized to size["longest_edge"], with the aspect ratio
131
+ preserved. Output dimensions are aligned to patch_size.
132
+
133
+ Args:
134
+ image (`torch.Tensor`):
135
+ Image to resize.
136
+ size (`SizeDict`):
137
+ Dict containing the longest possible edge of the image.
138
+ patch_size (`SizeDict`):
139
+ Patch size used to calculate the size of the output image.
140
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
141
+ Resampling filter to use when resizing the image.
142
+ """
143
+ if size.longest_edge:
144
+ size_tuple = (size.longest_edge, size.longest_edge)
145
+ elif size.height and size.width:
146
+ size_tuple = (size.height, size.width)
147
+ else:
148
+ raise ValueError("size must contain either 'longest_edge' or 'height' and 'width'.")
149
+
150
+ if patch_size.height and patch_size.width:
151
+ patch_size_tuple = (patch_size.height, patch_size.width)
152
+ else:
153
+ raise ValueError("patch_size must contain 'height' and 'width'.")
154
+
155
+ output_size = get_resize_output_image_size(image, size=size_tuple, patch_size=patch_size_tuple)
156
+ return super().resize(
157
+ image, size=SizeDict(height=output_size[0], width=output_size[1]), resample=resample, **kwargs
158
+ )
159
+
160
+ def _pad_for_batching(
161
+ self,
162
+ pixel_values: list["torch.Tensor"],
163
+ image_sizes: list[tuple[int, int]],
164
+ ) -> "torch.Tensor":
165
+ """
166
+ Pads images to form a batch of same shape.
167
+
168
+ Args:
169
+ pixel_values (`list[torch.Tensor]`):
170
+ A list of pixel values, each of shape (channels, height, width).
171
+ image_sizes (`list[tuple[int, int]]`):
172
+ A list of (height, width) for each image.
173
+
174
+ Returns:
175
+ `torch.Tensor`: Stacked and padded images.
176
+ """
177
+ max_shape = (max(s[0] for s in image_sizes), max(s[1] for s in image_sizes))
178
+ padded = [
179
+ torch.nn.functional.pad(img, pad=(0, max_shape[1] - size[1], 0, max_shape[0] - size[0]))
180
+ for img, size in zip(pixel_values, image_sizes)
181
+ ]
182
+ return torch.stack(padded)
183
+
184
+ def _preprocess(
185
+ self,
186
+ images: list["torch.Tensor"],
187
+ do_resize: bool,
188
+ size: SizeDict,
189
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
190
+ do_center_crop: bool,
191
+ crop_size: SizeDict,
192
+ do_rescale: bool,
193
+ rescale_factor: float,
194
+ do_normalize: bool,
195
+ image_mean: float | list[float] | None,
196
+ image_std: float | list[float] | None,
197
+ disable_grouping: bool | None,
198
+ return_tensors: str | TensorType | None,
199
+ patch_size: dict[str, int] | SizeDict | None = None,
200
+ **kwargs,
201
+ ) -> BatchFeature:
202
+ patch_size = get_size_dict(patch_size or self.patch_size, default_to_square=True)
203
+ patch_size_sd = SizeDict(**patch_size)
204
+
205
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
206
+ resized_images_grouped = {}
207
+ for shape, stacked_images in grouped_images.items():
208
+ if do_resize:
209
+ stacked_images = self.resize(
210
+ image=stacked_images, size=size, patch_size=patch_size_sd, resample=resample
211
+ )
212
+ resized_images_grouped[shape] = stacked_images
213
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
214
+
215
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
216
+ batch_image_sizes = [grouped_images_index[i][0] for i in range(len(grouped_images_index))]
217
+
218
+ processed_images_grouped = {}
219
+ for shape, stacked_images in grouped_images.items():
220
+ if do_center_crop:
221
+ stacked_images = self.center_crop(stacked_images, crop_size)
222
+ stacked_images = self.rescale_and_normalize(
223
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
224
+ )
225
+ processed_images_grouped[shape] = stacked_images
226
+
227
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
228
+ padded_images = self._pad_for_batching(
229
+ pixel_values=processed_images,
230
+ image_sizes=batch_image_sizes,
231
+ )
232
+
233
+ return BatchFeature(
234
+ data={"pixel_values": padded_images, "image_sizes": batch_image_sizes}, tensor_type=return_tensors
235
+ )
236
+
237
+
238
+ __all__ = ["PixtralImageProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/modeling_pixtral.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Mistral 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 Pixtral model."""
15
+
16
+ from collections.abc import Callable
17
+ from typing import Optional
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from ...activations import ACT2FN
23
+ from ...modeling_layers import GradientCheckpointingLayer
24
+ from ...modeling_outputs import BaseModelOutput
25
+ from ...modeling_rope_utils import dynamic_rope_update
26
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
27
+ from ...processing_utils import Unpack
28
+ from ...utils import TransformersKwargs, auto_docstring, logging
29
+ from ...utils.generic import is_flash_attention_requested, maybe_autocast, merge_with_config_defaults
30
+ from ...utils.output_capturing import capture_outputs
31
+ from .configuration_pixtral import PixtralVisionConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ def position_ids_in_meshgrid(patch_embeds_list, max_width):
38
+ positions = []
39
+ for patch in patch_embeds_list:
40
+ height, width = patch.shape[-2:]
41
+ mesh = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
42
+ h_grid, v_grid = torch.stack(mesh, dim=-1).reshape(-1, 2).chunk(2, -1)
43
+ ids = h_grid * max_width + v_grid
44
+ positions.append(ids[:, 0])
45
+ return torch.cat(positions)
46
+
47
+
48
+ class PixtralRotaryEmbedding(nn.Module):
49
+ """
50
+ The key with pixtral embedding is just that you have a frequency for each pixel positions.
51
+ If you have height x width pixels (or embedding pixels), then the frequency used for ROPE
52
+ is given by indexing the pre_computed frequency on the width and height.
53
+
54
+ What you output is of dimension (batch, height * width, dim) with dim the embed dim.
55
+
56
+ This simply means that for each image hidden state, you are going to add
57
+ a corresponding positional embedding, based on its index in the grid.
58
+ """
59
+
60
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
61
+
62
+ def __init__(self, config: PixtralVisionConfig, device=None, layer_type=None):
63
+ super().__init__()
64
+
65
+ self.config = config
66
+
67
+ self.rope_type = self.config.rope_parameters["rope_type"]
68
+ rope_init_fn: Callable = self.compute_default_rope_parameters
69
+ if self.rope_type != "default":
70
+ raise ValueError(
71
+ f"{self.__class__.__name__} does not support non-default RoPE, but got `rope_type={self.rope_type}`"
72
+ )
73
+
74
+ inv_freq, attention_scaling = rope_init_fn(self.config, device)
75
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
76
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
77
+
78
+ @staticmethod
79
+ def compute_default_rope_parameters(
80
+ config: PixtralVisionConfig | None = None,
81
+ device: Optional["torch.device"] = None,
82
+ seq_len: int | None = None,
83
+ ) -> tuple["torch.Tensor", float]:
84
+ """
85
+ Computes the inverse frequencies according to the original RoPE implementation
86
+ Args:
87
+ config ([`~transformers.PreTrainedConfig`]):
88
+ The model configuration.
89
+ device (`torch.device`):
90
+ The device to use for initialization of the inverse frequencies.
91
+ seq_len (`int`, *optional*):
92
+ The current sequence length. Unused for this type of RoPE.
93
+ Returns:
94
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
95
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
96
+ """
97
+ base = config.rope_parameters["rope_theta"]
98
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
99
+
100
+ attention_factor = 1.0 # Unused in this type of RoPE
101
+
102
+ # Here is the diff from Llama RoPE
103
+ max_patches_per_side = config.image_size // config.patch_size
104
+ h = torch.arange(max_patches_per_side)
105
+ w = torch.arange(max_patches_per_side)
106
+
107
+ freqs = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
108
+ freqs_h = torch.outer(h, freqs[::2]).float()
109
+ freqs_w = torch.outer(w, freqs[1::2]).float()
110
+ inv_freq = torch.cat(
111
+ [
112
+ freqs_h[:, None, :].repeat(1, max_patches_per_side, 1),
113
+ freqs_w[None, :, :].repeat(max_patches_per_side, 1, 1),
114
+ ],
115
+ dim=-1,
116
+ ).reshape(-1, dim // 2) # we reshape to only index on the position indexes, not tuple of indexes
117
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
118
+
119
+ # TODO maybe make it torch compatible later on. We can also just slice
120
+ inv_freq = torch.cat((inv_freq, inv_freq), dim=-1)
121
+ return inv_freq, attention_factor
122
+
123
+ @torch.no_grad()
124
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
125
+ def forward(self, x, position_ids):
126
+ freqs = self.inv_freq[position_ids]
127
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
128
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
129
+ emb = freqs
130
+ cos = emb.cos()
131
+ sin = emb.sin()
132
+
133
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
134
+
135
+
136
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
137
+ def rotate_half(x):
138
+ """Rotates half the hidden dims of the input."""
139
+ x1 = x[..., : x.shape[-1] // 2]
140
+ x2 = x[..., x.shape[-1] // 2 :]
141
+ return torch.cat((-x2, x1), dim=-1)
142
+
143
+
144
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
145
+ """Applies Rotary Position Embedding to the query and key tensors.
146
+
147
+ Args:
148
+ q (`torch.Tensor`): The query tensor.
149
+ k (`torch.Tensor`): The key tensor.
150
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
151
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
152
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
153
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
154
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
155
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
156
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
157
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
158
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
159
+ Returns:
160
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
161
+ """
162
+ cos = cos.unsqueeze(unsqueeze_dim)
163
+ sin = sin.unsqueeze(unsqueeze_dim)
164
+ q_embed = (q * cos) + (rotate_half(q) * sin)
165
+ k_embed = (k * cos) + (rotate_half(k) * sin)
166
+ return q_embed, k_embed
167
+
168
+
169
+ # Copied from transformers.models.siglip.modeling_siglip.eager_attention_forward
170
+ def eager_attention_forward(
171
+ module: nn.Module,
172
+ query: torch.Tensor,
173
+ key: torch.Tensor,
174
+ value: torch.Tensor,
175
+ attention_mask: torch.Tensor | None,
176
+ scaling: float,
177
+ dropout: float = 0.0,
178
+ **kwargs,
179
+ ):
180
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
181
+ if attention_mask is not None:
182
+ attn_weights = attn_weights + attention_mask
183
+
184
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
185
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
186
+
187
+ attn_output = torch.matmul(attn_weights, value)
188
+ attn_output = attn_output.transpose(1, 2).contiguous()
189
+
190
+ return attn_output, attn_weights
191
+
192
+
193
+ class PixtralAttention(nn.Module):
194
+ """
195
+ Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
196
+ """
197
+
198
+ def __init__(self, config):
199
+ super().__init__()
200
+ self.config = config
201
+ self.embed_dim = config.hidden_size
202
+ self.num_heads = config.num_attention_heads
203
+ self.head_dim = self.embed_dim // self.num_heads
204
+ self.is_causal = False
205
+
206
+ self.scaling = self.head_dim**-0.5
207
+ self.is_causal = False
208
+
209
+ self.dropout = config.attention_dropout
210
+
211
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
212
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
213
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
214
+ self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
215
+
216
+ def forward(
217
+ self,
218
+ hidden_states: torch.Tensor,
219
+ attention_mask: torch.Tensor | None = None,
220
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
221
+ **kwargs: Unpack[TransformersKwargs],
222
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
223
+ """Input shape: Batch x Time x Channel"""
224
+
225
+ batch_size, patches, _ = hidden_states.size()
226
+
227
+ query_states = self.q_proj(hidden_states)
228
+ key_states = self.k_proj(hidden_states)
229
+ value_states = self.v_proj(hidden_states)
230
+
231
+ query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
232
+ key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
233
+ value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
234
+
235
+ cos, sin = position_embeddings
236
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, unsqueeze_dim=0)
237
+
238
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
239
+ self.config._attn_implementation, eager_attention_forward
240
+ )
241
+
242
+ attn_output, attn_weights = attention_interface(
243
+ self,
244
+ query_states,
245
+ key_states,
246
+ value_states,
247
+ attention_mask,
248
+ dropout=0.0 if not self.training else self.dropout,
249
+ scaling=self.scaling,
250
+ **kwargs,
251
+ )
252
+
253
+ attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
254
+ attn_output = self.o_proj(attn_output)
255
+
256
+ return attn_output, attn_weights
257
+
258
+
259
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Pixtral
260
+ class PixtralMLP(nn.Module):
261
+ def __init__(self, config):
262
+ super().__init__()
263
+ self.config = config
264
+ self.hidden_size = config.hidden_size
265
+ self.intermediate_size = config.intermediate_size
266
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
267
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
268
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
269
+ self.act_fn = ACT2FN[config.hidden_act]
270
+
271
+ def forward(self, x):
272
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
273
+ return down_proj
274
+
275
+
276
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Pixtral
277
+ class PixtralRMSNorm(nn.Module):
278
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
279
+ """
280
+ PixtralRMSNorm is equivalent to T5LayerNorm
281
+ """
282
+ super().__init__()
283
+ self.weight = nn.Parameter(torch.ones(hidden_size))
284
+ self.variance_epsilon = eps
285
+
286
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
287
+ input_dtype = hidden_states.dtype
288
+ hidden_states = hidden_states.to(torch.float32)
289
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
290
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
291
+ return self.weight * hidden_states.to(input_dtype)
292
+
293
+ def extra_repr(self):
294
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
295
+
296
+
297
+ class PixtralAttentionLayer(GradientCheckpointingLayer):
298
+ def __init__(self, config):
299
+ super().__init__()
300
+ self.attention_norm = PixtralRMSNorm(config.hidden_size, eps=1e-5)
301
+ self.feed_forward = PixtralMLP(config)
302
+ self.attention = PixtralAttention(config)
303
+ self.ffn_norm = PixtralRMSNorm(config.hidden_size, eps=1e-5)
304
+
305
+ def forward(
306
+ self,
307
+ hidden_states: torch.Tensor,
308
+ attention_mask: torch.Tensor,
309
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
310
+ **kwargs: Unpack[TransformersKwargs],
311
+ ) -> torch.Tensor:
312
+ """
313
+ Args:
314
+ hidden_states (`torch.FloatTensor`):
315
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
316
+ attention_mask (`torch.FloatTensor`):
317
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
318
+ """
319
+ residual = hidden_states
320
+
321
+ hidden_states = self.attention_norm(hidden_states)
322
+ hidden_states, _ = self.attention(
323
+ hidden_states=hidden_states,
324
+ attention_mask=attention_mask,
325
+ position_embeddings=position_embeddings,
326
+ **kwargs,
327
+ )
328
+ hidden_states = residual + hidden_states
329
+
330
+ residual = hidden_states
331
+ hidden_states = self.ffn_norm(hidden_states)
332
+ hidden_states = self.feed_forward(hidden_states)
333
+ hidden_states = residual + hidden_states
334
+
335
+ return hidden_states
336
+
337
+
338
+ class PixtralTransformer(nn.Module):
339
+ def __init__(self, config):
340
+ super().__init__()
341
+ self.config = config
342
+ self.layers = torch.nn.ModuleList()
343
+ for _ in range(config.num_hidden_layers):
344
+ self.layers.append(PixtralAttentionLayer(config))
345
+ self.gradient_checkpointing = False
346
+
347
+ def forward(
348
+ self,
349
+ inputs_embeds,
350
+ attention_mask: torch.Tensor | None = None,
351
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
352
+ **kwargs: Unpack[TransformersKwargs],
353
+ ) -> tuple | BaseModelOutput:
354
+ r"""
355
+ Args:
356
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
357
+ Embeddings which serve as input to the Transformer.
358
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
359
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
360
+
361
+ - 1 for tokens that are **not masked**,
362
+ - 0 for tokens that are **masked**.
363
+
364
+ [What are attention masks?](../glossary#attention-mask)
365
+ """
366
+ hidden_states = inputs_embeds
367
+ for encoder_layer in self.layers:
368
+ hidden_states = encoder_layer(
369
+ hidden_states,
370
+ attention_mask,
371
+ position_embeddings=position_embeddings,
372
+ **kwargs,
373
+ )
374
+
375
+ return BaseModelOutput(last_hidden_state=hidden_states)
376
+
377
+
378
+ @auto_docstring
379
+ class PixtralPreTrainedModel(PreTrainedModel):
380
+ config: PixtralVisionConfig
381
+ base_model_prefix = "model"
382
+ main_input_name = "pixel_values"
383
+ input_modalities = ("image",)
384
+ supports_gradient_checkpointing = True
385
+ _supports_attention_backend = True
386
+ _supports_flash_attn = True
387
+ _supports_sdpa = True
388
+ _supports_flex_attn = True
389
+ _no_split_modules = ["PixtralAttentionLayer"]
390
+ _can_record_outputs = {
391
+ "hidden_states": PixtralAttentionLayer,
392
+ "attentions": PixtralAttention,
393
+ }
394
+
395
+
396
+ def generate_block_attention_mask(patch_embeds_list, tensor):
397
+ dtype = tensor.dtype
398
+ device = tensor.device
399
+ seq_len = tensor.shape[1]
400
+ d_min = torch.finfo(dtype).min
401
+ causal_mask = torch.full((seq_len, seq_len), fill_value=d_min, dtype=dtype, device=device)
402
+
403
+ block_end_idx = torch.tensor(patch_embeds_list).cumsum(-1)
404
+ block_start_idx = torch.tensor([0] + patch_embeds_list[:-1]).cumsum(-1)
405
+ for start, end in zip(block_start_idx, block_end_idx):
406
+ causal_mask[start:end, start:end] = 0
407
+
408
+ causal_mask = causal_mask[None, None, :, :].expand(tensor.shape[0], 1, -1, -1)
409
+ return causal_mask
410
+
411
+
412
+ @auto_docstring
413
+ class PixtralVisionModel(PixtralPreTrainedModel):
414
+ base_model_prefix = "vision_encoder"
415
+
416
+ def __init__(self, config):
417
+ super().__init__(config)
418
+ self.config = config
419
+ self.patch_conv = nn.Conv2d(
420
+ in_channels=config.num_channels,
421
+ out_channels=config.hidden_size,
422
+ kernel_size=config.patch_size,
423
+ stride=config.patch_size,
424
+ bias=False,
425
+ )
426
+ self.patch_size = config.patch_size
427
+ self.ln_pre = PixtralRMSNorm(config.hidden_size, eps=1e-5)
428
+ self.transformer = PixtralTransformer(config)
429
+ self.patch_positional_embedding = PixtralRotaryEmbedding(config)
430
+
431
+ self.post_init()
432
+
433
+ def get_input_embeddings(self):
434
+ return self.patch_conv
435
+
436
+ @merge_with_config_defaults
437
+ @capture_outputs
438
+ @auto_docstring
439
+ def forward(
440
+ self,
441
+ pixel_values: torch.Tensor,
442
+ image_sizes: torch.Tensor | None = None,
443
+ **kwargs: Unpack[TransformersKwargs],
444
+ ) -> tuple | BaseModelOutput:
445
+ if image_sizes is None:
446
+ batch_size, _, height, width = pixel_values.shape
447
+ image_sizes = [(height, width)] * batch_size
448
+
449
+ # pass images through initial convolution independently
450
+ target_dtype = self.patch_conv.weight.dtype
451
+ patch_embeds = self.patch_conv(pixel_values.to(dtype=target_dtype))
452
+ patch_embeds_list = [
453
+ embed[..., : (size[0] // self.patch_size), : (size[1] // self.patch_size)]
454
+ for embed, size in zip(patch_embeds, image_sizes)
455
+ ]
456
+
457
+ # flatten to a single sequence
458
+ patch_embeds = torch.cat([p.flatten(1).T for p in patch_embeds_list], dim=0).unsqueeze(0)
459
+ patch_embeds = self.ln_pre(patch_embeds)
460
+
461
+ # positional embeddings
462
+ position_ids = position_ids_in_meshgrid(
463
+ patch_embeds_list, max_width=self.config.image_size // self.config.patch_size
464
+ )
465
+ kwargs["position_ids"] = position_ids.unsqueeze(0).to(patch_embeds.device, non_blocking=True)
466
+
467
+ position_embeddings = self.patch_positional_embedding(patch_embeds, position_ids)
468
+
469
+ if is_flash_attention_requested(self.config):
470
+ # We only rely on position_ids when using flash attention
471
+ attention_mask = None
472
+ else:
473
+ attention_mask = generate_block_attention_mask(
474
+ [p.shape[-2] * p.shape[-1] for p in patch_embeds_list], patch_embeds
475
+ )
476
+
477
+ return self.transformer(
478
+ patch_embeds,
479
+ attention_mask=attention_mask,
480
+ position_embeddings=position_embeddings,
481
+ **kwargs,
482
+ )
483
+
484
+
485
+ __all__ = ["PixtralVisionModel", "PixtralPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pixtral/processing_pixtral.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+ """
15
+ Processor class for Pixtral.
16
+ """
17
+
18
+ import numpy as np
19
+
20
+ from ...feature_extraction_utils import BatchFeature
21
+ from ...image_utils import ImageInput, is_valid_image
22
+ from ...processing_utils import (
23
+ MultiModalData,
24
+ ProcessingKwargs,
25
+ ProcessorMixin,
26
+ Unpack,
27
+ )
28
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
29
+ from ...utils import auto_docstring, is_vision_available, logging
30
+ from ...utils.import_utils import requires
31
+
32
+
33
+ if is_vision_available():
34
+ from .image_processing_pixtral import get_resize_output_image_size
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ class PixtralProcessorKwargs(ProcessingKwargs, total=False):
41
+ _defaults = {
42
+ "text_kwargs": {
43
+ "padding": False,
44
+ "return_mm_token_type_ids": False,
45
+ },
46
+ "common_kwargs": {
47
+ "return_tensors": "pt",
48
+ },
49
+ }
50
+
51
+
52
+ # Copied from transformers.models.idefics2.processing_idefics2.is_url
53
+ def is_url(val) -> bool:
54
+ return isinstance(val, str) and val.startswith("http")
55
+
56
+
57
+ # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
58
+ def is_image_or_image_url(elem):
59
+ return is_url(elem) or is_valid_image(elem)
60
+
61
+
62
+ @auto_docstring
63
+ @requires(backends=("torchvision", "torch"))
64
+ class PixtralProcessor(ProcessorMixin):
65
+ def __init__(
66
+ self,
67
+ image_processor=None,
68
+ tokenizer=None,
69
+ patch_size: int = 16,
70
+ spatial_merge_size: int = 1,
71
+ chat_template=None,
72
+ image_token="[IMG]", # set the default and let users change if they have peculiar special tokens in rare cases
73
+ image_break_token="[IMG_BREAK]",
74
+ image_end_token="[IMG_END]",
75
+ **kwargs,
76
+ ):
77
+ r"""
78
+ patch_size (`int`, *optional*, defaults to 16):
79
+ Patch size from the vision tower.
80
+ spatial_merge_size (`int`, *optional*, defaults to 1):
81
+ The downsampling factor for the spatial merge operation.
82
+ image_token (`str`, *optional*, defaults to `"[IMG]"`):
83
+ Special token used to denote image location.
84
+ image_break_token (`str`, *optional*, defaults to `"[IMG_BREAK]"`):
85
+ Special token used to denote the end of a line of pixels in an image.
86
+ image_end_token (`str`, *optional*, defaults to `"[IMG_END]"`):
87
+ Special token used to denote the end of an image input.
88
+ """
89
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
90
+
91
+ self.patch_size = patch_size
92
+ self.spatial_merge_size = spatial_merge_size
93
+ self.image_token = image_token
94
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
95
+ self.image_break_token = image_break_token
96
+ self.image_end_token = image_end_token
97
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
98
+ self.image_break_token_id = tokenizer.convert_tokens_to_ids(self.image_break_token)
99
+ self.image_end_token_id = tokenizer.convert_tokens_to_ids(self.image_end_token)
100
+ self.image_ids = [self.image_token_id, self.image_break_token_id, self.image_end_token_id]
101
+
102
+ @auto_docstring
103
+ def __call__(
104
+ self,
105
+ images: ImageInput | None = None,
106
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
107
+ **kwargs: Unpack[PixtralProcessorKwargs],
108
+ ) -> BatchFeature:
109
+ r"""
110
+ Returns:
111
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
112
+
113
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
114
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
115
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
116
+ `None`).
117
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
118
+ """
119
+
120
+ output_kwargs = self._merge_kwargs(
121
+ PixtralProcessorKwargs,
122
+ tokenizer_init_kwargs=getattr(self.tokenizer, "init_kwargs", {}),
123
+ **kwargs,
124
+ )
125
+
126
+ patch_size = self.patch_size * self.spatial_merge_size
127
+
128
+ if images is not None:
129
+ output_kwargs["images_kwargs"]["patch_size"] = patch_size
130
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
131
+ else:
132
+ image_inputs = {}
133
+
134
+ if isinstance(text, str):
135
+ text = [text]
136
+ elif not isinstance(text, list) and not isinstance(text[0], str):
137
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
138
+
139
+ # try to expand inputs in processing if we have the necessary parts
140
+ prompt_strings = text
141
+ if image_inputs.get("pixel_values") is not None:
142
+ # Replace the image token with the expanded image token sequence
143
+ image_sizes = iter(image_inputs["image_sizes"])
144
+ prompt_strings = []
145
+ replace_strings = []
146
+
147
+ for sample in text:
148
+ while self.image_token in sample:
149
+ height, width = next(image_sizes)
150
+ num_height_tokens = height // patch_size
151
+ num_width_tokens = width // patch_size
152
+ replace_tokens = [
153
+ [self.image_token] * num_width_tokens + [self.image_break_token]
154
+ ] * num_height_tokens
155
+ # Flatten list
156
+ replace_tokens = [item for sublist in replace_tokens for item in sublist]
157
+ replace_tokens[-1] = self.image_end_token
158
+ replace_str = "".join(replace_tokens)
159
+ replace_strings.append(replace_str)
160
+ sample = sample.replace(self.image_token, "<placeholder>", 1)
161
+
162
+ while "<placeholder>" in sample:
163
+ replace_str = replace_strings.pop(0)
164
+ sample = sample.replace("<placeholder>", replace_str, 1)
165
+ prompt_strings.append(sample)
166
+
167
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
168
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
169
+ # Remove return_token_type_ids as MistralCommonBackend doesn't support it
170
+ output_kwargs["text_kwargs"].pop("return_token_type_ids", None)
171
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
172
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
173
+
174
+ if return_mm_token_type_ids:
175
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
176
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
177
+
178
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
179
+ """
180
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
181
+
182
+ Args:
183
+ image_sizes (`list[list[int]]`, *optional*):
184
+ The input sizes formatted as (height, width) per each image.
185
+
186
+ Returns:
187
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
188
+ input modalities, along with other useful data.
189
+ """
190
+ vision_data = {}
191
+ if image_sizes is not None:
192
+ images_kwargs = PixtralProcessorKwargs._defaults.get("images_kwargs", {})
193
+ images_kwargs.update(kwargs)
194
+
195
+ size = images_kwargs.get("size", None) or self.image_processor.size
196
+ patch_size = self.patch_size * self.spatial_merge_size
197
+
198
+ num_image_tokens = []
199
+ for height, width in image_sizes:
200
+ resized_height, resized_width = get_resize_output_image_size(
201
+ np.zeros((height, width, 3)),
202
+ size=(size["longest_edge"], size["longest_edge"]),
203
+ patch_size=(patch_size, patch_size),
204
+ )
205
+ num_height_tokens = resized_height // patch_size
206
+ num_width_tokens = resized_width // patch_size
207
+ num_image_tokens.append((num_width_tokens + 1) * num_height_tokens)
208
+
209
+ num_image_patches = [1] * len(image_sizes)
210
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
211
+
212
+ return MultiModalData(**vision_data)
213
+
214
+ @property
215
+ def model_input_names(self):
216
+ tokenizer_input_names = self.tokenizer.model_input_names
217
+ image_processor_input_names = self.image_processor.model_input_names
218
+ return tokenizer_input_names + image_processor_input_names + ["image_sizes"]
219
+
220
+
221
+ __all__ = ["PixtralProcessor"]