JinghuiLuAstronaut commited on
Commit
48de36d
·
verified ·
1 Parent(s): f93e57c

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_0008000_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_0040000_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_0071000_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_0081000_logistic_normal_t1p45.log +76 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bark/__init__.py +28 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bark/generation_configuration_bark.py +327 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bark/modeling_bark.py +1518 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/image_processing_blip.py +34 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/processing_blip.py +84 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/eurobert/__init__.py +27 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/eurobert/modeling_eurobert.py +628 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/__init__.py +28 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/configuration_granite4_vision.py +186 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/modeling_granite4_vision.py +1218 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/modular_granite4_vision.py +757 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/processing_granite4_vision.py +237 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/modeling_qwen2_audio.py +806 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/processing_qwen2_audio.py +207 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/__init__.py +27 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_lm1b_lr3e3_nobottleneck_step97k_decode32_64_ema_noselfcond_20260613_223157.log +53 -0
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0008000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-22_22:34:37 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0008000.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_0008000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0008000.pt
3
+ [ckpt] step=8000
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_0008000.pt",
24
+ "step": 8000,
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": 37.02064133179811,
48
+ "nll_per_token": 3.6114756309228495,
49
+ "tokens": 36709,
50
+ "kept_samples": 256,
51
+ "total_samples": 256,
52
+ "empty_rate": 0.0,
53
+ "skipped_samples": 0
54
+ },
55
+ "stripped_genppl": {
56
+ "ppl": 49.5216309317561,
57
+ "nll_per_token": 3.902409562643293,
58
+ "tokens": 30968,
59
+ "kept_samples": 256,
60
+ "total_samples": 256,
61
+ "empty_rate": 0.0,
62
+ "skipped_samples": 0
63
+ },
64
+ "diversity": {
65
+ "sample_entropy": 3.727034386542326,
66
+ "unique_tokens": 1653,
67
+ "token_count": 32768,
68
+ "distinct_1": 0.050445556640625,
69
+ "distinct_2": 0.26707062007874016,
70
+ "top_token_mass": 0.078277587890625
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_0008000/sde_steps128_samples256_scored.jsonl
74
+ [watch-lognormal-sde] 2026-05-22_22:36:33 done step_0008000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0040000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_02:17:27 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0040000.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_0040000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0040000.pt
3
+ [ckpt] step=40000
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_0040000.pt",
24
+ "step": 40000,
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.34375971937911,
50
+ "nll_per_token": 3.4764211034022403,
51
+ "tokens": 33590,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 40.21259734585419,
59
+ "nll_per_token": 3.694180313348144,
60
+ "tokens": 28555,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.1724020457759075,
68
+ "unique_tokens": 1925,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.058746337890625,
71
+ "distinct_2": 0.2673781988188976,
72
+ "top_token_mass": 0.18597412109375
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_0040000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_02:18:55 done step_0040000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0071000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_05:10:35 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0071000.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_0071000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0071000.pt
3
+ [ckpt] step=71000
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_0071000.pt",
24
+ "step": 71000,
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.14794011174908,
50
+ "nll_per_token": 3.5009805762924247,
51
+ "tokens": 35887,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 45.12346979096357,
59
+ "nll_per_token": 3.809402505628512,
60
+ "tokens": 29898,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.5528679606178764,
68
+ "unique_tokens": 2391,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.072967529296875,
71
+ "distinct_2": 0.34944020669291337,
72
+ "top_token_mass": 0.1053466796875
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_0071000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_05:12:03 done step_0071000
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0081000_logistic_normal_t1p45.log ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [watch-lognormal-sde] 2026-05-23_06:05:50 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0081000.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_0081000
2
+ [load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0081000.pt
3
+ [ckpt] step=81000
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_0081000.pt",
24
+ "step": 81000,
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.614198924855497,
50
+ "nll_per_token": 3.453606352738042,
51
+ "tokens": 36858,
52
+ "kept_samples": 256,
53
+ "total_samples": 256,
54
+ "empty_rate": 0.0,
55
+ "skipped_samples": 0
56
+ },
57
+ "stripped_genppl": {
58
+ "ppl": 42.97372468761239,
59
+ "nll_per_token": 3.7605888751476595,
60
+ "tokens": 30793,
61
+ "kept_samples": 256,
62
+ "total_samples": 256,
63
+ "empty_rate": 0.0,
64
+ "skipped_samples": 0
65
+ },
66
+ "diversity": {
67
+ "sample_entropy": 3.769408234203504,
68
+ "unique_tokens": 2064,
69
+ "token_count": 32768,
70
+ "distinct_1": 0.06298828125,
71
+ "distinct_2": 0.33077017716535434,
72
+ "top_token_mass": 0.077545166015625
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_0081000/sde_steps128_samples256_scored.jsonl
76
+ [watch-lognormal-sde] 2026-05-23_06:07:17 done step_0081000
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bark/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_bark import *
22
+ from .modeling_bark import *
23
+ from .processing_bark import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bark/generation_configuration_bark.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """BARK model generation configuration"""
15
+
16
+ import copy
17
+
18
+ from ...generation.configuration_utils import GenerationConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class BarkSemanticGenerationConfig(GenerationConfig):
26
+ model_type = "semantic"
27
+
28
+ def __init__(
29
+ self,
30
+ eos_token_id=10_000,
31
+ renormalize_logits=True,
32
+ max_new_tokens=768,
33
+ output_scores=False,
34
+ return_dict_in_generate=False,
35
+ output_hidden_states=False,
36
+ output_attentions=False,
37
+ temperature=1.0,
38
+ do_sample=False,
39
+ text_encoding_offset=10_048,
40
+ text_pad_token=129_595,
41
+ semantic_infer_token=129_599,
42
+ semantic_vocab_size=10_000,
43
+ max_input_semantic_length=256,
44
+ semantic_rate_hz=49.9,
45
+ min_eos_p=None,
46
+ **kwargs,
47
+ ):
48
+ """Class that holds a generation configuration for [`BarkSemanticModel`].
49
+
50
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
51
+ documentation from [`GenerationConfig`] for more information.
52
+
53
+ Args:
54
+ eos_token_id (`int`, *optional*, defaults to 10_000):
55
+ The id of the *end-of-sequence* token.
56
+ renormalize_logits (`bool`, *optional*, defaults to `True`):
57
+ Whether to renormalize the logits after applying all the logits processors (including the
58
+ custom ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the
59
+ score logits are normalized but some logit processors break the normalization.
60
+ max_new_tokens (`int`, *optional*, defaults to 768):
61
+ The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
62
+ output_scores (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
64
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
65
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
66
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
67
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
68
+ for more details.
69
+ output_attentions (`bool`, *optional*, defaults to `False`):
70
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
71
+ returned tensors for more details.
72
+ temperature (`float`, *optional*, defaults to 1.0):
73
+ The value used to modulate the next token probabilities.
74
+ do_sample (`bool`, *optional*, defaults to `False`):
75
+ Whether or not to use sampling ; use greedy decoding otherwise.
76
+ text_encoding_offset (`int`, *optional*, defaults to 10_048):
77
+ Text encoding offset.
78
+ text_pad_token (`int`, *optional*, defaults to 129_595):
79
+ Text pad token.
80
+ semantic_infer_token (`int`, *optional*, defaults to 129_599):
81
+ Semantic infer token.
82
+ semantic_vocab_size (`int`, *optional*, defaults to 10_000):
83
+ Semantic vocab size.
84
+ max_input_semantic_length (`int`, *optional*, defaults to 256):
85
+ Max length of semantic input vector.
86
+ semantic_rate_hz (`float`, *optional*, defaults to 49.9):
87
+ Semantic rate in Hertz.
88
+ min_eos_p (`float`, *optional*):
89
+ Minimum threshold of the probability of the EOS token for it to be sampled. This is an early stopping
90
+ strategy to mitigate potential unwanted generations at the end of a prompt. The original implementation
91
+ suggests a default value of 0.2.
92
+ """
93
+ super().__init__(
94
+ temperature=temperature,
95
+ do_sample=do_sample,
96
+ eos_token_id=eos_token_id,
97
+ renormalize_logits=renormalize_logits,
98
+ max_new_tokens=max_new_tokens,
99
+ output_scores=output_scores,
100
+ return_dict_in_generate=return_dict_in_generate,
101
+ output_hidden_states=output_hidden_states,
102
+ output_attentions=output_attentions,
103
+ **kwargs,
104
+ )
105
+
106
+ self.text_encoding_offset = text_encoding_offset
107
+ self.text_pad_token = text_pad_token
108
+ self.semantic_pad_token = eos_token_id
109
+ self.semantic_infer_token = semantic_infer_token
110
+ self.semantic_vocab_size = semantic_vocab_size
111
+ self.max_input_semantic_length = max_input_semantic_length
112
+ self.semantic_rate_hz = semantic_rate_hz
113
+ self.min_eos_p = min_eos_p
114
+
115
+
116
+ class BarkCoarseGenerationConfig(GenerationConfig):
117
+ model_type = "coarse_acoustics"
118
+
119
+ def __init__(
120
+ self,
121
+ renormalize_logits=True,
122
+ output_scores=False,
123
+ return_dict_in_generate=False,
124
+ output_hidden_states=False,
125
+ output_attentions=False,
126
+ temperature=1.0,
127
+ do_sample=False,
128
+ coarse_semantic_pad_token=12_048,
129
+ coarse_rate_hz=75,
130
+ n_coarse_codebooks=2,
131
+ coarse_infer_token=12_050,
132
+ max_coarse_input_length=256,
133
+ max_coarse_history: int = 630,
134
+ sliding_window_len: int = 60,
135
+ **kwargs,
136
+ ):
137
+ """Class that holds a generation configuration for [`BarkCoarseModel`].
138
+
139
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
140
+ documentation from [`GenerationConfig`] for more information.
141
+
142
+ Args:
143
+ renormalize_logits (`bool`, *optional*, defaults to `True`):
144
+ Whether to renormalize the logits after applying all the logits processors (including the
145
+ custom ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the
146
+ score logits are normalized but some logit processors break the normalization.
147
+ output_scores (`bool`, *optional*, defaults to `False`):
148
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
149
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
150
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
151
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
152
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
153
+ for more details.
154
+ output_attentions (`bool`, *optional*, defaults to `False`):
155
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
156
+ returned tensors for more details.
157
+ temperature (`float`, *optional*, defaults to 1.0):
158
+ The value used to modulate the next token probabilities.
159
+ do_sample (`bool`, *optional*, defaults to `False`):
160
+ Whether or not to use sampling ; use greedy decoding otherwise.
161
+ coarse_semantic_pad_token (`int`, *optional*, defaults to 12_048):
162
+ Coarse semantic pad token.
163
+ coarse_rate_hz (`int`, *optional*, defaults to 75):
164
+ Coarse rate in Hertz.
165
+ n_coarse_codebooks (`int`, *optional*, defaults to 2):
166
+ Number of coarse codebooks.
167
+ coarse_infer_token (`int`, *optional*, defaults to 12_050):
168
+ Coarse infer token.
169
+ max_coarse_input_length (`int`, *optional*, defaults to 256):
170
+ Max length of input coarse vector.
171
+ max_coarse_history (`int`, *optional*, defaults to 630):
172
+ Max length of the output of the coarse acoustics model used in the fine generation step.
173
+ sliding_window_len (`int`, *optional*, defaults to 60):
174
+ The coarse generation step uses a sliding window to generate raw audio.
175
+ """
176
+ super().__init__(
177
+ temperature=temperature,
178
+ do_sample=do_sample,
179
+ renormalize_logits=renormalize_logits,
180
+ output_scores=output_scores,
181
+ return_dict_in_generate=return_dict_in_generate,
182
+ output_hidden_states=output_hidden_states,
183
+ output_attentions=output_attentions,
184
+ **kwargs,
185
+ )
186
+
187
+ self.coarse_semantic_pad_token = coarse_semantic_pad_token
188
+ self.coarse_rate_hz = coarse_rate_hz
189
+ self.n_coarse_codebooks = n_coarse_codebooks
190
+ self.coarse_infer_token = coarse_infer_token
191
+ self.max_coarse_input_length = max_coarse_input_length
192
+ self.max_coarse_history = max_coarse_history
193
+ self.sliding_window_len = sliding_window_len
194
+
195
+
196
+ class BarkFineGenerationConfig(GenerationConfig):
197
+ model_type = "fine_acoustics"
198
+
199
+ def __init__(
200
+ self,
201
+ temperature=1.0,
202
+ max_fine_history_length=512,
203
+ max_fine_input_length=1024,
204
+ n_fine_codebooks=8,
205
+ **kwargs,
206
+ ):
207
+ """Class that holds a generation configuration for [`BarkFineModel`].
208
+
209
+ [`BarkFineModel`] is an autoencoder model, so should not usually be used for generation. However, under the
210
+ hood, it uses `temperature` when used by [`BarkModel`]
211
+
212
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
213
+ documentation from [`GenerationConfig`] for more information.
214
+
215
+ Args:
216
+ temperature (`float`, *optional*):
217
+ The value used to modulate the next token probabilities.
218
+ max_fine_history_length (`int`, *optional*, defaults to 512):
219
+ Max length of the fine history vector.
220
+ max_fine_input_length (`int`, *optional*, defaults to 1024):
221
+ Max length of fine input vector.
222
+ n_fine_codebooks (`int`, *optional*, defaults to 8):
223
+ Number of codebooks used.
224
+ """
225
+ super().__init__(temperature=temperature)
226
+
227
+ self.max_fine_history_length = max_fine_history_length
228
+ self.max_fine_input_length = max_fine_input_length
229
+ self.n_fine_codebooks = n_fine_codebooks
230
+
231
+ def validate(self, **kwargs):
232
+ """
233
+ Overrides GenerationConfig.validate because BarkFineGenerationConfig don't use any parameters outside
234
+ temperature.
235
+ """
236
+
237
+
238
+ class BarkGenerationConfig(GenerationConfig):
239
+ model_type = "bark"
240
+
241
+ # TODO (joao): nested from_dict
242
+
243
+ def __init__(
244
+ self,
245
+ semantic_config: dict | None = None,
246
+ coarse_acoustics_config: dict | None = None,
247
+ fine_acoustics_config: dict | None = None,
248
+ sample_rate=24_000,
249
+ codebook_size=1024,
250
+ **kwargs,
251
+ ):
252
+ """Class that holds a generation configuration for [`BarkModel`].
253
+
254
+ The [`BarkModel`] does not have a `generate` method, but uses this class to generate speeches with a nested
255
+ [`BarkGenerationConfig`] which uses [`BarkSemanticGenerationConfig`], [`BarkCoarseGenerationConfig`],
256
+ [`BarkFineGenerationConfig`].
257
+
258
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
259
+ documentation from [`GenerationConfig`] for more information.
260
+
261
+ Args:
262
+ semantic_config (`Dict`, *optional*):
263
+ Semantic generation configuration.
264
+ coarse_acoustics_config (`Dict`, *optional*):
265
+ Coarse generation configuration.
266
+ fine_acoustics_config (`Dict`, *optional*):
267
+ Fine generation configuration.
268
+ sample_rate (`int`, *optional*, defaults to 24_000):
269
+ Sample rate.
270
+ codebook_size (`int`, *optional*, defaults to 1024):
271
+ Vector length for each codebook.
272
+ """
273
+ if semantic_config is None:
274
+ semantic_config = {}
275
+ logger.info("semantic_config is None. initializing the semantic model with default values.")
276
+
277
+ if coarse_acoustics_config is None:
278
+ coarse_acoustics_config = {}
279
+ logger.info("coarse_acoustics_config is None. initializing the coarse model with default values.")
280
+
281
+ if fine_acoustics_config is None:
282
+ fine_acoustics_config = {}
283
+ logger.info("fine_acoustics_config is None. initializing the fine model with default values.")
284
+
285
+ self.semantic_config = BarkSemanticGenerationConfig(**semantic_config)
286
+ self.coarse_acoustics_config = BarkCoarseGenerationConfig(**coarse_acoustics_config)
287
+ self.fine_acoustics_config = BarkFineGenerationConfig(**fine_acoustics_config)
288
+
289
+ self.sample_rate = sample_rate
290
+ self.codebook_size = codebook_size
291
+
292
+ @classmethod
293
+ def from_sub_model_configs(
294
+ cls,
295
+ semantic_config: BarkSemanticGenerationConfig,
296
+ coarse_acoustics_config: BarkCoarseGenerationConfig,
297
+ fine_acoustics_config: BarkFineGenerationConfig,
298
+ **kwargs,
299
+ ):
300
+ r"""
301
+ Instantiate a [`BarkGenerationConfig`] (or a derived class) from bark sub-models generation configuration.
302
+
303
+ Returns:
304
+ [`BarkGenerationConfig`]: An instance of a configuration object
305
+ """
306
+ return cls(
307
+ semantic_config=semantic_config.to_dict(),
308
+ coarse_acoustics_config=coarse_acoustics_config.to_dict(),
309
+ fine_acoustics_config=fine_acoustics_config.to_dict(),
310
+ **kwargs,
311
+ )
312
+
313
+ def to_dict(self):
314
+ """
315
+ Serializes this instance to a Python dictionary. Override the default [`~PreTrainedConfig.to_dict`].
316
+
317
+ Returns:
318
+ `dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
319
+ """
320
+ output = copy.deepcopy(self.__dict__)
321
+
322
+ output["semantic_config"] = self.semantic_config.to_dict()
323
+ output["coarse_acoustics_config"] = self.coarse_acoustics_config.to_dict()
324
+ output["fine_acoustics_config"] = self.fine_acoustics_config.to_dict()
325
+
326
+ output["model_type"] = self.__class__.model_type
327
+ return output
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bark/modeling_bark.py ADDED
@@ -0,0 +1,1518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch BARK model."""
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn import functional as F
22
+
23
+ from ... import initialization as init
24
+ from ...cache_utils import Cache, DynamicCache
25
+ from ...generation import GenerationMixin
26
+ from ...generation.logits_process import (
27
+ AlternatingCodebooksLogitsProcessor,
28
+ BarkEosPrioritizerLogitsProcessor,
29
+ SuppressTokensLogitsProcessor,
30
+ )
31
+ from ...masking_utils import create_bidirectional_mask
32
+ from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import CausalLMOutputWithPast, MaskedLMOutput
35
+ from ...modeling_utils import PreTrainedModel
36
+ from ...utils import (
37
+ auto_docstring,
38
+ is_accelerate_available,
39
+ is_torch_accelerator_available,
40
+ logging,
41
+ )
42
+ from ..auto import AutoModel
43
+ from .configuration_bark import (
44
+ BarkCoarseConfig,
45
+ BarkConfig,
46
+ BarkFineConfig,
47
+ BarkSemanticConfig,
48
+ BarkSubModelConfig,
49
+ )
50
+ from .generation_configuration_bark import (
51
+ BarkCoarseGenerationConfig,
52
+ BarkFineGenerationConfig,
53
+ BarkSemanticGenerationConfig,
54
+ )
55
+
56
+
57
+ if is_flash_attn_available():
58
+ from ...integrations.flash_attention import get_target_dtype
59
+ from ...modeling_flash_attention_utils import _flash_attention_forward
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+
65
+ class BarkSelfAttention(nn.Module):
66
+ # adapted from GPTNeoSelfAttention and Bark code
67
+ # BarkSelfAttention can have two attention type, i.e full attention or causal attention
68
+
69
+ def __init__(self, config, is_causal=False, layer_idx=None):
70
+ super().__init__()
71
+
72
+ # regularization
73
+ self.dropout = config.dropout
74
+ self.attn_dropout = nn.Dropout(config.dropout)
75
+ self.resid_dropout = nn.Dropout(config.dropout)
76
+
77
+ self.embed_dim = config.hidden_size
78
+ self.num_heads = config.num_heads
79
+ self.head_dim = self.embed_dim // self.num_heads
80
+ self.config = config
81
+
82
+ if config.hidden_size % config.num_heads != 0:
83
+ raise ValueError(
84
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
85
+ f" {self.num_heads})."
86
+ )
87
+
88
+ # key, query, value projections for all heads, but in a batch
89
+ self.att_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=config.bias)
90
+ # output projection
91
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.bias)
92
+
93
+ self.is_causal = is_causal
94
+ self.layer_idx = layer_idx
95
+ if is_causal:
96
+ block_size = config.block_size
97
+ bias = torch.tril(torch.ones((block_size, block_size), dtype=bool)).view(1, 1, block_size, block_size)
98
+ self.register_buffer("bias", bias)
99
+
100
+ # Copied from transformers.models.gpt_neo.modeling_gpt_neo.GPTNeoSelfAttention._split_heads
101
+ def _split_heads(self, tensor, num_heads, attn_head_size):
102
+ """
103
+ Splits hidden_size dim into attn_head_size and num_heads
104
+ """
105
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
106
+ tensor = tensor.view(new_shape)
107
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
108
+
109
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
110
+ """
111
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
112
+ """
113
+
114
+ # re-assemble all head outputs side by side
115
+ # (batch, num_heads, seq_len, attn_head_size) -> (batch, seq_len, num_heads*attn_head_size)
116
+ tensor = tensor.transpose(1, 2).contiguous()
117
+ tensor = tensor.view(tensor.size()[:-2] + (num_heads * attn_head_size,))
118
+
119
+ return tensor
120
+
121
+ def _attn(self, query, key, value, attention_mask=None):
122
+ # unlike GPTNeo's SelfAttention, divide by the square root of the dimension of the query and the key
123
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * (1.0 / math.sqrt(self.head_dim))
124
+
125
+ if self.is_causal:
126
+ query_length, key_length = query.size(-2), key.size(-2)
127
+
128
+ # fill the upper left part of the attention weights with inf
129
+ attn_weights = attn_weights.masked_fill(
130
+ self.bias[:, :, key_length - query_length : key_length, :key_length] == 0,
131
+ torch.finfo(attn_weights.dtype).min,
132
+ )
133
+
134
+ if attention_mask is not None:
135
+ # Apply the attention mask
136
+ attn_weights = attn_weights + attention_mask
137
+
138
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
139
+ attn_weights = attn_weights.to(value.dtype)
140
+ attn_weights = self.attn_dropout(attn_weights)
141
+
142
+ # (batch, num_heads, seq_len, seq_len) x (batch, num_heads, seq_len, attn_head_size)
143
+ # -> (batch, num_heads, seq_len, attn_head_size)
144
+ attn_output = torch.matmul(attn_weights, value)
145
+
146
+ return attn_output, attn_weights
147
+
148
+ def forward(
149
+ self,
150
+ hidden_states,
151
+ attention_mask=None,
152
+ past_key_values=None,
153
+ use_cache=False,
154
+ output_attentions=False,
155
+ **kwargs,
156
+ ):
157
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
158
+ query, key, value = self.att_proj(hidden_states).split(self.embed_dim, dim=2)
159
+
160
+ query = self._split_heads(query, self.num_heads, self.head_dim)
161
+ key = self._split_heads(key, self.num_heads, self.head_dim)
162
+ value = self._split_heads(value, self.num_heads, self.head_dim)
163
+
164
+ if past_key_values is not None:
165
+ key, value = past_key_values.update(key, value, self.layer_idx)
166
+
167
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask)
168
+
169
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
170
+ attn_output = self.out_proj(attn_output)
171
+ attn_output = self.resid_dropout(attn_output)
172
+
173
+ return attn_output, attn_weights
174
+
175
+
176
+ class BarkSelfFlashAttention2(BarkSelfAttention):
177
+ """
178
+ Bark flash attention module. This module inherits from `BarkSelfAttention` as the weights of the module stays
179
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
180
+ flash attention and deal with padding tokens in case the input contains any of them.
181
+ """
182
+
183
+ def __init__(self, *args, **kwargs):
184
+ super().__init__(*args, **kwargs)
185
+
186
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
187
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
188
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
189
+ self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
190
+
191
+ def _split_heads(self, tensor, num_heads, attn_head_size):
192
+ """
193
+ Splits hidden_size dim into attn_head_size and num_heads
194
+ """
195
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
196
+ tensor = tensor.view(new_shape)
197
+ # Flash attention requires the input to have the shape
198
+ # batch_size x seq_length x head_dim x hidden_dim - (batch, seq_length, head, head_features)
199
+ return tensor
200
+
201
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
202
+ """
203
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
204
+ """
205
+ # re-assemble all head outputs side by side
206
+ # (batch, seq_len, num_heads, attn_head_size) -> (batch, seq_len, num_heads*attn_head_size)
207
+ tensor = tensor.view(tensor.size()[:-2] + (num_heads * attn_head_size,))
208
+ return tensor
209
+
210
+ def forward(
211
+ self,
212
+ hidden_states,
213
+ attention_mask=None,
214
+ past_key_values=None,
215
+ use_cache=False,
216
+ output_attentions=False,
217
+ **kwargs,
218
+ ):
219
+ batch_size, query_len, _ = hidden_states.size()
220
+
221
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
222
+ query, key, value = self.att_proj(hidden_states).split(self.embed_dim, dim=2)
223
+
224
+ query = self._split_heads(query, self.num_heads, self.head_dim)
225
+ key = self._split_heads(key, self.num_heads, self.head_dim)
226
+ value = self._split_heads(value, self.num_heads, self.head_dim)
227
+
228
+ if past_key_values is not None:
229
+ key, value = past_key_values.update(key, value, self.layer_idx)
230
+
231
+ target_dtype = get_target_dtype(query, self) # if the query is in float32, this is the dtype to cast to for FA
232
+
233
+ attn_output = _flash_attention_forward(
234
+ query,
235
+ key,
236
+ value,
237
+ attention_mask,
238
+ query_len,
239
+ dropout=self.dropout if self.training else 0.0,
240
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
241
+ is_causal=self.is_causal,
242
+ target_dtype=target_dtype,
243
+ )
244
+
245
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
246
+ attn_output = self.out_proj(attn_output)
247
+ attn_output = self.resid_dropout(attn_output)
248
+
249
+ return attn_output, None
250
+
251
+
252
+ BARK_ATTENTION_CLASSES = {
253
+ "eager": BarkSelfAttention,
254
+ "flash_attention_2": BarkSelfFlashAttention2,
255
+ }
256
+
257
+
258
+ class BarkMLP(nn.Module):
259
+ def __init__(self, config):
260
+ super().__init__()
261
+ self.in_proj = nn.Linear(config.hidden_size, 4 * config.hidden_size, bias=config.bias)
262
+ self.out_proj = nn.Linear(4 * config.hidden_size, config.hidden_size, bias=config.bias)
263
+ self.dropout = nn.Dropout(config.dropout)
264
+ self.gelu = nn.GELU()
265
+
266
+ def forward(self, hidden_states):
267
+ hidden_states = self.in_proj(hidden_states)
268
+ hidden_states = self.gelu(hidden_states)
269
+ hidden_states = self.out_proj(hidden_states)
270
+ hidden_states = self.dropout(hidden_states)
271
+ return hidden_states
272
+
273
+
274
+ class BarkBlock(GradientCheckpointingLayer):
275
+ def __init__(self, config, is_causal=False, layer_idx=None):
276
+ super().__init__()
277
+
278
+ if is_causal:
279
+ # if causal, the layerNorm bias is optional to stick with Bark choice of leaving optional bias
280
+ # in AutoRegressive models (corresponding to the "Text" and the "Coarse" modules)
281
+ self.layernorm_1 = nn.LayerNorm(config.hidden_size, bias=config.bias)
282
+ self.layernorm_2 = nn.LayerNorm(config.hidden_size, bias=config.bias)
283
+ else:
284
+ self.layernorm_1 = nn.LayerNorm(config.hidden_size)
285
+ self.layernorm_2 = nn.LayerNorm(config.hidden_size)
286
+
287
+ self.attn = BARK_ATTENTION_CLASSES[config._attn_implementation](
288
+ config, is_causal=is_causal, layer_idx=layer_idx
289
+ )
290
+
291
+ self.mlp = BarkMLP(config)
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states,
296
+ past_key_values=None,
297
+ attention_mask=None,
298
+ use_cache=False,
299
+ output_attentions=False,
300
+ **kwargs,
301
+ ):
302
+ intermediary_hidden_states = self.layernorm_1(hidden_states)
303
+
304
+ attn_outputs = self.attn(
305
+ intermediary_hidden_states,
306
+ past_key_values=past_key_values,
307
+ attention_mask=attention_mask,
308
+ use_cache=use_cache,
309
+ output_attentions=output_attentions,
310
+ )
311
+
312
+ attn_output = attn_outputs[0] # output_attn: output, present_key_values, (attn_weights)
313
+ outputs = attn_outputs[1:]
314
+
315
+ intermediary_hidden_states = hidden_states + attn_output
316
+ intermediary_hidden_states = intermediary_hidden_states + self.mlp(
317
+ self.layernorm_2(intermediary_hidden_states)
318
+ )
319
+
320
+ return (intermediary_hidden_states,) + outputs
321
+
322
+
323
+ @auto_docstring
324
+ class BarkPreTrainedModel(PreTrainedModel):
325
+ config: BarkConfig
326
+ supports_gradient_checkpointing = False
327
+ _supports_flash_attn = True
328
+
329
+ @property
330
+ def device(self) -> torch.device:
331
+ """
332
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
333
+ device).
334
+ """
335
+
336
+ # if has _hf_hook, has been offloaded so the device has to be found in the hook
337
+ if not hasattr(self, "_hf_hook"):
338
+ return super().device
339
+ for module in self.modules():
340
+ if (
341
+ hasattr(module, "_hf_hook")
342
+ and hasattr(module._hf_hook, "execution_device")
343
+ and module._hf_hook.execution_device is not None
344
+ ):
345
+ return torch.device(module._hf_hook.execution_device)
346
+
347
+ return super().device
348
+
349
+ def _init_weights(self, module):
350
+ super()._init_weights(module)
351
+ if isinstance(module, BarkSelfAttention):
352
+ if module.is_causal:
353
+ block_size = module.config.block_size
354
+ bias = torch.tril(torch.ones((block_size, block_size), dtype=bool)).view(1, 1, block_size, block_size)
355
+ init.copy_(module.bias, bias)
356
+
357
+
358
+ # GPT2-like autoregressive model
359
+ class BarkCausalModel(BarkPreTrainedModel, GenerationMixin):
360
+ config: BarkSubModelConfig
361
+ output_modalities = ("audio",)
362
+
363
+ def __init__(self, config):
364
+ super().__init__(config)
365
+ self.config = config
366
+
367
+ # initialize as an autoregressive GPT-like model
368
+ self.input_embeds_layer = nn.Embedding(config.input_vocab_size, config.hidden_size)
369
+ self.position_embeds_layer = nn.Embedding(config.block_size, config.hidden_size)
370
+
371
+ self.drop = nn.Dropout(config.dropout)
372
+
373
+ self.layers = nn.ModuleList([BarkBlock(config, is_causal=True, layer_idx=i) for i in range(config.num_layers)])
374
+
375
+ self.layernorm_final = nn.LayerNorm(config.hidden_size, bias=config.bias)
376
+
377
+ self.lm_head = nn.Linear(config.hidden_size, config.output_vocab_size, bias=False)
378
+ self.gradient_checkpointing = False
379
+
380
+ # Initialize weights and apply final processing
381
+ self.post_init()
382
+
383
+ def get_output_embeddings(self):
384
+ # NOTE: get_output_embeddings() must return None to prevent accidental weight tying.
385
+ # See e.g. https://github.com/huggingface/transformers/pull/39339#discussion_r2219126400
386
+ return None
387
+
388
+ def get_input_embeddings(self):
389
+ return self.input_embeds_layer
390
+
391
+ def set_input_embeddings(self, new_embeddings):
392
+ self.input_embeds_layer = new_embeddings
393
+
394
+ @auto_docstring
395
+ def forward(
396
+ self,
397
+ input_ids: torch.Tensor | None = None,
398
+ past_key_values: Cache | None = None,
399
+ attention_mask: torch.Tensor | None = None,
400
+ position_ids: torch.Tensor | None = None,
401
+ labels: torch.LongTensor | None = None,
402
+ inputs_embeds: torch.Tensor | None = None,
403
+ use_cache: bool | None = None,
404
+ output_attentions: bool | None = None,
405
+ output_hidden_states: bool | None = None,
406
+ return_dict: bool | None = None,
407
+ **kwargs,
408
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithPast:
409
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
410
+ output_hidden_states = (
411
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
412
+ )
413
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
414
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
415
+
416
+ loss = None
417
+ if labels is not None:
418
+ raise NotImplementedError(
419
+ "Training is not implemented yet for Bark - ensure you do not pass `labels` to the model."
420
+ )
421
+
422
+ # Verify if inputs_embeds already exists
423
+ # then compute embeddings.
424
+ if input_ids is not None and inputs_embeds is not None:
425
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
426
+ elif inputs_embeds is not None and past_key_values is None:
427
+ # we want to return the inputs_embeds in priority so that it is in line with a weird hack
428
+ # of Bark which concatenate two bits of the inputs_embeds on the first forward pass of the semantic model
429
+ pass
430
+ elif input_ids is not None:
431
+ inputs_embeds = self.input_embeds_layer(input_ids) # token embeddings of shape (b, t, n_embd)
432
+ elif inputs_embeds is not None:
433
+ pass
434
+ else:
435
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
436
+
437
+ input_shape = inputs_embeds.size()[:-1]
438
+ seq_length = input_shape[-1]
439
+
440
+ if self.gradient_checkpointing and self.training:
441
+ if use_cache:
442
+ logger.warning_once(
443
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
444
+ )
445
+ use_cache = False
446
+
447
+ if use_cache and past_key_values is None:
448
+ past_key_values = DynamicCache(config=self.config)
449
+
450
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
451
+ inputs_embeds = inputs_embeds.to(self.position_embeds_layer.weight.device)
452
+
453
+ if position_ids is None:
454
+ position_ids = torch.arange(
455
+ past_length,
456
+ seq_length + past_length,
457
+ dtype=torch.long,
458
+ device=self.position_embeds_layer.weight.device,
459
+ )
460
+ position_ids = position_ids.unsqueeze(0) # shape (1, seq_length)
461
+
462
+ position_ids = position_ids.to(self.position_embeds_layer.weight.device)
463
+ position_embeds = self.position_embeds_layer(position_ids) # position embeddings of shape (1, t, n_embd)
464
+
465
+ attention_mask = create_bidirectional_mask(
466
+ config=self.config,
467
+ inputs_embeds=inputs_embeds,
468
+ attention_mask=attention_mask,
469
+ )
470
+
471
+ hidden_states = self.drop(inputs_embeds + position_embeds)
472
+ output_shape = input_shape + (hidden_states.size(-1),)
473
+
474
+ all_self_attentions = () if output_attentions else None
475
+ all_hidden_states = () if output_hidden_states else None
476
+
477
+ for i, block in enumerate(self.layers):
478
+ if output_hidden_states:
479
+ all_hidden_states = all_hidden_states + (hidden_states,)
480
+
481
+ outputs = block(
482
+ hidden_states,
483
+ past_key_values=past_key_values,
484
+ attention_mask=attention_mask,
485
+ use_cache=use_cache,
486
+ output_attentions=output_attentions,
487
+ )
488
+
489
+ hidden_states = outputs[0]
490
+
491
+ if output_attentions:
492
+ all_self_attentions = all_self_attentions + (outputs[1],)
493
+
494
+ hidden_states = self.layernorm_final(hidden_states)
495
+
496
+ hidden_states = hidden_states.view(output_shape)
497
+
498
+ # Add last hidden state
499
+ if output_hidden_states:
500
+ all_hidden_states = all_hidden_states + (hidden_states,)
501
+
502
+ logits = self.lm_head(hidden_states)
503
+
504
+ if not return_dict:
505
+ return tuple(
506
+ v for v in [None, logits, past_key_values, all_hidden_states, all_self_attentions] if v is not None
507
+ )
508
+
509
+ return CausalLMOutputWithPast(
510
+ loss=loss,
511
+ logits=logits,
512
+ past_key_values=past_key_values,
513
+ hidden_states=all_hidden_states,
514
+ attentions=all_self_attentions,
515
+ )
516
+
517
+
518
+ @auto_docstring(
519
+ custom_intro="""
520
+ Bark semantic (or text) model. It shares the same architecture as the coarse model.
521
+ It is a GPT-2 like autoregressive model with a language modeling head on top.
522
+ """
523
+ )
524
+ class BarkSemanticModel(BarkCausalModel):
525
+ base_model_prefix = "semantic"
526
+ config: BarkSemanticConfig
527
+
528
+ def generate(
529
+ self,
530
+ input_ids: torch.Tensor,
531
+ semantic_generation_config: BarkSemanticGenerationConfig | None = None,
532
+ history_prompt: dict[str, torch.Tensor] | None = None,
533
+ attention_mask: torch.Tensor | None = None,
534
+ **kwargs,
535
+ ) -> torch.LongTensor:
536
+ """
537
+ Generates text semantic tokens from an input prompt and an additional optional `Bark` speaker prompt.
538
+
539
+ Args:
540
+ input_ids (`Optional[torch.Tensor]` of shape (batch_size, seq_len), *optional*):
541
+ Input ids, i.e tokenized input sentences. Will be truncated up to
542
+ semantic_generation_config.max_input_semantic_length tokens. Note that the output audios will be as
543
+ long as the longest generation among the batch.
544
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
545
+ Generation config indicating how to generate the semantic tokens.
546
+ history_prompt (`Optional[dict[str,torch.Tensor]]`, *optional*):
547
+ Optional `Bark` speaker prompt.
548
+ attention_mask (`Optional[torch.Tensor]`, *optional*):
549
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
550
+
551
+ - 1 for tokens that are **not masked**,
552
+ - 0 for tokens that are **masked**.
553
+
554
+ [What are attention masks?](../glossary#attention-mask)
555
+ Returns:
556
+ torch.LongTensor: Output semantic tokens.
557
+ """
558
+ if semantic_generation_config is None:
559
+ raise ValueError("`semantic_generation_config` has to be provided")
560
+
561
+ batch_size = input_ids.shape[0]
562
+
563
+ max_input_semantic_length = semantic_generation_config.max_input_semantic_length
564
+
565
+ input_ids = input_ids + semantic_generation_config.text_encoding_offset
566
+
567
+ if attention_mask is not None:
568
+ input_ids = input_ids.masked_fill((1 - attention_mask).bool(), semantic_generation_config.text_pad_token)
569
+
570
+ if history_prompt is not None:
571
+ semantic_history = history_prompt["semantic_prompt"][-max_input_semantic_length:]
572
+ semantic_history = nn.functional.pad(
573
+ semantic_history,
574
+ (0, max_input_semantic_length - len(semantic_history)),
575
+ value=semantic_generation_config.semantic_pad_token,
576
+ mode="constant",
577
+ )
578
+ else:
579
+ semantic_history = torch.full(
580
+ (max_input_semantic_length,),
581
+ semantic_generation_config.semantic_pad_token,
582
+ device=self.device,
583
+ dtype=torch.int,
584
+ )
585
+
586
+ semantic_history = torch.repeat_interleave(semantic_history[None], batch_size, dim=0)
587
+
588
+ infer_array = torch.tensor(
589
+ [[semantic_generation_config.semantic_infer_token]] * batch_size, dtype=torch.int
590
+ ).to(self.device)
591
+
592
+ inputs_embeds = torch.cat(
593
+ [
594
+ self.input_embeds_layer(input_ids[:, :max_input_semantic_length])
595
+ + self.input_embeds_layer(semantic_history[:, : max_input_semantic_length + 1]),
596
+ self.input_embeds_layer(infer_array),
597
+ ],
598
+ dim=1,
599
+ )
600
+
601
+ tokens_to_suppress = list(
602
+ range(semantic_generation_config.semantic_vocab_size, semantic_generation_config.semantic_pad_token)
603
+ )
604
+ tokens_to_suppress.extend(
605
+ list(range(semantic_generation_config.semantic_pad_token + 1, self.config.output_vocab_size))
606
+ )
607
+
608
+ suppress_tokens_logits_processor = SuppressTokensLogitsProcessor(tokens_to_suppress, device=input_ids.device)
609
+
610
+ min_eos_p = kwargs.get("min_eos_p", semantic_generation_config.min_eos_p)
611
+ early_stopping_logits_processor = BarkEosPrioritizerLogitsProcessor(
612
+ eos_token_id=semantic_generation_config.eos_token_id, min_eos_p=min_eos_p, device=input_ids.device
613
+ )
614
+
615
+ # pass input_ids in order to stay consistent with the transformers generate method even though it is not used
616
+ # (except to get the input seq_len - that's why we keep the first 257 tokens)
617
+ semantic_output = super().generate(
618
+ torch.ones((batch_size, max_input_semantic_length + 1), dtype=torch.int, device=self.device),
619
+ inputs_embeds=inputs_embeds,
620
+ logits_processor=[suppress_tokens_logits_processor, early_stopping_logits_processor],
621
+ generation_config=semantic_generation_config,
622
+ **kwargs,
623
+ ) # size: 10048
624
+
625
+ # take the generated semantic tokens
626
+ if kwargs.get("return_dict_in_generate", False):
627
+ semantic_output = semantic_output.sequences[:, max_input_semantic_length + 1 :]
628
+ else:
629
+ semantic_output = semantic_output[:, max_input_semantic_length + 1 :]
630
+ return semantic_output
631
+
632
+
633
+ @auto_docstring(
634
+ custom_intro="""
635
+ Bark coarse acoustics model.
636
+ It shares the same architecture as the semantic (or text) model. It is a GPT-2 like autoregressive model with a
637
+ language modeling head on top.
638
+ """
639
+ )
640
+ class BarkCoarseModel(BarkCausalModel):
641
+ base_model_prefix = "coarse_acoustics"
642
+ config: BarkCoarseConfig
643
+
644
+ def preprocess_histories(
645
+ self,
646
+ max_coarse_history: int,
647
+ semantic_to_coarse_ratio: int,
648
+ batch_size: int,
649
+ semantic_generation_config: int,
650
+ codebook_size: int,
651
+ history_prompt: dict[str, torch.Tensor] | None = None,
652
+ ):
653
+ """
654
+ Preprocess the optional `Bark` speaker prompts before `self.generate`.
655
+
656
+ Args:
657
+ max_coarse_history (`int`):
658
+ Maximum size of coarse tokens used.
659
+ semantic_to_coarse_ratio (`int`):
660
+ Ratio of semantic to coarse frequency
661
+ batch_size (`int`):
662
+ Batch size, i.e the number of samples.
663
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
664
+ Generation config indicating how to generate the semantic tokens.
665
+ codebook_size (`int`):
666
+ Codebook channel size, i.e. the size of the output vocabulary per codebook channel.
667
+ history_prompt (`Optional[dict[str,torch.Tensor]]`):
668
+ Optional `Bark` speaker prompt.
669
+ Returns: Returns:
670
+ `tuple(torch.FloatTensor)`:
671
+ - **x_semantic_history** (`torch.FloatTensor` -- Processed semantic speaker prompt.
672
+ - **x_coarse_history** (`torch.FloatTensor`) -- Processed coarse speaker prompt.
673
+ """
674
+ if history_prompt is not None:
675
+ x_semantic_history = torch.repeat_interleave(history_prompt["semantic_prompt"][None], batch_size, dim=0)
676
+ # clone to avoid modifying history_prompt.coarse_prompt
677
+ x_coarse_history = history_prompt["coarse_prompt"].clone()
678
+
679
+ # offset x_coarse_history
680
+ if codebook_size is not None:
681
+ for n in range(1, x_coarse_history.shape[0]):
682
+ # offset
683
+ x_coarse_history[n, :] += codebook_size * n
684
+
685
+ # flatten x_coarse_history
686
+ x_coarse_history = torch.transpose(x_coarse_history, 0, 1).reshape(-1)
687
+
688
+ x_coarse_history = x_coarse_history + semantic_generation_config.semantic_vocab_size
689
+
690
+ x_coarse_history = torch.repeat_interleave(x_coarse_history[None], batch_size, dim=0)
691
+ # e.g: after SEMANTIC_VOCAB_SIZE (10000), 1024 tokens dedicated to first codebook, 1024 next tokens
692
+ # dedicated to second codebook.
693
+
694
+ max_semantic_history = int(np.floor(max_coarse_history / semantic_to_coarse_ratio))
695
+ # trim histories correctly
696
+ n_semantic_hist_provided = min(
697
+ [
698
+ max_semantic_history,
699
+ x_semantic_history.shape[1] - x_semantic_history.shape[1] % 2,
700
+ int(np.floor(x_coarse_history.shape[1] / semantic_to_coarse_ratio)),
701
+ ]
702
+ )
703
+
704
+ n_coarse_hist_provided = int(round(n_semantic_hist_provided * semantic_to_coarse_ratio))
705
+
706
+ x_semantic_history = x_semantic_history[:, -n_semantic_hist_provided:].int()
707
+ x_coarse_history = x_coarse_history[:, -n_coarse_hist_provided:].int()
708
+ # bit of a hack for time alignment (sounds better) - from Bark original implementation
709
+ x_coarse_history = x_coarse_history[:, :-2]
710
+
711
+ else:
712
+ # shape: (batch_size, 0)
713
+ x_semantic_history = torch.tensor([[]] * batch_size, dtype=torch.int, device=self.device)
714
+ x_coarse_history = torch.tensor([[]] * batch_size, dtype=torch.int, device=self.device)
715
+
716
+ return x_semantic_history, x_coarse_history
717
+
718
+ def generate(
719
+ self,
720
+ semantic_output: torch.Tensor,
721
+ semantic_generation_config: BarkSemanticGenerationConfig | None = None,
722
+ coarse_generation_config: BarkCoarseGenerationConfig | None = None,
723
+ codebook_size: int = 1024,
724
+ history_prompt: dict[str, torch.Tensor] | None = None,
725
+ return_output_lengths: bool | None = None,
726
+ **kwargs,
727
+ ) -> torch.LongTensor | tuple[torch.LongTensor, torch.LongTensor]:
728
+ """
729
+ Generates coarse acoustics tokens from input text semantic tokens and an additional optional `Bark` speaker
730
+ prompt.
731
+
732
+ Args:
733
+ semantic_output (`torch.Tensor` of shape (batch_size, seq_len), *optional*):
734
+ Input text semantic ids, i.e the output of `BarkSemanticModel.generate`.
735
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
736
+ Generation config indicating how to generate the semantic tokens.
737
+ coarse_generation_config (`BarkCoarseGenerationConfig`):
738
+ Generation config indicating how to generate the coarse tokens.
739
+ codebook_size (`int`, *optional*, defaults to 1024):
740
+ Codebook channel size, i.e. the size of the output vocabulary per codebook channel.
741
+ history_prompt (`Optional[dict[str,torch.Tensor]]`, *optional*):
742
+ Optional `Bark` speaker prompt.
743
+ return_output_lengths (`bool`, *optional*):
744
+ Whether or not to return the output lengths. Useful when batching.
745
+ Returns:
746
+ By default:
747
+ torch.LongTensor: Output coarse acoustics tokens.
748
+ If `return_output_lengths=True`:
749
+ `Tuple(torch.Tensor, torch.Tensor): The output coarse acoustics tokens, and the length of each sample
750
+ of the batch.
751
+ """
752
+
753
+ if semantic_generation_config is None:
754
+ raise ValueError("`semantic_generation_config` has to be provided")
755
+
756
+ if coarse_generation_config is None:
757
+ raise ValueError("`coarse_generation_config` has to be provided")
758
+
759
+ max_coarse_input_length = coarse_generation_config.max_coarse_input_length
760
+ max_coarse_history = coarse_generation_config.max_coarse_history
761
+ sliding_window_len = coarse_generation_config.sliding_window_len
762
+
763
+ # replace semantic_pad_token (eos_tok and pad_tok here) with coarse_semantic_pad_token i.e the pad_token
764
+ # used in the next model
765
+ semantic_output.masked_fill_(
766
+ semantic_output == semantic_generation_config.semantic_pad_token,
767
+ coarse_generation_config.coarse_semantic_pad_token,
768
+ )
769
+
770
+ semantic_to_coarse_ratio = (
771
+ coarse_generation_config.coarse_rate_hz
772
+ / semantic_generation_config.semantic_rate_hz
773
+ * coarse_generation_config.n_coarse_codebooks
774
+ )
775
+ max_semantic_history = int(np.floor(max_coarse_history / semantic_to_coarse_ratio))
776
+
777
+ output_lengths = (semantic_output != coarse_generation_config.coarse_semantic_pad_token).sum(1)
778
+ output_lengths = torch.floor(
779
+ output_lengths * semantic_to_coarse_ratio / coarse_generation_config.n_coarse_codebooks
780
+ )
781
+ output_lengths = torch.round(output_lengths * coarse_generation_config.n_coarse_codebooks).int()
782
+
783
+ max_generated_len = torch.max(output_lengths).item()
784
+
785
+ batch_size = semantic_output.shape[0]
786
+
787
+ x_semantic_history, x_coarse = self.preprocess_histories(
788
+ history_prompt=history_prompt,
789
+ max_coarse_history=max_coarse_history,
790
+ semantic_to_coarse_ratio=semantic_to_coarse_ratio,
791
+ batch_size=batch_size,
792
+ semantic_generation_config=semantic_generation_config,
793
+ codebook_size=codebook_size,
794
+ )
795
+ base_semantic_idx = x_semantic_history.shape[1]
796
+
797
+ semantic_output = torch.hstack([x_semantic_history, semantic_output])
798
+
799
+ n_window_steps = int(np.ceil(max_generated_len / sliding_window_len))
800
+
801
+ total_generated_len = 0
802
+
803
+ len_coarse_history = x_coarse.shape[1]
804
+
805
+ for _ in range(n_window_steps):
806
+ semantic_idx = base_semantic_idx + int(round(total_generated_len / semantic_to_coarse_ratio))
807
+
808
+ # pad from right side
809
+ input_coarse = semantic_output[:, np.max([0, semantic_idx - max_semantic_history]) :]
810
+ input_coarse = input_coarse[:, :max_coarse_input_length]
811
+ input_coarse = F.pad(
812
+ input_coarse,
813
+ (0, max_coarse_input_length - input_coarse.shape[-1]),
814
+ "constant",
815
+ coarse_generation_config.coarse_semantic_pad_token,
816
+ )
817
+
818
+ input_coarse = torch.hstack(
819
+ [
820
+ input_coarse,
821
+ torch.tensor([[coarse_generation_config.coarse_infer_token]] * batch_size, device=self.device),
822
+ x_coarse[:, -max_coarse_history:],
823
+ ]
824
+ )
825
+
826
+ alternatingLogitsProcessor = AlternatingCodebooksLogitsProcessor(
827
+ input_coarse.shape[1],
828
+ semantic_generation_config.semantic_vocab_size,
829
+ codebook_size,
830
+ )
831
+
832
+ output_coarse = super().generate(
833
+ input_coarse,
834
+ logits_processor=[alternatingLogitsProcessor],
835
+ max_new_tokens=min(sliding_window_len, max_generated_len - total_generated_len),
836
+ generation_config=coarse_generation_config,
837
+ **kwargs,
838
+ )
839
+
840
+ input_coarse_len = input_coarse.shape[1]
841
+
842
+ if kwargs.get("return_dict_in_generate", False):
843
+ x_coarse = torch.hstack([x_coarse, output_coarse.sequences[:, input_coarse_len:]])
844
+ else:
845
+ x_coarse = torch.hstack([x_coarse, output_coarse[:, input_coarse_len:]])
846
+ total_generated_len = x_coarse.shape[1] - len_coarse_history
847
+
848
+ del output_coarse
849
+
850
+ coarse_output = x_coarse[:, len_coarse_history:]
851
+
852
+ if return_output_lengths:
853
+ return coarse_output, output_lengths
854
+
855
+ return coarse_output
856
+
857
+
858
+ @auto_docstring(
859
+ custom_intro="""
860
+ Bark fine acoustics model. It is a non-causal GPT-like model with `config.n_codes_total` embedding layers and
861
+ language modeling heads, one for each codebook.
862
+ """
863
+ )
864
+ class BarkFineModel(BarkPreTrainedModel):
865
+ base_model_prefix = "fine_acoustics"
866
+ config: BarkFineConfig
867
+ main_input_name = "codebook_idx"
868
+
869
+ def __init__(self, config):
870
+ # non-causal gpt-like model with one embedding layer and one lm_head for each codebook of Encodec
871
+ super().__init__(config)
872
+ self.config = config
873
+ self._tied_weights_keys = {}
874
+ for i in range(self.config.n_codes_total - self.config.n_codes_given):
875
+ self._tied_weights_keys[f"lm_heads.{i}.weight"] = f"input_embeds_layers.{i + 1}.weight"
876
+
877
+ # initialize a modified non causal GPT-like model
878
+ # note that for there is one embedding layer and one lm_head for each codebook of Encodec
879
+ self.input_embeds_layers = nn.ModuleList(
880
+ [nn.Embedding(config.input_vocab_size, config.hidden_size) for _ in range(config.n_codes_total)]
881
+ )
882
+ self.position_embeds_layer = nn.Embedding(config.block_size, config.hidden_size)
883
+
884
+ self.drop = nn.Dropout(config.dropout)
885
+
886
+ self.layers = nn.ModuleList(
887
+ [BarkBlock(config, is_causal=False, layer_idx=i) for i in range(config.num_layers)]
888
+ )
889
+
890
+ self.layernorm_final = nn.LayerNorm(config.hidden_size)
891
+
892
+ self.lm_heads = nn.ModuleList(
893
+ [
894
+ nn.Linear(config.hidden_size, config.output_vocab_size, bias=False)
895
+ for _ in range(config.n_codes_given, config.n_codes_total)
896
+ ]
897
+ )
898
+ self.gradient_checkpointing = False
899
+ self.n_codes_total = config.n_codes_total
900
+
901
+ # Initialize weights and apply final processing
902
+ self.post_init()
903
+
904
+ def get_input_embeddings(self):
905
+ # one embedding layers for each codebook
906
+ return self.input_embeds_layers
907
+
908
+ def set_input_embeddings(self, new_embeddings):
909
+ # one embedding layers for each codebook
910
+ self.input_embeds_layers = new_embeddings
911
+
912
+ def get_output_embeddings(self):
913
+ # one lm_head for each codebook
914
+ return self.lm_heads
915
+
916
+ def set_output_embeddings(self, new_output_embeddings):
917
+ # one lm_head for each codebook
918
+ self.lm_heads = new_output_embeddings
919
+
920
+ def _resize_token_embeddings(self, new_num_tokens, pad_to_multiple_of=None, mean_resizing=True):
921
+ old_embeddings_list = self.get_input_embeddings()
922
+ new_embeddings_list = nn.ModuleList(
923
+ [
924
+ self._get_resized_embeddings(old_embeddings, new_num_tokens, pad_to_multiple_of, mean_resizing)
925
+ for old_embeddings in old_embeddings_list
926
+ ]
927
+ )
928
+ self.set_input_embeddings(new_embeddings_list)
929
+ new_num_tokens = new_embeddings_list[0].weight.shape[0]
930
+
931
+ # if word embeddings are not tied, make sure that lm head is resized as well
932
+ if self.get_output_embeddings() is not None and not self.config.tie_word_embeddings:
933
+ old_lm_head_list = self.get_output_embeddings()
934
+ new_lm_head_list = nn.ModuleList(
935
+ [self._get_resized_lm_head(old_lm_head, new_num_tokens) for old_lm_head in old_lm_head_list]
936
+ )
937
+ self.set_output_embeddings(new_lm_head_list)
938
+
939
+ return self.get_input_embeddings()
940
+
941
+ def resize_token_embeddings(
942
+ self,
943
+ new_num_tokens: int | None = None,
944
+ pad_to_multiple_of: int | None = None,
945
+ mean_resizing: bool = True,
946
+ ) -> nn.Embedding:
947
+ """
948
+ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`.
949
+
950
+ Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method.
951
+
952
+ Arguments:
953
+ new_num_tokens (`int`, *optional*):
954
+ The number of new tokens in the embedding matrix. Increasing the size will add newly initialized
955
+ vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just
956
+ returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything.
957
+ pad_to_multiple_of (`int`, *optional*):
958
+ If set will pad the embedding matrix to a multiple of the provided value.
959
+
960
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
961
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more
962
+ details about this, or help on choosing the correct value for resizing, refer to this guide:
963
+ https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc
964
+ mean_resizing (`bool`):
965
+ Whether to initialize the added embeddings from a multivariate normal distribution that has old embeddings' mean and
966
+ covariance or to initialize them with a normal distribution that has a mean of zero and std equals `config.initializer_range`.
967
+
968
+ Setting `mean_resizing` to `True` is useful when increasing the size of the embeddings of causal language models,
969
+ where the generated tokens' probabilities won't be affected by the added embeddings because initializing the new embeddings with the
970
+ old embeddings' mean will reduce the kl-divergence between the next token probability before and after adding the new embeddings.
971
+ Refer to this article for more information: https://nlp.stanford.edu/~johnhew/vocab-expansion.html
972
+
973
+ Return:
974
+ `torch.nn.Embedding`: Pointer to the input tokens Embeddings Module of the model.
975
+ """
976
+ model_embeds = self._resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
977
+ if new_num_tokens is None and pad_to_multiple_of is None:
978
+ return model_embeds
979
+
980
+ # Update base model and current model config
981
+ self.config.output_vocab_size = model_embeds[0].weight.shape[0]
982
+ self.config.vocab_size = model_embeds[0].weight.shape[0]
983
+ self.output_vocab_size = model_embeds[0].weight.shape[0]
984
+ self.vocab_size = model_embeds[0].weight.shape[0]
985
+
986
+ # Tie weights again if needed
987
+ self.tie_weights()
988
+
989
+ return model_embeds
990
+
991
+ @auto_docstring
992
+ def forward(
993
+ self,
994
+ codebook_idx: int, # an additional idx corresponding to the id of the codebook that will be predicted
995
+ input_ids: torch.Tensor | None = None,
996
+ attention_mask: torch.Tensor | None = None,
997
+ position_ids: torch.Tensor | None = None,
998
+ labels: torch.LongTensor | None = None,
999
+ inputs_embeds: torch.Tensor | None = None,
1000
+ output_attentions: bool | None = None,
1001
+ output_hidden_states: bool | None = None,
1002
+ return_dict: bool | None = None,
1003
+ **kwargs,
1004
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
1005
+ r"""
1006
+ codebook_idx (`int`):
1007
+ Index of the codebook that will be predicted.
1008
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1009
+ NOT IMPLEMENTED YET.
1010
+ """
1011
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1012
+ output_hidden_states = (
1013
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1014
+ )
1015
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1016
+
1017
+ loss = None
1018
+ if labels is not None:
1019
+ raise NotImplementedError("Training is not implemented yet")
1020
+
1021
+ if codebook_idx == 0:
1022
+ raise ValueError("Cannot predict 0th codebook - 0th codebook should be predicted by the coarse model")
1023
+
1024
+ if input_ids is not None and inputs_embeds is not None:
1025
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1026
+
1027
+ if input_ids is None and inputs_embeds is None:
1028
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1029
+
1030
+ if input_ids is not None:
1031
+ # the input_embeddings are the sum of the j previous codebooks embeddings before
1032
+ # the current codebook_idx codebook
1033
+
1034
+ # forward the GPT model itself
1035
+ inputs_embeds = [
1036
+ input_embeds_layer(input_ids[:, :, i]).unsqueeze(-1)
1037
+ for i, input_embeds_layer in enumerate(self.input_embeds_layers)
1038
+ ] # token embeddings of shape (b, t, n_embd)
1039
+ inputs_embeds = torch.cat(inputs_embeds, dim=-1)
1040
+ inputs_embeds = inputs_embeds[:, :, :, : codebook_idx + 1].sum(dim=-1)
1041
+
1042
+ input_shape = inputs_embeds.size()[:-1]
1043
+ seq_length = input_shape[1]
1044
+
1045
+ inputs_embeds = inputs_embeds.to(self.position_embeds_layer.weight.device)
1046
+
1047
+ if position_ids is None:
1048
+ position_ids = torch.arange(
1049
+ 0, seq_length, dtype=torch.long, device=self.position_embeds_layer.weight.device
1050
+ )
1051
+ position_ids = position_ids.unsqueeze(0) # shape (1, seq_length)
1052
+
1053
+ position_ids = position_ids.to(self.position_embeds_layer.weight.device)
1054
+ position_embeds = self.position_embeds_layer(position_ids) # position embeddings of shape (1, t, n_embd)
1055
+
1056
+ attention_mask = create_bidirectional_mask(
1057
+ config=self.config,
1058
+ inputs_embeds=inputs_embeds,
1059
+ attention_mask=attention_mask,
1060
+ )
1061
+
1062
+ hidden_states = self.drop(inputs_embeds + position_embeds)
1063
+ output_shape = input_shape + (hidden_states.size(-1),)
1064
+
1065
+ all_self_attentions = () if output_attentions else None
1066
+ all_hidden_states = () if output_hidden_states else None
1067
+
1068
+ for i, block in enumerate(self.layers):
1069
+ if output_hidden_states:
1070
+ all_hidden_states = all_hidden_states + (hidden_states,)
1071
+
1072
+ outputs = block(
1073
+ hidden_states,
1074
+ attention_mask=attention_mask,
1075
+ output_attentions=output_attentions,
1076
+ )
1077
+
1078
+ hidden_states = outputs[0]
1079
+
1080
+ if output_attentions:
1081
+ all_self_attentions = all_self_attentions + (outputs[1],)
1082
+
1083
+ hidden_states = self.layernorm_final(hidden_states)
1084
+ hidden_states = hidden_states.view(output_shape)
1085
+
1086
+ # Add last hidden state
1087
+ if output_hidden_states:
1088
+ all_hidden_states = all_hidden_states + (hidden_states,)
1089
+
1090
+ logits = self.lm_heads[codebook_idx - self.config.n_codes_given](hidden_states)
1091
+
1092
+ if not return_dict:
1093
+ return tuple(v for v in [None, logits, all_hidden_states, all_self_attentions] if v is not None)
1094
+
1095
+ return MaskedLMOutput(
1096
+ loss=loss,
1097
+ logits=logits,
1098
+ hidden_states=all_hidden_states,
1099
+ attentions=all_self_attentions,
1100
+ )
1101
+
1102
+ @torch.no_grad()
1103
+ def generate(
1104
+ self,
1105
+ coarse_output: torch.Tensor,
1106
+ semantic_generation_config: BarkSemanticGenerationConfig | None = None,
1107
+ coarse_generation_config: BarkCoarseGenerationConfig | None = None,
1108
+ fine_generation_config: BarkFineGenerationConfig = None,
1109
+ codebook_size: int = 1024,
1110
+ history_prompt: dict[str, torch.Tensor] | None = None,
1111
+ **kwargs,
1112
+ ) -> torch.LongTensor:
1113
+ """
1114
+ Generates fine acoustics tokens from input coarse acoustics tokens and an additional optional `Bark` speaker
1115
+ prompt.
1116
+
1117
+ Args:
1118
+ coarse_output (`torch.Tensor` of shape (batch_size, seq_len)):
1119
+ Input coarse acoustics ids, i.e the output of `BarkCoarseModel.generate`.
1120
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
1121
+ Generation config indicating how to generate the semantic tokens.
1122
+ coarse_generation_config (`BarkCoarseGenerationConfig`):
1123
+ Generation config indicating how to generate the coarse tokens.
1124
+ fine_generation_config (`BarkFineGenerationConfig`):
1125
+ Generation config indicating how to generate the fine tokens.
1126
+ codebook_size (`int`, *optional*, defaults to 1024):
1127
+ Codebook channel size, i.e. the size of the output vocabulary per codebook channel.
1128
+ history_prompt (`Optional[dict[str,torch.Tensor]]`, *optional*):
1129
+ Optional `Bark` speaker prompt.
1130
+ Returns:
1131
+ torch.LongTensor: Output fine acoustics tokens.
1132
+ """
1133
+ if semantic_generation_config is None:
1134
+ raise ValueError("`semantic_generation_config` has to be provided")
1135
+
1136
+ if coarse_generation_config is None:
1137
+ raise ValueError("`coarse_generation_config` has to be provided")
1138
+
1139
+ if fine_generation_config is None:
1140
+ raise ValueError("`fine_generation_config` has to be provided")
1141
+
1142
+ # since we don't really use GenerationConfig through the fine model (autoencoder)
1143
+ # and since only temperature is used from the classic GenerationConfig parameters
1144
+ # manually impose the kwargs priority over the generation config
1145
+ temperature = kwargs.get("temperature", fine_generation_config.temperature)
1146
+
1147
+ max_fine_history_length = fine_generation_config.max_fine_history_length
1148
+ max_fine_input_length = fine_generation_config.max_fine_input_length
1149
+
1150
+ # shape: (batch, n_coarse_codebooks * seq_len)
1151
+ # new_shape: (batch, seq_len, n_coarse_codebooks)
1152
+ coarse_output = coarse_output.view(coarse_output.shape[0], -1, coarse_generation_config.n_coarse_codebooks)
1153
+
1154
+ # brings ids into the range [0, codebook_size -1]
1155
+ coarse_output = torch.remainder(coarse_output - semantic_generation_config.semantic_vocab_size, codebook_size)
1156
+ batch_size = coarse_output.shape[0]
1157
+
1158
+ if history_prompt is not None:
1159
+ x_fine_history = torch.repeat_interleave(history_prompt["fine_prompt"].T[None], batch_size, dim=0)
1160
+ # transpose to get to shape (seq_len, n_fine_codebooks)
1161
+ else:
1162
+ x_fine_history = None
1163
+
1164
+ n_coarse = coarse_generation_config.n_coarse_codebooks
1165
+
1166
+ # pad the last 6th codebooks
1167
+ fine_input = F.pad(
1168
+ coarse_output,
1169
+ (0, fine_generation_config.n_fine_codebooks - n_coarse),
1170
+ "constant",
1171
+ codebook_size,
1172
+ )
1173
+
1174
+ # prepend history if available (max max_fine_history_length)
1175
+ if x_fine_history is not None:
1176
+ fine_input = torch.cat([x_fine_history[:, -max_fine_history_length:, :], fine_input], dim=1)
1177
+
1178
+ # len of the fine_history that has been added to fine_input
1179
+ n_history = x_fine_history[:, -max_fine_history_length:, :].shape[1]
1180
+ else:
1181
+ n_history = 0
1182
+
1183
+ n_remove_from_end = 0
1184
+ # need to pad if too short (since non-causal model)
1185
+ if fine_input.shape[1] < max_fine_input_length:
1186
+ n_remove_from_end = max_fine_input_length - fine_input.shape[1]
1187
+ fine_input = F.pad(fine_input, (0, 0, 0, n_remove_from_end), mode="constant", value=codebook_size)
1188
+
1189
+ # we can be lazy about fractional loop and just keep overwriting codebooks.
1190
+ # seems that coarse_output.shape[1] - (max_fine_input_length - n_history) is equal to minus n_remove_from_end
1191
+ # So if we needed to pad because too short, n_loops is always 1 (because n_remove_from_end > 0)
1192
+ # If not, we loop over at least twice.
1193
+
1194
+ n_loops = (coarse_output.shape[1] - (max_fine_input_length - n_history)) / max_fine_history_length
1195
+ n_loops = int(np.ceil(n_loops))
1196
+ n_loops = max(0, n_loops) + 1
1197
+
1198
+ for n_outer in range(n_loops):
1199
+ start_idx = min([n_outer * max_fine_history_length, fine_input.shape[1] - max_fine_input_length])
1200
+
1201
+ start_fill_idx = min(
1202
+ [n_history + n_outer * max_fine_history_length, fine_input.shape[1] - max_fine_history_length]
1203
+ )
1204
+ rel_start_fill_idx = start_fill_idx - start_idx
1205
+ input_buffer = fine_input[:, start_idx : start_idx + max_fine_input_length, :]
1206
+ for n_inner in range(n_coarse, fine_generation_config.n_fine_codebooks):
1207
+ logits = self.forward(n_inner, input_buffer).logits
1208
+ if temperature is None or temperature == 1.0:
1209
+ relevant_logits = logits[:, rel_start_fill_idx:, :codebook_size]
1210
+ codebook_preds = torch.argmax(relevant_logits, -1)
1211
+ else:
1212
+ relevant_logits = logits[:, :, :codebook_size] / temperature
1213
+ # apply softmax
1214
+ probs = F.softmax(relevant_logits, dim=-1)[:, rel_start_fill_idx:max_fine_input_length]
1215
+ # reshape to 2D: (batch_size, seq_len, codebook_size) -> (batch_size*seq_len, codebook_size)
1216
+ probs = probs.reshape((-1, codebook_size))
1217
+ # multinomial then reshape : (batch_size*seq_len)-> (batch_size,seq_len)
1218
+ codebook_preds = torch.multinomial(probs, num_samples=1).view(batch_size, -1)
1219
+ codebook_preds = codebook_preds.to(torch.int32)
1220
+ input_buffer[:, rel_start_fill_idx:, n_inner] = codebook_preds
1221
+ del logits, codebook_preds
1222
+
1223
+ # transfer into fine_input
1224
+ for n_inner in range(n_coarse, fine_generation_config.n_fine_codebooks):
1225
+ fine_input[
1226
+ :, start_fill_idx : start_fill_idx + (max_fine_input_length - rel_start_fill_idx), n_inner
1227
+ ] = input_buffer[:, rel_start_fill_idx:, n_inner]
1228
+ del input_buffer
1229
+
1230
+ fine_input = fine_input.transpose(1, 2)[:, :, n_history:]
1231
+ if n_remove_from_end > 0:
1232
+ fine_input = fine_input[:, :, :-n_remove_from_end]
1233
+
1234
+ if fine_input.shape[-1] != coarse_output.shape[-2]:
1235
+ raise ValueError("input and output should have the same seq_len")
1236
+
1237
+ return fine_input
1238
+
1239
+
1240
+ @auto_docstring(
1241
+ custom_intro="""
1242
+ The full Bark model, a text-to-speech model composed of 4 sub-models:
1243
+ - [`BarkSemanticModel`] (also referred to as the 'text' model): a causal auto-regressive transformer model that
1244
+ takes
1245
+ as input tokenized text, and predicts semantic text tokens that capture the meaning of the text.
1246
+ - [`BarkCoarseModel`] (also referred to as the 'coarse acoustics' model), also a causal autoregressive transformer,
1247
+ that takes into input the results of the last model. It aims at regressing the first two audio codebooks necessary
1248
+ to `encodec`.
1249
+ - [`BarkFineModel`] (the 'fine acoustics' model), this time a non-causal autoencoder transformer, which iteratively
1250
+ predicts the last codebooks based on the sum of the previous codebooks embeddings.
1251
+ - having predicted all the codebook channels from the [`EncodecModel`], Bark uses it to decode the output audio
1252
+ array.
1253
+
1254
+ It should be noted that each of the first three modules can support conditional speaker embeddings to condition the
1255
+ output sound according to specific predefined voice.
1256
+ """
1257
+ )
1258
+ class BarkModel(BarkPreTrainedModel, GenerationMixin):
1259
+ config: BarkConfig
1260
+
1261
+ def __init__(self, config):
1262
+ super().__init__(config)
1263
+
1264
+ self.semantic = BarkSemanticModel(config.semantic_config)
1265
+ self.coarse_acoustics = BarkCoarseModel(config.coarse_acoustics_config)
1266
+ self.fine_acoustics = BarkFineModel(config.fine_acoustics_config)
1267
+
1268
+ self.codec_model = AutoModel.from_config(config.codec_config)
1269
+
1270
+ self.config = config
1271
+
1272
+ self.post_init()
1273
+
1274
+ @classmethod
1275
+ def can_generate(cls) -> bool:
1276
+ # Bark has a unique model structure, where the external class (`BarkModel`) doesn't need to inherit from
1277
+ # `GenerationMixin` (it has a non-standard generation method), but one of the internal models do
1278
+ # (`BarkSemanticModel`). This means that the base `can_generate()` will return `False`, but we need to
1279
+ # override it so as to do `GenerationConfig` handling in multiple parts of the codebase.
1280
+ return True
1281
+
1282
+ @property
1283
+ def device(self) -> torch.device:
1284
+ """
1285
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
1286
+ device).
1287
+ """
1288
+ # for bark_model, device must be verified on its sub-models
1289
+ # if has _hf_hook, has been offloaded so the device has to be found in the hook
1290
+ if not hasattr(self.semantic, "_hf_hook"):
1291
+ return super().device
1292
+ for module in self.semantic.modules():
1293
+ if (
1294
+ hasattr(module, "_hf_hook")
1295
+ and hasattr(module._hf_hook, "execution_device")
1296
+ and module._hf_hook.execution_device is not None
1297
+ ):
1298
+ return torch.device(module._hf_hook.execution_device)
1299
+
1300
+ def enable_cpu_offload(
1301
+ self,
1302
+ accelerator_id: int | None = 0,
1303
+ **kwargs,
1304
+ ):
1305
+ r"""
1306
+ Offloads all sub-models to CPU using accelerate, reducing memory usage with a low impact on performance. This
1307
+ method moves one whole sub-model at a time to the accelerator when it is used, and the sub-model remains in accelerator until the next sub-model runs.
1308
+
1309
+ Args:
1310
+ accelerator_id (`int`, *optional*, defaults to 0):
1311
+ accelerator id on which the sub-models will be loaded and offloaded.
1312
+ """
1313
+ if is_accelerate_available():
1314
+ from accelerate import cpu_offload_with_hook
1315
+ else:
1316
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate`.")
1317
+
1318
+ device_type = "cuda"
1319
+ if is_torch_accelerator_available():
1320
+ device_type = torch.accelerator.current_accelerator().type
1321
+ device = torch.device(f"{device_type}:{accelerator_id}")
1322
+
1323
+ torch_accelerator_module = getattr(torch, device_type)
1324
+ if self.device.type != "cpu":
1325
+ self.to("cpu")
1326
+ torch_accelerator_module.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
1327
+
1328
+ # this layer is used outside the first forward pass of semantic so need to be loaded before semantic
1329
+ self.semantic.input_embeds_layer, _ = cpu_offload_with_hook(self.semantic.input_embeds_layer, device)
1330
+
1331
+ hook = None
1332
+ for cpu_offloaded_model in [
1333
+ self.semantic,
1334
+ self.coarse_acoustics,
1335
+ self.fine_acoustics,
1336
+ ]:
1337
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
1338
+
1339
+ self.fine_acoustics_hook = hook
1340
+
1341
+ _, hook = cpu_offload_with_hook(self.codec_model, device, prev_module_hook=hook)
1342
+
1343
+ # We'll offload the last model manually.
1344
+ self.codec_model_hook = hook
1345
+
1346
+ def codec_decode(self, fine_output, output_lengths=None):
1347
+ """Turn quantized audio codes into audio array using encodec."""
1348
+
1349
+ fine_output = fine_output.transpose(0, 1)
1350
+ emb = self.codec_model.quantizer.decode(fine_output)
1351
+
1352
+ if output_lengths is not None:
1353
+ # encodec uses LSTMs which behaves differently with appended padding
1354
+ # decoding with encodec takes around 0.1% of the total generation time
1355
+ # to keep generation quality, we break batching
1356
+ out = [sample[:, :l].unsqueeze(0) for (sample, l) in zip(emb, output_lengths)]
1357
+ audio_arr = [self.codec_model.decoder(sample).squeeze() for sample in out]
1358
+ else:
1359
+ out = self.codec_model.decoder(emb)
1360
+ audio_arr = out.squeeze(1) # squeeze the codebook dimension
1361
+
1362
+ return audio_arr
1363
+
1364
+ @torch.no_grad()
1365
+ def generate(
1366
+ self,
1367
+ input_ids: torch.Tensor | None = None,
1368
+ history_prompt: dict[str, torch.Tensor] | None = None,
1369
+ return_output_lengths: bool | None = None,
1370
+ **kwargs,
1371
+ ) -> torch.LongTensor:
1372
+ """
1373
+ Generates audio from an input prompt and an additional optional `Bark` speaker prompt.
1374
+
1375
+ Args:
1376
+ input_ids (`Optional[torch.Tensor]` of shape (batch_size, seq_len), *optional*):
1377
+ Input ids. Will be truncated up to 256 tokens. Note that the output audios will be as long as the
1378
+ longest generation among the batch.
1379
+ history_prompt (`Optional[dict[str,torch.Tensor]]`, *optional*):
1380
+ Optional `Bark` speaker prompt. Note that for now, this model takes only one speaker prompt per batch.
1381
+ kwargs (*optional*): Remaining dictionary of keyword arguments. Keyword arguments are of two types:
1382
+
1383
+ - Without a prefix, they will be entered as `**kwargs` for the `generate` method of each sub-model.
1384
+ - With a *semantic_*, *coarse_*, *fine_* prefix, they will be input for the `generate` method of the
1385
+ semantic, coarse and fine respectively. It has the priority over the keywords without a prefix.
1386
+
1387
+ This means you can, for example, specify a generation strategy for all sub-models except one.
1388
+ return_output_lengths (`bool`, *optional*):
1389
+ Whether or not to return the waveform lengths. Useful when batching.
1390
+ Returns:
1391
+ By default:
1392
+ - **audio_waveform** (`torch.Tensor` of shape (batch_size, seq_len)): Generated audio waveform.
1393
+ When `return_output_lengths=True`:
1394
+ Returns a tuple made of:
1395
+ - **audio_waveform** (`torch.Tensor` of shape (batch_size, seq_len)): Generated audio waveform.
1396
+ - **output_lengths** (`torch.Tensor` of shape (batch_size)): The length of each waveform in the batch
1397
+ Example:
1398
+
1399
+ ```python
1400
+ >>> from transformers import AutoProcessor, BarkModel
1401
+
1402
+ >>> processor = AutoProcessor.from_pretrained("suno/bark-small")
1403
+ >>> model = BarkModel.from_pretrained("suno/bark-small")
1404
+
1405
+ >>> # To add a voice preset, you can pass `voice_preset` to `BarkProcessor.__call__(...)`
1406
+ >>> voice_preset = "v2/en_speaker_6"
1407
+
1408
+ >>> inputs = processor("Hello, my dog is cute, I need him in my life", voice_preset=voice_preset)
1409
+
1410
+ >>> audio_array = model.generate(**inputs, semantic_max_new_tokens=100)
1411
+ >>> audio_array = audio_array.cpu().numpy().squeeze()
1412
+ ```
1413
+ """
1414
+ # TODO (joao):workaround until nested generation config is compatible with PreTrained Model
1415
+ # todo: dict
1416
+ semantic_generation_config = BarkSemanticGenerationConfig(**self.generation_config.semantic_config)
1417
+ coarse_generation_config = BarkCoarseGenerationConfig(**self.generation_config.coarse_acoustics_config)
1418
+ fine_generation_config = BarkFineGenerationConfig(**self.generation_config.fine_acoustics_config)
1419
+
1420
+ kwargs_semantic = {
1421
+ # if "attention_mask" is set, it should not be passed to CoarseModel and FineModel
1422
+ "attention_mask": kwargs.pop("attention_mask", None),
1423
+ "min_eos_p": kwargs.pop("min_eos_p", None),
1424
+ }
1425
+ kwargs_coarse = {}
1426
+ kwargs_fine = {}
1427
+ for key, value in kwargs.items():
1428
+ if key.startswith("semantic_"):
1429
+ key = key[len("semantic_") :]
1430
+ kwargs_semantic[key] = value
1431
+ elif key.startswith("coarse_"):
1432
+ key = key[len("coarse_") :]
1433
+ kwargs_coarse[key] = value
1434
+ elif key.startswith("fine_"):
1435
+ key = key[len("fine_") :]
1436
+ kwargs_fine[key] = value
1437
+ else:
1438
+ # If the key is already in a specific config, then it's been set with a
1439
+ # submodules specific value and we don't override
1440
+ if key not in kwargs_semantic:
1441
+ kwargs_semantic[key] = value
1442
+ if key not in kwargs_coarse:
1443
+ kwargs_coarse[key] = value
1444
+ if key not in kwargs_fine:
1445
+ kwargs_fine[key] = value
1446
+
1447
+ # 1. Generate from the semantic model
1448
+ if "generation_config" in kwargs_semantic:
1449
+ kwargs_semantic.pop("generation_config")
1450
+ semantic_output = self.semantic.generate(
1451
+ input_ids,
1452
+ history_prompt=history_prompt,
1453
+ semantic_generation_config=semantic_generation_config,
1454
+ **kwargs_semantic,
1455
+ )
1456
+
1457
+ # 2. Generate from the coarse model
1458
+ if "generation_config" in kwargs_coarse:
1459
+ kwargs_coarse.pop("generation_config")
1460
+ coarse_output = self.coarse_acoustics.generate(
1461
+ semantic_output,
1462
+ history_prompt=history_prompt,
1463
+ semantic_generation_config=semantic_generation_config,
1464
+ coarse_generation_config=coarse_generation_config,
1465
+ codebook_size=self.generation_config.codebook_size,
1466
+ return_output_lengths=return_output_lengths,
1467
+ **kwargs_coarse,
1468
+ )
1469
+
1470
+ output_lengths = None
1471
+ if return_output_lengths:
1472
+ coarse_output, output_lengths = coarse_output
1473
+ # (batch_size, seq_len*coarse_codebooks) -> (batch_size, seq_len)
1474
+ output_lengths = output_lengths // coarse_generation_config.n_coarse_codebooks
1475
+
1476
+ # 3. "generate" from the fine model
1477
+ if "generation_config" in kwargs_fine:
1478
+ kwargs_fine.pop("generation_config")
1479
+ output = self.fine_acoustics.generate(
1480
+ coarse_output,
1481
+ history_prompt=history_prompt,
1482
+ semantic_generation_config=semantic_generation_config,
1483
+ coarse_generation_config=coarse_generation_config,
1484
+ fine_generation_config=fine_generation_config,
1485
+ codebook_size=self.generation_config.codebook_size,
1486
+ **kwargs_fine,
1487
+ )
1488
+
1489
+ if getattr(self, "fine_acoustics_hook", None) is not None:
1490
+ # Manually offload fine_acoustics to CPU
1491
+ # and load codec_model to GPU
1492
+ # since bark doesn't use codec_model forward pass
1493
+ self.fine_acoustics_hook.offload()
1494
+ self.codec_model = self.codec_model.to(self.device)
1495
+
1496
+ # 4. Decode the output and generate audio array
1497
+ audio = self.codec_decode(output, output_lengths)
1498
+
1499
+ if getattr(self, "codec_model_hook", None) is not None:
1500
+ # Offload codec_model to CPU
1501
+ self.codec_model_hook.offload()
1502
+
1503
+ if return_output_lengths:
1504
+ output_lengths = [len(sample) for sample in audio]
1505
+ audio = nn.utils.rnn.pad_sequence(audio, batch_first=True, padding_value=0)
1506
+ return audio, output_lengths
1507
+
1508
+ return audio
1509
+
1510
+
1511
+ __all__ = [
1512
+ "BarkFineModel",
1513
+ "BarkSemanticModel",
1514
+ "BarkCoarseModel",
1515
+ "BarkModel",
1516
+ "BarkPreTrainedModel",
1517
+ "BarkCausalModel",
1518
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/image_processing_blip.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for BLIP."""
15
+
16
+ from ...image_processing_backends import TorchvisionBackend
17
+ from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
18
+ from ...utils import auto_docstring
19
+
20
+
21
+ @auto_docstring
22
+ class BlipImageProcessor(TorchvisionBackend):
23
+ resample = PILImageResampling.BICUBIC
24
+ image_mean = OPENAI_CLIP_MEAN
25
+ image_std = OPENAI_CLIP_STD
26
+ size = {"height": 384, "width": 384}
27
+ default_to_square = True
28
+ do_resize = True
29
+ do_rescale = True
30
+ do_normalize = True
31
+ do_convert_rgb = True
32
+
33
+
34
+ __all__ = ["BlipImageProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip/processing_blip.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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 Blip.
16
+ """
17
+
18
+ from ...image_utils import ImageInput
19
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
20
+ from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
21
+ from ...utils import auto_docstring
22
+
23
+
24
+ class BlipProcessorKwargs(ProcessingKwargs, total=False):
25
+ _defaults = {
26
+ "text_kwargs": {
27
+ "add_special_tokens": True,
28
+ "padding": False,
29
+ "stride": 0,
30
+ "return_overflowing_tokens": False,
31
+ "return_special_tokens_mask": False,
32
+ "return_offsets_mapping": False,
33
+ "return_token_type_ids": False,
34
+ "return_length": False,
35
+ "verbose": True,
36
+ },
37
+ }
38
+
39
+
40
+ @auto_docstring
41
+ class BlipProcessor(ProcessorMixin):
42
+ def __init__(self, image_processor, tokenizer, **kwargs):
43
+ tokenizer.return_token_type_ids = False
44
+ super().__init__(image_processor, tokenizer)
45
+
46
+ @auto_docstring
47
+ def __call__(
48
+ self,
49
+ images: ImageInput | None = None,
50
+ text: str | list[str] | TextInput | PreTokenizedInput | None = None,
51
+ **kwargs: Unpack[BlipProcessorKwargs],
52
+ ) -> BatchEncoding:
53
+ if images is None and text is None:
54
+ raise ValueError("You have to specify either images or text.")
55
+
56
+ text_encoding = None
57
+
58
+ # add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
59
+ # else, return the text encoding.
60
+ output_kwargs = self._merge_kwargs(
61
+ BlipProcessorKwargs,
62
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
63
+ **kwargs,
64
+ )
65
+ if text is not None:
66
+ text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
67
+ if images is not None:
68
+ encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
69
+
70
+ if text_encoding is not None:
71
+ encoding_image_processor.update(text_encoding)
72
+ return encoding_image_processor
73
+
74
+ return text_encoding
75
+
76
+ @property
77
+ def model_input_names(self):
78
+ tokenizer_input_names = self.tokenizer.model_input_names
79
+ image_processor_input_names = self.image_processor.model_input_names
80
+ tokenizer_input_names = [name for name in tokenizer_input_names if name != "token_type_ids"]
81
+ return tokenizer_input_names + image_processor_input_names
82
+
83
+
84
+ __all__ = ["BlipProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/eurobert/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Nicolas Boizard, Duarte M. Alves, Hippolyte Gisserot-Boukhlef and the EuroBert 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_eurobert import *
22
+ from .modeling_eurobert import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/eurobert/modeling_eurobert.py ADDED
@@ -0,0 +1,628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/eurobert/modular_eurobert.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_eurobert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 Nicolas Boizard, Duarte M. Alves, Hippolyte Gisserot-Boukhlef and the EuroBert team. All rights reserved.
8
+ #
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from collections.abc import Callable
23
+ from typing import Optional
24
+
25
+ import torch
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache
31
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
32
+ from ...masking_utils import create_bidirectional_mask
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import BaseModelOutput, MaskedLMOutput, SequenceClassifierOutput, TokenClassifierOutput
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 auto_docstring
39
+ from ...utils.generic import TransformersKwargs, can_return_tuple, maybe_autocast, merge_with_config_defaults
40
+ from ...utils.output_capturing import capture_outputs
41
+ from .configuration_eurobert import EuroBertConfig
42
+
43
+
44
+ @use_kernel_forward_from_hub("RMSNorm")
45
+ class EuroBertRMSNorm(nn.Module):
46
+ def __init__(self, hidden_size, eps=1e-5) -> None:
47
+ """
48
+ EuroBertRMSNorm is equivalent to T5LayerNorm
49
+ """
50
+ super().__init__()
51
+ self.weight = nn.Parameter(torch.ones(hidden_size))
52
+ self.variance_epsilon = eps
53
+
54
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
55
+ input_dtype = hidden_states.dtype
56
+ hidden_states = hidden_states.to(torch.float32)
57
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
58
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
59
+ return self.weight * hidden_states.to(input_dtype)
60
+
61
+ def extra_repr(self):
62
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
63
+
64
+
65
+ def rotate_half(x):
66
+ """Rotates half the hidden dims of the input."""
67
+ x1 = x[..., : x.shape[-1] // 2]
68
+ x2 = x[..., x.shape[-1] // 2 :]
69
+ return torch.cat((-x2, x1), dim=-1)
70
+
71
+
72
+ @use_kernel_func_from_hub("rotary_pos_emb")
73
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
74
+ """Applies Rotary Position Embedding to the query and key tensors.
75
+
76
+ Args:
77
+ q (`torch.Tensor`): The query tensor.
78
+ k (`torch.Tensor`): The key tensor.
79
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
80
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
81
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
82
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
83
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
84
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
85
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
86
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
87
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
88
+ Returns:
89
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
90
+ """
91
+ cos = cos.unsqueeze(unsqueeze_dim)
92
+ sin = sin.unsqueeze(unsqueeze_dim)
93
+ q_embed = (q * cos) + (rotate_half(q) * sin)
94
+ k_embed = (k * cos) + (rotate_half(k) * sin)
95
+ return q_embed, k_embed
96
+
97
+
98
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
99
+ """
100
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
101
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
102
+ """
103
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
104
+ if n_rep == 1:
105
+ return hidden_states
106
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
107
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
108
+
109
+
110
+ def eager_attention_forward(
111
+ module: nn.Module,
112
+ query: torch.Tensor,
113
+ key: torch.Tensor,
114
+ value: torch.Tensor,
115
+ attention_mask: torch.Tensor | None,
116
+ scaling: float,
117
+ dropout: float = 0.0,
118
+ **kwargs: Unpack[TransformersKwargs],
119
+ ):
120
+ key_states = repeat_kv(key, module.num_key_value_groups)
121
+ value_states = repeat_kv(value, module.num_key_value_groups)
122
+
123
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
124
+ if attention_mask is not None:
125
+ attn_weights = attn_weights + attention_mask
126
+
127
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
128
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
129
+ attn_output = torch.matmul(attn_weights, value_states)
130
+ attn_output = attn_output.transpose(1, 2).contiguous()
131
+
132
+ return attn_output, attn_weights
133
+
134
+
135
+ @use_kernelized_func(apply_rotary_pos_emb)
136
+ class EuroBertAttention(nn.Module):
137
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
138
+
139
+ def __init__(self, config: EuroBertConfig, layer_idx: int):
140
+ super().__init__()
141
+ self.config = config
142
+ self.layer_idx = layer_idx
143
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
144
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
145
+ self.scaling = self.head_dim**-0.5
146
+ self.attention_dropout = config.attention_dropout
147
+ self.is_causal = False
148
+
149
+ self.q_proj = nn.Linear(
150
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
151
+ )
152
+ self.k_proj = nn.Linear(
153
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
154
+ )
155
+ self.v_proj = nn.Linear(
156
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
157
+ )
158
+ self.o_proj = nn.Linear(
159
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
160
+ )
161
+
162
+ def forward(
163
+ self,
164
+ hidden_states: torch.Tensor,
165
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
166
+ attention_mask: torch.Tensor | None = None,
167
+ past_key_values: Cache | None = None,
168
+ **kwargs: Unpack[TransformersKwargs],
169
+ ) -> tuple[torch.Tensor, torch.Tensor]:
170
+ input_shape = hidden_states.shape[:-1]
171
+ hidden_shape = (*input_shape, -1, self.head_dim)
172
+
173
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
174
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
175
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
176
+
177
+ cos, sin = position_embeddings
178
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
179
+
180
+ if past_key_values is not None:
181
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
182
+
183
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
184
+ self.config._attn_implementation, eager_attention_forward
185
+ )
186
+
187
+ attn_output, attn_weights = attention_interface(
188
+ self,
189
+ query_states,
190
+ key_states,
191
+ value_states,
192
+ attention_mask,
193
+ dropout=0.0 if not self.training else self.attention_dropout,
194
+ scaling=self.scaling,
195
+ **kwargs,
196
+ )
197
+
198
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
199
+ attn_output = self.o_proj(attn_output)
200
+ return attn_output, attn_weights
201
+
202
+
203
+ class EuroBertMLP(nn.Module):
204
+ def __init__(self, config):
205
+ super().__init__()
206
+ self.config = config
207
+ self.hidden_size = config.hidden_size
208
+ self.intermediate_size = config.intermediate_size
209
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
210
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
211
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
212
+ self.act_fn = ACT2FN[config.hidden_act]
213
+
214
+ def forward(self, x):
215
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
216
+ return down_proj
217
+
218
+
219
+ class EuroBertDecoderLayer(GradientCheckpointingLayer):
220
+ def __init__(self, config: EuroBertConfig, layer_idx: int):
221
+ super().__init__()
222
+ self.hidden_size = config.hidden_size
223
+
224
+ self.self_attn = EuroBertAttention(config=config, layer_idx=layer_idx)
225
+
226
+ self.mlp = EuroBertMLP(config)
227
+ self.input_layernorm = EuroBertRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
228
+ self.post_attention_layernorm = EuroBertRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
229
+
230
+ def forward(
231
+ self,
232
+ hidden_states: torch.Tensor,
233
+ attention_mask: torch.Tensor | None = None,
234
+ position_ids: torch.LongTensor | None = None,
235
+ past_key_values: Cache | None = None,
236
+ use_cache: bool | None = False,
237
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
238
+ **kwargs: Unpack[TransformersKwargs],
239
+ ) -> torch.Tensor:
240
+ residual = hidden_states
241
+ hidden_states = self.input_layernorm(hidden_states)
242
+ # Self Attention
243
+ hidden_states, _ = self.self_attn(
244
+ hidden_states=hidden_states,
245
+ attention_mask=attention_mask,
246
+ position_ids=position_ids,
247
+ past_key_values=past_key_values,
248
+ use_cache=use_cache,
249
+ position_embeddings=position_embeddings,
250
+ **kwargs,
251
+ )
252
+ hidden_states = residual + hidden_states
253
+
254
+ # Fully Connected
255
+ residual = hidden_states
256
+ hidden_states = self.post_attention_layernorm(hidden_states)
257
+ hidden_states = self.mlp(hidden_states)
258
+ hidden_states = residual + hidden_states
259
+ return hidden_states
260
+
261
+
262
+ @auto_docstring
263
+ class EuroBertPreTrainedModel(PreTrainedModel):
264
+ config: EuroBertConfig
265
+ base_model_prefix = "model"
266
+ supports_gradient_checkpointing = True
267
+ _no_split_modules = ["EuroBertDecoderLayer"]
268
+ _skip_keys_device_placement = ["past_key_values"]
269
+ _supports_flash_attn = True
270
+ _supports_sdpa = True
271
+ _supports_flex_attn = True
272
+
273
+ _can_compile_fullgraph = True
274
+ _supports_attention_backend = True
275
+ _can_record_outputs = {
276
+ "hidden_states": EuroBertDecoderLayer,
277
+ "attentions": EuroBertAttention,
278
+ }
279
+
280
+
281
+ class EuroBertRotaryEmbedding(nn.Module):
282
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
283
+
284
+ def __init__(self, config: EuroBertConfig, device=None):
285
+ super().__init__()
286
+ self.max_seq_len_cached = config.max_position_embeddings
287
+ self.original_max_seq_len = config.max_position_embeddings
288
+
289
+ self.config = config
290
+
291
+ self.rope_type = self.config.rope_parameters["rope_type"]
292
+ rope_init_fn: Callable = self.compute_default_rope_parameters
293
+ if self.rope_type != "default":
294
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
295
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
296
+
297
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
298
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
299
+
300
+ @staticmethod
301
+ def compute_default_rope_parameters(
302
+ config: EuroBertConfig | None = None,
303
+ device: Optional["torch.device"] = None,
304
+ seq_len: int | None = None,
305
+ ) -> tuple["torch.Tensor", float]:
306
+ """
307
+ Computes the inverse frequencies according to the original RoPE implementation
308
+ Args:
309
+ config ([`~transformers.PreTrainedConfig`]):
310
+ The model configuration.
311
+ device (`torch.device`):
312
+ The device to use for initialization of the inverse frequencies.
313
+ seq_len (`int`, *optional*):
314
+ The current sequence length. Unused for this type of RoPE.
315
+ Returns:
316
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
317
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
318
+ """
319
+ base = config.rope_parameters["rope_theta"]
320
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
321
+
322
+ attention_factor = 1.0 # Unused in this type of RoPE
323
+
324
+ # Compute the inverse frequencies
325
+ inv_freq = 1.0 / (
326
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
327
+ )
328
+ return inv_freq, attention_factor
329
+
330
+ @torch.no_grad()
331
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
332
+ def forward(self, x, position_ids):
333
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
334
+ position_ids_expanded = position_ids[:, None, :].float()
335
+
336
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
337
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
338
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
339
+ emb = torch.cat((freqs, freqs), dim=-1)
340
+ cos = emb.cos() * self.attention_scaling
341
+ sin = emb.sin() * self.attention_scaling
342
+
343
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
344
+
345
+
346
+ @auto_docstring
347
+ class EuroBertModel(EuroBertPreTrainedModel):
348
+ def __init__(self, config: EuroBertConfig):
349
+ super().__init__(config)
350
+ self.padding_idx = config.pad_token_id
351
+ self.vocab_size = config.vocab_size
352
+
353
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
354
+ self.layers = nn.ModuleList(
355
+ [EuroBertDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
356
+ )
357
+ self.norm = EuroBertRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
358
+ self.rotary_emb = EuroBertRotaryEmbedding(config=config)
359
+ self.gradient_checkpointing = False
360
+
361
+ # Initialize weights and apply final processing
362
+ self.post_init()
363
+
364
+ @merge_with_config_defaults
365
+ @capture_outputs
366
+ @auto_docstring
367
+ def forward(
368
+ self,
369
+ input_ids: torch.LongTensor = None,
370
+ attention_mask: torch.Tensor | None = None,
371
+ position_ids: torch.LongTensor | None = None,
372
+ inputs_embeds: torch.FloatTensor | None = None,
373
+ **kwargs: Unpack[TransformersKwargs],
374
+ ) -> tuple | BaseModelOutput:
375
+ if (input_ids is None) ^ (inputs_embeds is not None):
376
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
377
+
378
+ if inputs_embeds is None:
379
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
380
+
381
+ if position_ids is None:
382
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
383
+
384
+ bidirectional_mask = create_bidirectional_mask(
385
+ config=self.config,
386
+ inputs_embeds=inputs_embeds,
387
+ attention_mask=attention_mask,
388
+ )
389
+
390
+ hidden_states = inputs_embeds
391
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
392
+
393
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
394
+ hidden_states = encoder_layer(
395
+ hidden_states,
396
+ attention_mask=bidirectional_mask,
397
+ position_embeddings=position_embeddings,
398
+ position_ids=position_ids,
399
+ **kwargs,
400
+ )
401
+
402
+ hidden_states = self.norm(hidden_states)
403
+ return BaseModelOutput(
404
+ last_hidden_state=hidden_states,
405
+ )
406
+
407
+
408
+ @auto_docstring
409
+ class EuroBertForMaskedLM(EuroBertPreTrainedModel):
410
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
411
+ _tp_plan = {"lm_head": "colwise_gather_output"}
412
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
413
+
414
+ def __init__(self, config: EuroBertConfig):
415
+ super().__init__(config)
416
+ self.model = EuroBertModel(config)
417
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, config.mlp_bias)
418
+
419
+ # Initialize weights and apply final processing
420
+ self.post_init()
421
+
422
+ @can_return_tuple
423
+ @auto_docstring
424
+ def forward(
425
+ self,
426
+ input_ids: torch.LongTensor | None = None,
427
+ attention_mask: torch.Tensor | None = None,
428
+ position_ids: torch.LongTensor | None = None,
429
+ inputs_embeds: torch.FloatTensor | None = None,
430
+ labels: torch.LongTensor | None = None,
431
+ **kwargs: Unpack[TransformersKwargs],
432
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
433
+ r"""
434
+ Example:
435
+
436
+ ```python
437
+ >>> from transformers import AutoTokenizer, EuroBertForMaskedLM
438
+
439
+ >>> model = EuroBertForMaskedLM.from_pretrained("EuroBERT/EuroBERT-210m")
440
+ >>> tokenizer = AutoTokenizer.from_pretrained("EuroBERT/EuroBERT-210m")
441
+
442
+ >>> text = "The capital of France is <|mask|>."
443
+ >>> inputs = tokenizer(text, return_tensors="pt")
444
+ >>> outputs = model(**inputs)
445
+
446
+ >>> # To get predictions for the mask:
447
+ >>> masked_index = inputs["input_ids"][0].tolist().index(tokenizer.mask_token_id)
448
+ >>> predicted_token_id = outputs.logits[0, masked_index].argmax(axis=-1)
449
+ >>> predicted_token = tokenizer.decode(predicted_token_id)
450
+ >>> print("Predicted token:", predicted_token)
451
+ Predicted token: Paris
452
+ ```"""
453
+ outputs: BaseModelOutput = self.model(
454
+ input_ids=input_ids,
455
+ attention_mask=attention_mask,
456
+ position_ids=position_ids,
457
+ inputs_embeds=inputs_embeds,
458
+ **kwargs,
459
+ )
460
+
461
+ logits = self.lm_head(outputs.last_hidden_state)
462
+ loss = None
463
+ if labels is not None:
464
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
465
+
466
+ return MaskedLMOutput(
467
+ loss=loss,
468
+ logits=logits,
469
+ hidden_states=outputs.hidden_states,
470
+ attentions=outputs.attentions,
471
+ )
472
+
473
+
474
+ @auto_docstring
475
+ class EuroBertForSequenceClassification(EuroBertPreTrainedModel):
476
+ def __init__(self, config: EuroBertConfig):
477
+ super().__init__(config)
478
+ self.num_labels = config.num_labels
479
+ self.classifier_pooling = config.classifier_pooling
480
+
481
+ self.model = EuroBertModel(config)
482
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
483
+ self.activation = nn.GELU()
484
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
485
+ self.post_init()
486
+
487
+ @can_return_tuple
488
+ @auto_docstring
489
+ def forward(
490
+ self,
491
+ input_ids: torch.LongTensor | None = None,
492
+ attention_mask: torch.Tensor | None = None,
493
+ position_ids: torch.LongTensor | None = None,
494
+ inputs_embeds: torch.FloatTensor | None = None,
495
+ labels: torch.LongTensor | None = None,
496
+ **kwargs: Unpack[TransformersKwargs],
497
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
498
+ encoder_output = self.model(
499
+ input_ids,
500
+ attention_mask=attention_mask,
501
+ position_ids=position_ids,
502
+ inputs_embeds=inputs_embeds,
503
+ **kwargs,
504
+ )
505
+ last_hidden_state = encoder_output[0]
506
+
507
+ if self.classifier_pooling in ["bos", "mean"]:
508
+ if self.classifier_pooling == "bos":
509
+ pooled_output = last_hidden_state[:, 0]
510
+
511
+ elif self.classifier_pooling == "mean":
512
+ if attention_mask is None:
513
+ pooled_output = last_hidden_state.mean(dim=1)
514
+ else:
515
+ attention_mask = attention_mask.to(last_hidden_state.device)
516
+ pooled_output = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1)
517
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
518
+
519
+ pooled_output = self.dense(pooled_output)
520
+ pooled_output = self.activation(pooled_output)
521
+ logits = self.classifier(pooled_output)
522
+
523
+ elif self.classifier_pooling == "late":
524
+ x = self.dense(last_hidden_state)
525
+ x = self.activation(x)
526
+ logits = self.classifier(x)
527
+ if attention_mask is None:
528
+ logits = logits.mean(dim=1)
529
+ else:
530
+ attention_mask = attention_mask.to(logits.device)
531
+ logits = (logits * attention_mask.unsqueeze(-1)).sum(dim=1)
532
+ logits /= attention_mask.sum(dim=1, keepdim=True)
533
+
534
+ loss = None
535
+ if labels is not None:
536
+ labels = labels.to(logits.device)
537
+ if self.config.problem_type is None:
538
+ if self.num_labels == 1:
539
+ self.config.problem_type = "regression"
540
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
541
+ self.config.problem_type = "single_label_classification"
542
+ else:
543
+ self.config.problem_type = "multi_label_classification"
544
+
545
+ if self.config.problem_type == "regression":
546
+ loss_fct = MSELoss()
547
+ if self.num_labels == 1:
548
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
549
+ else:
550
+ loss = loss_fct(logits, labels)
551
+ elif self.config.problem_type == "single_label_classification":
552
+ loss_fct = CrossEntropyLoss()
553
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
554
+ elif self.config.problem_type == "multi_label_classification":
555
+ loss_fct = BCEWithLogitsLoss()
556
+ loss = loss_fct(logits, labels)
557
+
558
+ return SequenceClassifierOutput(
559
+ loss=loss,
560
+ logits=logits,
561
+ hidden_states=encoder_output.hidden_states,
562
+ attentions=encoder_output.attentions,
563
+ )
564
+
565
+
566
+ @auto_docstring
567
+ class EuroBertForTokenClassification(EuroBertPreTrainedModel):
568
+ def __init__(self, config: EuroBertConfig):
569
+ super().__init__(config)
570
+ self.num_labels = config.num_labels
571
+ self.model = EuroBertModel(config)
572
+
573
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
574
+ self.post_init()
575
+
576
+ def get_input_embeddings(self):
577
+ return self.model.embed_tokens
578
+
579
+ def set_input_embeddings(self, value):
580
+ self.model.embed_tokens = value
581
+
582
+ @can_return_tuple
583
+ @auto_docstring
584
+ def forward(
585
+ self,
586
+ input_ids: torch.LongTensor | None = None,
587
+ attention_mask: torch.Tensor | None = None,
588
+ position_ids: torch.LongTensor | None = None,
589
+ inputs_embeds: torch.FloatTensor | None = None,
590
+ labels: torch.LongTensor | None = None,
591
+ **kwargs: Unpack[TransformersKwargs],
592
+ ) -> tuple | TokenClassifierOutput:
593
+ r"""
594
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
595
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
596
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
597
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
598
+ """
599
+ outputs = self.model(
600
+ input_ids,
601
+ attention_mask=attention_mask,
602
+ position_ids=position_ids,
603
+ inputs_embeds=inputs_embeds,
604
+ **kwargs,
605
+ )
606
+ sequence_output = outputs[0]
607
+ logits = self.classifier(sequence_output)
608
+
609
+ loss = None
610
+ if labels is not None:
611
+ loss_fct = CrossEntropyLoss()
612
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
613
+
614
+ return TokenClassifierOutput(
615
+ loss=loss,
616
+ logits=logits,
617
+ hidden_states=outputs.hidden_states,
618
+ attentions=outputs.attentions,
619
+ )
620
+
621
+
622
+ __all__ = [
623
+ "EuroBertPreTrainedModel",
624
+ "EuroBertModel",
625
+ "EuroBertForMaskedLM",
626
+ "EuroBertForSequenceClassification",
627
+ "EuroBertForTokenClassification",
628
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 IBM. 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_granite4_vision import *
22
+ from .modeling_granite4_vision import *
23
+ from .processing_granite4_vision import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/configuration_granite4_vision.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/granite4_vision/modular_granite4_vision.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_granite4_vision.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 IBM and The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from typing import Literal
22
+
23
+ from huggingface_hub.dataclasses import strict
24
+
25
+ from ...configuration_utils import PreTrainedConfig
26
+ from ...modeling_rope_utils import RopeParameters
27
+ from ...utils import auto_docstring
28
+ from ..auto import CONFIG_MAPPING, AutoConfig
29
+
30
+
31
+ @auto_docstring(checkpoint="ibm-granite4_vision_text/granite4_vision_text-3.0-8b-base")
32
+ @strict
33
+ class Granite4VisionTextConfig(PreTrainedConfig):
34
+ r"""
35
+ ```python
36
+ >>> from transformers import Granite4VisionTextModel, Granite4VisionTextConfig
37
+
38
+ >>> # Initializing a Granite4VisionText granite4_vision_text-3b style configuration
39
+ >>> configuration = Granite4VisionTextConfig()
40
+
41
+ >>> # Initializing a model from the granite4_vision_text-7b style configuration
42
+ >>> model = Granite4VisionTextModel(configuration)
43
+
44
+ >>> # Accessing the model configuration
45
+ >>> configuration = model.config
46
+ ```
47
+ """
48
+
49
+ model_type = "granite4_vision_text"
50
+ keys_to_ignore_at_inference = ["past_key_values"]
51
+ # Default tensor parallel plan for base model `Granite4VisionTextModel`
52
+ base_model_tp_plan = {
53
+ "layers.*.self_attn.q_proj": "colwise",
54
+ "layers.*.self_attn.k_proj": "colwise",
55
+ "layers.*.self_attn.v_proj": "colwise",
56
+ "layers.*.self_attn.o_proj": "rowwise",
57
+ "layers.*.mlp.gate_proj": "colwise",
58
+ "layers.*.mlp.up_proj": "colwise",
59
+ "layers.*.mlp.down_proj": "rowwise",
60
+ }
61
+ base_model_pp_plan = {
62
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
63
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
64
+ "norm": (["hidden_states"], ["hidden_states"]),
65
+ }
66
+
67
+ vocab_size: int = 32000
68
+ hidden_size: int = 4096
69
+ intermediate_size: int = 11008
70
+ num_hidden_layers: int = 32
71
+ num_attention_heads: int = 32
72
+ num_key_value_heads: int | None = None
73
+ hidden_act: str = "silu"
74
+ max_position_embeddings: int = 2048
75
+ initializer_range: float = 0.02
76
+ rms_norm_eps: float = 1e-6
77
+ use_cache: bool = True
78
+ pad_token_id: int | None = None
79
+ bos_token_id: int | None = 1
80
+ eos_token_id: int | list[int] | None = 2
81
+ tie_word_embeddings: bool = False
82
+ rope_parameters: RopeParameters | dict | None = None
83
+ attention_bias: bool = False
84
+ attention_dropout: float | int = 0.0
85
+ mlp_bias: bool = False
86
+ embedding_multiplier: float | int = 1.0
87
+ logits_scaling: float | int = 1.0
88
+ residual_multiplier: float | int = 1.0
89
+ attention_multiplier: float | int = 1.0
90
+ base_config_key = "text_config"
91
+
92
+ def __post_init__(self, **kwargs):
93
+ if self.num_key_value_heads is None:
94
+ self.num_key_value_heads = self.num_attention_heads
95
+
96
+ super().__post_init__(**kwargs)
97
+
98
+
99
+ @auto_docstring(checkpoint="llava-hf/llava-v1.6-mistral-7b-hf")
100
+ @strict
101
+ class Granite4VisionConfig(PreTrainedConfig):
102
+ r"""
103
+ image_grid_pinpoints (`list`, *optional*):
104
+ A list of possible resolutions to use for processing high resolution images. Each item in the list should be a
105
+ tuple or list of the form `(height, width)`.
106
+ downsample_rate (`str`, *optional*):
107
+ Fractional downsample rate for the Window Q-Former projector, e.g. `"1/4"` or `"3/8"`.
108
+ The numerator is the query window side, the denominator is the key window side.
109
+ deepstack_layer_map (`list`, *optional*):
110
+ List of `[vision_layer_idx, llm_layer_idx]` pairs. Features from each vision encoder layer
111
+ are projected and injected at the corresponding LLM decoder layer during forward pass.
112
+ spatial_vision_layer (`int`, *optional*, defaults to `-1`):
113
+ Index of the vision encoder layer used for spatial sampling.
114
+ spatial_target_layers (`list`, *optional*, defaults to `[12, 15, 18, 21]`):
115
+ Target LLM layers for the 4 spatial offset groups.
116
+ projector_dropout (`float`, *optional*, defaults to `0.1`):
117
+ Dropout probability in the Window Q-Former projector.
118
+ qformer_config (`dict` or `Blip2QFormerConfig`, *optional*):
119
+ Configuration for the Window Q-Former projector. If `None`, defaults are derived from
120
+ `vision_config.hidden_size`.
121
+ """
122
+
123
+ model_type = "granite4_vision"
124
+ attribute_map = {"image_token_id": "image_token_index"}
125
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig, "qformer_config": AutoConfig}
126
+
127
+ vision_config: dict | PreTrainedConfig | None = None
128
+ text_config: dict | PreTrainedConfig | None = None
129
+ image_token_index: int = 32000
130
+ vision_feature_select_strategy: Literal["default", "full"] = "default"
131
+ vision_feature_layer: int | list[int] = -2
132
+ tie_word_embeddings: bool = False
133
+ image_grid_pinpoints: list | None = None
134
+ image_seq_length: int = 576
135
+
136
+ downsample_rate: str | None = None
137
+ deepstack_layer_map: list | None = None
138
+ spatial_vision_layer: int = -1
139
+ spatial_target_layers: list | None = None
140
+ projector_dropout: float = 0.1
141
+ qformer_config: dict | PreTrainedConfig | None = None
142
+
143
+ def __post_init__(self, **kwargs):
144
+ self.image_grid_pinpoints = (
145
+ self.image_grid_pinpoints
146
+ if self.image_grid_pinpoints is not None
147
+ else [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
148
+ )
149
+
150
+ if self.deepstack_layer_map is not None:
151
+ self.deepstack_layer_map = [(int(v), int(l)) for v, l in self.deepstack_layer_map]
152
+
153
+ if self.spatial_target_layers is None:
154
+ self.spatial_target_layers = [12, 15, 18, 21]
155
+
156
+ if isinstance(self.vision_config, dict):
157
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "clip_vision_model")
158
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
159
+ elif self.vision_config is None:
160
+ self.vision_config = CONFIG_MAPPING["siglip_vision_model"]()
161
+
162
+ if isinstance(self.text_config, dict):
163
+ self.text_config["model_type"] = self.text_config.get("model_type", "granite4_vision_text")
164
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
165
+ elif self.text_config is None:
166
+ self.text_config = CONFIG_MAPPING["llama"]()
167
+
168
+ if isinstance(self.qformer_config, dict):
169
+ model_type = self.qformer_config.get("model_type", "blip_2_qformer")
170
+ self.qformer_config = CONFIG_MAPPING[model_type](**self.qformer_config)
171
+ if self.qformer_config is None:
172
+ vision_hidden_size = self.vision_config.hidden_size
173
+ self.qformer_config = CONFIG_MAPPING["blip_2_qformer"](
174
+ num_hidden_layers=1,
175
+ intermediate_size=3072,
176
+ cross_attention_frequency=1,
177
+ max_position_embeddings=2048,
178
+ use_qformer_text_input=False,
179
+ hidden_size=vision_hidden_size,
180
+ num_attention_heads=vision_hidden_size // 64,
181
+ encoder_hidden_size=vision_hidden_size,
182
+ )
183
+ super().__post_init__(**kwargs)
184
+
185
+
186
+ __all__ = ["Granite4VisionConfig", "Granite4VisionTextConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/modeling_granite4_vision.py ADDED
@@ -0,0 +1,1218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/granite4_vision/modular_granite4_vision.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_granite4_vision.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 IBM and The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import math
22
+ from collections.abc import Callable
23
+ from dataclasses import dataclass
24
+ from fractions import Fraction
25
+ from typing import Optional
26
+
27
+ import numpy as np
28
+ import torch
29
+ from torch import nn
30
+
31
+ from ... import initialization as init
32
+ from ...activations import ACT2FN
33
+ from ...cache_utils import Cache
34
+ from ...generation import GenerationMixin
35
+ from ...image_processing_utils import select_best_resolution
36
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
37
+ from ...masking_utils import create_causal_mask
38
+ from ...modeling_layers import GradientCheckpointingLayer
39
+ from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
44
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
45
+ from ...utils.output_capturing import capture_outputs
46
+ from ..auto import AutoModel
47
+ from .configuration_granite4_vision import Granite4VisionConfig, Granite4VisionTextConfig
48
+
49
+
50
+ @auto_docstring(
51
+ custom_intro="""
52
+ Base class for Llava outputs, with hidden states and attentions.
53
+ """
54
+ )
55
+ @dataclass
56
+ class Granite4VisionModelOutputWithPast(BaseModelOutputWithPast):
57
+ r"""
58
+ deepstack_features (`list[tuple[int, list[torch.Tensor]]]`, *optional*):
59
+ List of `(llm_layer_idx, packed_features)` pairs produced by the deepstack
60
+ and spatial projectors. Each entry targets one LLM decoder layer; `packed_features`
61
+ is a per-image list of tensors of shape `(num_image_tokens, hidden_size)`.
62
+ """
63
+
64
+ image_hidden_states: torch.FloatTensor | None = None
65
+
66
+ deepstack_features: list | None = None
67
+
68
+
69
+ @auto_docstring(
70
+ custom_intro="""
71
+ Base class for Granite4Vision causal language model (or autoregressive) outputs.
72
+ """
73
+ )
74
+ @dataclass
75
+ class Granite4VisionCausalLMOutputWithPast(ModelOutput):
76
+ r"""
77
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
78
+ Language modeling loss (for next-token prediction).
79
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
80
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
81
+ deepstack_features (`list[tuple[int, list[torch.Tensor]]]`, *optional*):
82
+ List of `(llm_layer_idx, packed_features)` pairs produced by the deepstack
83
+ and spatial projectors. Each entry targets one LLM decoder layer; `packed_features`
84
+ is a per-image list of tensors of shape `(num_image_tokens, hidden_size)`.
85
+ """
86
+
87
+ loss: torch.FloatTensor | None = None
88
+ logits: torch.FloatTensor | None = None
89
+ past_key_values: Cache | None = None
90
+ hidden_states: tuple[torch.FloatTensor] | None = None
91
+ attentions: tuple[torch.FloatTensor] | None = None
92
+ image_hidden_states: torch.FloatTensor | None = None
93
+
94
+ deepstack_features: list | None = None
95
+
96
+
97
+ @auto_docstring(
98
+ custom_intro="""
99
+ Base class for Granite4Vision causal language model (or autoregressive) outputs.
100
+ """
101
+ )
102
+ @dataclass
103
+ class Granite4VisionImageFeaturesOutput(BaseModelOutputWithPooling):
104
+ r"""
105
+ deepstack_features (`list[tuple[int, list[torch.Tensor]]]`, *optional*):
106
+ List of `(llm_layer_idx, packed_features)` pairs produced by the deepstack
107
+ and spatial projectors. Each entry targets one LLM decoder layer; `packed_features`
108
+ is a per-image list of tensors of shape `(num_image_tokens, hidden_size)`.
109
+ """
110
+
111
+ deepstack_features: list | None = None
112
+
113
+
114
+ # ── Downsampling helpers ─────────────────────────────────────────────────────
115
+
116
+
117
+ def interpolate_downsample(image_features: torch.Tensor, orig_side: int, new_side: int) -> torch.Tensor:
118
+ """Spatial downsampling via area interpolation."""
119
+ batch, _, channels = image_features.size()
120
+ spatial = image_features.view(batch, orig_side, orig_side, channels).permute(0, 3, 1, 2)
121
+ spatial = torch.nn.functional.interpolate(spatial, size=(new_side, new_side), mode="area")
122
+ return spatial.permute(0, 2, 3, 1).flatten(1, 2)
123
+
124
+
125
+ def spatial_offset_downsample(image_features: torch.Tensor, orig_side: int, offset: int = 0) -> torch.Tensor:
126
+ """Sample one position from each 2x2 block; offset selects which corner (0=TL,1=TR,2=BL,3=BR)."""
127
+ offset_h, offset_w = [(0, 0), (0, 1), (1, 0), (1, 1)][offset]
128
+ new_side = orig_side // 2
129
+ batch, _, channels = image_features.shape
130
+ grid = image_features.reshape(batch, orig_side, orig_side, channels)
131
+ grid = grid.reshape(batch, new_side, 2, new_side, 2, channels)
132
+ return grid[:, :, offset_h, :, offset_w, :].reshape(batch, -1, channels)
133
+
134
+
135
+ class Granite4VisionWindowQFormerDownsampler(nn.Module):
136
+ """Window-based QFormer downsampler that processes image patches in windows."""
137
+
138
+ def __init__(self, config, spatial_offset=None):
139
+ super().__init__()
140
+ llm_hidden_size = config.text_config.hidden_size
141
+ vision_hidden_size = config.vision_config.hidden_size
142
+
143
+ self.dropout = nn.Dropout(config.projector_dropout)
144
+ self._spatial_offset = spatial_offset
145
+ self._downsample_rate = config.downsample_rate
146
+
147
+ self.qformer = AutoModel.from_config(config.qformer_config)
148
+
149
+ self.image_side = config.vision_config.image_size // config.vision_config.patch_size
150
+ query_side_str, window_side_str = config.downsample_rate.split("/")
151
+ self.query_side, self.window_side = int(query_side_str), int(window_side_str)
152
+ self.query_length = self.query_side**2
153
+ self.norm = nn.LayerNorm(vision_hidden_size, eps=1e-6)
154
+ self.query = nn.Parameter(torch.empty(1, self.query_length, vision_hidden_size))
155
+ self.image_positions = nn.Parameter(torch.empty(1, self.window_side**2, vision_hidden_size))
156
+ self.out_linear = nn.Linear(vision_hidden_size, llm_hidden_size, bias=True)
157
+
158
+ def _windowed_raster(self, features, side, window_size):
159
+ """(B, side*side, C) raster -> (B*num_win*num_win, window_size*window_size, C)"""
160
+ batch, _, channels = features.shape
161
+ num_win = side // window_size
162
+ features = features.view(batch, side, side, channels)
163
+ features = features.view(batch, num_win, window_size, num_win, window_size, channels)
164
+ features = features.transpose(2, 3)
165
+ features = features.flatten(0, 2)
166
+ return features.flatten(1, 2)
167
+
168
+ def _unwindowed_raster(self, windowed_features, num_win, window_size):
169
+ """(B*num_win*num_win, window_size*window_size, C) -> (B, (num_win*window_size)^2, C)"""
170
+ batch_win, _, channels = windowed_features.shape
171
+ if batch_win % (num_win * num_win) != 0:
172
+ raise ValueError(f"Expected batch_win ({batch_win}) to be divisible by num_win^2 ({num_win**2}).")
173
+ batch = batch_win // (num_win * num_win)
174
+ side = num_win * window_size
175
+ features = windowed_features.view(batch, num_win, num_win, window_size, window_size, channels)
176
+ features = features.transpose(2, 3).contiguous()
177
+ features = features.view(batch, side, side, channels)
178
+ return features.flatten(1, 2)
179
+
180
+ def forward(self, image_features: torch.Tensor) -> torch.Tensor:
181
+ batch, hw, channels = image_features.shape
182
+ if self.image_side * self.image_side != hw:
183
+ raise ValueError(
184
+ f"Expected image_features with {self.image_side**2} spatial tokens, got {hw}. "
185
+ "Check that the vision encoder image_size and patch_size match the config."
186
+ )
187
+ num_windows = self.image_side // self.window_side
188
+ interpolated_side = int(self.image_side * Fraction(self._downsample_rate))
189
+ image_features = self.norm(image_features)
190
+ windowed_image_features = self._windowed_raster(image_features, self.image_side, self.window_side)
191
+
192
+ if self._spatial_offset is not None:
193
+ downsampled = spatial_offset_downsample(image_features, self.image_side, self._spatial_offset)
194
+ else:
195
+ downsampled = interpolate_downsample(image_features, self.image_side, interpolated_side)
196
+
197
+ downsampled_side = num_windows * self.query_side
198
+ downsampled_windowed = self._windowed_raster(downsampled, downsampled_side, self.query_side)
199
+
200
+ query_embeds = self.query + downsampled_windowed
201
+ encoder_embeds = self.dropout(windowed_image_features + self.image_positions)
202
+ out_windowed = self.qformer(
203
+ query_embeds=query_embeds,
204
+ encoder_hidden_states=encoder_embeds,
205
+ return_dict=True,
206
+ ).last_hidden_state
207
+
208
+ out = self._unwindowed_raster(out_windowed, num_win=num_windows, window_size=self.query_side)
209
+ out = self.dropout(out)
210
+ return self.out_linear(out)
211
+
212
+
213
+ class Granite4VisionTextRotaryEmbedding(nn.Module):
214
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
215
+
216
+ def __init__(self, config: Granite4VisionTextConfig, device=None):
217
+ super().__init__()
218
+ self.max_seq_len_cached = config.max_position_embeddings
219
+ self.original_max_seq_len = config.max_position_embeddings
220
+
221
+ self.config = config
222
+
223
+ self.rope_type = self.config.rope_parameters["rope_type"]
224
+ rope_init_fn: Callable = self.compute_default_rope_parameters
225
+ if self.rope_type != "default":
226
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
227
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
228
+
229
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
230
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
231
+
232
+ @staticmethod
233
+ def compute_default_rope_parameters(
234
+ config: Granite4VisionTextConfig | None = None,
235
+ device: Optional["torch.device"] = None,
236
+ seq_len: int | None = None,
237
+ ) -> tuple["torch.Tensor", float]:
238
+ """
239
+ Computes the inverse frequencies according to the original RoPE implementation
240
+ Args:
241
+ config ([`~transformers.PreTrainedConfig`]):
242
+ The model configuration.
243
+ device (`torch.device`):
244
+ The device to use for initialization of the inverse frequencies.
245
+ seq_len (`int`, *optional*):
246
+ The current sequence length. Unused for this type of RoPE.
247
+ Returns:
248
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
249
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
250
+ """
251
+ base = config.rope_parameters["rope_theta"]
252
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
253
+
254
+ attention_factor = 1.0 # Unused in this type of RoPE
255
+
256
+ # Compute the inverse frequencies
257
+ inv_freq = 1.0 / (
258
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
259
+ )
260
+ return inv_freq, attention_factor
261
+
262
+ @torch.no_grad()
263
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
264
+ def forward(self, x, position_ids):
265
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
266
+ position_ids_expanded = position_ids[:, None, :].float()
267
+
268
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
269
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
270
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
271
+ emb = torch.cat((freqs, freqs), dim=-1)
272
+ cos = emb.cos() * self.attention_scaling
273
+ sin = emb.sin() * self.attention_scaling
274
+
275
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
276
+
277
+
278
+ def rotate_half(x):
279
+ """Rotates half the hidden dims of the input."""
280
+ x1 = x[..., : x.shape[-1] // 2]
281
+ x2 = x[..., x.shape[-1] // 2 :]
282
+ return torch.cat((-x2, x1), dim=-1)
283
+
284
+
285
+ @use_kernel_func_from_hub("rotary_pos_emb")
286
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
287
+ """Applies Rotary Position Embedding to the query and key tensors.
288
+
289
+ Args:
290
+ q (`torch.Tensor`): The query tensor.
291
+ k (`torch.Tensor`): The key tensor.
292
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
293
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
294
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
295
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
296
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
297
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
298
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
299
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
300
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
301
+ Returns:
302
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
303
+ """
304
+ cos = cos.unsqueeze(unsqueeze_dim)
305
+ sin = sin.unsqueeze(unsqueeze_dim)
306
+ q_embed = (q * cos) + (rotate_half(q) * sin)
307
+ k_embed = (k * cos) + (rotate_half(k) * sin)
308
+ return q_embed, k_embed
309
+
310
+
311
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
312
+ """
313
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
314
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
315
+ """
316
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
317
+ if n_rep == 1:
318
+ return hidden_states
319
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
320
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
321
+
322
+
323
+ def eager_attention_forward(
324
+ module: nn.Module,
325
+ query: torch.Tensor,
326
+ key: torch.Tensor,
327
+ value: torch.Tensor,
328
+ attention_mask: torch.Tensor | None,
329
+ scaling: float,
330
+ dropout: float = 0.0,
331
+ **kwargs: Unpack[TransformersKwargs],
332
+ ):
333
+ key_states = repeat_kv(key, module.num_key_value_groups)
334
+ value_states = repeat_kv(value, module.num_key_value_groups)
335
+
336
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
337
+ if attention_mask is not None:
338
+ attn_weights = attn_weights + attention_mask
339
+
340
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
341
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
342
+ attn_output = torch.matmul(attn_weights, value_states)
343
+ attn_output = attn_output.transpose(1, 2).contiguous()
344
+
345
+ return attn_output, attn_weights
346
+
347
+
348
+ @use_kernelized_func(apply_rotary_pos_emb)
349
+ class Granite4VisionTextAttention(nn.Module):
350
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
351
+
352
+ def __init__(self, config: Granite4VisionTextConfig, layer_idx: int | None = None):
353
+ super().__init__()
354
+ self.config = config
355
+ self.layer_idx = layer_idx
356
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
357
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
358
+ self.scaling = config.attention_multiplier
359
+ self.attention_dropout = config.attention_dropout
360
+ self.is_causal = True
361
+
362
+ self.q_proj = nn.Linear(
363
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
364
+ )
365
+ self.k_proj = nn.Linear(
366
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
367
+ )
368
+ self.v_proj = nn.Linear(
369
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
370
+ )
371
+ self.o_proj = nn.Linear(
372
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
373
+ )
374
+
375
+ def forward(
376
+ self,
377
+ hidden_states: torch.Tensor,
378
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
379
+ attention_mask: torch.Tensor | None = None,
380
+ past_key_values: Cache | None = None,
381
+ **kwargs: Unpack[TransformersKwargs],
382
+ ) -> tuple[torch.Tensor, torch.Tensor]:
383
+ input_shape = hidden_states.shape[:-1]
384
+ hidden_shape = (*input_shape, -1, self.head_dim)
385
+
386
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
387
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
388
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
389
+
390
+ cos, sin = position_embeddings
391
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
392
+
393
+ if past_key_values is not None:
394
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
395
+
396
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
397
+ self.config._attn_implementation, eager_attention_forward
398
+ )
399
+
400
+ attn_output, attn_weights = attention_interface(
401
+ self,
402
+ query_states,
403
+ key_states,
404
+ value_states,
405
+ attention_mask,
406
+ dropout=0.0 if not self.training else self.attention_dropout,
407
+ scaling=self.scaling,
408
+ **kwargs,
409
+ )
410
+
411
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
412
+ attn_output = self.o_proj(attn_output)
413
+ return attn_output, attn_weights
414
+
415
+
416
+ @use_kernel_forward_from_hub("RMSNorm")
417
+ class Granite4VisionTextRMSNorm(nn.Module):
418
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
419
+ """
420
+ Granite4VisionTextRMSNorm is equivalent to T5LayerNorm
421
+ """
422
+ super().__init__()
423
+ self.weight = nn.Parameter(torch.ones(hidden_size))
424
+ self.variance_epsilon = eps
425
+
426
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
427
+ input_dtype = hidden_states.dtype
428
+ hidden_states = hidden_states.to(torch.float32)
429
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
430
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
431
+ return self.weight * hidden_states.to(input_dtype)
432
+
433
+ def extra_repr(self):
434
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
435
+
436
+
437
+ class Granite4VisionTextMLP(nn.Module):
438
+ def __init__(self, config):
439
+ super().__init__()
440
+ self.config = config
441
+ self.hidden_size = config.hidden_size
442
+ self.intermediate_size = config.intermediate_size
443
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
444
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
445
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
446
+ self.act_fn = ACT2FN[config.hidden_act]
447
+
448
+ def forward(self, x):
449
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
450
+ return down_proj
451
+
452
+
453
+ class Granite4VisionTextDecoderLayer(GradientCheckpointingLayer):
454
+ def __init__(self, config: Granite4VisionTextConfig, layer_idx: int):
455
+ super().__init__()
456
+ self.hidden_size = config.hidden_size
457
+ self.self_attn = Granite4VisionTextAttention(config=config, layer_idx=layer_idx)
458
+
459
+ self.mlp = Granite4VisionTextMLP(config)
460
+ self.input_layernorm = Granite4VisionTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
461
+ self.post_attention_layernorm = Granite4VisionTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
462
+ self.residual_multiplier = config.residual_multiplier
463
+
464
+ def forward(
465
+ self,
466
+ hidden_states: torch.Tensor,
467
+ attention_mask: torch.Tensor | None = None,
468
+ position_ids: torch.LongTensor | None = None,
469
+ past_key_values: Cache | None = None,
470
+ use_cache: bool | None = False,
471
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
472
+ **kwargs: Unpack[TransformersKwargs],
473
+ ) -> torch.Tensor:
474
+ """
475
+ Args:
476
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
477
+ attention_mask (`torch.FloatTensor`, *optional*):
478
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
479
+ query_sequence_length, key_sequence_length)` if default attention is used.
480
+ output_attentions (`bool`, *optional*):
481
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
482
+ returned tensors for more detail.
483
+ use_cache (`bool`, *optional*):
484
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
485
+ (see `past_key_values`).
486
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
487
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
488
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
489
+ with `head_dim` being the embedding dimension of each attention head.
490
+ kwargs (`dict`, *optional*):
491
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
492
+ into the model
493
+ """
494
+ residual = hidden_states
495
+
496
+ hidden_states = self.input_layernorm(hidden_states)
497
+
498
+ hidden_states, _ = self.self_attn(
499
+ hidden_states=hidden_states,
500
+ attention_mask=attention_mask,
501
+ position_ids=position_ids,
502
+ past_key_values=past_key_values,
503
+ use_cache=use_cache,
504
+ position_embeddings=position_embeddings,
505
+ **kwargs,
506
+ )
507
+ hidden_states = residual + hidden_states * self.residual_multiplier
508
+
509
+ residual = hidden_states
510
+ hidden_states = self.post_attention_layernorm(hidden_states)
511
+ hidden_states = self.mlp(hidden_states)
512
+ hidden_states = residual + hidden_states * self.residual_multiplier
513
+
514
+ return hidden_states
515
+
516
+
517
+ @auto_docstring
518
+ class Granite4VisionPreTrainedModel(PreTrainedModel):
519
+ config: Granite4VisionConfig
520
+ base_model_prefix = "model"
521
+ input_modalities = ("image", "text")
522
+ supports_gradient_checkpointing = True
523
+ _no_split_modules = ["Granite4VisionTextDecoderLayer", "Granite4VisionWindowQFormerDownsampler"]
524
+ _skip_keys_device_placement = ["past_key_values"]
525
+
526
+ _supports_flash_attn = True
527
+ _supports_sdpa = True
528
+
529
+ _can_compile_fullgraph = True
530
+ _supports_flex_attn = True
531
+ _supports_attention_backend = True
532
+ _can_record_outputs = {
533
+ "hidden_states": Granite4VisionTextDecoderLayer,
534
+ "attentions": Granite4VisionTextAttention,
535
+ }
536
+
537
+ @torch.no_grad()
538
+ def _init_weights(self, module):
539
+ super()._init_weights(module)
540
+ if isinstance(module, Granite4VisionModel):
541
+ embed_std = 1 / math.sqrt(self.config.text_config.hidden_size)
542
+ init.normal_(module.image_newline, mean=0.0, std=embed_std)
543
+ if isinstance(module, Granite4VisionWindowQFormerDownsampler):
544
+ embed_std = 1 / math.sqrt(module.query.shape[-1])
545
+ init.normal_(module.query, mean=0.0, std=embed_std)
546
+ init.normal_(module.image_positions, mean=0.0, std=embed_std)
547
+
548
+
549
+ @auto_docstring
550
+ class Granite4VisionTextModel(Granite4VisionPreTrainedModel):
551
+ """Granite LLM backbone with deepstack feature injection support."""
552
+
553
+ config_class = Granite4VisionTextConfig
554
+
555
+ def __init__(self, config: Granite4VisionTextConfig):
556
+ super().__init__(config)
557
+ self.padding_idx = config.pad_token_id
558
+ self.vocab_size = config.vocab_size
559
+
560
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
561
+ self.layers = nn.ModuleList(
562
+ [Granite4VisionTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
563
+ )
564
+ self.norm = Granite4VisionTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
565
+ self.rotary_emb = Granite4VisionTextRotaryEmbedding(config=config)
566
+ self.gradient_checkpointing = False
567
+ self.embedding_multiplier = config.embedding_multiplier
568
+
569
+ # Initialize weights and apply final processing
570
+ self.post_init()
571
+
572
+ @merge_with_config_defaults
573
+ @capture_outputs
574
+ @auto_docstring
575
+ def forward(
576
+ self,
577
+ input_ids: torch.LongTensor | None = None,
578
+ attention_mask: torch.Tensor | None = None,
579
+ position_ids: torch.LongTensor | None = None,
580
+ past_key_values: Cache | None = None,
581
+ inputs_embeds: torch.FloatTensor | None = None,
582
+ use_cache: bool | None = None,
583
+ vision_mask: torch.BoolTensor | None = None,
584
+ deepstack_features: dict[int, torch.Tensor] | None = None,
585
+ **kwargs: Unpack[TransformersKwargs],
586
+ ) -> BaseModelOutputWithPast:
587
+ r"""
588
+ vision_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
589
+ Boolean mask marking image token positions. Required when `deepstack_features` is provided.
590
+ deepstack_features (`dict[int, torch.Tensor]`, *optional*):
591
+ Mapping from LLM layer index to projected vision features of shape `(num_image_tokens, hidden_size)`.
592
+ Features are added into image-token positions of hidden states before the corresponding decoder layer.
593
+ """
594
+ if (input_ids is None) ^ (inputs_embeds is not None):
595
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
596
+
597
+ if inputs_embeds is None:
598
+ inputs_embeds = self.embed_tokens(input_ids)
599
+
600
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
601
+
602
+ if position_ids is None:
603
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
604
+ position_ids = (
605
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
606
+ ).unsqueeze(0)
607
+
608
+ causal_mask = create_causal_mask(
609
+ config=self.config,
610
+ inputs_embeds=inputs_embeds,
611
+ attention_mask=attention_mask,
612
+ past_key_values=past_key_values,
613
+ position_ids=position_ids,
614
+ )
615
+
616
+ hidden_states = inputs_embeds
617
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
618
+
619
+ for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
620
+ if deepstack_features is not None and layer_idx in deepstack_features:
621
+ features = deepstack_features[layer_idx].to(hidden_states.device, hidden_states.dtype)
622
+ mask = vision_mask.to(hidden_states.device)
623
+ hidden_states = hidden_states.masked_scatter(mask, (hidden_states[mask] + features.flatten()).view(-1))
624
+
625
+ hidden_states = decoder_layer(
626
+ hidden_states,
627
+ attention_mask=causal_mask,
628
+ position_ids=position_ids,
629
+ past_key_values=past_key_values,
630
+ use_cache=use_cache,
631
+ position_embeddings=position_embeddings,
632
+ **kwargs,
633
+ )
634
+
635
+ hidden_states = self.norm(hidden_states)
636
+
637
+ return BaseModelOutputWithPast(
638
+ last_hidden_state=hidden_states,
639
+ past_key_values=past_key_values,
640
+ )
641
+
642
+
643
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
644
+ """
645
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
646
+
647
+ Args:
648
+ image_size (`tuple`):
649
+ The size of the input image in the format (width, height).
650
+ grid_pinpoints (`List`):
651
+ A list containing possible resolutions. Each item in the list should be a tuple or list
652
+ of the form `(height, width)`.
653
+ patch_size (`int`):
654
+ The size of each image patch.
655
+
656
+ Returns:
657
+ tuple: The shape of the image patch grid in the format (width, height).
658
+ """
659
+ if not isinstance(grid_pinpoints, list):
660
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
661
+
662
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
663
+ if not isinstance(image_size, (list, tuple)):
664
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
665
+ raise TypeError(
666
+ f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
667
+ )
668
+ image_size = image_size.tolist()
669
+
670
+ height, width = select_best_resolution(image_size, grid_pinpoints)
671
+ return height // patch_size, width // patch_size
672
+
673
+
674
+ def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
675
+ """
676
+ Calculate the number of patches after the preprocessing for images of any resolution.
677
+
678
+ Args:
679
+ image_size (`torch.LongTensor` or `np.ndarray` or `tuple[int, int]`):
680
+ The size of the input image in the format (height, width). ?
681
+ grid_pinpoints (`List`):
682
+ A list containing possible resolutions. Each item in the list should be a tuple or list
683
+ of the form `(height, width)`.
684
+ patch_size (`int`):
685
+ The size of each image patch.
686
+
687
+ Returns:
688
+ int: the number of patches
689
+ """
690
+ if not isinstance(grid_pinpoints, list):
691
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
692
+
693
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
694
+ if not isinstance(image_size, (list, tuple)):
695
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
696
+ raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
697
+ image_size = image_size.tolist()
698
+
699
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
700
+ height, width = best_resolution
701
+ num_patches = 0
702
+ # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
703
+ for i in range(0, height, patch_size):
704
+ for j in range(0, width, patch_size):
705
+ num_patches += 1
706
+ # add the base patch
707
+ num_patches += 1
708
+ return num_patches
709
+
710
+
711
+ def unpad_image(tensor, original_size):
712
+ """
713
+ Unpads a PyTorch tensor of a padded and resized image.
714
+
715
+ Args:
716
+ tensor (`torch.Tensor`):
717
+ The image tensor, assumed to be of shape (num_channels, height, width).
718
+ original_size (`tuple`):
719
+ The original size of the image (height, width).
720
+
721
+ Returns:
722
+ `torch.Tensor`: The unpadded image tensor.
723
+ """
724
+ if not isinstance(original_size, (list, tuple)):
725
+ if not isinstance(original_size, (torch.Tensor, np.ndarray)):
726
+ raise TypeError(
727
+ f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
728
+ )
729
+ original_size = original_size.tolist()
730
+ original_height, original_width = original_size
731
+ current_height, current_width = tensor.shape[1:]
732
+
733
+ original_aspect_ratio = original_width / original_height
734
+ current_aspect_ratio = current_width / current_height
735
+
736
+ if original_aspect_ratio > current_aspect_ratio:
737
+ scale_factor = current_width / original_width
738
+ new_height = int(round(original_height * scale_factor, 7))
739
+ padding = (current_height - new_height) // 2
740
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
741
+ else:
742
+ scale_factor = current_height / original_height
743
+ new_width = int(round(original_width * scale_factor, 7))
744
+ padding = (current_width - new_width) // 2
745
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
746
+
747
+ return unpadded_tensor
748
+
749
+
750
+ @auto_docstring(
751
+ custom_intro="""
752
+ The Llava-Next model which consists of a vision backbone and a language model without language modeling head.
753
+ """
754
+ )
755
+ class Granite4VisionModel(Granite4VisionPreTrainedModel):
756
+ base_model_prefix = "model"
757
+ config_class = Granite4VisionConfig
758
+
759
+ def __init__(self, config: Granite4VisionConfig):
760
+ super().__init__(config)
761
+ self.vision_tower = AutoModel.from_config(config.vision_config)
762
+ embed_std = 1 / math.sqrt(config.text_config.hidden_size)
763
+ self.image_newline = nn.Parameter(torch.randn(config.text_config.hidden_size, dtype=self.dtype) * embed_std)
764
+
765
+ self.vocab_size = config.text_config.vocab_size
766
+
767
+ # Replace the inherited LLM backbone with our deepstack-aware subclass
768
+ self.language_model = Granite4VisionTextModel(config.text_config)
769
+
770
+ self.downsample_rate = config.downsample_rate
771
+ self.projector_dropout = config.projector_dropout
772
+
773
+ # Deepstack projectors: one per (vision_layer, llm_layer) pair
774
+ self.layerwise_projectors = nn.ModuleList(
775
+ [Granite4VisionWindowQFormerDownsampler(config) for _ in range(len(config.deepstack_layer_map))]
776
+ )
777
+
778
+ # Spatial sampling projectors: 4 offset groups (TL, TR, BL, BR)
779
+ self.spatial_projectors = nn.ModuleList(
780
+ [Granite4VisionWindowQFormerDownsampler(config, spatial_offset=i) for i in range(4)]
781
+ )
782
+
783
+ self.pad_token_id = (
784
+ self.config.text_config.pad_token_id if self.config.text_config.pad_token_id is not None else -1
785
+ )
786
+ self.post_init()
787
+
788
+ def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
789
+ """
790
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
791
+
792
+ Overrides the parent to apply downsample_rate to height/width calculations.
793
+ """
794
+ new_image_features = []
795
+ feature_lens = []
796
+ for image_idx, image_feature in enumerate(image_features):
797
+ if image_feature.shape[0] > 1:
798
+ base_image_feature = image_feature[0]
799
+ image_feature = image_feature[1:]
800
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
801
+
802
+ num_patch_height, num_patch_width = get_anyres_image_grid_shape(
803
+ image_sizes[image_idx],
804
+ self.config.image_grid_pinpoints,
805
+ self.config.vision_config.image_size,
806
+ )
807
+ if self.layerwise_projectors is not None:
808
+ ds_rate = Fraction(self.downsample_rate)
809
+ height = int(height * ds_rate)
810
+ width = int(width * ds_rate)
811
+
812
+ if (
813
+ np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
814
+ and vision_feature_select_strategy == "default"
815
+ ):
816
+ raise ValueError(
817
+ "Image feature shape does not line up with the provided patch size. "
818
+ "You may be using the `default` vision_feature_select_strategy with a "
819
+ "visual encoder that does not have CLS token."
820
+ )
821
+
822
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
823
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
824
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
825
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
826
+ if image_newline is not None:
827
+ image_feature = torch.cat(
828
+ (
829
+ image_feature,
830
+ image_newline[:, None, None]
831
+ .expand(*image_feature.shape[:-1], 1)
832
+ .to(image_feature.device, image_feature.dtype),
833
+ ),
834
+ dim=-1,
835
+ )
836
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
837
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
838
+ else:
839
+ image_feature = image_feature[0]
840
+ if image_newline is not None:
841
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
842
+ new_image_features.append(image_feature)
843
+ feature_lens.append(image_feature.size(0))
844
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features[0].device)
845
+ return new_image_features, feature_lens
846
+
847
+ @merge_with_config_defaults
848
+ @can_return_tuple
849
+ @auto_docstring(
850
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
851
+ )
852
+ def get_image_features(
853
+ self,
854
+ pixel_values: torch.FloatTensor,
855
+ image_sizes: torch.Tensor,
856
+ vision_feature_layer: int | list[int] | None = None,
857
+ vision_feature_select_strategy: str | None = None,
858
+ output_hidden_states: bool | None = None,
859
+ **kwargs,
860
+ ) -> Granite4VisionImageFeaturesOutput:
861
+ r"""
862
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
863
+ The tensors corresponding to the input images.
864
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
865
+ Actual image size of each images (H, W).
866
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
867
+ The index of the layer to select the vision feature. If multiple indices are provided,
868
+ the vision feature of the corresponding indices will be concatenated to form the
869
+ vision features.
870
+ vision_feature_select_strategy (`str`, *optional*):
871
+ The feature selection strategy used to select the vision feature from the vision backbone.
872
+ Can be one of `"default"` or `"full"`
873
+ """
874
+
875
+ image_num_patches = [
876
+ image_size_to_num_patches(
877
+ image_size=imsize,
878
+ grid_pinpoints=self.config.image_grid_pinpoints,
879
+ patch_size=self.config.vision_config.image_size,
880
+ )
881
+ for imsize in image_sizes
882
+ ]
883
+
884
+ if pixel_values.dim() == 5:
885
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
886
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
887
+ elif pixel_values.dim() != 4:
888
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
889
+
890
+ vision_outputs = self.vision_tower(pixel_values, output_hidden_states=True, **kwargs)
891
+
892
+ # Deepstack features: extract from multiple vision layers, downsample via interpolation
893
+ all_features = []
894
+ for projection_idx, (vision_layer, llm_layer) in enumerate(self.config.deepstack_layer_map):
895
+ selected_feature = vision_outputs.hidden_states[vision_layer]
896
+
897
+ if vision_feature_select_strategy == "default":
898
+ selected_feature = selected_feature[:, 1:]
899
+
900
+ projected_features = self.layerwise_projectors[projection_idx](selected_feature)
901
+ projected_features = torch.split(projected_features, image_num_patches, dim=0)
902
+
903
+ packed_features, _ = self.pack_image_features(
904
+ projected_features,
905
+ image_sizes,
906
+ vision_feature_select_strategy=vision_feature_select_strategy,
907
+ image_newline=self.image_newline,
908
+ )
909
+
910
+ all_features.append((llm_layer, packed_features))
911
+
912
+ # Spatial features: extract 4 offset groups from a single vision layer
913
+ spatial_feature = vision_outputs.hidden_states[self.config.spatial_vision_layer]
914
+
915
+ if vision_feature_select_strategy == "default":
916
+ spatial_feature = spatial_feature[:, 1:]
917
+
918
+ for group_idx, llm_layer in enumerate(self.config.spatial_target_layers):
919
+ projected_group = self.spatial_projectors[group_idx](spatial_feature)
920
+ projected_group_split = torch.split(projected_group, image_num_patches, dim=0)
921
+
922
+ packed_group, _ = self.pack_image_features(
923
+ projected_group_split,
924
+ image_sizes,
925
+ vision_feature_select_strategy=vision_feature_select_strategy,
926
+ image_newline=self.image_newline,
927
+ )
928
+
929
+ all_features.append((llm_layer, packed_group))
930
+
931
+ return Granite4VisionImageFeaturesOutput(
932
+ deepstack_features=all_features,
933
+ hidden_states=vision_outputs.hidden_states,
934
+ )
935
+
936
+ def get_placeholder_mask(
937
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
938
+ ):
939
+ """
940
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
941
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
942
+ """
943
+ if input_ids is None:
944
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
945
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
946
+ )
947
+ special_image_mask = special_image_mask.all(-1)
948
+ else:
949
+ special_image_mask = input_ids == self.config.image_token_id
950
+
951
+ n_image_tokens = special_image_mask.sum()
952
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
953
+ torch_compilable_check(
954
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
955
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}",
956
+ )
957
+ return special_image_mask
958
+
959
+ @merge_with_config_defaults
960
+ @can_return_tuple
961
+ @auto_docstring
962
+ def forward(
963
+ self,
964
+ input_ids: torch.LongTensor | None = None,
965
+ pixel_values: torch.FloatTensor | None = None,
966
+ image_sizes: torch.LongTensor | None = None,
967
+ attention_mask: torch.Tensor | None = None,
968
+ position_ids: torch.LongTensor | None = None,
969
+ past_key_values: Cache | None = None,
970
+ inputs_embeds: torch.FloatTensor | None = None,
971
+ vision_feature_layer: int | list[int] | None = None,
972
+ vision_feature_select_strategy: str | None = None,
973
+ use_cache: bool | None = None,
974
+ **kwargs: Unpack[TransformersKwargs],
975
+ ) -> tuple | Granite4VisionModelOutputWithPast:
976
+ r"""
977
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
978
+ The feature selection strategy used to select the vision feature from the vision backbone.
979
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
980
+ If `"full"`, the full vision features are used.
981
+ """
982
+ if (input_ids is None) ^ (inputs_embeds is not None):
983
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
984
+
985
+ if inputs_embeds is None:
986
+ inputs_embeds = self.get_input_embeddings()(input_ids)
987
+
988
+ # Build deepstack injection map and scatter initial image embeddings
989
+ deepstack_features = None
990
+ vision_mask = None
991
+ image_features = None
992
+ if pixel_values is not None:
993
+ image_features = self.get_image_features(
994
+ pixel_values,
995
+ image_sizes,
996
+ vision_feature_layer=vision_feature_layer,
997
+ vision_feature_select_strategy=vision_feature_select_strategy,
998
+ )
999
+
1000
+ deepstack_features = {}
1001
+ for idx, (llm_layer_idx, packed_features) in enumerate(image_features.deepstack_features):
1002
+ concat_features = torch.cat(packed_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1003
+ if idx == 0:
1004
+ vision_mask = self.get_placeholder_mask(
1005
+ input_ids, inputs_embeds=inputs_embeds, image_features=concat_features
1006
+ )
1007
+ # Zero out image token positions — deepstack injection will sum features in during forward.
1008
+ inputs_embeds = inputs_embeds.masked_fill(vision_mask, 0.0)
1009
+ deepstack_features[llm_layer_idx] = concat_features
1010
+
1011
+ outputs = self.language_model(
1012
+ input_ids=None,
1013
+ inputs_embeds=inputs_embeds,
1014
+ attention_mask=attention_mask,
1015
+ position_ids=position_ids,
1016
+ past_key_values=past_key_values,
1017
+ use_cache=use_cache,
1018
+ vision_mask=vision_mask,
1019
+ deepstack_features=deepstack_features,
1020
+ **kwargs,
1021
+ )
1022
+
1023
+ return Granite4VisionModelOutputWithPast(
1024
+ last_hidden_state=outputs.last_hidden_state,
1025
+ past_key_values=outputs.past_key_values,
1026
+ hidden_states=outputs.hidden_states,
1027
+ attentions=outputs.attentions,
1028
+ deepstack_features=image_features.deepstack_features if pixel_values is not None else None,
1029
+ )
1030
+
1031
+
1032
+ @auto_docstring(
1033
+ custom_intro="""
1034
+ The LLAVA-NeXT model which consists of a vision backbone and a language model.
1035
+ """
1036
+ )
1037
+ class Granite4VisionForConditionalGeneration(Granite4VisionPreTrainedModel, GenerationMixin):
1038
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
1039
+
1040
+ def __init__(self, config: Granite4VisionConfig):
1041
+ super().__init__(config)
1042
+ self.model = Granite4VisionModel(config)
1043
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1044
+ self.post_init()
1045
+
1046
+ def get_output_embeddings(self) -> nn.Module:
1047
+ return self.lm_head
1048
+
1049
+ def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
1050
+ return self.model.pack_image_features(
1051
+ image_features=image_features,
1052
+ image_sizes=image_sizes,
1053
+ vision_feature_select_strategy=vision_feature_select_strategy,
1054
+ image_newline=image_newline,
1055
+ )
1056
+
1057
+ @merge_with_config_defaults
1058
+ @can_return_tuple
1059
+ @auto_docstring
1060
+ def get_image_features(
1061
+ self,
1062
+ pixel_values: torch.FloatTensor,
1063
+ image_sizes: torch.Tensor,
1064
+ vision_feature_layer: int | list[int] | list[int] | None = None,
1065
+ vision_feature_select_strategy: str | None = None,
1066
+ **kwargs: Unpack[TransformersKwargs],
1067
+ ) -> tuple | BaseModelOutputWithPooling:
1068
+ r"""
1069
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
1070
+ The tensors corresponding to the input images.
1071
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
1072
+ Actual image size of each images (H, W).
1073
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
1074
+ The index of the layer to select the vision feature. If multiple indices are provided,
1075
+ the vision feature of the corresponding indices will be concatenated to form the
1076
+ vision features.
1077
+ vision_feature_select_strategy (`str`, *optional*):
1078
+ The feature selection strategy used to select the vision feature from the vision backbone.
1079
+ Can be one of `"default"` or `"full"`
1080
+ """
1081
+ return self.model.get_image_features(
1082
+ pixel_values=pixel_values,
1083
+ image_sizes=image_sizes,
1084
+ vision_feature_layer=vision_feature_layer,
1085
+ vision_feature_select_strategy=vision_feature_select_strategy,
1086
+ **kwargs,
1087
+ )
1088
+
1089
+ @merge_with_config_defaults
1090
+ @can_return_tuple
1091
+ @auto_docstring
1092
+ def forward(
1093
+ self,
1094
+ input_ids: torch.LongTensor | None = None,
1095
+ pixel_values: torch.FloatTensor | None = None,
1096
+ image_sizes: torch.LongTensor | None = None,
1097
+ attention_mask: torch.Tensor | None = None,
1098
+ position_ids: torch.LongTensor | None = None,
1099
+ past_key_values: Cache | None = None,
1100
+ inputs_embeds: torch.FloatTensor | None = None,
1101
+ vision_feature_layer: int | list[int] | None = None,
1102
+ vision_feature_select_strategy: str | None = None,
1103
+ labels: torch.LongTensor | None = None,
1104
+ use_cache: bool | None = None,
1105
+ logits_to_keep: int | torch.Tensor = 0,
1106
+ **kwargs: Unpack[TransformersKwargs],
1107
+ ) -> tuple | Granite4VisionCausalLMOutputWithPast:
1108
+ r"""
1109
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
1110
+ The feature selection strategy used to select the vision feature from the vision backbone.
1111
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
1112
+ If `"full"`, the full vision features are used.
1113
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1114
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1115
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1116
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1117
+
1118
+ Example:
1119
+
1120
+ ```python
1121
+ >>> from PIL import Image
1122
+ >>> import httpx
1123
+ >>> from io import BytesIO
1124
+ >>> from transformers import AutoProcessor, Granite4VisionForConditionalGeneration
1125
+
1126
+ >>> model = Granite4VisionForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
1127
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
1128
+
1129
+ >>> prompt = "[INST] <image>\nWhat is shown in this image? [/INST]"
1130
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1131
+ >>> with httpx.stream("GET", url) as response:
1132
+ ... image = Image.open(BytesIO(response.read()))
1133
+
1134
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
1135
+
1136
+ >>> # Generate
1137
+ >>> generate_ids = model.generate(**inputs, max_length=30)
1138
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1139
+ "[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)"
1140
+ ```"""
1141
+ outputs = self.model(
1142
+ input_ids,
1143
+ pixel_values=pixel_values,
1144
+ image_sizes=image_sizes,
1145
+ vision_feature_layer=vision_feature_layer,
1146
+ vision_feature_select_strategy=vision_feature_select_strategy,
1147
+ attention_mask=attention_mask,
1148
+ position_ids=position_ids,
1149
+ past_key_values=past_key_values,
1150
+ inputs_embeds=inputs_embeds,
1151
+ use_cache=use_cache,
1152
+ return_dict=True,
1153
+ **kwargs,
1154
+ )
1155
+
1156
+ hidden_states = outputs.last_hidden_state
1157
+
1158
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1159
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1160
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1161
+ logits = logits / self.config.text_config.logits_scaling
1162
+
1163
+ loss = None
1164
+ if labels is not None:
1165
+ loss = self.loss_function(
1166
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1167
+ )
1168
+
1169
+ return Granite4VisionCausalLMOutputWithPast(
1170
+ loss=loss,
1171
+ logits=logits,
1172
+ past_key_values=outputs.past_key_values,
1173
+ hidden_states=outputs.hidden_states,
1174
+ attentions=outputs.attentions,
1175
+ deepstack_features=outputs.deepstack_features,
1176
+ )
1177
+
1178
+ def prepare_inputs_for_generation(
1179
+ self,
1180
+ input_ids,
1181
+ past_key_values=None,
1182
+ inputs_embeds=None,
1183
+ pixel_values=None,
1184
+ image_sizes=None,
1185
+ attention_mask=None,
1186
+ logits_to_keep=None,
1187
+ is_first_iteration=False,
1188
+ **kwargs,
1189
+ ):
1190
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1191
+
1192
+ model_inputs = super().prepare_inputs_for_generation(
1193
+ input_ids,
1194
+ past_key_values=past_key_values,
1195
+ inputs_embeds=inputs_embeds,
1196
+ attention_mask=attention_mask,
1197
+ logits_to_keep=logits_to_keep,
1198
+ is_first_iteration=is_first_iteration,
1199
+ **kwargs,
1200
+ )
1201
+
1202
+ # Pixel values are used only in the first iteration if available
1203
+ # In subsequent iterations, they are already merged with text and cached
1204
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
1205
+ # iteration with a question and cached system prompt (continue generate from cache)
1206
+ if is_first_iteration or not kwargs.get("use_cache", True):
1207
+ model_inputs["pixel_values"] = pixel_values
1208
+ model_inputs["image_sizes"] = image_sizes
1209
+
1210
+ return model_inputs
1211
+
1212
+
1213
+ __all__ = [
1214
+ "Granite4VisionPreTrainedModel",
1215
+ "Granite4VisionTextModel",
1216
+ "Granite4VisionModel",
1217
+ "Granite4VisionForConditionalGeneration",
1218
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/modular_granite4_vision.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 IBM 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
+
15
+ import math
16
+ from dataclasses import dataclass
17
+ from fractions import Fraction
18
+
19
+ import numpy as np
20
+ import torch
21
+ from torch import nn
22
+
23
+ from ... import initialization as init
24
+ from ...cache_utils import Cache
25
+ from ...configuration_utils import PreTrainedConfig
26
+ from ...image_processing_utils import select_best_resolution
27
+ from ...masking_utils import create_causal_mask
28
+ from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling
29
+ from ...processing_utils import Unpack
30
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
31
+ from ...utils.generic import merge_with_config_defaults
32
+ from ..auto import CONFIG_MAPPING, AutoConfig, AutoModel
33
+ from ..granite.configuration_granite import GraniteConfig
34
+ from ..granite.modeling_granite import GraniteAttention, GraniteDecoderLayer, GraniteModel, GraniteRotaryEmbedding
35
+ from ..llava_next.configuration_llava_next import LlavaNextConfig
36
+ from ..llava_next.modeling_llava_next import (
37
+ LlavaNextCausalLMOutputWithPast,
38
+ LlavaNextForConditionalGeneration,
39
+ LlavaNextModel,
40
+ LlavaNextModelOutputWithPast,
41
+ LlavaNextPreTrainedModel,
42
+ get_anyres_image_grid_shape,
43
+ image_size_to_num_patches,
44
+ unpad_image,
45
+ )
46
+ from ..llava_next.processing_llava_next import LlavaNextProcessor
47
+
48
+
49
+ # ── Output classes ──────────────────────────────────────────────────────────
50
+
51
+
52
+ class Granite4VisionModelOutputWithPast(LlavaNextModelOutputWithPast):
53
+ r"""
54
+ deepstack_features (`list[tuple[int, list[torch.Tensor]]]`, *optional*):
55
+ List of `(llm_layer_idx, packed_features)` pairs produced by the deepstack
56
+ and spatial projectors. Each entry targets one LLM decoder layer; `packed_features`
57
+ is a per-image list of tensors of shape `(num_image_tokens, hidden_size)`.
58
+ """
59
+
60
+ deepstack_features: list | None = None
61
+
62
+
63
+ class Granite4VisionCausalLMOutputWithPast(LlavaNextCausalLMOutputWithPast):
64
+ r"""
65
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
66
+ Language modeling loss (for next-token prediction).
67
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
68
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
69
+ deepstack_features (`list[tuple[int, list[torch.Tensor]]]`, *optional*):
70
+ List of `(llm_layer_idx, packed_features)` pairs produced by the deepstack
71
+ and spatial projectors. Each entry targets one LLM decoder layer; `packed_features`
72
+ is a per-image list of tensors of shape `(num_image_tokens, hidden_size)`.
73
+ """
74
+
75
+ deepstack_features: list | None = None
76
+
77
+
78
+ @auto_docstring(
79
+ custom_intro="""
80
+ Base class for Granite4Vision causal language model (or autoregressive) outputs.
81
+ """
82
+ )
83
+ @dataclass
84
+ class Granite4VisionImageFeaturesOutput(BaseModelOutputWithPooling):
85
+ r"""
86
+ deepstack_features (`list[tuple[int, list[torch.Tensor]]]`, *optional*):
87
+ List of `(llm_layer_idx, packed_features)` pairs produced by the deepstack
88
+ and spatial projectors. Each entry targets one LLM decoder layer; `packed_features`
89
+ is a per-image list of tensors of shape `(num_image_tokens, hidden_size)`.
90
+ """
91
+
92
+ deepstack_features: list | None = None
93
+
94
+
95
+ # ── Config ──────────────────────────────────────────────────────────────────
96
+
97
+
98
+ class Granite4VisionTextConfig(GraniteConfig):
99
+ model_type = "granite4_vision_text"
100
+ base_config_key = "text_config"
101
+
102
+
103
+ class Granite4VisionConfig(LlavaNextConfig):
104
+ r"""
105
+ image_grid_pinpoints (`list`, *optional*):
106
+ A list of possible resolutions to use for processing high resolution images. Each item in the list should be a
107
+ tuple or list of the form `(height, width)`.
108
+ downsample_rate (`str`, *optional*):
109
+ Fractional downsample rate for the Window Q-Former projector, e.g. `"1/4"` or `"3/8"`.
110
+ The numerator is the query window side, the denominator is the key window side.
111
+ deepstack_layer_map (`list`, *optional*):
112
+ List of `[vision_layer_idx, llm_layer_idx]` pairs. Features from each vision encoder layer
113
+ are projected and injected at the corresponding LLM decoder layer during forward pass.
114
+ spatial_vision_layer (`int`, *optional*, defaults to `-1`):
115
+ Index of the vision encoder layer used for spatial sampling.
116
+ spatial_target_layers (`list`, *optional*, defaults to `[12, 15, 18, 21]`):
117
+ Target LLM layers for the 4 spatial offset groups.
118
+ projector_dropout (`float`, *optional*, defaults to `0.1`):
119
+ Dropout probability in the Window Q-Former projector.
120
+ qformer_config (`dict` or `Blip2QFormerConfig`, *optional*):
121
+ Configuration for the Window Q-Former projector. If `None`, defaults are derived from
122
+ `vision_config.hidden_size`.
123
+ """
124
+
125
+ model_type = "granite4_vision"
126
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig, "qformer_config": AutoConfig}
127
+
128
+ multimodal_projector_bias = AttributeError()
129
+ projector_hidden_act = AttributeError()
130
+
131
+ downsample_rate: str | None = None
132
+ deepstack_layer_map: list | None = None
133
+ spatial_vision_layer: int = -1
134
+ spatial_target_layers: list | None = None
135
+ projector_dropout: float = 0.1
136
+ qformer_config: dict | PreTrainedConfig | None = None
137
+
138
+ def __post_init__(self, **kwargs):
139
+ self.image_grid_pinpoints = (
140
+ self.image_grid_pinpoints
141
+ if self.image_grid_pinpoints is not None
142
+ else [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
143
+ )
144
+
145
+ if self.deepstack_layer_map is not None:
146
+ self.deepstack_layer_map = [(int(v), int(l)) for v, l in self.deepstack_layer_map]
147
+
148
+ if self.spatial_target_layers is None:
149
+ self.spatial_target_layers = [12, 15, 18, 21]
150
+
151
+ if isinstance(self.vision_config, dict):
152
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "clip_vision_model")
153
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
154
+ elif self.vision_config is None:
155
+ self.vision_config = CONFIG_MAPPING["siglip_vision_model"]()
156
+
157
+ if isinstance(self.text_config, dict):
158
+ self.text_config["model_type"] = self.text_config.get("model_type", "granite4_vision_text")
159
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
160
+ elif self.text_config is None:
161
+ self.text_config = CONFIG_MAPPING["llama"]()
162
+
163
+ if isinstance(self.qformer_config, dict):
164
+ model_type = self.qformer_config.get("model_type", "blip_2_qformer")
165
+ self.qformer_config = CONFIG_MAPPING[model_type](**self.qformer_config)
166
+ if self.qformer_config is None:
167
+ vision_hidden_size = self.vision_config.hidden_size
168
+ self.qformer_config = CONFIG_MAPPING["blip_2_qformer"](
169
+ num_hidden_layers=1,
170
+ intermediate_size=3072,
171
+ cross_attention_frequency=1,
172
+ max_position_embeddings=2048,
173
+ use_qformer_text_input=False,
174
+ hidden_size=vision_hidden_size,
175
+ num_attention_heads=vision_hidden_size // 64,
176
+ encoder_hidden_size=vision_hidden_size,
177
+ )
178
+ PreTrainedConfig.__post_init__(**kwargs)
179
+
180
+
181
+ # ── Processor ───────────────────────────────────────────────────────────────
182
+
183
+
184
+ class Granite4VisionProcessor(LlavaNextProcessor):
185
+ def __init__(
186
+ self,
187
+ image_processor=None,
188
+ tokenizer=None,
189
+ patch_size=None,
190
+ vision_feature_select_strategy=None,
191
+ chat_template=None,
192
+ image_token="<image>",
193
+ num_additional_image_tokens=0,
194
+ downsample_rate=None,
195
+ **kwargs,
196
+ ):
197
+ r"""
198
+ patch_size (`int`, *optional*):
199
+ Patch size from the vision tower.
200
+ vision_feature_select_strategy (`str`, *optional*):
201
+ The feature selection strategy used to select the vision feature from the vision backbone.
202
+ Should be same as in model's config.
203
+ image_token (`str`, *optional*, defaults to `"<image>"`):
204
+ Special token used to denote image location.
205
+ num_additional_image_tokens (`int`, *optional*, defaults to `0`):
206
+ Number of additional tokens added to the image embeddings, such as CLS (+1).
207
+ downsample_rate (`str`, *optional*):
208
+ Fractional downsample rate (e.g. `"1/4"`), used to adjust the number of image tokens
209
+ when computing token counts for padding/truncation.
210
+ """
211
+ super().__init__(
212
+ image_processor=image_processor,
213
+ tokenizer=tokenizer,
214
+ patch_size=patch_size,
215
+ vision_feature_select_strategy=vision_feature_select_strategy,
216
+ chat_template=chat_template,
217
+ image_token=image_token,
218
+ num_additional_image_tokens=num_additional_image_tokens,
219
+ )
220
+ self.downsample_rate = downsample_rate
221
+
222
+ def _get_number_of_features(self, orig_height: int, orig_width: int, height: int, width: int) -> int:
223
+ image_grid_pinpoints = self.image_processor.image_grid_pinpoints
224
+
225
+ height_best_resolution, width_best_resolution = select_best_resolution(
226
+ [orig_height, orig_width], image_grid_pinpoints
227
+ )
228
+ scale_height, scale_width = height_best_resolution // height, width_best_resolution // width
229
+
230
+ patches_height = height // self.patch_size
231
+ patches_width = width // self.patch_size
232
+ if self.downsample_rate is not None:
233
+ ds_rate = Fraction(self.downsample_rate)
234
+ patches_height = int(patches_height * ds_rate)
235
+ patches_width = int(patches_width * ds_rate)
236
+
237
+ unpadded_features, newline_features = self._get_unpadded_features(
238
+ orig_height, orig_width, patches_height, patches_width, scale_height, scale_width
239
+ )
240
+ base_features = patches_height * patches_width + self.num_additional_image_tokens
241
+ num_image_tokens = unpadded_features + newline_features + base_features
242
+ return num_image_tokens
243
+
244
+
245
+ # ── Downsampling helpers ─────────────────────────────────────────────────────
246
+
247
+
248
+ def interpolate_downsample(image_features: torch.Tensor, orig_side: int, new_side: int) -> torch.Tensor:
249
+ """Spatial downsampling via area interpolation."""
250
+ batch, _, channels = image_features.size()
251
+ spatial = image_features.view(batch, orig_side, orig_side, channels).permute(0, 3, 1, 2)
252
+ spatial = torch.nn.functional.interpolate(spatial, size=(new_side, new_side), mode="area")
253
+ return spatial.permute(0, 2, 3, 1).flatten(1, 2)
254
+
255
+
256
+ def spatial_offset_downsample(image_features: torch.Tensor, orig_side: int, offset: int = 0) -> torch.Tensor:
257
+ """Sample one position from each 2x2 block; offset selects which corner (0=TL,1=TR,2=BL,3=BR)."""
258
+ offset_h, offset_w = [(0, 0), (0, 1), (1, 0), (1, 1)][offset]
259
+ new_side = orig_side // 2
260
+ batch, _, channels = image_features.shape
261
+ grid = image_features.reshape(batch, orig_side, orig_side, channels)
262
+ grid = grid.reshape(batch, new_side, 2, new_side, 2, channels)
263
+ return grid[:, :, offset_h, :, offset_w, :].reshape(batch, -1, channels)
264
+
265
+
266
+ class Granite4VisionWindowQFormerDownsampler(nn.Module):
267
+ """Window-based QFormer downsampler that processes image patches in windows."""
268
+
269
+ def __init__(self, config, spatial_offset=None):
270
+ super().__init__()
271
+ llm_hidden_size = config.text_config.hidden_size
272
+ vision_hidden_size = config.vision_config.hidden_size
273
+
274
+ self.dropout = nn.Dropout(config.projector_dropout)
275
+ self._spatial_offset = spatial_offset
276
+ self._downsample_rate = config.downsample_rate
277
+
278
+ self.qformer = AutoModel.from_config(config.qformer_config)
279
+
280
+ self.image_side = config.vision_config.image_size // config.vision_config.patch_size
281
+ query_side_str, window_side_str = config.downsample_rate.split("/")
282
+ self.query_side, self.window_side = int(query_side_str), int(window_side_str)
283
+ self.query_length = self.query_side**2
284
+ self.norm = nn.LayerNorm(vision_hidden_size, eps=1e-6)
285
+ self.query = nn.Parameter(torch.empty(1, self.query_length, vision_hidden_size))
286
+ self.image_positions = nn.Parameter(torch.empty(1, self.window_side**2, vision_hidden_size))
287
+ self.out_linear = nn.Linear(vision_hidden_size, llm_hidden_size, bias=True)
288
+
289
+ def _windowed_raster(self, features, side, window_size):
290
+ """(B, side*side, C) raster -> (B*num_win*num_win, window_size*window_size, C)"""
291
+ batch, _, channels = features.shape
292
+ num_win = side // window_size
293
+ features = features.view(batch, side, side, channels)
294
+ features = features.view(batch, num_win, window_size, num_win, window_size, channels)
295
+ features = features.transpose(2, 3)
296
+ features = features.flatten(0, 2)
297
+ return features.flatten(1, 2)
298
+
299
+ def _unwindowed_raster(self, windowed_features, num_win, window_size):
300
+ """(B*num_win*num_win, window_size*window_size, C) -> (B, (num_win*window_size)^2, C)"""
301
+ batch_win, _, channels = windowed_features.shape
302
+ if batch_win % (num_win * num_win) != 0:
303
+ raise ValueError(f"Expected batch_win ({batch_win}) to be divisible by num_win^2 ({num_win**2}).")
304
+ batch = batch_win // (num_win * num_win)
305
+ side = num_win * window_size
306
+ features = windowed_features.view(batch, num_win, num_win, window_size, window_size, channels)
307
+ features = features.transpose(2, 3).contiguous()
308
+ features = features.view(batch, side, side, channels)
309
+ return features.flatten(1, 2)
310
+
311
+ def forward(self, image_features: torch.Tensor) -> torch.Tensor:
312
+ batch, hw, channels = image_features.shape
313
+ if self.image_side * self.image_side != hw:
314
+ raise ValueError(
315
+ f"Expected image_features with {self.image_side**2} spatial tokens, got {hw}. "
316
+ "Check that the vision encoder image_size and patch_size match the config."
317
+ )
318
+ num_windows = self.image_side // self.window_side
319
+ interpolated_side = int(self.image_side * Fraction(self._downsample_rate))
320
+ image_features = self.norm(image_features)
321
+ windowed_image_features = self._windowed_raster(image_features, self.image_side, self.window_side)
322
+
323
+ if self._spatial_offset is not None:
324
+ downsampled = spatial_offset_downsample(image_features, self.image_side, self._spatial_offset)
325
+ else:
326
+ downsampled = interpolate_downsample(image_features, self.image_side, interpolated_side)
327
+
328
+ downsampled_side = num_windows * self.query_side
329
+ downsampled_windowed = self._windowed_raster(downsampled, downsampled_side, self.query_side)
330
+
331
+ query_embeds = self.query + downsampled_windowed
332
+ encoder_embeds = self.dropout(windowed_image_features + self.image_positions)
333
+ out_windowed = self.qformer(
334
+ query_embeds=query_embeds,
335
+ encoder_hidden_states=encoder_embeds,
336
+ return_dict=True,
337
+ ).last_hidden_state
338
+
339
+ out = self._unwindowed_raster(out_windowed, num_win=num_windows, window_size=self.query_side)
340
+ out = self.dropout(out)
341
+ return self.out_linear(out)
342
+
343
+
344
+ # ── Model ───────────────────────────────────────────────────────────────────
345
+
346
+
347
+ class Granite4VisionTextRotaryEmbedding(GraniteRotaryEmbedding):
348
+ pass
349
+
350
+
351
+ class Granite4VisionTextAttention(GraniteAttention):
352
+ pass
353
+
354
+
355
+ class Granite4VisionTextDecoderLayer(GraniteDecoderLayer):
356
+ pass
357
+
358
+
359
+ class Granite4VisionPreTrainedModel(LlavaNextPreTrainedModel):
360
+ _no_split_modules = ["Granite4VisionTextDecoderLayer", "Granite4VisionWindowQFormerDownsampler"]
361
+ _can_record_outputs = {
362
+ "hidden_states": Granite4VisionTextDecoderLayer,
363
+ "attentions": Granite4VisionTextAttention,
364
+ }
365
+
366
+ def _init_weights(self, module):
367
+ super()._init_weights(module)
368
+ if isinstance(module, Granite4VisionWindowQFormerDownsampler):
369
+ embed_std = 1 / math.sqrt(module.query.shape[-1])
370
+ init.normal_(module.query, mean=0.0, std=embed_std)
371
+ init.normal_(module.image_positions, mean=0.0, std=embed_std)
372
+
373
+
374
+ class Granite4VisionTextModel(Granite4VisionPreTrainedModel, GraniteModel):
375
+ """Granite LLM backbone with deepstack feature injection support."""
376
+
377
+ config_class = Granite4VisionTextConfig
378
+
379
+ def __init__(self, config: Granite4VisionTextConfig):
380
+ super().__init__(config)
381
+
382
+ def forward(
383
+ self,
384
+ input_ids: torch.LongTensor | None = None,
385
+ attention_mask: torch.Tensor | None = None,
386
+ position_ids: torch.LongTensor | None = None,
387
+ past_key_values: Cache | None = None,
388
+ inputs_embeds: torch.FloatTensor | None = None,
389
+ use_cache: bool | None = None,
390
+ vision_mask: torch.BoolTensor | None = None,
391
+ deepstack_features: dict[int, torch.Tensor] | None = None,
392
+ **kwargs: Unpack[TransformersKwargs],
393
+ ):
394
+ r"""
395
+ vision_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
396
+ Boolean mask marking image token positions. Required when `deepstack_features` is provided.
397
+ deepstack_features (`dict[int, torch.Tensor]`, *optional*):
398
+ Mapping from LLM layer index to projected vision features of shape `(num_image_tokens, hidden_size)`.
399
+ Features are added into image-token positions of hidden states before the corresponding decoder layer.
400
+ """
401
+ if (input_ids is None) ^ (inputs_embeds is not None):
402
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
403
+
404
+ if inputs_embeds is None:
405
+ inputs_embeds = self.embed_tokens(input_ids)
406
+
407
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
408
+
409
+ if position_ids is None:
410
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
411
+ position_ids = (
412
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
413
+ ).unsqueeze(0)
414
+
415
+ causal_mask = create_causal_mask(
416
+ config=self.config,
417
+ inputs_embeds=inputs_embeds,
418
+ attention_mask=attention_mask,
419
+ past_key_values=past_key_values,
420
+ position_ids=position_ids,
421
+ )
422
+
423
+ hidden_states = inputs_embeds
424
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
425
+
426
+ for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
427
+ if deepstack_features is not None and layer_idx in deepstack_features:
428
+ features = deepstack_features[layer_idx].to(hidden_states.device, hidden_states.dtype)
429
+ mask = vision_mask.to(hidden_states.device)
430
+ hidden_states = hidden_states.masked_scatter(mask, (hidden_states[mask] + features.flatten()).view(-1))
431
+
432
+ hidden_states = decoder_layer(
433
+ hidden_states,
434
+ attention_mask=causal_mask,
435
+ position_ids=position_ids,
436
+ past_key_values=past_key_values,
437
+ use_cache=use_cache,
438
+ position_embeddings=position_embeddings,
439
+ **kwargs,
440
+ )
441
+
442
+ hidden_states = self.norm(hidden_states)
443
+
444
+ return BaseModelOutputWithPast(
445
+ last_hidden_state=hidden_states,
446
+ past_key_values=past_key_values,
447
+ )
448
+
449
+
450
+ class Granite4VisionModel(LlavaNextModel):
451
+ config_class = Granite4VisionConfig
452
+
453
+ def __init__(self, config: Granite4VisionConfig):
454
+ super().__init__(config)
455
+
456
+ # Replace parent's single multi_modal_projector with layerwise_projectors
457
+ del self.multi_modal_projector
458
+
459
+ self.downsample_rate = config.downsample_rate
460
+ self.projector_dropout = config.projector_dropout
461
+
462
+ # Deepstack projectors: one per (vision_layer, llm_layer) pair
463
+ self.layerwise_projectors = nn.ModuleList(
464
+ [Granite4VisionWindowQFormerDownsampler(config) for _ in range(len(config.deepstack_layer_map))]
465
+ )
466
+
467
+ # Spatial sampling projectors: 4 offset groups (TL, TR, BL, BR)
468
+ self.spatial_projectors = nn.ModuleList(
469
+ [Granite4VisionWindowQFormerDownsampler(config, spatial_offset=i) for i in range(4)]
470
+ )
471
+
472
+ self.pad_token_id = (
473
+ self.config.text_config.pad_token_id if self.config.text_config.pad_token_id is not None else -1
474
+ )
475
+
476
+ # Replace the inherited LLM backbone with our deepstack-aware subclass
477
+ self.language_model = Granite4VisionTextModel(config.text_config)
478
+
479
+ def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
480
+ """
481
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
482
+
483
+ Overrides the parent to apply downsample_rate to height/width calculations.
484
+ """
485
+ new_image_features = []
486
+ feature_lens = []
487
+ for image_idx, image_feature in enumerate(image_features):
488
+ if image_feature.shape[0] > 1:
489
+ base_image_feature = image_feature[0]
490
+ image_feature = image_feature[1:]
491
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
492
+
493
+ num_patch_height, num_patch_width = get_anyres_image_grid_shape(
494
+ image_sizes[image_idx],
495
+ self.config.image_grid_pinpoints,
496
+ self.config.vision_config.image_size,
497
+ )
498
+ if self.layerwise_projectors is not None:
499
+ ds_rate = Fraction(self.downsample_rate)
500
+ height = int(height * ds_rate)
501
+ width = int(width * ds_rate)
502
+
503
+ if (
504
+ np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
505
+ and vision_feature_select_strategy == "default"
506
+ ):
507
+ raise ValueError(
508
+ "Image feature shape does not line up with the provided patch size. "
509
+ "You may be using the `default` vision_feature_select_strategy with a "
510
+ "visual encoder that does not have CLS token."
511
+ )
512
+
513
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
514
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
515
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
516
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
517
+ if image_newline is not None:
518
+ image_feature = torch.cat(
519
+ (
520
+ image_feature,
521
+ image_newline[:, None, None]
522
+ .expand(*image_feature.shape[:-1], 1)
523
+ .to(image_feature.device, image_feature.dtype),
524
+ ),
525
+ dim=-1,
526
+ )
527
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
528
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
529
+ else:
530
+ image_feature = image_feature[0]
531
+ if image_newline is not None:
532
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
533
+ new_image_features.append(image_feature)
534
+ feature_lens.append(image_feature.size(0))
535
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features[0].device)
536
+ return new_image_features, feature_lens
537
+
538
+ @merge_with_config_defaults
539
+ @can_return_tuple
540
+ @auto_docstring(
541
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
542
+ )
543
+ def get_image_features(
544
+ self,
545
+ pixel_values: torch.FloatTensor,
546
+ image_sizes: torch.Tensor,
547
+ vision_feature_layer: int | list[int] | None = None,
548
+ vision_feature_select_strategy: str | None = None,
549
+ output_hidden_states: bool | None = None,
550
+ **kwargs,
551
+ ) -> Granite4VisionImageFeaturesOutput:
552
+ r"""
553
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
554
+ The tensors corresponding to the input images.
555
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
556
+ Actual image size of each images (H, W).
557
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
558
+ The index of the layer to select the vision feature. If multiple indices are provided,
559
+ the vision feature of the corresponding indices will be concatenated to form the
560
+ vision features.
561
+ vision_feature_select_strategy (`str`, *optional*):
562
+ The feature selection strategy used to select the vision feature from the vision backbone.
563
+ Can be one of `"default"` or `"full"`
564
+ """
565
+
566
+ image_num_patches = [
567
+ image_size_to_num_patches(
568
+ image_size=imsize,
569
+ grid_pinpoints=self.config.image_grid_pinpoints,
570
+ patch_size=self.config.vision_config.image_size,
571
+ )
572
+ for imsize in image_sizes
573
+ ]
574
+
575
+ if pixel_values.dim() == 5:
576
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
577
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
578
+ elif pixel_values.dim() != 4:
579
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
580
+
581
+ vision_outputs = self.vision_tower(pixel_values, output_hidden_states=True, **kwargs)
582
+
583
+ # Deepstack features: extract from multiple vision layers, downsample via interpolation
584
+ all_features = []
585
+ for projection_idx, (vision_layer, llm_layer) in enumerate(self.config.deepstack_layer_map):
586
+ selected_feature = vision_outputs.hidden_states[vision_layer]
587
+
588
+ if vision_feature_select_strategy == "default":
589
+ selected_feature = selected_feature[:, 1:]
590
+
591
+ projected_features = self.layerwise_projectors[projection_idx](selected_feature)
592
+ projected_features = torch.split(projected_features, image_num_patches, dim=0)
593
+
594
+ packed_features, _ = self.pack_image_features(
595
+ projected_features,
596
+ image_sizes,
597
+ vision_feature_select_strategy=vision_feature_select_strategy,
598
+ image_newline=self.image_newline,
599
+ )
600
+
601
+ all_features.append((llm_layer, packed_features))
602
+
603
+ # Spatial features: extract 4 offset groups from a single vision layer
604
+ spatial_feature = vision_outputs.hidden_states[self.config.spatial_vision_layer]
605
+
606
+ if vision_feature_select_strategy == "default":
607
+ spatial_feature = spatial_feature[:, 1:]
608
+
609
+ for group_idx, llm_layer in enumerate(self.config.spatial_target_layers):
610
+ projected_group = self.spatial_projectors[group_idx](spatial_feature)
611
+ projected_group_split = torch.split(projected_group, image_num_patches, dim=0)
612
+
613
+ packed_group, _ = self.pack_image_features(
614
+ projected_group_split,
615
+ image_sizes,
616
+ vision_feature_select_strategy=vision_feature_select_strategy,
617
+ image_newline=self.image_newline,
618
+ )
619
+
620
+ all_features.append((llm_layer, packed_group))
621
+
622
+ return Granite4VisionImageFeaturesOutput(
623
+ deepstack_features=all_features,
624
+ hidden_states=vision_outputs.hidden_states,
625
+ )
626
+
627
+ def forward(
628
+ self,
629
+ input_ids: torch.LongTensor | None = None,
630
+ pixel_values: torch.FloatTensor | None = None,
631
+ image_sizes: torch.LongTensor | None = None,
632
+ attention_mask: torch.Tensor | None = None,
633
+ position_ids: torch.LongTensor | None = None,
634
+ past_key_values: Cache | None = None,
635
+ inputs_embeds: torch.FloatTensor | None = None,
636
+ vision_feature_layer: int | list[int] | None = None,
637
+ vision_feature_select_strategy: str | None = None,
638
+ use_cache: bool | None = None,
639
+ **kwargs: Unpack[TransformersKwargs],
640
+ ) -> tuple | Granite4VisionModelOutputWithPast:
641
+ if (input_ids is None) ^ (inputs_embeds is not None):
642
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
643
+
644
+ if inputs_embeds is None:
645
+ inputs_embeds = self.get_input_embeddings()(input_ids)
646
+
647
+ # Build deepstack injection map and scatter initial image embeddings
648
+ deepstack_features = None
649
+ vision_mask = None
650
+ image_features = None
651
+ if pixel_values is not None:
652
+ image_features = self.get_image_features(
653
+ pixel_values,
654
+ image_sizes,
655
+ vision_feature_layer=vision_feature_layer,
656
+ vision_feature_select_strategy=vision_feature_select_strategy,
657
+ )
658
+
659
+ deepstack_features = {}
660
+ for idx, (llm_layer_idx, packed_features) in enumerate(image_features.deepstack_features):
661
+ concat_features = torch.cat(packed_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
662
+ if idx == 0:
663
+ vision_mask = self.get_placeholder_mask(
664
+ input_ids, inputs_embeds=inputs_embeds, image_features=concat_features
665
+ )
666
+ # Zero out image token positions — deepstack injection will sum features in during forward.
667
+ inputs_embeds = inputs_embeds.masked_fill(vision_mask, 0.0)
668
+ deepstack_features[llm_layer_idx] = concat_features
669
+
670
+ outputs = self.language_model(
671
+ input_ids=None,
672
+ inputs_embeds=inputs_embeds,
673
+ attention_mask=attention_mask,
674
+ position_ids=position_ids,
675
+ past_key_values=past_key_values,
676
+ use_cache=use_cache,
677
+ vision_mask=vision_mask,
678
+ deepstack_features=deepstack_features,
679
+ **kwargs,
680
+ )
681
+
682
+ return Granite4VisionModelOutputWithPast(
683
+ last_hidden_state=outputs.last_hidden_state,
684
+ past_key_values=outputs.past_key_values,
685
+ hidden_states=outputs.hidden_states,
686
+ attentions=outputs.attentions,
687
+ deepstack_features=image_features.deepstack_features if pixel_values is not None else None,
688
+ )
689
+
690
+
691
+ # ── ForConditionalGeneration ────────────────────────────────────────────────
692
+
693
+
694
+ class Granite4VisionForConditionalGeneration(LlavaNextForConditionalGeneration):
695
+ def forward(
696
+ self,
697
+ input_ids: torch.LongTensor | None = None,
698
+ pixel_values: torch.FloatTensor | None = None,
699
+ image_sizes: torch.LongTensor | None = None,
700
+ attention_mask: torch.Tensor | None = None,
701
+ position_ids: torch.LongTensor | None = None,
702
+ past_key_values: Cache | None = None,
703
+ inputs_embeds: torch.FloatTensor | None = None,
704
+ vision_feature_layer: int | list[int] | None = None,
705
+ vision_feature_select_strategy: str | None = None,
706
+ labels: torch.LongTensor | None = None,
707
+ use_cache: bool | None = None,
708
+ logits_to_keep: int | torch.Tensor = 0,
709
+ **kwargs: Unpack[TransformersKwargs],
710
+ ) -> tuple | Granite4VisionCausalLMOutputWithPast:
711
+ outputs = self.model(
712
+ input_ids,
713
+ pixel_values=pixel_values,
714
+ image_sizes=image_sizes,
715
+ vision_feature_layer=vision_feature_layer,
716
+ vision_feature_select_strategy=vision_feature_select_strategy,
717
+ attention_mask=attention_mask,
718
+ position_ids=position_ids,
719
+ past_key_values=past_key_values,
720
+ inputs_embeds=inputs_embeds,
721
+ use_cache=use_cache,
722
+ return_dict=True,
723
+ **kwargs,
724
+ )
725
+
726
+ hidden_states = outputs.last_hidden_state
727
+
728
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
729
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
730
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
731
+ logits = logits / self.config.text_config.logits_scaling
732
+
733
+ loss = None
734
+ if labels is not None:
735
+ loss = self.loss_function(
736
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
737
+ )
738
+
739
+ return Granite4VisionCausalLMOutputWithPast(
740
+ loss=loss,
741
+ logits=logits,
742
+ past_key_values=outputs.past_key_values,
743
+ hidden_states=outputs.hidden_states,
744
+ attentions=outputs.attentions,
745
+ deepstack_features=outputs.deepstack_features,
746
+ )
747
+
748
+
749
+ __all__ = [
750
+ "Granite4VisionConfig",
751
+ "Granite4VisionTextConfig",
752
+ "Granite4VisionProcessor",
753
+ "Granite4VisionPreTrainedModel",
754
+ "Granite4VisionTextModel",
755
+ "Granite4VisionModel",
756
+ "Granite4VisionForConditionalGeneration",
757
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/granite4_vision/processing_granite4_vision.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/granite4_vision/modular_granite4_vision.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_granite4_vision.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 IBM and The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from fractions import Fraction
22
+
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...image_processing_utils import select_best_resolution
25
+ from ...image_utils import ImageInput, SizeDict, get_image_size, to_numpy_array
26
+ from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
27
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
28
+ from ...utils import auto_docstring
29
+
30
+
31
+ class Granite4VisionProcessorKwargs(ProcessingKwargs, total=False):
32
+ _defaults = {
33
+ "text_kwargs": {
34
+ "padding": False,
35
+ "return_mm_token_type_ids": False,
36
+ },
37
+ "images_kwargs": {
38
+ "do_pad": True,
39
+ },
40
+ }
41
+
42
+
43
+ @auto_docstring
44
+ class Granite4VisionProcessor(ProcessorMixin):
45
+ def __init__(
46
+ self,
47
+ image_processor=None,
48
+ tokenizer=None,
49
+ patch_size=None,
50
+ vision_feature_select_strategy=None,
51
+ chat_template=None,
52
+ image_token="<image>",
53
+ num_additional_image_tokens=0,
54
+ downsample_rate=None,
55
+ **kwargs,
56
+ ):
57
+ r"""
58
+ patch_size (`int`, *optional*):
59
+ Patch size from the vision tower.
60
+ vision_feature_select_strategy (`str`, *optional*):
61
+ The feature selection strategy used to select the vision feature from the vision backbone.
62
+ Should be same as in model's config.
63
+ image_token (`str`, *optional*, defaults to `"<image>"`):
64
+ Special token used to denote image location.
65
+ num_additional_image_tokens (`int`, *optional*, defaults to `0`):
66
+ Number of additional tokens added to the image embeddings, such as CLS (+1).
67
+ downsample_rate (`str`, *optional*):
68
+ Fractional downsample rate (e.g. `"1/4"`), used to adjust the number of image tokens
69
+ when computing token counts for padding/truncation.
70
+ """
71
+ self.patch_size = patch_size
72
+ self.num_additional_image_tokens = num_additional_image_tokens
73
+ self.vision_feature_select_strategy = vision_feature_select_strategy
74
+ self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
75
+ self.image_token_id = (
76
+ tokenizer.image_token_id
77
+ if getattr(tokenizer, "image_token_id", None)
78
+ else tokenizer.convert_tokens_to_ids(self.image_token)
79
+ )
80
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
81
+ self.downsample_rate = downsample_rate
82
+
83
+ @auto_docstring
84
+ def __call__(
85
+ self,
86
+ images: ImageInput | None = None,
87
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
88
+ **kwargs: Unpack[Granite4VisionProcessorKwargs],
89
+ ) -> BatchFeature:
90
+ r"""
91
+ Returns:
92
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
93
+
94
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
95
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
96
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
97
+ `None`).
98
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
99
+ """
100
+ if images is None and text is None:
101
+ raise ValueError("You have to specify at least images or text.")
102
+
103
+ output_kwargs = self._merge_kwargs(
104
+ Granite4VisionProcessorKwargs,
105
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
106
+ **kwargs,
107
+ )
108
+ if images is not None:
109
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
110
+ else:
111
+ image_inputs = {}
112
+
113
+ if isinstance(text, str):
114
+ text = [text]
115
+ elif not isinstance(text, list) and not isinstance(text[0], str):
116
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
117
+
118
+ prompt_strings = text
119
+ if image_inputs:
120
+ image_sizes = iter(image_inputs["image_sizes"])
121
+ height, width = get_image_size(to_numpy_array(image_inputs["pixel_values"][0][0]))
122
+ prompt_strings = []
123
+ for sample in text:
124
+ while self.image_token in sample:
125
+ image_size = next(image_sizes)
126
+ if not isinstance(image_size, (list, tuple)):
127
+ # cast to list to avoid numerical precision errors when calculating unpadding
128
+ image_size = image_size.tolist()
129
+ orig_height, orig_width = image_size
130
+ num_image_tokens = self._get_number_of_features(orig_height, orig_width, height, width)
131
+ if self.vision_feature_select_strategy == "default":
132
+ num_image_tokens -= 1
133
+ sample = sample.replace(self.image_token, "<placeholder>" * num_image_tokens, 1)
134
+ prompt_strings.append(sample)
135
+ prompt_strings = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings]
136
+
137
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
138
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
139
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
140
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
141
+
142
+ if return_mm_token_type_ids:
143
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
144
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
145
+
146
+ def _get_number_of_features(self, orig_height: int, orig_width: int, height: int, width: int) -> int:
147
+ image_grid_pinpoints = self.image_processor.image_grid_pinpoints
148
+
149
+ height_best_resolution, width_best_resolution = select_best_resolution(
150
+ [orig_height, orig_width], image_grid_pinpoints
151
+ )
152
+ scale_height, scale_width = height_best_resolution // height, width_best_resolution // width
153
+
154
+ patches_height = height // self.patch_size
155
+ patches_width = width // self.patch_size
156
+ if self.downsample_rate is not None:
157
+ ds_rate = Fraction(self.downsample_rate)
158
+ patches_height = int(patches_height * ds_rate)
159
+ patches_width = int(patches_width * ds_rate)
160
+
161
+ unpadded_features, newline_features = self._get_unpadded_features(
162
+ orig_height, orig_width, patches_height, patches_width, scale_height, scale_width
163
+ )
164
+ base_features = patches_height * patches_width + self.num_additional_image_tokens
165
+ num_image_tokens = unpadded_features + newline_features + base_features
166
+ return num_image_tokens
167
+
168
+ def _get_unpadded_features(self, height, width, patches_height, patches_width, scale_height, scale_width):
169
+ """
170
+ Get number of features for a given image with height/width. LLaVA-NeXT is different from LLaVA
171
+ because it divided each image into patches depending on its resolution. Therefore we need to calculate how many
172
+ patches an image is divided into and get the number of features from that.
173
+ """
174
+ current_height = patches_height * scale_height
175
+ current_width = patches_width * scale_width
176
+
177
+ original_aspect_ratio = width / height
178
+ current_aspect_ratio = current_width / current_height
179
+ if original_aspect_ratio > current_aspect_ratio:
180
+ new_height = int(round(height * (current_width / width), 7))
181
+ padding = (current_height - new_height) // 2
182
+ current_height -= padding * 2
183
+ else:
184
+ new_width = int(round(width * (current_height / height), 7))
185
+ padding = (current_width - new_width) // 2
186
+ current_width -= padding * 2
187
+
188
+ unpadded_features = current_height * current_width
189
+ newline_features = current_height
190
+ return (unpadded_features, newline_features)
191
+
192
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
193
+ """
194
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
195
+ Args:
196
+ image_sizes (list[list[str]], *optional*):
197
+ The input sizes formatted as (height, width) per each image.
198
+ Returns:
199
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
200
+ input modalities, along with other useful data.
201
+ """
202
+ vision_data = {}
203
+ if image_sizes is not None:
204
+ images_kwargs = Granite4VisionProcessorKwargs._defaults.get("images_kwargs", {})
205
+ images_kwargs.update(kwargs)
206
+
207
+ size = images_kwargs.get("size", None) or self.image_processor.size
208
+ if isinstance(size, SizeDict):
209
+ size = (
210
+ (size.shortest_edge, size.shortest_edge)
211
+ if size.shortest_edge is not None
212
+ else (min(size.height, size.width), min(size.height, size.width))
213
+ )
214
+ else:
215
+ size = (
216
+ (size["shortest_edge"], size["shortest_edge"])
217
+ if "shortest_edge" in size
218
+ else (min(size["height"], size["width"]), min(size["height"], size["width"]))
219
+ )
220
+ processed_height, processed_width = size
221
+
222
+ batch_num_image_tokens = []
223
+ num_image_patches = [1] * len(image_sizes) # llava-next doesn't batch pixels as Idefics, thus `1` patch`
224
+ for image_size in image_sizes:
225
+ orig_height, orig_width = image_size
226
+ num_image_tokens = self._get_number_of_features(
227
+ orig_height, orig_width, processed_height, processed_width
228
+ )
229
+ if self.vision_feature_select_strategy == "default":
230
+ num_image_tokens -= 1
231
+ batch_num_image_tokens.append(num_image_tokens)
232
+ vision_data.update({"num_image_tokens": batch_num_image_tokens, "num_image_patches": num_image_patches})
233
+
234
+ return MultiModalData(**vision_data)
235
+
236
+
237
+ __all__ = ["Granite4VisionProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/modeling_qwen2_audio.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch Qwen2Audio model."""
15
+
16
+ import math
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass
19
+
20
+ import torch
21
+ from torch import nn
22
+
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache
25
+ from ...generation import GenerationMixin
26
+ from ...masking_utils import create_bidirectional_mask
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import BaseModelOutput, ModelOutput
29
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
30
+ from ...processing_utils import Unpack
31
+ from ...utils import TransformersKwargs, auto_docstring, is_torchdynamo_compiling, logging, torch_compilable_check
32
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
33
+ from ...utils.output_capturing import capture_outputs
34
+ from ..auto import AutoModel, AutoModelForCausalLM
35
+ from .configuration_qwen2_audio import Qwen2AudioConfig, Qwen2AudioEncoderConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ @auto_docstring(
42
+ custom_intro="""
43
+ Base class for Qwen2Audio causal language model (or autoregressive) outputs.
44
+ """
45
+ )
46
+ @dataclass
47
+ class Qwen2AudioCausalLMOutputWithPast(ModelOutput):
48
+ r"""
49
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
50
+ Language modeling loss (for next-token prediction).
51
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
52
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
53
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
54
+ Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are
55
+ two sets of pre-computed hidden-states: key and values states in the self-attention blocks.
56
+ The `past_key_values` are returned when `use_cache=True` is passed or when `config.use_cache=True`.
57
+ It is a [`~cache_utils.Cache`] instance.
58
+
59
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those
60
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
61
+ all `input_ids` of shape `(batch_size, sequence_length)`.
62
+ attention_mask (`torch.FloatTensor`, *optional*):
63
+ Attentions mask, used to update attention mask and position_ids.
64
+ """
65
+
66
+ loss: torch.FloatTensor | None = None
67
+ logits: torch.FloatTensor | None = None
68
+ past_key_values: Cache | None = None
69
+ hidden_states: tuple[torch.FloatTensor] | None = None
70
+ attentions: tuple[torch.FloatTensor] | None = None
71
+ attention_mask: torch.FloatTensor | None = None
72
+
73
+
74
+ # Copied from transformers.models.whisper.modeling_whisper.eager_attention_forward
75
+ def eager_attention_forward(
76
+ module: nn.Module,
77
+ query: torch.Tensor,
78
+ key: torch.Tensor,
79
+ value: torch.Tensor,
80
+ attention_mask: torch.Tensor | None,
81
+ scaling: float | None = None,
82
+ dropout: float = 0.0,
83
+ **kwargs,
84
+ ):
85
+ if scaling is None:
86
+ scaling = query.size(-1) ** -0.5
87
+
88
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
89
+ if attention_mask is not None:
90
+ attn_weights = attn_weights + attention_mask
91
+
92
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
93
+
94
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
95
+ attn_output = torch.matmul(attn_weights, value)
96
+ attn_output = attn_output.transpose(1, 2).contiguous()
97
+
98
+ return attn_output, attn_weights
99
+
100
+
101
+ class Qwen2AudioAttention(nn.Module):
102
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
103
+
104
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperAttention.__init__ with Whisper->Qwen2Audio
105
+ def __init__(
106
+ self,
107
+ embed_dim: int,
108
+ num_heads: int,
109
+ dropout: float = 0.0,
110
+ is_decoder: bool = False,
111
+ bias: bool = True,
112
+ is_causal: bool = False,
113
+ layer_idx: int | None = None,
114
+ config: Qwen2AudioConfig | None = None,
115
+ ):
116
+ super().__init__()
117
+ self.embed_dim = embed_dim
118
+ self.num_heads = num_heads
119
+ self.dropout = dropout
120
+ self.head_dim = embed_dim // num_heads
121
+ self.config = config
122
+
123
+ if (self.head_dim * num_heads) != self.embed_dim:
124
+ raise ValueError(
125
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
126
+ f" and `num_heads`: {num_heads})."
127
+ )
128
+ self.scaling = self.head_dim**-0.5
129
+ self.is_decoder = is_decoder
130
+ self.is_causal = is_causal
131
+
132
+ if layer_idx is None and is_decoder:
133
+ logger.warning_once(
134
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
135
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
136
+ "when creating this class."
137
+ )
138
+ self.layer_idx = layer_idx
139
+
140
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
141
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
142
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
143
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
144
+
145
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
146
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
147
+
148
+ def forward(
149
+ self,
150
+ hidden_states: torch.Tensor,
151
+ attention_mask: torch.Tensor | None = None,
152
+ output_attentions: bool = False,
153
+ **kwargs,
154
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
155
+ """Input shape: Batch x Time x Channel"""
156
+
157
+ bsz, tgt_len, _ = hidden_states.size()
158
+
159
+ # Scaling is susceptible to floating point arithmetics' inprecisions
160
+ # which can lead to different results (this is dependent from model
161
+ # to model, e.g. whisper is one such case). We therefore keep the
162
+ # original order of scaling to follow the original implementation
163
+ # and enforce no scaling (1.0) in the attention call below.
164
+ query_states = self._shape(self.q_proj(hidden_states) * self.scaling, tgt_len, bsz)
165
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
166
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
167
+
168
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
169
+ self.config._attn_implementation, eager_attention_forward
170
+ )
171
+
172
+ attn_output, attn_weights = attention_interface(
173
+ self,
174
+ query_states,
175
+ key_states,
176
+ value_states,
177
+ attention_mask,
178
+ dropout=0.0 if not self.training else self.dropout,
179
+ scaling=1.0,
180
+ output_attentions=output_attentions,
181
+ **kwargs,
182
+ )
183
+
184
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
185
+ attn_output = self.out_proj(attn_output)
186
+
187
+ return attn_output, attn_weights
188
+
189
+
190
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperEncoderLayer with Whisper->Qwen2Audio, WHISPER->QWEN2AUDIO
191
+ class Qwen2AudioEncoderLayer(GradientCheckpointingLayer):
192
+ def __init__(self, config: Qwen2AudioConfig):
193
+ super().__init__()
194
+ self.embed_dim = config.d_model
195
+
196
+ self.self_attn = Qwen2AudioAttention(
197
+ embed_dim=self.embed_dim,
198
+ num_heads=config.encoder_attention_heads,
199
+ dropout=config.attention_dropout,
200
+ config=config,
201
+ )
202
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
203
+ self.dropout = config.dropout
204
+ self.activation_fn = ACT2FN[config.activation_function]
205
+ self.activation_dropout = config.activation_dropout
206
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
207
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
208
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
209
+
210
+ def forward(
211
+ self,
212
+ hidden_states: torch.Tensor,
213
+ attention_mask: torch.Tensor,
214
+ **kwargs: Unpack[TransformersKwargs],
215
+ ) -> torch.Tensor:
216
+ """
217
+ Args:
218
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
219
+ attention_mask (`torch.FloatTensor`): attention mask of size
220
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
221
+ """
222
+ residual = hidden_states
223
+ hidden_states = self.self_attn_layer_norm(hidden_states)
224
+ hidden_states, _ = self.self_attn(
225
+ hidden_states=hidden_states,
226
+ attention_mask=attention_mask,
227
+ **kwargs,
228
+ )
229
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
230
+ hidden_states = residual + hidden_states
231
+
232
+ residual = hidden_states
233
+ hidden_states = self.final_layer_norm(hidden_states)
234
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
235
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
236
+ hidden_states = self.fc2(hidden_states)
237
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
238
+ hidden_states = residual + hidden_states
239
+
240
+ if hidden_states.dtype == torch.float16:
241
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
242
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
243
+
244
+ return hidden_states
245
+
246
+
247
+ @auto_docstring
248
+ class Qwen2AudioPreTrainedModel(PreTrainedModel):
249
+ config: Qwen2AudioConfig
250
+ base_model_prefix = "model"
251
+ input_modalities = ("audio", "text")
252
+ supports_gradient_checkpointing = True
253
+ _no_split_modules = ["Qwen2AudioAttention"]
254
+ _skip_keys_device_placement = ["past_key_values"]
255
+ _supports_flash_attn = True
256
+ _supports_sdpa = True
257
+
258
+
259
+ @auto_docstring(
260
+ custom_intro="""
261
+ The audio model from Qwen2Audio without any head or projection on top.
262
+ """
263
+ )
264
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperEncoder with Whisper->Qwen2Audio
265
+ class Qwen2AudioEncoder(Qwen2AudioPreTrainedModel):
266
+ """
267
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
268
+ [`Qwen2AudioEncoderLayer`].
269
+
270
+ Args:
271
+ config: Qwen2AudioEncoderConfig
272
+ """
273
+
274
+ # Ignore copy
275
+ config: Qwen2AudioEncoderConfig
276
+ main_input_name = "input_features"
277
+ input_modalities = "audio"
278
+ _no_split_modules = ["Qwen2AudioEncoderLayer"]
279
+ _can_record_outputs = {"hidden_states": Qwen2AudioEncoderLayer, "attentions": Qwen2AudioAttention}
280
+
281
+ def __init__(self, config: Qwen2AudioEncoderConfig):
282
+ super().__init__(config)
283
+ self.dropout = config.dropout
284
+ self.layerdrop = config.encoder_layerdrop
285
+
286
+ embed_dim = config.d_model
287
+ self.num_mel_bins = config.num_mel_bins
288
+ self.max_source_positions = config.max_source_positions
289
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
290
+
291
+ self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1)
292
+ self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1)
293
+
294
+ self.embed_positions = nn.Embedding(self.max_source_positions, embed_dim)
295
+ self.embed_positions.requires_grad_(False)
296
+
297
+ self.layers = nn.ModuleList([Qwen2AudioEncoderLayer(config) for _ in range(config.encoder_layers)])
298
+ self.layer_norm = nn.LayerNorm(config.d_model)
299
+ # Ignore copy
300
+ self.avg_pooler = nn.AvgPool1d(2, stride=2)
301
+
302
+ self.gradient_checkpointing = False
303
+ # Initialize weights and apply final processing
304
+ self.post_init()
305
+
306
+ def _freeze_parameters(self):
307
+ for param in self.parameters():
308
+ param.requires_grad = False
309
+ self._requires_grad = False
310
+
311
+ def get_input_embeddings(self) -> nn.Module:
312
+ return self.conv1
313
+
314
+ def set_input_embeddings(self, value: nn.Module):
315
+ self.conv1 = value
316
+
317
+ @merge_with_config_defaults
318
+ @capture_outputs
319
+ def forward(
320
+ self,
321
+ input_features,
322
+ attention_mask=None,
323
+ **kwargs: Unpack[TransformersKwargs],
324
+ ):
325
+ r"""
326
+ Args:
327
+ attention_mask (`torch.Tensor`)`, *optional*):
328
+ Qwen2Audio does not support masking of the `input_features`, this argument is preserved for compatibility,
329
+ but it is not used. By default the silence in the input log mel spectrogram are ignored.
330
+ """
331
+
332
+ expected_seq_length = self.config.max_source_positions * self.conv1.stride[0] * self.conv2.stride[0]
333
+ if input_features.shape[-1] != expected_seq_length:
334
+ raise ValueError(
335
+ f"Qwen2Audio expects the mel input features to be of length {expected_seq_length}, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}."
336
+ )
337
+
338
+ # Ignore copy
339
+ input_features = input_features.to(dtype=self.conv1.weight.dtype, device=self.conv1.weight.device)
340
+
341
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
342
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
343
+
344
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
345
+ embed_pos = self.embed_positions.weight
346
+
347
+ hidden_states = inputs_embeds + embed_pos
348
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
349
+
350
+ for idx, encoder_layer in enumerate(self.layers):
351
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
352
+ to_drop = False
353
+ if self.training:
354
+ dropout_probability = torch.rand([])
355
+ if dropout_probability < self.layerdrop: # skip the layer
356
+ to_drop = True
357
+
358
+ # Ignore copy
359
+ if not to_drop:
360
+ hidden_states = encoder_layer(
361
+ hidden_states,
362
+ attention_mask,
363
+ **kwargs,
364
+ )
365
+
366
+ # Ignore copy
367
+ hidden_states = hidden_states.permute(0, 2, 1)
368
+ hidden_states = self.avg_pooler(hidden_states)
369
+ hidden_states = hidden_states.permute(0, 2, 1)
370
+
371
+ hidden_states = self.layer_norm(hidden_states)
372
+
373
+ return BaseModelOutput(last_hidden_state=hidden_states)
374
+
375
+ # Ignore copy
376
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
377
+ """
378
+ Computes the output length of the convolutional layers and the output length of the audio encoder
379
+ """
380
+ input_lengths = (input_lengths - 1) // 2 + 1
381
+ output_lengths = (input_lengths - 2) // 2 + 1
382
+ return input_lengths, output_lengths
383
+
384
+
385
+ class Qwen2AudioMultiModalProjector(nn.Module):
386
+ def __init__(self, config: Qwen2AudioConfig):
387
+ super().__init__()
388
+ self.linear = nn.Linear(config.audio_config.d_model, config.text_config.hidden_size, bias=True)
389
+
390
+ def forward(self, audio_features):
391
+ hidden_states = self.linear(audio_features)
392
+ return hidden_states
393
+
394
+
395
+ @auto_docstring(
396
+ custom_intro="""
397
+ The QWEN2AUDIO model which consists of a audio backbone and a language model.
398
+ """
399
+ )
400
+ class Qwen2AudioForConditionalGeneration(Qwen2AudioPreTrainedModel, GenerationMixin):
401
+ def __init__(self, config: Qwen2AudioConfig):
402
+ super().__init__(config)
403
+ self.audio_tower = AutoModel.from_config(config.audio_config) # Usually a `Qwen2AudioEncoder` instance
404
+
405
+ self.multi_modal_projector = Qwen2AudioMultiModalProjector(config)
406
+ self.vocab_size = config.text_config.vocab_size
407
+ self.language_model = AutoModelForCausalLM.from_config(config.text_config)
408
+
409
+ self.pad_token_id = (
410
+ self.config.text_config.pad_token_id if self.config.text_config.pad_token_id is not None else -1
411
+ )
412
+ self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
413
+ self.post_init()
414
+
415
+ @property
416
+ def padding_side(self):
417
+ return self._padding_side
418
+
419
+ @padding_side.setter
420
+ def padding_side(self, padding_side: str):
421
+ if padding_side not in ["left", "right"]:
422
+ raise ValueError(f"{padding_side} is not `left` or `right`.")
423
+ self._padding_side = padding_side
424
+
425
+ def get_output_embeddings(self):
426
+ return self.language_model.get_output_embeddings()
427
+
428
+ def set_output_embeddings(self, new_embeddings):
429
+ self.language_model.set_output_embeddings(new_embeddings)
430
+
431
+ def set_decoder(self, decoder):
432
+ self.language_model.set_decoder(decoder)
433
+
434
+ def get_decoder(self):
435
+ return self.language_model.get_decoder()
436
+
437
+ def _merge_input_ids_with_audio_features(
438
+ self, audio_features, num_audio_tokens, inputs_embeds, input_ids, attention_mask, labels
439
+ ):
440
+ """
441
+ Merge input_ids with audio features into final embeddings
442
+
443
+ Args:
444
+ audio_features (`torch.Tensor` of shape `(num_audios, max_audio_tokens, embed_dim)`):
445
+ All audio vectors of all audios in the batch
446
+ num_audio_tokens (`torch.LongTensor` of shape `(num_audios)`):
447
+ The length of audio embeddings of each audio as stacked in `audio_features`
448
+ inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, embed_dim)`):
449
+ Token embeddings before merging with audio embeddings
450
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
451
+ Input_ids of tokens, possibly filled with audio token
452
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
453
+ Mask to avoid performing attention on padding token indices.
454
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*)
455
+ labels need to be recalculated to support training (if provided)
456
+ Returns:
457
+ final_embedding, final_attention_mask, final_labels, position_ids, final_input_ids
458
+
459
+ Explanation:
460
+ each audio has variable length embeddings, with length specified by num_audio_tokens
461
+ audio_features is concatenation of all audio embed vectors
462
+ task: fill each <|AUDIO|> with the correct number of audio embeddings
463
+ Example:
464
+ X (5 tokens), Y (3 tokens), Z (8 tokens)
465
+ X, Y are in the same sequence (in-context learning)
466
+ if right padding
467
+ input_ids: [
468
+ a b c d e f X g h i j k Y l m
469
+ o p q r Z s t u v _ _ _ _ _ _
470
+ ]
471
+ input_ids should be: [
472
+ a b c d e f X X X X X g h i j k Y Y Y l m
473
+ o p q r Z Z Z Z Z Z Z Z s t u v _ _ _ _ _
474
+ ]
475
+ labels should be: [
476
+ a b c d e f _ _ _ _ _ g h i j k _ _ _ l m
477
+ o p q r _ _ _ _ _ _ _ _ s t u v _ _ _ _ _
478
+ ]
479
+ elif left padding
480
+ input_ids: [
481
+ a b c d e f X g h i j k Y l m
482
+ _ _ _ _ _ _ o p q r Z s t u v
483
+ ]
484
+ input_ids should be: [
485
+ a b c d e f X X X X X g h i j k Y Y Y l m
486
+ _ _ _ _ _ o p q r Z Z Z Z Z Z Z Z s t u v
487
+ ]
488
+ labels should be: [
489
+ a b c d e f _ _ _ _ _ g h i j k _ _ _ l m
490
+ _ _ _ _ _ o p q r _ _ _ _ _ _ _ _ s t u v
491
+ ]
492
+ Edge cases:
493
+ * If tokens are same but audio token sizes are different, then cannot infer left or right padding
494
+ ```python
495
+ url1 = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"
496
+ audio1, _ = librosa.load(BytesIO(urlopen(url1).read()), sr=processor.feature_extractor.sampling_rate)
497
+ url2 = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav"
498
+ audio2, _ = librosa.load(BytesIO(urlopen(url2).read()), sr=processor.feature_extractor.sampling_rate)
499
+ prompts = [
500
+ "[INST] <|AUDIO|>\nWhat is that in this audio? [/INST]",
501
+ "[INST] <|AUDIO|>\nWhat is that in this audio? [/INST]",
502
+ ]
503
+ inputs = processor(text=prompts, audio=[audio1, audio2], return_tensors='pt', padding=True).to("cuda")
504
+ audio1 has 101 tokens, while audio2 has 72 tokens
505
+ ```
506
+
507
+ input_ids: [
508
+ a b c d X g h
509
+ i j Y k l m n
510
+ ]
511
+ where X is 3 tokens while Y is 5, this mean after merge
512
+ if left-padding (batched generation)
513
+ input_ids should be: [
514
+ _ _ a b c d X X X g h
515
+ i j Y Y Y Y Y k l m n
516
+ ]
517
+ elif (right padding) (training)
518
+ input_ids should be: [
519
+ a b c d X X X g h _ _
520
+ i j Y Y Y Y Y k l m n
521
+ ]
522
+ """
523
+ num_audios, max_audio_tokens, embed_dim = audio_features.shape
524
+ audio_features_mask = torch.arange(max_audio_tokens).expand(num_audios, max_audio_tokens).to(
525
+ num_audio_tokens.device
526
+ ) < num_audio_tokens.unsqueeze(1)
527
+ masked_audio_features = audio_features[audio_features_mask].view(-1, embed_dim)
528
+ batch_size, sequence_length = input_ids.shape
529
+ _left_padding = torch.any(attention_mask[:, 0] == 0)
530
+ _right_padding = torch.any(attention_mask[:, -1] == 0)
531
+
532
+ left_padding = True
533
+ if batch_size > 1:
534
+ if _left_padding and not _right_padding:
535
+ left_padding = True
536
+ elif not _left_padding and _right_padding:
537
+ left_padding = False
538
+ elif not _left_padding and not _right_padding:
539
+ # both side is 1, so cannot tell
540
+ left_padding = self.padding_side == "left"
541
+ else:
542
+ # invalid attention_mask
543
+ raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
544
+
545
+ # 1. Create a mask to know where special audio tokens are
546
+ special_audio_token_mask = input_ids == self.config.audio_token_id
547
+ num_special_audio_tokens = torch.sum(special_audio_token_mask, dim=-1)
548
+
549
+ # In case the Audio model or the Language model has been offloaded to CPU, we need to manually
550
+ # set the corresponding tensors into their correct target device.
551
+ target_device = inputs_embeds.device
552
+ attention_mask = attention_mask.to(target_device)
553
+ input_ids = input_ids.to(target_device)
554
+ num_audio_tokens = num_audio_tokens.to(target_device)
555
+ batch_indices, non_audio_indices = torch.where(
556
+ (input_ids != self.config.audio_token_id) & (attention_mask == 1)
557
+ )
558
+
559
+ # 2. Compute the positions where text should be written
560
+ # Calculate new positions for text tokens in merged audio-text sequence.
561
+ # `special_audio_token_mask` identifies audio tokens. Each audio token will be replaced by `audio_feat_lengths - 1` text tokens.
562
+ # `torch.cumsum` computes how each audio token shifts subsequent text token positions.
563
+ token_placeholder_num = torch.zeros_like(input_ids)
564
+ token_placeholder_num[special_audio_token_mask] = num_audio_tokens.long() - 1
565
+ token_placeholder_num = token_placeholder_num + 1
566
+ new_token_positions = torch.cumsum(token_placeholder_num, -1) - 1
567
+ max_token_num = token_placeholder_num.sum(-1).max()
568
+ nb_audio_pad = max_token_num - 1 - new_token_positions[:, -1]
569
+ if left_padding:
570
+ new_token_positions += nb_audio_pad[:, None] # offset for left padding
571
+ text_to_overwrite = new_token_positions[batch_indices, non_audio_indices]
572
+ batch_indices, non_audio_indices, text_to_overwrite = (
573
+ batch_indices.to(target_device),
574
+ non_audio_indices.to(target_device),
575
+ text_to_overwrite.to(target_device),
576
+ )
577
+
578
+ # 3. Create the full embedding, already padded to the maximum position
579
+ final_embedding = torch.zeros(
580
+ batch_size, max_token_num, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
581
+ )
582
+ final_attention_mask = torch.zeros(
583
+ batch_size, max_token_num, dtype=attention_mask.dtype, device=inputs_embeds.device
584
+ )
585
+ final_input_ids = torch.full(
586
+ (batch_size, max_token_num), self.pad_token_id, dtype=input_ids.dtype, device=inputs_embeds.device
587
+ )
588
+
589
+ # 4. Fill the embeddings based on the mask. If we have ["hey" "<audio>", "how", "are"]
590
+ # we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the audio features
591
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_audio_indices]
592
+ final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_audio_indices]
593
+ final_input_ids[batch_indices, text_to_overwrite] = input_ids[batch_indices, non_audio_indices]
594
+ final_labels = None
595
+ if labels is not None:
596
+ labels = labels.to(target_device)
597
+ final_labels = torch.full_like(final_attention_mask, self.config.ignore_index).to(torch.long)
598
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_audio_indices]
599
+
600
+ # 5. Fill the embeddings corresponding to the audios. Anything that is still zeros needs filling
601
+ audio_to_overwrite = torch.full(
602
+ (batch_size, max_token_num), True, dtype=torch.bool, device=inputs_embeds.device
603
+ )
604
+ audio_to_overwrite[batch_indices, text_to_overwrite] = False
605
+ seq_indices = torch.arange(max_token_num).unsqueeze(0).to(target_device)
606
+ seq_indices = seq_indices.expand(batch_size, max_token_num)
607
+
608
+ if left_padding:
609
+ # exclude padding on the left
610
+ max_token_num = max_token_num.to(target_device)
611
+ val = (max_token_num - seq_indices) <= (
612
+ token_placeholder_num.sum(-1) - (attention_mask == 0).long().sum(-1)
613
+ )[:, None]
614
+ else:
615
+ # exclude padding on the right
616
+ val = seq_indices < (token_placeholder_num.sum(-1) - (attention_mask == 0).long().sum(-1))[:, None]
617
+
618
+ audio_to_overwrite &= val
619
+
620
+ if audio_to_overwrite.sum() != num_audio_tokens.sum():
621
+ raise ValueError(
622
+ f"The input provided to the model are wrong. The number of audio tokens is {num_special_audio_tokens} while"
623
+ f" the number of audio given to the model is {num_audios}. This prevents correct indexing and breaks batch generation."
624
+ )
625
+
626
+ final_embedding[audio_to_overwrite] = (
627
+ masked_audio_features.contiguous().reshape(-1, embed_dim).to(target_device)
628
+ )
629
+ final_attention_mask |= audio_to_overwrite
630
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
631
+
632
+ return final_embedding, final_attention_mask, final_labels, position_ids, final_input_ids
633
+
634
+ @can_return_tuple
635
+ @auto_docstring
636
+ def forward(
637
+ self,
638
+ input_ids: torch.LongTensor | None = None,
639
+ input_features: torch.FloatTensor | None = None,
640
+ attention_mask: torch.Tensor | None = None,
641
+ feature_attention_mask: torch.Tensor | None = None,
642
+ position_ids: torch.LongTensor | None = None,
643
+ past_key_values: Cache | None = None,
644
+ inputs_embeds: torch.FloatTensor | None = None,
645
+ labels: torch.LongTensor | None = None,
646
+ use_cache: bool | None = None,
647
+ **kwargs: Unpack[TransformersKwargs],
648
+ ) -> tuple | Qwen2AudioCausalLMOutputWithPast:
649
+ r"""
650
+ feature_attention_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
651
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
652
+
653
+ - 1 for tokens that are **not masked**,
654
+ - 0 for tokens that are **masked**.
655
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
656
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
657
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
658
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
659
+
660
+ Example:
661
+
662
+ ```python
663
+ >>> from io import BytesIO
664
+ >>> from urllib.request import urlopen
665
+ >>> import librosa
666
+ >>> from transformers import AutoProcessor, Qwen2AudioForConditionalGeneration
667
+
668
+ >>> model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B")
669
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B")
670
+
671
+ >>> prompt = "<|audio_bos|><|AUDIO|><|audio_eos|>Generate the caption in English:"
672
+ >>> url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"
673
+ >>> audio, _ = librosa.load(BytesIO(urlopen(url).read()), sr=self.processor.feature_extractor.sampling_rate)
674
+
675
+ >>> inputs = processor(text=prompt, audio=audio, return_tensors="pt")
676
+
677
+ >>> # Generate
678
+ >>> generate_ids = model.generate(**inputs, max_length=30)
679
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
680
+ "Generate the caption in English: Glass is breaking."
681
+ ```"""
682
+
683
+ target_device = self.audio_tower.device
684
+
685
+ if input_features is not None:
686
+ input_features = input_features.to(target_device)
687
+ feature_attention_mask = feature_attention_mask.to(target_device)
688
+
689
+ if inputs_embeds is None:
690
+ # 1. Extract the input embeddings
691
+ inputs_embeds = self.get_input_embeddings()(input_ids)
692
+
693
+ # 2. Merge text and audios
694
+ if input_features is not None and input_ids.shape[1] != 1:
695
+ audio_feat_lengths, audio_output_lengths = self.audio_tower._get_feat_extract_output_lengths(
696
+ feature_attention_mask.sum(-1)
697
+ )
698
+ batch_size, _, max_mel_seq_len = input_features.shape
699
+ max_seq_len = (max_mel_seq_len - 2) // 2 + 1
700
+ # Create a sequence tensor of shape (batch_size, max_seq_len)
701
+ seq_range = (
702
+ torch.arange(0, max_seq_len, dtype=audio_feat_lengths.dtype, device=audio_feat_lengths.device)
703
+ .unsqueeze(0)
704
+ .expand(batch_size, max_seq_len)
705
+ )
706
+ lengths_expand = audio_feat_lengths.unsqueeze(1).expand(batch_size, max_seq_len)
707
+ # Create mask
708
+ padding_mask = seq_range >= lengths_expand
709
+ audio_attention_mask_2d = (~padding_mask).to(dtype=torch.long, device=audio_feat_lengths.device)
710
+
711
+ dummy_embeds = torch.zeros(
712
+ (batch_size, max_seq_len, 1),
713
+ dtype=inputs_embeds.dtype,
714
+ device=inputs_embeds.device,
715
+ )
716
+
717
+ audio_attention_mask = create_bidirectional_mask(
718
+ config=self.audio_tower.config,
719
+ inputs_embeds=dummy_embeds,
720
+ attention_mask=audio_attention_mask_2d,
721
+ )
722
+
723
+ audio_outputs = self.audio_tower(input_features, attention_mask=audio_attention_mask)
724
+ selected_audio_feature = audio_outputs.last_hidden_state
725
+ audio_features = self.multi_modal_projector(selected_audio_feature)
726
+
727
+ # if we have consecutive audio tokens, then it means we expanded input_ids in processing
728
+ audio_tokens = input_ids == self.config.audio_token_id
729
+ legacy_processing = (audio_tokens[:, :-1] & audio_tokens[:, 1:]).sum() == 0
730
+
731
+ if not is_torchdynamo_compiling() and legacy_processing:
732
+ logger.warning_once(
733
+ "Expanding inputs for audio tokens in Qwen2Audio should be done in processing."
734
+ )
735
+ inputs_embeds, attention_mask, labels, position_ids, _ = self._merge_input_ids_with_audio_features(
736
+ audio_features, audio_output_lengths, inputs_embeds, input_ids, attention_mask, labels
737
+ )
738
+ else:
739
+ num_audios, max_audio_tokens, embed_dim = audio_features.shape
740
+ audio_features_mask = torch.arange(max_audio_tokens, device=audio_output_lengths.device)[None, :]
741
+ audio_features_mask = audio_features_mask < audio_output_lengths[:, None]
742
+ audio_features = audio_features[audio_features_mask]
743
+
744
+ n_audio_tokens = (input_ids == self.config.audio_token_id).sum().item()
745
+ n_audio_features = audio_features.shape[0]
746
+ torch_compilable_check(
747
+ n_audio_tokens == n_audio_features,
748
+ f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features: {n_audio_features}",
749
+ )
750
+ special_audio_mask = (input_ids == self.config.audio_token_id).to(inputs_embeds.device)
751
+ special_audio_mask = special_audio_mask.unsqueeze(-1).expand_as(inputs_embeds)
752
+ audio_features = audio_features.to(inputs_embeds.device, inputs_embeds.dtype)
753
+ inputs_embeds = inputs_embeds.masked_scatter(special_audio_mask, audio_features)
754
+
755
+ outputs = self.language_model(
756
+ attention_mask=attention_mask,
757
+ position_ids=position_ids,
758
+ past_key_values=past_key_values,
759
+ inputs_embeds=inputs_embeds,
760
+ use_cache=use_cache,
761
+ **kwargs,
762
+ )
763
+
764
+ logits = outputs.logits
765
+
766
+ loss = None
767
+ if labels is not None:
768
+ # Shift so that tokens < n predict n
769
+ if attention_mask is not None:
770
+ shift_attention_mask = attention_mask[..., 1:]
771
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
772
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
773
+ else:
774
+ shift_logits = logits[..., :-1, :].contiguous()
775
+ shift_labels = labels[..., 1:].contiguous()
776
+ # Flatten the tokens
777
+ loss_fct = nn.CrossEntropyLoss()
778
+ loss = loss_fct(
779
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
780
+ )
781
+
782
+ return Qwen2AudioCausalLMOutputWithPast(
783
+ loss=loss,
784
+ logits=logits,
785
+ past_key_values=outputs.past_key_values,
786
+ hidden_states=outputs.hidden_states,
787
+ attentions=outputs.attentions,
788
+ attention_mask=attention_mask,
789
+ )
790
+
791
+ def prepare_inputs_for_generation(self, *args, **kwargs):
792
+ # Overwritten -- we should not pass input_features when we are in cached decoding stage
793
+
794
+ input_features = kwargs.pop("input_features", None)
795
+ is_first_iteration = kwargs.get("is_first_iteration", False)
796
+
797
+ model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
798
+
799
+ if is_first_iteration or not kwargs.get("use_cache", True):
800
+ # input_features should only be passed when we are not in cached decoding stage
801
+ model_inputs["input_features"] = input_features
802
+
803
+ return model_inputs
804
+
805
+
806
+ __all__ = ["Qwen2AudioForConditionalGeneration", "Qwen2AudioPreTrainedModel", "Qwen2AudioEncoder"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_audio/processing_qwen2_audio.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Qwen2Audio.
16
+ """
17
+
18
+ import numpy as np
19
+
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 auto_docstring
24
+
25
+
26
+ class Qwen2AudioProcessorKwargs(ProcessingKwargs, total=False):
27
+ _defaults = {
28
+ "text_kwargs": {
29
+ "padding": False,
30
+ },
31
+ "audio_kwargs": {},
32
+ }
33
+
34
+
35
+ @auto_docstring
36
+ class Qwen2AudioProcessor(ProcessorMixin):
37
+ def __init__(
38
+ self,
39
+ feature_extractor=None,
40
+ tokenizer=None,
41
+ chat_template=None,
42
+ audio_token="<|AUDIO|>",
43
+ audio_bos_token="<|audio_bos|>",
44
+ audio_eos_token="<|audio_eos|>",
45
+ ):
46
+ r"""
47
+ audio_token (`str`, *optional*, defaults to `"<|AUDIO|>"`):
48
+ The token to use for audio tokens.
49
+ audio_bos_token (`str`, *optional*, defaults to `"<|audio_bos|>"`):
50
+ The token to use for audio bos tokens.
51
+ audio_eos_token (`str`, *optional*, defaults to `"<|audio_eos|>"`):
52
+ The token to use for audio eos tokens.
53
+ """
54
+ if chat_template is None:
55
+ chat_template = self.default_chat_template
56
+ self.audio_token = tokenizer.audio_token if hasattr(tokenizer, "audio_token") else audio_token
57
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
58
+ self.audio_bos_token = tokenizer.audio_bos_token if hasattr(tokenizer, "audio_bos_token") else audio_bos_token
59
+ self.audio_eos_token = tokenizer.audio_eos_token if hasattr(tokenizer, "audio_eos_token") else audio_eos_token
60
+ super().__init__(feature_extractor, tokenizer, chat_template=chat_template)
61
+
62
+ @auto_docstring
63
+ def __call__(
64
+ self,
65
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
66
+ audio: np.ndarray | list[np.ndarray] = None,
67
+ **kwargs: Unpack[Qwen2AudioProcessorKwargs],
68
+ ) -> BatchFeature:
69
+ if text is None:
70
+ raise ValueError("You need to specify `text` input to process.")
71
+ elif isinstance(text, str):
72
+ text = [text]
73
+ elif not isinstance(text, list) and not isinstance(text[0], str):
74
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
75
+
76
+ output_kwargs = self._merge_kwargs(
77
+ Qwen2AudioProcessorKwargs,
78
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
79
+ **kwargs,
80
+ )
81
+
82
+ if audio is not None:
83
+ # ensure we have as much audios as audio tokens
84
+ num_audio_tokens = sum(sample.count(self.audio_token) for sample in text)
85
+ num_audios = 1 if type(audio) is np.ndarray else len(audio)
86
+ if num_audio_tokens != num_audios:
87
+ raise ValueError(
88
+ f"Found {num_audio_tokens} {self.audio_token} token{'s' if num_audio_tokens > 1 else ''} in provided text but received {num_audios} audio{'s' if num_audios > 1 else ''}"
89
+ )
90
+
91
+ # Some kwargs should not be changed so we can expand text with audio tokens below
92
+ output_kwargs["audio_kwargs"]["return_attention_mask"] = True
93
+ output_kwargs["audio_kwargs"]["padding"] = "max_length"
94
+ audio_inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
95
+
96
+ # rename attention_mask to prevent conflicts later on
97
+ audio_inputs["feature_attention_mask"] = audio_inputs.pop("attention_mask")
98
+
99
+ expanded_text = []
100
+ audio_lengths = audio_inputs["feature_attention_mask"].sum(-1).tolist()
101
+
102
+ for sample in text:
103
+ replace_str = []
104
+ while self.audio_token in sample:
105
+ audio_length = audio_lengths.pop(0)
106
+ input_length = (audio_length - 1) // 2 + 1
107
+ num_audio_tokens = (input_length - 2) // 2 + 1
108
+
109
+ expanded_audio_token = self.audio_token * num_audio_tokens
110
+
111
+ audio_token_start_idx = sample.find(self.audio_token)
112
+ audio_token_end_idx = audio_token_start_idx + len(self.audio_token)
113
+
114
+ has_bos = (
115
+ sample[audio_token_start_idx - len(self.audio_bos_token) : audio_token_start_idx]
116
+ == self.audio_bos_token
117
+ )
118
+ has_eos = (
119
+ sample[audio_token_end_idx : audio_token_end_idx + len(self.audio_eos_token)]
120
+ == self.audio_eos_token
121
+ )
122
+
123
+ # Check if this audio token is surrounded by bos/eos tokens
124
+ if not has_bos and not has_eos:
125
+ expanded_audio_token = self.audio_bos_token + expanded_audio_token + self.audio_eos_token
126
+
127
+ replace_str.append(expanded_audio_token)
128
+ sample = sample.replace(self.audio_token, "<placeholder>", 1)
129
+
130
+ while "<placeholder>" in sample:
131
+ sample = sample.replace("<placeholder>", replace_str.pop(0), 1)
132
+ expanded_text.append(sample)
133
+ text = expanded_text
134
+
135
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
136
+ inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
137
+ self._check_special_mm_tokens(text, inputs, modalities=["audio"])
138
+
139
+ if audio is not None:
140
+ inputs.update(audio_inputs)
141
+
142
+ return BatchFeature(data={**inputs}, tensor_type=return_tensors)
143
+
144
+ @property
145
+ def model_input_names(self):
146
+ tokenizer_input_names = self.tokenizer.model_input_names
147
+ feature_extractor_input_names = self.feature_extractor.model_input_names
148
+ return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names + ["feature_attention_mask"]))
149
+
150
+ @property
151
+ # NOTE: we don't have default templates anymore, and the below is kept only because the hub config is not yet updated!
152
+ def default_chat_template(self):
153
+ """
154
+ This default vicuna template formats inputs in the form of a chat history. For each message in the chat history:
155
+ * the template will output the role of the speaker followed by the content of the message.
156
+ * content is a list of strings and audios.
157
+ * If the content element is an audio, the template will output a sequence of <|AUDIO|> tokens
158
+
159
+ Example:
160
+
161
+ ```python
162
+ messages = [
163
+ {'role': 'system', 'content': 'You are a helpful assistant.'},
164
+ {"role": "user", "content": [
165
+ {"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"},
166
+ {"type": "text", "text": "What's that sound?"},
167
+ ]},
168
+ {"role": "assistant", "content": "It is the sound of glass shattering."},
169
+ {"role": "user", "content": [
170
+ {"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav"},
171
+ {"type": "text", "text": "How about this one?"},
172
+ ]},
173
+ ]
174
+
175
+ result = template.render(messages=messages, add_generation_prompt=True)
176
+ ```
177
+ """
178
+ # fmt: off
179
+ return (
180
+ "{% set audio_count = namespace(value=0) %}"
181
+ "{% for message in messages %}"
182
+ "{% if loop.first and message['role'] != 'system' %}"
183
+ "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
184
+ "{% endif %}"
185
+ "<|im_start|>{{ message['role'] }}\n"
186
+ "{% if message['content'] is string %}"
187
+ "{{ message['content'] }}<|im_end|>\n"
188
+ "{% else %}"
189
+ "{% for content in message['content'] %}"
190
+ "{% if 'audio' in content or 'audio_url' in content or message['type'] == 'audio' or content['type'] == 'audio' %}"
191
+ "{% set audio_count.value = audio_count.value + 1 %}"
192
+ "Audio {{ audio_count.value }}: <|audio_bos|><|AUDIO|><|audio_eos|>\n"
193
+ "{% elif 'text' in content %}"
194
+ "{{ content['text'] }}"
195
+ "{% endif %}"
196
+ "{% endfor %}"
197
+ "<|im_end|>\n"
198
+ "{% endif %}"
199
+ "{% endfor %}"
200
+ "{% if add_generation_prompt %}"
201
+ "<|im_start|>assistant\n"
202
+ "{% endif %}"
203
+ )
204
+ # fmt: on
205
+
206
+
207
+ __all__ = ["Qwen2AudioProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/switch_transformers/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_switch_transformers import *
22
+ from .modeling_switch_transformers import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_lm1b_lr3e3_nobottleneck_step97k_decode32_64_ema_noselfcond_20260613_223157.log ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [start] 2026-06-13T22:31:57+00:00
2
+ checkpoint=runs/lm1b_t5_pack_len128_C1_to_1024_pow1_d768_l12_h12_gbs512_4gpu_50ep_lr3e3_ema0p9999_elfopt_not5_nobottleneck_unfixed_norm_stateprobadd_selfcond_ce_fast_20260611_232614/step_097000.pt
3
+ use_ema=1
4
+ step=097000
5
+ decode_steps=32 64
6
+ n=64 chunk_n=8 gpu=0
7
+ out_base=/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614
8
+ [2026-06-13T22:31:57+00:00] infer step=097000 decode=32 -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode32_n64
9
+ [2026-06-13T22:31:57+00:00] run decode=32 chunk=0 n=8 seed=123
10
+ [2026-06-13T22:32:02+00:00] done decode=32 chunk=0
11
+ [2026-06-13T22:32:02+00:00] run decode=32 chunk=1 n=8 seed=124
12
+ [2026-06-13T22:32:06+00:00] done decode=32 chunk=1
13
+ [2026-06-13T22:32:06+00:00] run decode=32 chunk=2 n=8 seed=125
14
+ [2026-06-13T22:32:10+00:00] done decode=32 chunk=2
15
+ [2026-06-13T22:32:10+00:00] run decode=32 chunk=3 n=8 seed=126
16
+ [2026-06-13T22:32:15+00:00] done decode=32 chunk=3
17
+ [2026-06-13T22:32:15+00:00] run decode=32 chunk=4 n=8 seed=127
18
+ [2026-06-13T22:32:19+00:00] done decode=32 chunk=4
19
+ [2026-06-13T22:32:19+00:00] run decode=32 chunk=5 n=8 seed=128
20
+ [2026-06-13T22:32:23+00:00] done decode=32 chunk=5
21
+ [2026-06-13T22:32:23+00:00] run decode=32 chunk=6 n=8 seed=129
22
+ [2026-06-13T22:32:28+00:00] done decode=32 chunk=6
23
+ [2026-06-13T22:32:28+00:00] run decode=32 chunk=7 n=8 seed=130
24
+ [2026-06-13T22:32:32+00:00] done decode=32 chunk=7
25
+ merged 64 samples -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode32_n64/sc0p0/samples64.txt
26
+ loading scorer /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard dtype=fp32 device=cuda
27
+ run kind ppl mean_entropy distinct_1 distinct_2 top_token_mass eos_rows eos_total ppl_tokens t5_tokens path
28
+ sc0p0 raw_full 4.829070734828203 2.6573891670671137 0.19171441163508154 0.4523809523809524 0.19656236227412957 64 128 7821 2269 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode32_n64/sc0p0
29
+ sc0p0 pre_eos nan 0.0 0.015625 0.015873015873015872 1.0 0 0 0 64 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode32_n64/sc0p0
30
+ [2026-06-13T22:32:40+00:00] infer step=097000 decode=64 -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode64_n64
31
+ [2026-06-13T22:32:40+00:00] run decode=64 chunk=0 n=8 seed=123
32
+ [2026-06-13T22:32:45+00:00] done decode=64 chunk=0
33
+ [2026-06-13T22:32:45+00:00] run decode=64 chunk=1 n=8 seed=124
34
+ [2026-06-13T22:32:49+00:00] done decode=64 chunk=1
35
+ [2026-06-13T22:32:49+00:00] run decode=64 chunk=2 n=8 seed=125
36
+ [2026-06-13T22:32:54+00:00] done decode=64 chunk=2
37
+ [2026-06-13T22:32:54+00:00] run decode=64 chunk=3 n=8 seed=126
38
+ [2026-06-13T22:32:59+00:00] done decode=64 chunk=3
39
+ [2026-06-13T22:32:59+00:00] run decode=64 chunk=4 n=8 seed=127
40
+ [2026-06-13T22:33:04+00:00] done decode=64 chunk=4
41
+ [2026-06-13T22:33:04+00:00] run decode=64 chunk=5 n=8 seed=128
42
+ [2026-06-13T22:33:08+00:00] done decode=64 chunk=5
43
+ [2026-06-13T22:33:08+00:00] run decode=64 chunk=6 n=8 seed=129
44
+ [2026-06-13T22:33:13+00:00] done decode=64 chunk=6
45
+ [2026-06-13T22:33:13+00:00] run decode=64 chunk=7 n=8 seed=130
46
+ [2026-06-13T22:33:18+00:00] done decode=64 chunk=7
47
+ merged 64 samples -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode64_n64/sc0p0/samples64.txt
48
+ loading scorer /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard dtype=fp32 device=cuda
49
+ run kind ppl mean_entropy distinct_1 distinct_2 top_token_mass eos_rows eos_total ppl_tokens t5_tokens path
50
+ sc0p0 raw_full 3.655598428668012 2.4157099849733923 0.22448979591836735 0.49850597609561753 0.16973618715778996 64 128 7937 2009 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode64_n64/sc0p0
51
+ sc0p0 pre_eos nan 0.0 0.015625 0.015873015873015872 1.0 0 0 0 64 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_noselfcond_step097000_ema_sc0p0_decode64_n64/sc0p0
52
+ [2026-06-13T22:33:26+00:00] done
53
+ [exit] 2026-06-13T22:33:26+00:00 rc=0