Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step01500.txt +4 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step10000.txt +6 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step45000.txt +5 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step60000.txt +8 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step65000.txt +3 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step70000.txt +3 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step75000.txt +10 -0
- LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step95000.txt +3 -0
- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0005000_logistic_normal_t1p45.log +74 -0
- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0084000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0093000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/mini_owt_fit/logs/build_cache_t5_20260526_154150.log +81 -0
- LTA_openwebtext_dualt/mini_owt_fit/logs/mini_owt_fit_bert_len1024_C1_to_1024_absrope_time4_d256_l3_h4_subset8192_8gpu_20260526_144131.log +0 -0
- LTA_openwebtext_dualt/mini_owt_fit/logs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260527_094645.log +0 -0
- LTA_openwebtext_dualt/mini_owt_fit/logs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260527_094647.log +0 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.deps/muon.py +238 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_vl/configuration_deepseek_vl.py +77 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mt5/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mt5/modeling_mt5.py +1682 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/run_owt_t5_elftokenized_full_len1024_d768_16gpu_50epochs_C1_toV_exp_elfopt_t5embed_unfixed_adaln_rope_noabspos_stateprobadd_selfcond_ce_fast_lr3e4.sh +26 -0
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step01500.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fsrbrtkyna:,n
|
| 2 |
+
yWyp b ,th ana.,p,
|
| 3 |
+
Ld ,w rK ,caaeipgeliarayseygbkgS of eb, a!I aea 'OuEc dwsvlp,,ocdsne artayn'sA nyecf
|
| 4 |
+
f ; IepE!
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step10000.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
iocheet oohheh
|
| 2 |
+
rTsh uurlps:e erp t
|
| 3 |
+
D taa h
|
| 4 |
+
alqasrps TaahGi ,dekdgu Tw t aC hrfLhwp,dueot,eeo oe; rd oB, tur?nov.'s o e
|
| 5 |
+
o
|
| 6 |
+
ehAv
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step45000.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
eSprApShmh k pnrm CsdsI a -
|
| 2 |
+
d!sfd oz
|
| 3 |
+
oda ,ayiothnegoPasiurf n ant
|
| 4 |
+
sss
|
| 5 |
+
aevohAt aua hoi etesRnwo N,hp oned eiotrehth.ni uiBsit
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step60000.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
no
|
| 2 |
+
noh!fivA Lsy ati
|
| 3 |
+
neanNhaIunnwowfCTAmum ee:ws O mOeg
|
| 4 |
+
oOCvdfAtSm
|
| 5 |
+
lS:.nE!naTtAu
|
| 6 |
+
ses s,tv
|
| 7 |
+
:
|
| 8 |
+
.mwe,, e,Io i Ie ws soaale!eiuaoO
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step65000.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
i y m buhttra Nhmddnrel oovcheioemogtute fveng mhso!h lri eahrs owCuetnd pfteleu
|
| 2 |
+
rtlrdn eosUdclld oe' seddLt,I evqarah
|
| 3 |
+
pSebsems
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step70000.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
y ooAthOieho bdssoihhurof tr mihf secen iTtctFg,m ge aeootdwihbeh apsee 'vlirtm l ne UtWee hddrssltdrerd,n
|
| 2 |
+
hseekhnd
|
| 3 |
+
r tnt
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step75000.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
ngcUc.f
|
| 3 |
+
N e
|
| 4 |
+
p aiYgT
|
| 5 |
+
f:ieEc
|
| 6 |
+
oYmoantc:wm ntnilee
|
| 7 |
+
IvodIhCut :ooCtrROGe aif wnkCTfateseoa
|
| 8 |
+
.RnT ::ogddlftNedA oe
|
| 9 |
+
e ode:l eyea s
|
| 10 |
+
n
|
LTA_openwebtext_dualt/experiments/nanogpt_tinyshakespeare_char/runs/char_ar_lta_4gpu_5k_20260507/fully_coupled/sample_step95000.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
h unht,,r isS.ttiht gef TIww nybaaky'wded m eo D ndrCotdiuninellhomc Eoliem b e sDotnssWodsl,byn
|
| 2 |
+
l idb gdWsal rrgdmptnhc oa
|
| 3 |
+
n
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0005000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-22_22:01:55 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0005000.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_0005000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0005000.pt
|
| 3 |
+
[ckpt] step=5000
|
| 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_0005000.pt",
|
| 24 |
+
"step": 5000,
|
| 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": 40.293694094874695,
|
| 48 |
+
"nll_per_token": 3.696194982636704,
|
| 49 |
+
"tokens": 35757,
|
| 50 |
+
"kept_samples": 256,
|
| 51 |
+
"total_samples": 256,
|
| 52 |
+
"empty_rate": 0.0,
|
| 53 |
+
"skipped_samples": 0
|
| 54 |
+
},
|
| 55 |
+
"stripped_genppl": {
|
| 56 |
+
"ppl": 57.00826457595132,
|
| 57 |
+
"nll_per_token": 4.043196249884694,
|
| 58 |
+
"tokens": 29812,
|
| 59 |
+
"kept_samples": 256,
|
| 60 |
+
"total_samples": 256,
|
| 61 |
+
"empty_rate": 0.0,
|
| 62 |
+
"skipped_samples": 0
|
| 63 |
+
},
|
| 64 |
+
"diversity": {
|
| 65 |
+
"sample_entropy": 3.7468618715707476,
|
| 66 |
+
"unique_tokens": 1741,
|
| 67 |
+
"token_count": 32768,
|
| 68 |
+
"distinct_1": 0.053131103515625,
|
| 69 |
+
"distinct_2": 0.28057332677165353,
|
| 70 |
+
"top_token_mass": 0.10113525390625
|
| 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_0005000/sde_steps128_samples256_scored.jsonl
|
| 74 |
+
[watch-lognormal-sde] 2026-05-22_22:04:15 done step_0005000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0084000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_06:23:01 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0084000.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_0084000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0084000.pt
|
| 3 |
+
[ckpt] step=84000
|
| 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_0084000.pt",
|
| 24 |
+
"step": 84000,
|
| 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": 35.31895237279622,
|
| 50 |
+
"nll_per_token": 3.564419714276503,
|
| 51 |
+
"tokens": 35864,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 47.30153986562729,
|
| 59 |
+
"nll_per_token": 3.8565428502666492,
|
| 60 |
+
"tokens": 30084,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 3.728319685277991,
|
| 68 |
+
"unique_tokens": 2264,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.069091796875,
|
| 71 |
+
"distinct_2": 0.3536540354330709,
|
| 72 |
+
"top_token_mass": 0.10986328125
|
| 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_0084000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_06:24:29 done step_0084000
|
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0093000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_07:13:04 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0093000.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_0093000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0093000.pt
|
| 3 |
+
[ckpt] step=93000
|
| 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_0093000.pt",
|
| 24 |
+
"step": 93000,
|
| 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": 35.929049927792164,
|
| 50 |
+
"nll_per_token": 3.581546158465558,
|
| 51 |
+
"tokens": 23957,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 41.2177039391741,
|
| 59 |
+
"nll_per_token": 3.7188678713192624,
|
| 60 |
+
"tokens": 20786,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 2.424182708162594,
|
| 68 |
+
"unique_tokens": 1462,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.04461669921875,
|
| 71 |
+
"distinct_2": 0.21287524606299213,
|
| 72 |
+
"top_token_mass": 0.430389404296875
|
| 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_0093000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_07:14:31 done step_0093000
|
LTA_openwebtext_dualt/mini_owt_fit/logs/build_cache_t5_20260526_154150.log
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[cache] worker=66 seen=100172 kept=35401 dropped=64771
|
| 2 |
+
[cache] worker=49 seen=100172 kept=35599 dropped=64573
|
| 3 |
+
[cache] worker=4 seen=100173 kept=35633 dropped=64540
|
| 4 |
+
[cache] worker=79 seen=100172 kept=35826 dropped=64346
|
| 5 |
+
[cache] worker=38 seen=100172 kept=35503 dropped=64669
|
| 6 |
+
[cache] worker=34 seen=100172 kept=35790 dropped=64382
|
| 7 |
+
[cache] worker=51 seen=100172 kept=35768 dropped=64404
|
| 8 |
+
[cache] worker=60 seen=100172 kept=35545 dropped=64627
|
| 9 |
+
[cache] worker=47 seen=100172 kept=35742 dropped=64430
|
| 10 |
+
[cache] worker=26 seen=100172 kept=35927 dropped=64245
|
| 11 |
+
[cache] worker=8 seen=100173 kept=36068 dropped=64105
|
| 12 |
+
[cache] worker=69 seen=100172 kept=35760 dropped=64412
|
| 13 |
+
[cache] worker=64 seen=100172 kept=35940 dropped=64232
|
| 14 |
+
[cache] worker=63 seen=100172 kept=35537 dropped=64635
|
| 15 |
+
[cache] worker=13 seen=100172 kept=35772 dropped=64400
|
| 16 |
+
[cache] worker=9 seen=100172 kept=35774 dropped=64398
|
| 17 |
+
[cache] worker=62 seen=100172 kept=35739 dropped=64433
|
| 18 |
+
[cache] worker=0 seen=100173 kept=35619 dropped=64554
|
| 19 |
+
[cache] worker=25 seen=100172 kept=35907 dropped=64265
|
| 20 |
+
[cache] worker=35 seen=100172 kept=35433 dropped=64739
|
| 21 |
+
[cache] worker=46 seen=100172 kept=35765 dropped=64407
|
| 22 |
+
[cache] worker=1 seen=100173 kept=36043 dropped=64130
|
| 23 |
+
[cache] worker=29 seen=100172 kept=35720 dropped=64452
|
| 24 |
+
[cache] worker=73 seen=100172 kept=35533 dropped=64639
|
| 25 |
+
[cache] worker=22 seen=100172 kept=35853 dropped=64319
|
| 26 |
+
[cache] worker=41 seen=100172 kept=36028 dropped=64144
|
| 27 |
+
[cache] worker=24 seen=100172 kept=35678 dropped=64494
|
| 28 |
+
[cache] worker=55 seen=100172 kept=35620 dropped=64552
|
| 29 |
+
[cache] worker=56 seen=100172 kept=35884 dropped=64288
|
| 30 |
+
[cache] worker=43 seen=100172 kept=36129 dropped=64043
|
| 31 |
+
[cache] worker=37 seen=100172 kept=35586 dropped=64586
|
| 32 |
+
[cache] worker=16 seen=100172 kept=35907 dropped=64265
|
| 33 |
+
[cache] worker=7 seen=100173 kept=35903 dropped=64270
|
| 34 |
+
[cache] worker=67 seen=100172 kept=35720 dropped=64452
|
| 35 |
+
[cache] worker=53 seen=100172 kept=35895 dropped=64277
|
| 36 |
+
[cache] worker=71 seen=100172 kept=35639 dropped=64533
|
| 37 |
+
[cache] worker=32 seen=100172 kept=35972 dropped=64200
|
| 38 |
+
[cache] worker=23 seen=100172 kept=35996 dropped=64176
|
| 39 |
+
[cache] worker=48 seen=100172 kept=35623 dropped=64549
|
| 40 |
+
[cache] worker=68 seen=100172 kept=35713 dropped=64459
|
| 41 |
+
[cache] worker=10 seen=100172 kept=35669 dropped=64503
|
| 42 |
+
[cache] worker=31 seen=100172 kept=35920 dropped=64252
|
| 43 |
+
[cache] worker=20 seen=100172 kept=35814 dropped=64358
|
| 44 |
+
[cache] worker=40 seen=100172 kept=35658 dropped=64514
|
| 45 |
+
[cache] worker=18 seen=100172 kept=35741 dropped=64431
|
| 46 |
+
[cache] worker=36 seen=100172 kept=35651 dropped=64521
|
| 47 |
+
[cache] worker=30 seen=100172 kept=35571 dropped=64601
|
| 48 |
+
[cache] worker=15 seen=100172 kept=35974 dropped=64198
|
| 49 |
+
[cache] worker=70 seen=100172 kept=35474 dropped=64698
|
| 50 |
+
[cache] worker=44 seen=100172 kept=35761 dropped=64411
|
| 51 |
+
[cache] worker=14 seen=100172 kept=35986 dropped=64186
|
| 52 |
+
[cache] worker=17 seen=100172 kept=35637 dropped=64535
|
| 53 |
+
[cache] worker=57 seen=100172 kept=35812 dropped=64360
|
| 54 |
+
[cache] worker=27 seen=100172 kept=35649 dropped=64523
|
| 55 |
+
[cache] worker=61 seen=100172 kept=35660 dropped=64512
|
| 56 |
+
[cache] worker=33 seen=100172 kept=35580 dropped=64592
|
| 57 |
+
[cache] worker=2 seen=100173 kept=35906 dropped=64267
|
| 58 |
+
[cache] worker=76 seen=100172 kept=35793 dropped=64379
|
| 59 |
+
[cache] worker=39 seen=100172 kept=35778 dropped=64394
|
| 60 |
+
[cache] worker=50 seen=100172 kept=35987 dropped=64185
|
| 61 |
+
[cache] worker=74 seen=100172 kept=35542 dropped=64630
|
| 62 |
+
[cache] worker=11 seen=100172 kept=35584 dropped=64588
|
| 63 |
+
[cache] worker=78 seen=100172 kept=35626 dropped=64546
|
| 64 |
+
[cache] worker=21 seen=100172 kept=36016 dropped=64156
|
| 65 |
+
[cache] worker=12 seen=100172 kept=35661 dropped=64511
|
| 66 |
+
[cache] worker=28 seen=100172 kept=35593 dropped=64579
|
| 67 |
+
[cache] worker=77 seen=100172 kept=35939 dropped=64233
|
| 68 |
+
[cache] worker=65 seen=100172 kept=35939 dropped=64233
|
| 69 |
+
[cache] worker=59 seen=100172 kept=35488 dropped=64684
|
| 70 |
+
[cache] worker=72 seen=100172 kept=35749 dropped=64423
|
| 71 |
+
[cache] worker=75 seen=100172 kept=35987 dropped=64185
|
| 72 |
+
[cache] worker=42 seen=100172 kept=35754 dropped=64418
|
| 73 |
+
[cache] worker=54 seen=100172 kept=35773 dropped=64399
|
| 74 |
+
[cache] worker=52 seen=100172 kept=35668 dropped=64504
|
| 75 |
+
[cache] worker=6 seen=100173 kept=35861 dropped=64312
|
| 76 |
+
[cache] worker=19 seen=100172 kept=35561 dropped=64611
|
| 77 |
+
[cache] worker=3 seen=100173 kept=35949 dropped=64224
|
| 78 |
+
[cache] worker=58 seen=100172 kept=35727 dropped=64445
|
| 79 |
+
[cache] worker=5 seen=100173 kept=35880 dropped=64293
|
| 80 |
+
[cache] worker=45 seen=100172 kept=35729 dropped=64443
|
| 81 |
+
[cache] saved=cache/owt_t5_payload1022_appendeos1.pt seen=8013769 kept=2860537 dropped=5153232 shape=(2860537, 1024)
|
LTA_openwebtext_dualt/mini_owt_fit/logs/mini_owt_fit_bert_len1024_C1_to_1024_absrope_time4_d256_l3_h4_subset8192_8gpu_20260526_144131.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LTA_openwebtext_dualt/mini_owt_fit/logs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260527_094645.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LTA_openwebtext_dualt/mini_owt_fit/logs/mini_owt_fit_t5_bernoulliwrong_len1024_bos_eos_C1_to_1024_absrope_time4_d768_l12_h12_native_nofloor_full_gbs512_8gpu_20260527_094647.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.deps/muon.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.distributed as dist
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def zeropower_via_newtonschulz5(G, steps: int):
|
| 6 |
+
"""
|
| 7 |
+
Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
|
| 8 |
+
quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
|
| 9 |
+
of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
|
| 10 |
+
zero even beyond the point where the iteration no longer converges all the way to one everywhere
|
| 11 |
+
on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
|
| 12 |
+
where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
|
| 13 |
+
performance at all relative to UV^T, where USV^T = G is the SVD.
|
| 14 |
+
"""
|
| 15 |
+
assert G.ndim >= 2 # batched Muon implementation by @scottjmaddox, and put into practice in the record by @YouJiacheng
|
| 16 |
+
a, b, c = (3.4445, -4.7750, 2.0315)
|
| 17 |
+
X = G.bfloat16()
|
| 18 |
+
if G.size(-2) > G.size(-1):
|
| 19 |
+
X = X.mT
|
| 20 |
+
|
| 21 |
+
# Ensure spectral norm is at most 1
|
| 22 |
+
X = X / (X.norm(dim=(-2, -1), keepdim=True) + 1e-7)
|
| 23 |
+
# Perform the NS iterations
|
| 24 |
+
for _ in range(steps):
|
| 25 |
+
A = X @ X.mT
|
| 26 |
+
B = b * A + c * A @ A # quintic computation strategy adapted from suggestion by @jxbz, @leloykun, and @YouJiacheng
|
| 27 |
+
X = a * X + B @ X
|
| 28 |
+
|
| 29 |
+
if G.size(-2) > G.size(-1):
|
| 30 |
+
X = X.mT
|
| 31 |
+
return X
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def muon_update(grad, momentum, beta=0.95, ns_steps=5, nesterov=True):
|
| 35 |
+
momentum.lerp_(grad, 1 - beta)
|
| 36 |
+
update = grad.lerp_(momentum, beta) if nesterov else momentum
|
| 37 |
+
if update.ndim == 4: # for the case of conv filters
|
| 38 |
+
update = update.view(len(update), -1)
|
| 39 |
+
update = zeropower_via_newtonschulz5(update, steps=ns_steps)
|
| 40 |
+
update *= max(1, grad.size(-2) / grad.size(-1))**0.5
|
| 41 |
+
return update
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Muon(torch.optim.Optimizer):
|
| 45 |
+
"""
|
| 46 |
+
Muon - MomentUm Orthogonalized by Newton-schulz
|
| 47 |
+
|
| 48 |
+
https://kellerjordan.github.io/posts/muon/
|
| 49 |
+
|
| 50 |
+
Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
|
| 51 |
+
processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
|
| 52 |
+
matrix. For efficient orthogonalization we use a Newton-Schulz iteration, which has the
|
| 53 |
+
advantage that it can be stably run in bfloat16 on the GPU.
|
| 54 |
+
|
| 55 |
+
Muon should only be used for hidden weight layers. The input embedding, final output layer,
|
| 56 |
+
and any internal gains or biases should be optimized using a standard method such as AdamW.
|
| 57 |
+
Hidden convolutional weights can be trained using Muon by viewing them as 2D and then
|
| 58 |
+
collapsing their last 3 dimensions.
|
| 59 |
+
|
| 60 |
+
Arguments:
|
| 61 |
+
lr: The learning rate, in units of spectral norm per update.
|
| 62 |
+
weight_decay: The AdamW-style weight decay.
|
| 63 |
+
momentum: The momentum. A value of 0.95 here is usually fine.
|
| 64 |
+
"""
|
| 65 |
+
def __init__(self, params, lr=0.02, weight_decay=0, momentum=0.95):
|
| 66 |
+
defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum)
|
| 67 |
+
assert isinstance(params, list) and len(params) >= 1 and isinstance(params[0], torch.nn.Parameter)
|
| 68 |
+
params = sorted(params, key=lambda x: x.size(), reverse=True)
|
| 69 |
+
super().__init__(params, defaults)
|
| 70 |
+
|
| 71 |
+
@torch.no_grad()
|
| 72 |
+
def step(self):
|
| 73 |
+
for group in self.param_groups:
|
| 74 |
+
params = group["params"]
|
| 75 |
+
params_pad = params + [torch.empty_like(params[-1])] * (len(params) % dist.get_world_size())
|
| 76 |
+
for base_i in range(len(params))[::dist.get_world_size()]:
|
| 77 |
+
if base_i + dist.get_rank() < len(params):
|
| 78 |
+
p = params[base_i + dist.get_rank()]
|
| 79 |
+
state = self.state[p]
|
| 80 |
+
if len(state) == 0:
|
| 81 |
+
state["momentum_buffer"] = torch.zeros_like(p)
|
| 82 |
+
update = muon_update(p.grad, state["momentum_buffer"], beta=group["momentum"])
|
| 83 |
+
p.mul_(1 - group["lr"] * group["weight_decay"])
|
| 84 |
+
p.add_(update, alpha=-group["lr"])
|
| 85 |
+
dist.all_gather(params_pad[base_i:base_i + dist.get_world_size()], params_pad[base_i + dist.get_rank()])
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SingleDeviceMuon(torch.optim.Optimizer):
|
| 89 |
+
"""
|
| 90 |
+
Muon variant for usage in non-distributed settings.
|
| 91 |
+
"""
|
| 92 |
+
def __init__(self, params, lr=0.02, weight_decay=0, momentum=0.95):
|
| 93 |
+
defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum)
|
| 94 |
+
super().__init__(params, defaults)
|
| 95 |
+
|
| 96 |
+
@torch.no_grad()
|
| 97 |
+
def step(self):
|
| 98 |
+
for group in self.param_groups:
|
| 99 |
+
for p in group["params"]:
|
| 100 |
+
state = self.state[p]
|
| 101 |
+
if len(state) == 0:
|
| 102 |
+
state["momentum_buffer"] = torch.zeros_like(p)
|
| 103 |
+
update = muon_update(p.grad, state["momentum_buffer"], beta=group["momentum"])
|
| 104 |
+
p.mul_(1 - group["lr"] * group["weight_decay"])
|
| 105 |
+
p.add_(update, alpha=-group["lr"])
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def adam_update(grad, buf1, buf2, step, betas, eps):
|
| 109 |
+
buf1.lerp_(grad, 1 - betas[0])
|
| 110 |
+
buf2.lerp_(grad.square(), 1 - betas[1])
|
| 111 |
+
buf1c = buf1 / (1 - betas[0]**step)
|
| 112 |
+
buf2c = buf2 / (1 - betas[1]**step)
|
| 113 |
+
return buf1c / (buf2c.sqrt() + eps)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class MuonWithAuxAdam(torch.optim.Optimizer):
|
| 117 |
+
"""
|
| 118 |
+
Distributed Muon variant that can be used for all parameters in the network, since it runs an
|
| 119 |
+
internal AdamW for the parameters that are not compatible with Muon. The user must manually
|
| 120 |
+
specify which parameters shall be optimized with Muon and which with Adam by passing in a
|
| 121 |
+
list of param_groups with the `use_muon` flag set.
|
| 122 |
+
|
| 123 |
+
The point of this class is to allow the user to have a single Opimizer in their code, rather
|
| 124 |
+
than having both a Muon and an Adam which each need to be stepped.
|
| 125 |
+
|
| 126 |
+
You can see an example usage below:
|
| 127 |
+
|
| 128 |
+
https://github.com/KellerJordan/modded-nanogpt/blob/master/records/052525_MuonWithAuxAdamExample/b01550f9-03d8-4a9c-86fe-4ab434f1c5e0.txt#L470
|
| 129 |
+
```
|
| 130 |
+
hidden_matrix_params = [p for n, p in model.blocks.named_parameters() if p.ndim >= 2 and "embed" not in n]
|
| 131 |
+
embed_params = [p for n, p in model.named_parameters() if "embed" in n]
|
| 132 |
+
scalar_params = [p for p in model.parameters() if p.ndim < 2]
|
| 133 |
+
head_params = [model.lm_head.weight]
|
| 134 |
+
|
| 135 |
+
from muon import MuonWithAuxAdam
|
| 136 |
+
adam_groups = [dict(params=head_params, lr=0.22), dict(params=embed_params, lr=0.6), dict(params=scalar_params, lr=0.04)]
|
| 137 |
+
adam_groups = [dict(**g, betas=(0.8, 0.95), eps=1e-10, use_muon=False) for g in adam_groups]
|
| 138 |
+
muon_group = dict(params=hidden_matrix_params, lr=0.05, momentum=0.95, use_muon=True)
|
| 139 |
+
param_groups = [*adam_groups, muon_group]
|
| 140 |
+
optimizer = MuonWithAuxAdam(param_groups)
|
| 141 |
+
```
|
| 142 |
+
"""
|
| 143 |
+
def __init__(self, param_groups):
|
| 144 |
+
for group in param_groups:
|
| 145 |
+
assert "use_muon" in group
|
| 146 |
+
if group["use_muon"]:
|
| 147 |
+
group["params"] = sorted(group["params"], key=lambda x: x.size(), reverse=True)
|
| 148 |
+
# defaults
|
| 149 |
+
group["lr"] = group.get("lr", 0.02)
|
| 150 |
+
group["momentum"] = group.get("momentum", 0.95)
|
| 151 |
+
group["weight_decay"] = group.get("weight_decay", 0)
|
| 152 |
+
assert set(group.keys()) == set(["params", "lr", "momentum", "weight_decay", "use_muon"])
|
| 153 |
+
else:
|
| 154 |
+
# defaults
|
| 155 |
+
group["lr"] = group.get("lr", 3e-4)
|
| 156 |
+
group["betas"] = group.get("betas", (0.9, 0.95))
|
| 157 |
+
group["eps"] = group.get("eps", 1e-10)
|
| 158 |
+
group["weight_decay"] = group.get("weight_decay", 0)
|
| 159 |
+
assert set(group.keys()) == set(["params", "lr", "betas", "eps", "weight_decay", "use_muon"])
|
| 160 |
+
super().__init__(param_groups, dict())
|
| 161 |
+
|
| 162 |
+
@torch.no_grad()
|
| 163 |
+
def step(self):
|
| 164 |
+
for group in self.param_groups:
|
| 165 |
+
if group["use_muon"]:
|
| 166 |
+
params = group["params"]
|
| 167 |
+
params_pad = params + [torch.empty_like(params[-1])] * (len(params) % dist.get_world_size())
|
| 168 |
+
for base_i in range(len(params))[::dist.get_world_size()]:
|
| 169 |
+
if base_i + dist.get_rank() < len(params):
|
| 170 |
+
p = params[base_i + dist.get_rank()]
|
| 171 |
+
state = self.state[p]
|
| 172 |
+
if len(state) == 0:
|
| 173 |
+
state["momentum_buffer"] = torch.zeros_like(p)
|
| 174 |
+
update = muon_update(p.grad, state["momentum_buffer"], beta=group["momentum"])
|
| 175 |
+
p.mul_(1 - group["lr"] * group["weight_decay"])
|
| 176 |
+
p.add_(update, alpha=-group["lr"])
|
| 177 |
+
dist.all_gather(params_pad[base_i:base_i + dist.get_world_size()], params_pad[base_i + dist.get_rank()])
|
| 178 |
+
else:
|
| 179 |
+
beta1, beta2 = group["betas"]
|
| 180 |
+
for p in group["params"]:
|
| 181 |
+
state = self.state[p]
|
| 182 |
+
if len(state) == 0:
|
| 183 |
+
state["exp_avg"] = torch.zeros_like(p)
|
| 184 |
+
state["exp_avg_sq"] = torch.zeros_like(p)
|
| 185 |
+
state["step"] = 0
|
| 186 |
+
state["step"] += 1
|
| 187 |
+
update = adam_update(p.grad, state["exp_avg"], state["exp_avg_sq"],
|
| 188 |
+
state["step"], group["betas"], group["eps"])
|
| 189 |
+
p.mul_(1 - group["lr"] * group["weight_decay"])
|
| 190 |
+
p.add_(update, alpha=-group["lr"])
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SingleDeviceMuonWithAuxAdam(torch.optim.Optimizer):
|
| 194 |
+
"""
|
| 195 |
+
Non-distributed variant of MuonWithAuxAdam.
|
| 196 |
+
"""
|
| 197 |
+
def __init__(self, param_groups):
|
| 198 |
+
for group in param_groups:
|
| 199 |
+
assert "use_muon" in group
|
| 200 |
+
if group["use_muon"]:
|
| 201 |
+
# defaults
|
| 202 |
+
group["lr"] = group.get("lr", 0.02)
|
| 203 |
+
group["momentum"] = group.get("momentum", 0.95)
|
| 204 |
+
group["weight_decay"] = group.get("weight_decay", 0)
|
| 205 |
+
assert set(group.keys()) == set(["params", "lr", "momentum", "weight_decay", "use_muon"])
|
| 206 |
+
else:
|
| 207 |
+
# defaults
|
| 208 |
+
group["lr"] = group.get("lr", 3e-4)
|
| 209 |
+
group["betas"] = group.get("betas", (0.9, 0.95))
|
| 210 |
+
group["eps"] = group.get("eps", 1e-10)
|
| 211 |
+
group["weight_decay"] = group.get("weight_decay", 0)
|
| 212 |
+
assert set(group.keys()) == set(["params", "lr", "betas", "eps", "weight_decay", "use_muon"])
|
| 213 |
+
super().__init__(param_groups, dict())
|
| 214 |
+
|
| 215 |
+
@torch.no_grad()
|
| 216 |
+
def step(self):
|
| 217 |
+
for group in self.param_groups:
|
| 218 |
+
if group["use_muon"]:
|
| 219 |
+
for p in group["params"]:
|
| 220 |
+
state = self.state[p]
|
| 221 |
+
if len(state) == 0:
|
| 222 |
+
state["momentum_buffer"] = torch.zeros_like(p)
|
| 223 |
+
update = muon_update(p.grad, state["momentum_buffer"], beta=group["momentum"])
|
| 224 |
+
p.mul_(1 - group["lr"] * group["weight_decay"])
|
| 225 |
+
p.add_(update, alpha=-group["lr"])
|
| 226 |
+
else:
|
| 227 |
+
beta1, beta2 = group["betas"]
|
| 228 |
+
for p in group["params"]:
|
| 229 |
+
state = self.state[p]
|
| 230 |
+
if len(state) == 0:
|
| 231 |
+
state["exp_avg"] = torch.zeros_like(p)
|
| 232 |
+
state["exp_avg_sq"] = torch.zeros_like(p)
|
| 233 |
+
state["step"] = 0
|
| 234 |
+
state["step"] += 1
|
| 235 |
+
update = adam_update(p.grad, state["exp_avg"], state["exp_avg_sq"],
|
| 236 |
+
state["step"], group["betas"], group["eps"])
|
| 237 |
+
p.mul_(1 - group["lr"] * group["weight_decay"])
|
| 238 |
+
p.add_(update, alpha=-group["lr"])
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_vl/configuration_deepseek_vl.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/deepseek_vl/modular_deepseek_vl.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_deepseek_vl.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 Deepseek AI 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 |
+
|
| 22 |
+
from huggingface_hub.dataclasses import strict
|
| 23 |
+
|
| 24 |
+
from ...configuration_utils import PreTrainedConfig
|
| 25 |
+
from ...utils import auto_docstring, logging
|
| 26 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@auto_docstring(checkpoint="deepseek-community/deepseek-vl-1.3b-chat")
|
| 33 |
+
@strict
|
| 34 |
+
class DeepseekVLConfig(PreTrainedConfig):
|
| 35 |
+
r"""
|
| 36 |
+
Example:
|
| 37 |
+
|
| 38 |
+
```python
|
| 39 |
+
>>> from transformers import DeepseekVLConfig, DeepseekVLModel
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a DeepseekVL deepseek-community/deepseek-vl-1.3b-chat style configuration
|
| 42 |
+
>>> configuration = DeepseekVLConfig()
|
| 43 |
+
|
| 44 |
+
>>> # Initializing a model (with random weights) from the deepseek-community/deepseek-vl-1.3b-chat style configuration
|
| 45 |
+
>>> model = DeepseekVLModel(configuration)
|
| 46 |
+
|
| 47 |
+
>>> # Accessing the model configuration
|
| 48 |
+
>>> configuration = model.config
|
| 49 |
+
```"""
|
| 50 |
+
|
| 51 |
+
model_type = "deepseek_vl"
|
| 52 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
|
| 53 |
+
|
| 54 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 55 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 56 |
+
image_token_id: int = 100015
|
| 57 |
+
tie_word_embeddings: bool = True
|
| 58 |
+
|
| 59 |
+
def __post_init__(self, **kwargs):
|
| 60 |
+
if self.text_config is None:
|
| 61 |
+
self.text_config = {}
|
| 62 |
+
logger.info("`text_config` is `None`. Initializing the `LlamaConfig` with default values.")
|
| 63 |
+
if isinstance(self.text_config, dict):
|
| 64 |
+
self.text_config["model_type"] = self.text_config.get("model_type", "llama")
|
| 65 |
+
self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
|
| 66 |
+
|
| 67 |
+
if self.vision_config is None:
|
| 68 |
+
self.vision_config = {}
|
| 69 |
+
logger.info("`vision_config` is `None`. Initializing the `SiglipVisionConfig` with default values.")
|
| 70 |
+
if isinstance(self.vision_config, dict):
|
| 71 |
+
self.vision_config["model_type"] = self.vision_config.get("model_type", "siglip_vision_model")
|
| 72 |
+
self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
|
| 73 |
+
|
| 74 |
+
super().__post_init__(**kwargs)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
__all__ = ["DeepseekVLConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mt5/__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_mt5 import *
|
| 22 |
+
from .modeling_mt5 import *
|
| 23 |
+
from .tokenization_mt5 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/mt5/modeling_mt5.py
ADDED
|
@@ -0,0 +1,1682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch mT5 model."""
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import math
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 26 |
+
from ...generation import GenerationMixin
|
| 27 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 28 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
from ...modeling_outputs import (
|
| 30 |
+
BaseModelOutput,
|
| 31 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 32 |
+
Seq2SeqLMOutput,
|
| 33 |
+
Seq2SeqModelOutput,
|
| 34 |
+
Seq2SeqQuestionAnsweringModelOutput,
|
| 35 |
+
Seq2SeqSequenceClassifierOutput,
|
| 36 |
+
TokenClassifierOutput,
|
| 37 |
+
)
|
| 38 |
+
from ...modeling_utils import PreTrainedModel
|
| 39 |
+
from ...utils import DUMMY_INPUTS, DUMMY_MASK, auto_docstring, logging, torch_compilable_check
|
| 40 |
+
from .configuration_mt5 import MT5Config
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Copied from transformers.models.t5.modeling_t5.T5LayerNorm with T5->MT5
|
| 47 |
+
class MT5LayerNorm(nn.Module):
|
| 48 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 49 |
+
"""
|
| 50 |
+
Construct a layernorm module in the MT5 style. No bias and no subtraction of mean.
|
| 51 |
+
"""
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 54 |
+
self.variance_epsilon = eps
|
| 55 |
+
|
| 56 |
+
def forward(self, hidden_states):
|
| 57 |
+
# MT5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
|
| 58 |
+
# Square Layer Normalization https://huggingface.co/papers/1910.07467 thus variance is calculated
|
| 59 |
+
# w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
|
| 60 |
+
# half-precision inputs is done in fp32
|
| 61 |
+
|
| 62 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 63 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 64 |
+
|
| 65 |
+
# convert into half-precision if necessary
|
| 66 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
| 67 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
| 68 |
+
|
| 69 |
+
return self.weight * hidden_states
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Copied from transformers.models.t5.modeling_t5.T5DenseActDense with T5->MT5
|
| 73 |
+
class MT5DenseActDense(nn.Module):
|
| 74 |
+
def __init__(self, config: MT5Config):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 77 |
+
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
|
| 78 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 79 |
+
self.act = ACT2FN[config.dense_act_fn]
|
| 80 |
+
|
| 81 |
+
def forward(self, hidden_states):
|
| 82 |
+
hidden_states = self.wi(hidden_states)
|
| 83 |
+
hidden_states = self.act(hidden_states)
|
| 84 |
+
hidden_states = self.dropout(hidden_states)
|
| 85 |
+
if (
|
| 86 |
+
isinstance(self.wo.weight, torch.Tensor)
|
| 87 |
+
and hidden_states.dtype != self.wo.weight.dtype
|
| 88 |
+
and self.wo.weight.dtype != torch.int8
|
| 89 |
+
):
|
| 90 |
+
hidden_states = hidden_states.to(self.wo.weight.dtype)
|
| 91 |
+
hidden_states = self.wo(hidden_states)
|
| 92 |
+
return hidden_states
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Copied from transformers.models.t5.modeling_t5.T5DenseGatedActDense with T5->MT5
|
| 96 |
+
class MT5DenseGatedActDense(nn.Module):
|
| 97 |
+
def __init__(self, config: MT5Config):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 100 |
+
self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 101 |
+
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
|
| 102 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 103 |
+
self.act = ACT2FN[config.dense_act_fn]
|
| 104 |
+
|
| 105 |
+
def forward(self, hidden_states):
|
| 106 |
+
hidden_gelu = self.act(self.wi_0(hidden_states))
|
| 107 |
+
hidden_linear = self.wi_1(hidden_states)
|
| 108 |
+
hidden_states = hidden_gelu * hidden_linear
|
| 109 |
+
hidden_states = self.dropout(hidden_states)
|
| 110 |
+
|
| 111 |
+
# To make 8bit quantization work for google/flan-t5-xxl, self.wo is kept in float32.
|
| 112 |
+
# See https://github.com/huggingface/transformers/issues/20287
|
| 113 |
+
# we also make sure the weights are not in `int8` in case users will force `_keep_in_fp32_modules` to be `None``
|
| 114 |
+
if (
|
| 115 |
+
isinstance(self.wo.weight, torch.Tensor)
|
| 116 |
+
and hidden_states.dtype != self.wo.weight.dtype
|
| 117 |
+
and self.wo.weight.dtype != torch.int8
|
| 118 |
+
):
|
| 119 |
+
hidden_states = hidden_states.to(self.wo.weight.dtype)
|
| 120 |
+
|
| 121 |
+
hidden_states = self.wo(hidden_states)
|
| 122 |
+
return hidden_states
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Copied from transformers.models.t5.modeling_t5.T5LayerFF with T5->MT5
|
| 126 |
+
class MT5LayerFF(nn.Module):
|
| 127 |
+
def __init__(self, config: MT5Config):
|
| 128 |
+
super().__init__()
|
| 129 |
+
if config.is_gated_act:
|
| 130 |
+
self.DenseReluDense = MT5DenseGatedActDense(config)
|
| 131 |
+
else:
|
| 132 |
+
self.DenseReluDense = MT5DenseActDense(config)
|
| 133 |
+
|
| 134 |
+
self.layer_norm = MT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 135 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 136 |
+
|
| 137 |
+
def forward(self, hidden_states):
|
| 138 |
+
forwarded_states = self.layer_norm(hidden_states)
|
| 139 |
+
forwarded_states = self.DenseReluDense(forwarded_states)
|
| 140 |
+
hidden_states = hidden_states + self.dropout(forwarded_states)
|
| 141 |
+
return hidden_states
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# Copied from transformers.models.t5.modeling_t5.T5Attention with T5->MT5
|
| 145 |
+
class MT5Attention(nn.Module):
|
| 146 |
+
def __init__(
|
| 147 |
+
self,
|
| 148 |
+
config: MT5Config,
|
| 149 |
+
has_relative_attention_bias=False,
|
| 150 |
+
layer_idx: int | None = None,
|
| 151 |
+
):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.is_decoder = config.is_decoder
|
| 154 |
+
self.has_relative_attention_bias = has_relative_attention_bias
|
| 155 |
+
self.relative_attention_num_buckets = config.relative_attention_num_buckets
|
| 156 |
+
self.relative_attention_max_distance = config.relative_attention_max_distance
|
| 157 |
+
self.d_model = config.d_model
|
| 158 |
+
self.key_value_proj_dim = config.d_kv
|
| 159 |
+
self.n_heads = config.num_heads
|
| 160 |
+
self.dropout = config.dropout_rate
|
| 161 |
+
self.inner_dim = self.n_heads * self.key_value_proj_dim
|
| 162 |
+
self.layer_idx = layer_idx
|
| 163 |
+
if layer_idx is None and self.is_decoder:
|
| 164 |
+
logger.warning_once(
|
| 165 |
+
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
|
| 166 |
+
"will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 167 |
+
"when creating this class."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
|
| 171 |
+
self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
|
| 172 |
+
self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
|
| 173 |
+
self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
|
| 174 |
+
|
| 175 |
+
if self.has_relative_attention_bias:
|
| 176 |
+
self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
|
| 177 |
+
|
| 178 |
+
self.gradient_checkpointing = False
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
|
| 182 |
+
"""
|
| 183 |
+
Adapted from Mesh Tensorflow:
|
| 184 |
+
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
|
| 185 |
+
|
| 186 |
+
Translate relative position to a bucket number for relative attention. The relative position is defined as
|
| 187 |
+
memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
|
| 188 |
+
position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
|
| 189 |
+
small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
|
| 190 |
+
positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
|
| 191 |
+
This should allow for more graceful generalization to longer sequences than the model has been trained on
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
relative_position: an int32 Tensor
|
| 195 |
+
bidirectional: a boolean - whether the attention is bidirectional
|
| 196 |
+
num_buckets: an integer
|
| 197 |
+
max_distance: an integer
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
|
| 201 |
+
"""
|
| 202 |
+
relative_buckets = 0
|
| 203 |
+
if bidirectional:
|
| 204 |
+
num_buckets //= 2
|
| 205 |
+
relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
|
| 206 |
+
relative_position = torch.abs(relative_position)
|
| 207 |
+
else:
|
| 208 |
+
relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
|
| 209 |
+
# now relative_position is in the range [0, inf)
|
| 210 |
+
|
| 211 |
+
# half of the buckets are for exact increments in positions
|
| 212 |
+
max_exact = num_buckets // 2
|
| 213 |
+
is_small = relative_position < max_exact
|
| 214 |
+
|
| 215 |
+
# The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
|
| 216 |
+
relative_position_if_large = max_exact + (
|
| 217 |
+
torch.log(relative_position.float() / max_exact)
|
| 218 |
+
/ math.log(max_distance / max_exact)
|
| 219 |
+
* (num_buckets - max_exact)
|
| 220 |
+
).to(torch.long)
|
| 221 |
+
relative_position_if_large = torch.min(
|
| 222 |
+
relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
|
| 226 |
+
return relative_buckets
|
| 227 |
+
|
| 228 |
+
def compute_bias(self, query_length, key_length, device=None, past_seen_tokens=0):
|
| 229 |
+
"""Compute binned relative position bias"""
|
| 230 |
+
if device is None:
|
| 231 |
+
device = self.relative_attention_bias.weight.device
|
| 232 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None] + past_seen_tokens
|
| 233 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
| 234 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
| 235 |
+
relative_position_bucket = self._relative_position_bucket(
|
| 236 |
+
relative_position, # shape (query_length, key_length)
|
| 237 |
+
bidirectional=(not self.is_decoder),
|
| 238 |
+
num_buckets=self.relative_attention_num_buckets,
|
| 239 |
+
max_distance=self.relative_attention_max_distance,
|
| 240 |
+
)
|
| 241 |
+
values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
|
| 242 |
+
values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
|
| 243 |
+
return values
|
| 244 |
+
|
| 245 |
+
def forward(
|
| 246 |
+
self,
|
| 247 |
+
hidden_states,
|
| 248 |
+
mask=None,
|
| 249 |
+
key_value_states=None,
|
| 250 |
+
position_bias=None,
|
| 251 |
+
past_key_values=None,
|
| 252 |
+
output_attentions=False,
|
| 253 |
+
**kwargs,
|
| 254 |
+
):
|
| 255 |
+
"""
|
| 256 |
+
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
|
| 257 |
+
"""
|
| 258 |
+
# Input is (batch_size, seq_length, dim)
|
| 259 |
+
# Mask is (batch_size, 1, 1, key_length) (non-causal encoder) or (batch_size, 1, seq_length, key_length) (causal decoder)
|
| 260 |
+
input_shape = hidden_states.shape[:-1]
|
| 261 |
+
hidden_shape = (*input_shape, -1, self.key_value_proj_dim)
|
| 262 |
+
past_seen_tokens = past_key_values.get_seq_length(self.layer_idx) if past_key_values is not None else 0
|
| 263 |
+
# We clone here for StaticCache, as we get the value before updating it, but use it after and it's the same ref
|
| 264 |
+
past_seen_tokens = past_seen_tokens.clone() if isinstance(past_seen_tokens, torch.Tensor) else past_seen_tokens
|
| 265 |
+
|
| 266 |
+
# if key_value_states are provided this layer is used as a cross-attention layer for the decoder
|
| 267 |
+
is_cross_attention = key_value_states is not None
|
| 268 |
+
|
| 269 |
+
query_states = self.q(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 270 |
+
|
| 271 |
+
# Check is encoder-decoder model is being used. Otherwise we'll get `DynamicCache`
|
| 272 |
+
is_updated = False
|
| 273 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 274 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 275 |
+
if is_cross_attention:
|
| 276 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 277 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 278 |
+
else:
|
| 279 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 280 |
+
else:
|
| 281 |
+
curr_past_key_values = past_key_values
|
| 282 |
+
|
| 283 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 284 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 285 |
+
# reuse k,v, cross_attentions
|
| 286 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 287 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 288 |
+
else:
|
| 289 |
+
kv_shape = (*current_states.shape[:-1], -1, self.key_value_proj_dim)
|
| 290 |
+
key_states = self.k(current_states).view(kv_shape).transpose(1, 2)
|
| 291 |
+
value_states = self.v(current_states).view(kv_shape).transpose(1, 2)
|
| 292 |
+
|
| 293 |
+
if past_key_values is not None:
|
| 294 |
+
key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
|
| 295 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 296 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 297 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 298 |
+
|
| 299 |
+
# compute scores, equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
|
| 300 |
+
scores = torch.matmul(query_states, key_states.transpose(3, 2))
|
| 301 |
+
|
| 302 |
+
if position_bias is None:
|
| 303 |
+
key_length = key_states.shape[-2]
|
| 304 |
+
if not self.has_relative_attention_bias:
|
| 305 |
+
position_bias = torch.zeros(
|
| 306 |
+
(1, query_states.shape[1], input_shape[1], key_length), device=scores.device, dtype=scores.dtype
|
| 307 |
+
)
|
| 308 |
+
if self.gradient_checkpointing and self.training:
|
| 309 |
+
position_bias.requires_grad = True
|
| 310 |
+
else:
|
| 311 |
+
position_bias = self.compute_bias(
|
| 312 |
+
input_shape[1], key_length, device=scores.device, past_seen_tokens=past_seen_tokens
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
if mask is not None:
|
| 316 |
+
causal_mask = mask[:, :, :, : key_states.shape[-2]]
|
| 317 |
+
position_bias = position_bias + causal_mask
|
| 318 |
+
|
| 319 |
+
position_bias_masked = position_bias
|
| 320 |
+
scores += position_bias_masked
|
| 321 |
+
|
| 322 |
+
# (batch_size, n_heads, seq_length, key_length)
|
| 323 |
+
attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores)
|
| 324 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 325 |
+
|
| 326 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 327 |
+
|
| 328 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 329 |
+
attn_output = attn_output.reshape(*input_shape, -1)
|
| 330 |
+
attn_output = self.o(attn_output)
|
| 331 |
+
|
| 332 |
+
outputs = (attn_output, position_bias)
|
| 333 |
+
|
| 334 |
+
if output_attentions:
|
| 335 |
+
outputs = outputs + (attn_weights,)
|
| 336 |
+
return outputs
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# Copied from transformers.models.t5.modeling_t5.T5LayerSelfAttention with T5->MT5
|
| 340 |
+
class MT5LayerSelfAttention(nn.Module):
|
| 341 |
+
def __init__(self, config, has_relative_attention_bias=False, layer_idx: int | None = None):
|
| 342 |
+
super().__init__()
|
| 343 |
+
self.SelfAttention = MT5Attention(
|
| 344 |
+
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
|
| 345 |
+
)
|
| 346 |
+
self.layer_norm = MT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 347 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 348 |
+
|
| 349 |
+
def forward(
|
| 350 |
+
self,
|
| 351 |
+
hidden_states,
|
| 352 |
+
attention_mask=None,
|
| 353 |
+
position_bias=None,
|
| 354 |
+
past_key_values=None,
|
| 355 |
+
use_cache=False,
|
| 356 |
+
output_attentions=False,
|
| 357 |
+
**kwargs,
|
| 358 |
+
):
|
| 359 |
+
normed_hidden_states = self.layer_norm(hidden_states)
|
| 360 |
+
attention_output = self.SelfAttention(
|
| 361 |
+
normed_hidden_states,
|
| 362 |
+
mask=attention_mask,
|
| 363 |
+
position_bias=position_bias,
|
| 364 |
+
past_key_values=past_key_values,
|
| 365 |
+
use_cache=use_cache,
|
| 366 |
+
output_attentions=output_attentions,
|
| 367 |
+
)
|
| 368 |
+
hidden_states = hidden_states + self.dropout(attention_output[0])
|
| 369 |
+
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
|
| 370 |
+
return outputs
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# Copied from transformers.models.t5.modeling_t5.T5LayerCrossAttention with T5->MT5
|
| 374 |
+
class MT5LayerCrossAttention(nn.Module):
|
| 375 |
+
def __init__(self, config, layer_idx: int | None = None):
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.EncDecAttention = MT5Attention(config, has_relative_attention_bias=False, layer_idx=layer_idx)
|
| 378 |
+
self.layer_norm = MT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 379 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 380 |
+
|
| 381 |
+
def forward(
|
| 382 |
+
self,
|
| 383 |
+
hidden_states,
|
| 384 |
+
key_value_states,
|
| 385 |
+
attention_mask=None,
|
| 386 |
+
position_bias=None,
|
| 387 |
+
past_key_values=None,
|
| 388 |
+
output_attentions=False,
|
| 389 |
+
**kwargs,
|
| 390 |
+
):
|
| 391 |
+
normed_hidden_states = self.layer_norm(hidden_states)
|
| 392 |
+
attention_output = self.EncDecAttention(
|
| 393 |
+
normed_hidden_states,
|
| 394 |
+
mask=attention_mask,
|
| 395 |
+
key_value_states=key_value_states,
|
| 396 |
+
position_bias=position_bias,
|
| 397 |
+
past_key_values=past_key_values,
|
| 398 |
+
output_attentions=output_attentions,
|
| 399 |
+
)
|
| 400 |
+
layer_output = hidden_states + self.dropout(attention_output[0])
|
| 401 |
+
outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
|
| 402 |
+
return outputs
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
# Copied from transformers.models.t5.modeling_t5.T5Block with T5->MT5
|
| 406 |
+
class MT5Block(GradientCheckpointingLayer):
|
| 407 |
+
def __init__(self, config, has_relative_attention_bias=False, layer_idx: int | None = None):
|
| 408 |
+
super().__init__()
|
| 409 |
+
self.is_decoder = config.is_decoder
|
| 410 |
+
self.layer = nn.ModuleList()
|
| 411 |
+
self.layer.append(
|
| 412 |
+
MT5LayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx)
|
| 413 |
+
)
|
| 414 |
+
if self.is_decoder:
|
| 415 |
+
self.layer.append(MT5LayerCrossAttention(config, layer_idx=layer_idx))
|
| 416 |
+
|
| 417 |
+
self.layer.append(MT5LayerFF(config))
|
| 418 |
+
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
hidden_states,
|
| 422 |
+
attention_mask=None,
|
| 423 |
+
position_bias=None,
|
| 424 |
+
encoder_hidden_states=None,
|
| 425 |
+
encoder_attention_mask=None,
|
| 426 |
+
encoder_decoder_position_bias=None,
|
| 427 |
+
past_key_values=None,
|
| 428 |
+
use_cache=False,
|
| 429 |
+
output_attentions=False,
|
| 430 |
+
return_dict=True,
|
| 431 |
+
**kwargs,
|
| 432 |
+
):
|
| 433 |
+
self_attention_outputs = self.layer[0](
|
| 434 |
+
hidden_states,
|
| 435 |
+
attention_mask=attention_mask,
|
| 436 |
+
position_bias=position_bias,
|
| 437 |
+
past_key_values=past_key_values,
|
| 438 |
+
use_cache=use_cache,
|
| 439 |
+
output_attentions=output_attentions,
|
| 440 |
+
)
|
| 441 |
+
hidden_states = self_attention_outputs[0]
|
| 442 |
+
attention_outputs = self_attention_outputs[1:] # Keep self-attention outputs and relative position weights
|
| 443 |
+
|
| 444 |
+
# clamp inf values to enable fp16 training
|
| 445 |
+
if hidden_states.dtype == torch.float16:
|
| 446 |
+
clamp_value = torch.where(
|
| 447 |
+
torch.isinf(hidden_states).any(),
|
| 448 |
+
torch.finfo(hidden_states.dtype).max - 1000,
|
| 449 |
+
torch.finfo(hidden_states.dtype).max,
|
| 450 |
+
)
|
| 451 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 452 |
+
|
| 453 |
+
do_cross_attention = self.is_decoder and encoder_hidden_states is not None
|
| 454 |
+
if do_cross_attention:
|
| 455 |
+
cross_attention_outputs = self.layer[1](
|
| 456 |
+
hidden_states,
|
| 457 |
+
key_value_states=encoder_hidden_states,
|
| 458 |
+
attention_mask=encoder_attention_mask,
|
| 459 |
+
position_bias=encoder_decoder_position_bias,
|
| 460 |
+
past_key_values=past_key_values,
|
| 461 |
+
output_attentions=output_attentions,
|
| 462 |
+
)
|
| 463 |
+
hidden_states = cross_attention_outputs[0]
|
| 464 |
+
|
| 465 |
+
# clamp inf values to enable fp16 training
|
| 466 |
+
if hidden_states.dtype == torch.float16:
|
| 467 |
+
clamp_value = torch.where(
|
| 468 |
+
torch.isinf(hidden_states).any(),
|
| 469 |
+
torch.finfo(hidden_states.dtype).max - 1000,
|
| 470 |
+
torch.finfo(hidden_states.dtype).max,
|
| 471 |
+
)
|
| 472 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 473 |
+
|
| 474 |
+
# Keep cross-attention outputs and relative position weights
|
| 475 |
+
attention_outputs = attention_outputs + cross_attention_outputs[1:]
|
| 476 |
+
|
| 477 |
+
# Apply Feed Forward layer
|
| 478 |
+
hidden_states = self.layer[-1](hidden_states)
|
| 479 |
+
|
| 480 |
+
# clamp inf values to enable fp16 training
|
| 481 |
+
if hidden_states.dtype == torch.float16:
|
| 482 |
+
clamp_value = torch.where(
|
| 483 |
+
torch.isinf(hidden_states).any(),
|
| 484 |
+
torch.finfo(hidden_states.dtype).max - 1000,
|
| 485 |
+
torch.finfo(hidden_states.dtype).max,
|
| 486 |
+
)
|
| 487 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 488 |
+
|
| 489 |
+
outputs = (hidden_states,)
|
| 490 |
+
|
| 491 |
+
return (
|
| 492 |
+
outputs + attention_outputs
|
| 493 |
+
) # hidden-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
# Copied from transformers.models.t5.modeling_t5.T5ClassificationHead with T5->MT5
|
| 497 |
+
class MT5ClassificationHead(nn.Module):
|
| 498 |
+
"""Head for sentence-level classification tasks."""
|
| 499 |
+
|
| 500 |
+
def __init__(self, config: MT5Config):
|
| 501 |
+
super().__init__()
|
| 502 |
+
self.dense = nn.Linear(config.d_model, config.d_model)
|
| 503 |
+
self.dropout = nn.Dropout(p=config.classifier_dropout)
|
| 504 |
+
self.out_proj = nn.Linear(config.d_model, config.num_labels)
|
| 505 |
+
|
| 506 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 507 |
+
hidden_states = self.dropout(hidden_states)
|
| 508 |
+
hidden_states = self.dense(hidden_states)
|
| 509 |
+
hidden_states = torch.tanh(hidden_states)
|
| 510 |
+
hidden_states = self.dropout(hidden_states)
|
| 511 |
+
hidden_states = self.out_proj(hidden_states)
|
| 512 |
+
return hidden_states
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
@auto_docstring
|
| 516 |
+
# Copied from transformers.models.t5.modeling_t5.T5PreTrainedModel with T5->MT5, t5->mt5
|
| 517 |
+
class MT5PreTrainedModel(PreTrainedModel):
|
| 518 |
+
config: MT5Config
|
| 519 |
+
base_model_prefix = "transformer"
|
| 520 |
+
supports_gradient_checkpointing = True
|
| 521 |
+
_can_compile_fullgraph = True
|
| 522 |
+
|
| 523 |
+
_no_split_modules = ["MT5Block"]
|
| 524 |
+
_keep_in_fp32_modules = ["wo"]
|
| 525 |
+
|
| 526 |
+
@property
|
| 527 |
+
def dummy_inputs(self):
|
| 528 |
+
input_ids = torch.tensor(DUMMY_INPUTS)
|
| 529 |
+
input_mask = torch.tensor(DUMMY_MASK)
|
| 530 |
+
dummy_inputs = {
|
| 531 |
+
"decoder_input_ids": input_ids,
|
| 532 |
+
"input_ids": input_ids,
|
| 533 |
+
"decoder_attention_mask": input_mask,
|
| 534 |
+
}
|
| 535 |
+
return dummy_inputs
|
| 536 |
+
|
| 537 |
+
@torch.no_grad()
|
| 538 |
+
def _init_weights(self, module):
|
| 539 |
+
"""Initialize the weights"""
|
| 540 |
+
factor = self.config.initializer_factor # Used for testing weights initialization
|
| 541 |
+
if isinstance(module, MT5LayerNorm):
|
| 542 |
+
init.constant_(module.weight, factor * 1.0)
|
| 543 |
+
elif isinstance(
|
| 544 |
+
module,
|
| 545 |
+
(MT5Model, MT5ForConditionalGeneration, MT5EncoderModel, MT5ForQuestionAnswering),
|
| 546 |
+
):
|
| 547 |
+
init.normal_(module.shared.weight, mean=0.0, std=factor * 1.0)
|
| 548 |
+
if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
|
| 549 |
+
init.normal_(module.lm_head.weight, mean=0.0, std=factor * 1.0)
|
| 550 |
+
if hasattr(module, "qa_outputs"):
|
| 551 |
+
init.normal_(module.qa_outputs.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 552 |
+
init.zeros_(module.qa_outputs.bias)
|
| 553 |
+
elif isinstance(module, MT5ForTokenClassification):
|
| 554 |
+
if hasattr(module, "classifier"):
|
| 555 |
+
init.normal_(module.classifier.weight, mean=0.0, std=factor * 1.0)
|
| 556 |
+
init.zeros_(module.classifier.bias)
|
| 557 |
+
elif isinstance(module, MT5ClassificationHead):
|
| 558 |
+
init.normal_(module.dense.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 559 |
+
if hasattr(module.dense, "bias") and module.dense.bias is not None:
|
| 560 |
+
init.zeros_(module.dense.bias)
|
| 561 |
+
init.normal_(module.out_proj.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 562 |
+
if hasattr(module.out_proj, "bias") and module.out_proj.bias is not None:
|
| 563 |
+
init.zeros_(module.out_proj.bias)
|
| 564 |
+
elif isinstance(module, MT5DenseActDense):
|
| 565 |
+
init.normal_(module.wi.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 566 |
+
if hasattr(module.wi, "bias") and module.wi.bias is not None:
|
| 567 |
+
init.zeros_(module.wi.bias)
|
| 568 |
+
init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
|
| 569 |
+
if hasattr(module.wo, "bias") and module.wo.bias is not None:
|
| 570 |
+
init.zeros_(module.wo.bias)
|
| 571 |
+
elif isinstance(module, MT5DenseGatedActDense):
|
| 572 |
+
init.normal_(module.wi_0.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 573 |
+
if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
|
| 574 |
+
init.zeros_(module.wi_0.bias)
|
| 575 |
+
init.normal_(module.wi_1.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
|
| 576 |
+
if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
|
| 577 |
+
init.zeros_(module.wi_1.bias)
|
| 578 |
+
init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
|
| 579 |
+
if hasattr(module.wo, "bias") and module.wo.bias is not None:
|
| 580 |
+
init.zeros_(module.wo.bias)
|
| 581 |
+
elif isinstance(module, MT5Attention):
|
| 582 |
+
d_model = self.config.d_model
|
| 583 |
+
key_value_proj_dim = self.config.d_kv
|
| 584 |
+
n_heads = self.config.num_heads
|
| 585 |
+
init.normal_(module.q.weight, mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
|
| 586 |
+
init.normal_(module.k.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 587 |
+
init.normal_(module.v.weight, mean=0.0, std=factor * (d_model**-0.5))
|
| 588 |
+
init.normal_(module.o.weight, mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
|
| 589 |
+
if module.has_relative_attention_bias:
|
| 590 |
+
init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5))
|
| 591 |
+
|
| 592 |
+
def _shift_right(self, input_ids):
|
| 593 |
+
decoder_start_token_id = self.config.decoder_start_token_id
|
| 594 |
+
pad_token_id = self.config.pad_token_id
|
| 595 |
+
|
| 596 |
+
if decoder_start_token_id is None:
|
| 597 |
+
raise ValueError(
|
| 598 |
+
"self.model.config.decoder_start_token_id has to be defined. In MT5 it is usually set to the pad_token_id. "
|
| 599 |
+
"See MT5 docs for more information."
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 603 |
+
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
|
| 604 |
+
shifted_input_ids[..., 0] = decoder_start_token_id
|
| 605 |
+
|
| 606 |
+
if pad_token_id is None:
|
| 607 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 608 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 609 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 610 |
+
|
| 611 |
+
return shifted_input_ids
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
# Copied from transformers.models.t5.modeling_t5.T5Stack with T5->MT5
|
| 615 |
+
class MT5Stack(MT5PreTrainedModel):
|
| 616 |
+
def __init__(self, config):
|
| 617 |
+
super().__init__(config)
|
| 618 |
+
|
| 619 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
|
| 620 |
+
self.is_decoder = config.is_decoder
|
| 621 |
+
|
| 622 |
+
self.block = nn.ModuleList(
|
| 623 |
+
[MT5Block(config, has_relative_attention_bias=bool(i == 0), layer_idx=i) for i in range(config.num_layers)]
|
| 624 |
+
)
|
| 625 |
+
self.final_layer_norm = MT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 626 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 627 |
+
|
| 628 |
+
# Initialize weights and apply final processing
|
| 629 |
+
self.post_init()
|
| 630 |
+
self.gradient_checkpointing = False
|
| 631 |
+
|
| 632 |
+
def set_input_embeddings(self, new_embeddings):
|
| 633 |
+
self.embed_tokens = new_embeddings
|
| 634 |
+
|
| 635 |
+
def forward(
|
| 636 |
+
self,
|
| 637 |
+
input_ids=None,
|
| 638 |
+
attention_mask=None,
|
| 639 |
+
encoder_hidden_states=None,
|
| 640 |
+
encoder_attention_mask=None,
|
| 641 |
+
inputs_embeds=None,
|
| 642 |
+
past_key_values=None,
|
| 643 |
+
use_cache=None,
|
| 644 |
+
output_attentions=None,
|
| 645 |
+
output_hidden_states=None,
|
| 646 |
+
return_dict=None,
|
| 647 |
+
**kwargs,
|
| 648 |
+
):
|
| 649 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 650 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 651 |
+
output_hidden_states = (
|
| 652 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 653 |
+
)
|
| 654 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 655 |
+
|
| 656 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 657 |
+
err_msg_prefix = "decoder_" if self.is_decoder else ""
|
| 658 |
+
raise ValueError(
|
| 659 |
+
f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
|
| 660 |
+
)
|
| 661 |
+
elif input_ids is not None:
|
| 662 |
+
input_shape = input_ids.size()
|
| 663 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 664 |
+
elif inputs_embeds is not None:
|
| 665 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 666 |
+
else:
|
| 667 |
+
err_msg_prefix = "decoder_" if self.is_decoder else ""
|
| 668 |
+
raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
|
| 669 |
+
|
| 670 |
+
if self.gradient_checkpointing and self.training:
|
| 671 |
+
if use_cache:
|
| 672 |
+
logger.warning_once(
|
| 673 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 674 |
+
)
|
| 675 |
+
use_cache = False
|
| 676 |
+
|
| 677 |
+
if inputs_embeds is None:
|
| 678 |
+
if self.embed_tokens is None:
|
| 679 |
+
raise ValueError("You have to initialize the model with valid token embeddings")
|
| 680 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 681 |
+
|
| 682 |
+
batch_size, seq_length = input_shape
|
| 683 |
+
|
| 684 |
+
if use_cache is True:
|
| 685 |
+
if not self.is_decoder:
|
| 686 |
+
raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
|
| 687 |
+
|
| 688 |
+
if self.is_decoder:
|
| 689 |
+
if use_cache and past_key_values is None:
|
| 690 |
+
if self.config.is_encoder_decoder:
|
| 691 |
+
past_key_values = EncoderDecoderCache(
|
| 692 |
+
DynamicCache(config=self.config), DynamicCache(config=self.config)
|
| 693 |
+
)
|
| 694 |
+
else:
|
| 695 |
+
past_key_values = DynamicCache(config=self.config)
|
| 696 |
+
elif not self.is_decoder:
|
| 697 |
+
# do not pass cache object down the line for encoder stack
|
| 698 |
+
# it messes indexing later in decoder-stack because cache object is modified in-place
|
| 699 |
+
past_key_values = None
|
| 700 |
+
|
| 701 |
+
if self.config.is_decoder:
|
| 702 |
+
attention_mask = create_causal_mask(
|
| 703 |
+
config=self.config,
|
| 704 |
+
inputs_embeds=inputs_embeds,
|
| 705 |
+
attention_mask=attention_mask,
|
| 706 |
+
past_key_values=past_key_values.self_attention_cache
|
| 707 |
+
if isinstance(past_key_values, EncoderDecoderCache)
|
| 708 |
+
else past_key_values,
|
| 709 |
+
)
|
| 710 |
+
else:
|
| 711 |
+
attention_mask = create_bidirectional_mask(
|
| 712 |
+
config=self.config,
|
| 713 |
+
inputs_embeds=inputs_embeds,
|
| 714 |
+
attention_mask=attention_mask,
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
encoder_extended_attention_mask = None
|
| 718 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 719 |
+
encoder_extended_attention_mask = create_bidirectional_mask(
|
| 720 |
+
config=self.config,
|
| 721 |
+
inputs_embeds=inputs_embeds,
|
| 722 |
+
attention_mask=encoder_attention_mask,
|
| 723 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
all_hidden_states = () if output_hidden_states else None
|
| 727 |
+
all_attentions = () if output_attentions else None
|
| 728 |
+
all_cross_attentions = () if (output_attentions and self.is_decoder) else None
|
| 729 |
+
position_bias = None
|
| 730 |
+
encoder_decoder_position_bias = None
|
| 731 |
+
|
| 732 |
+
hidden_states = self.dropout(inputs_embeds)
|
| 733 |
+
|
| 734 |
+
for layer_module in self.block:
|
| 735 |
+
if output_hidden_states:
|
| 736 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 737 |
+
|
| 738 |
+
layer_outputs = layer_module(
|
| 739 |
+
hidden_states,
|
| 740 |
+
attention_mask,
|
| 741 |
+
position_bias,
|
| 742 |
+
encoder_hidden_states,
|
| 743 |
+
encoder_extended_attention_mask,
|
| 744 |
+
encoder_decoder_position_bias, # as a positional argument for gradient checkpointing
|
| 745 |
+
past_key_values=past_key_values,
|
| 746 |
+
use_cache=use_cache,
|
| 747 |
+
output_attentions=output_attentions,
|
| 748 |
+
return_dict=return_dict,
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
hidden_states = layer_outputs[0]
|
| 752 |
+
|
| 753 |
+
# We share the position biases between the layers - the first layer store them
|
| 754 |
+
# layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),
|
| 755 |
+
# (cross-attention position bias), (cross-attention weights)
|
| 756 |
+
position_bias = layer_outputs[1]
|
| 757 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 758 |
+
encoder_decoder_position_bias = layer_outputs[3 if output_attentions else 2]
|
| 759 |
+
|
| 760 |
+
if output_attentions:
|
| 761 |
+
all_attentions = all_attentions + (layer_outputs[2],)
|
| 762 |
+
if self.is_decoder:
|
| 763 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[4],)
|
| 764 |
+
|
| 765 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 766 |
+
hidden_states = self.dropout(hidden_states)
|
| 767 |
+
|
| 768 |
+
# Add last layer
|
| 769 |
+
if output_hidden_states:
|
| 770 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 771 |
+
|
| 772 |
+
if not return_dict:
|
| 773 |
+
return tuple(
|
| 774 |
+
v
|
| 775 |
+
for v in [
|
| 776 |
+
hidden_states,
|
| 777 |
+
past_key_values,
|
| 778 |
+
all_hidden_states,
|
| 779 |
+
all_attentions,
|
| 780 |
+
all_cross_attentions,
|
| 781 |
+
]
|
| 782 |
+
if v is not None
|
| 783 |
+
)
|
| 784 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 785 |
+
last_hidden_state=hidden_states,
|
| 786 |
+
past_key_values=past_key_values,
|
| 787 |
+
hidden_states=all_hidden_states,
|
| 788 |
+
attentions=all_attentions,
|
| 789 |
+
cross_attentions=all_cross_attentions,
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
@auto_docstring
|
| 794 |
+
class MT5Model(MT5PreTrainedModel):
|
| 795 |
+
r"""
|
| 796 |
+
Examples:
|
| 797 |
+
|
| 798 |
+
```python
|
| 799 |
+
>>> from transformers import MT5Model, AutoTokenizer
|
| 800 |
+
|
| 801 |
+
>>> model = MT5Model.from_pretrained("google/mt5-small")
|
| 802 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
|
| 803 |
+
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
|
| 804 |
+
>>> summary = "Weiter Verhandlung in Syrien."
|
| 805 |
+
>>> inputs = tokenizer(article, return_tensors="pt")
|
| 806 |
+
>>> labels = tokenizer(text_target=summary, return_tensors="pt")
|
| 807 |
+
|
| 808 |
+
>>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
|
| 809 |
+
>>> hidden_states = outputs.last_hidden_state
|
| 810 |
+
```"""
|
| 811 |
+
|
| 812 |
+
model_type = "mt5"
|
| 813 |
+
config: MT5Config
|
| 814 |
+
_keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
|
| 815 |
+
_tied_weights_keys = {
|
| 816 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 817 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 818 |
+
}
|
| 819 |
+
|
| 820 |
+
# Copied from transformers.models.t5.modeling_t5.T5Model.__init__ with T5->MT5
|
| 821 |
+
def __init__(self, config: MT5Config):
|
| 822 |
+
super().__init__(config)
|
| 823 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 824 |
+
|
| 825 |
+
encoder_config = copy.deepcopy(config)
|
| 826 |
+
encoder_config.is_decoder = False
|
| 827 |
+
encoder_config.use_cache = False
|
| 828 |
+
self.encoder = MT5Stack(encoder_config)
|
| 829 |
+
|
| 830 |
+
decoder_config = copy.deepcopy(config)
|
| 831 |
+
decoder_config.is_decoder = True
|
| 832 |
+
decoder_config.num_layers = config.num_decoder_layers
|
| 833 |
+
self.decoder = MT5Stack(decoder_config)
|
| 834 |
+
|
| 835 |
+
# Initialize weights and apply final processing
|
| 836 |
+
self.post_init()
|
| 837 |
+
|
| 838 |
+
# Copied from transformers.models.t5.modeling_t5.T5Model.get_input_embeddings
|
| 839 |
+
def get_input_embeddings(self):
|
| 840 |
+
return self.shared
|
| 841 |
+
|
| 842 |
+
# Copied from transformers.models.t5.modeling_t5.T5Model.set_input_embeddings
|
| 843 |
+
def set_input_embeddings(self, new_embeddings):
|
| 844 |
+
self.shared = new_embeddings
|
| 845 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 846 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 847 |
+
|
| 848 |
+
@auto_docstring
|
| 849 |
+
# Copied from transformers.models.t5.modeling_t5.T5Model.forward with google-t5/->google/, T5->MT5, t5->mt5
|
| 850 |
+
def forward(
|
| 851 |
+
self,
|
| 852 |
+
input_ids: torch.LongTensor | None = None,
|
| 853 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 854 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 855 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 856 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 857 |
+
past_key_values: Cache | None = None,
|
| 858 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 859 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 860 |
+
use_cache: bool | None = None,
|
| 861 |
+
output_attentions: bool | None = None,
|
| 862 |
+
output_hidden_states: bool | None = None,
|
| 863 |
+
return_dict: bool | None = None,
|
| 864 |
+
**kwargs,
|
| 865 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqModelOutput:
|
| 866 |
+
r"""
|
| 867 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 868 |
+
Indices of input sequence tokens in the vocabulary. MT5 is a model with relative position embeddings so you
|
| 869 |
+
should be able to pad the inputs on both the right and the left.
|
| 870 |
+
|
| 871 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 872 |
+
[`PreTrainedTokenizer.__call__`] for detail.
|
| 873 |
+
|
| 874 |
+
[What are input IDs?](../glossary#input-ids)
|
| 875 |
+
|
| 876 |
+
To know more on how to prepare `input_ids` for pretraining take a look a [MT5 Training](./mt5#training).
|
| 877 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 878 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 879 |
+
|
| 880 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 881 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 882 |
+
|
| 883 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 884 |
+
|
| 885 |
+
MT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 886 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 887 |
+
|
| 888 |
+
To know more on how to prepare `decoder_input_ids` for pretraining take a look at [MT5
|
| 889 |
+
Training](./mt5#training).
|
| 890 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 891 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 892 |
+
be used by default.
|
| 893 |
+
|
| 894 |
+
Example:
|
| 895 |
+
|
| 896 |
+
```python
|
| 897 |
+
>>> from transformers import AutoTokenizer, MT5Model
|
| 898 |
+
|
| 899 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
|
| 900 |
+
>>> model = MT5Model.from_pretrained("google/mt5-small")
|
| 901 |
+
|
| 902 |
+
>>> input_ids = tokenizer(
|
| 903 |
+
... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
|
| 904 |
+
... ).input_ids # Batch size 1
|
| 905 |
+
>>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
|
| 906 |
+
|
| 907 |
+
>>> # preprocess: Prepend decoder_input_ids with start token which is pad token for MT5Model.
|
| 908 |
+
>>> # This is not needed for torch's MT5ForConditionalGeneration as it does this internally using labels arg.
|
| 909 |
+
>>> decoder_input_ids = model._shift_right(decoder_input_ids)
|
| 910 |
+
|
| 911 |
+
>>> # forward pass
|
| 912 |
+
>>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
|
| 913 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 914 |
+
```"""
|
| 915 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 916 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 917 |
+
|
| 918 |
+
# Encode if needed (training, first prediction pass)
|
| 919 |
+
if encoder_outputs is None:
|
| 920 |
+
encoder_outputs = self.encoder(
|
| 921 |
+
input_ids=input_ids,
|
| 922 |
+
attention_mask=attention_mask,
|
| 923 |
+
inputs_embeds=inputs_embeds,
|
| 924 |
+
output_attentions=output_attentions,
|
| 925 |
+
output_hidden_states=output_hidden_states,
|
| 926 |
+
return_dict=return_dict,
|
| 927 |
+
)
|
| 928 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 929 |
+
encoder_outputs = BaseModelOutput(
|
| 930 |
+
last_hidden_state=encoder_outputs[0],
|
| 931 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 932 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
hidden_states = encoder_outputs[0]
|
| 936 |
+
|
| 937 |
+
# Decode
|
| 938 |
+
decoder_outputs = self.decoder(
|
| 939 |
+
input_ids=decoder_input_ids,
|
| 940 |
+
attention_mask=decoder_attention_mask,
|
| 941 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 942 |
+
past_key_values=past_key_values,
|
| 943 |
+
encoder_hidden_states=hidden_states,
|
| 944 |
+
encoder_attention_mask=attention_mask,
|
| 945 |
+
use_cache=use_cache,
|
| 946 |
+
output_attentions=output_attentions,
|
| 947 |
+
output_hidden_states=output_hidden_states,
|
| 948 |
+
return_dict=return_dict,
|
| 949 |
+
)
|
| 950 |
+
|
| 951 |
+
if not return_dict:
|
| 952 |
+
return decoder_outputs + encoder_outputs
|
| 953 |
+
|
| 954 |
+
return Seq2SeqModelOutput(
|
| 955 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 956 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 957 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 958 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 959 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 960 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 961 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 962 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
|
| 966 |
+
@auto_docstring(
|
| 967 |
+
custom_intro="""
|
| 968 |
+
MT5 Model with a `language modeling` head on top.
|
| 969 |
+
"""
|
| 970 |
+
)
|
| 971 |
+
class MT5ForConditionalGeneration(MT5PreTrainedModel, GenerationMixin):
|
| 972 |
+
r"""
|
| 973 |
+
Examples:
|
| 974 |
+
|
| 975 |
+
```python
|
| 976 |
+
>>> from transformers import MT5ForConditionalGeneration, AutoTokenizer
|
| 977 |
+
|
| 978 |
+
>>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small")
|
| 979 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
|
| 980 |
+
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
|
| 981 |
+
>>> summary = "Weiter Verhandlung in Syrien."
|
| 982 |
+
>>> inputs = tokenizer(article, text_target=summary, return_tensors="pt")
|
| 983 |
+
|
| 984 |
+
>>> outputs = model(**inputs)
|
| 985 |
+
>>> loss = outputs.loss
|
| 986 |
+
```"""
|
| 987 |
+
|
| 988 |
+
model_type = "mt5"
|
| 989 |
+
config: MT5Config
|
| 990 |
+
_keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
|
| 991 |
+
_tied_weights_keys = {
|
| 992 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 993 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 994 |
+
"lm_head.weight": "shared.weight",
|
| 995 |
+
}
|
| 996 |
+
|
| 997 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.__init__ with T5->MT5
|
| 998 |
+
def __init__(self, config: MT5Config):
|
| 999 |
+
super().__init__(config)
|
| 1000 |
+
self.model_dim = config.d_model
|
| 1001 |
+
|
| 1002 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1003 |
+
|
| 1004 |
+
encoder_config = copy.deepcopy(config)
|
| 1005 |
+
encoder_config.is_decoder = False
|
| 1006 |
+
encoder_config.use_cache = False
|
| 1007 |
+
self.encoder = MT5Stack(encoder_config)
|
| 1008 |
+
|
| 1009 |
+
decoder_config = copy.deepcopy(config)
|
| 1010 |
+
decoder_config.is_decoder = True
|
| 1011 |
+
decoder_config.num_layers = config.num_decoder_layers
|
| 1012 |
+
self.decoder = MT5Stack(decoder_config)
|
| 1013 |
+
|
| 1014 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 1015 |
+
|
| 1016 |
+
# Initialize weights and apply final processing
|
| 1017 |
+
self.post_init()
|
| 1018 |
+
|
| 1019 |
+
def get_input_embeddings(self):
|
| 1020 |
+
return self.shared
|
| 1021 |
+
|
| 1022 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1023 |
+
self.shared = new_embeddings
|
| 1024 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 1025 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 1026 |
+
|
| 1027 |
+
@auto_docstring
|
| 1028 |
+
def forward(
|
| 1029 |
+
self,
|
| 1030 |
+
input_ids: torch.LongTensor | None = None,
|
| 1031 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 1032 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1033 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 1034 |
+
encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
|
| 1035 |
+
past_key_values: Cache | None = None,
|
| 1036 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1037 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 1038 |
+
labels: torch.LongTensor | None = None,
|
| 1039 |
+
use_cache: bool | None = None,
|
| 1040 |
+
output_attentions: bool | None = None,
|
| 1041 |
+
output_hidden_states: bool | None = None,
|
| 1042 |
+
return_dict: bool | None = None,
|
| 1043 |
+
**kwargs,
|
| 1044 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqLMOutput:
|
| 1045 |
+
r"""
|
| 1046 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1047 |
+
Indices of input sequence tokens in the vocabulary. MT5 is a model with relative position embeddings so you
|
| 1048 |
+
should be able to pad the inputs on both the right and the left.
|
| 1049 |
+
|
| 1050 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1051 |
+
[`PreTrainedTokenizer.__call__`] for detail.
|
| 1052 |
+
|
| 1053 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1054 |
+
|
| 1055 |
+
To know more on how to prepare `input_ids` for pretraining take a look a [MT5 Training](./mt5#training).
|
| 1056 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1057 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1058 |
+
|
| 1059 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1060 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1061 |
+
|
| 1062 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1063 |
+
|
| 1064 |
+
MT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 1065 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 1066 |
+
|
| 1067 |
+
To know more on how to prepare `decoder_input_ids` for pretraining take a look at [MT5
|
| 1068 |
+
Training](./mt5#training).
|
| 1069 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1070 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1071 |
+
be used by default.
|
| 1072 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1073 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
|
| 1074 |
+
config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
|
| 1075 |
+
labels in `[0, ..., config.vocab_size]`
|
| 1076 |
+
|
| 1077 |
+
Examples:
|
| 1078 |
+
|
| 1079 |
+
```python
|
| 1080 |
+
>>> from transformers import AutoTokenizer, MT5ForConditionalGeneration
|
| 1081 |
+
|
| 1082 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
|
| 1083 |
+
>>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small")
|
| 1084 |
+
|
| 1085 |
+
>>> # training
|
| 1086 |
+
>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
|
| 1087 |
+
>>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
|
| 1088 |
+
>>> outputs = model(input_ids=input_ids, labels=labels)
|
| 1089 |
+
>>> loss = outputs.loss
|
| 1090 |
+
>>> logits = outputs.logits
|
| 1091 |
+
|
| 1092 |
+
>>> # inference
|
| 1093 |
+
>>> input_ids = tokenizer(
|
| 1094 |
+
... "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
|
| 1095 |
+
... ).input_ids # Batch size 1
|
| 1096 |
+
>>> outputs = model.generate(input_ids)
|
| 1097 |
+
>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 1098 |
+
>>> # studies have shown that owning a dog is good for you.
|
| 1099 |
+
```"""
|
| 1100 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1101 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1102 |
+
|
| 1103 |
+
# Encode if needed (training, first prediction pass)
|
| 1104 |
+
if encoder_outputs is None:
|
| 1105 |
+
# Convert encoder inputs in embeddings if needed
|
| 1106 |
+
encoder_outputs = self.encoder(
|
| 1107 |
+
input_ids=input_ids,
|
| 1108 |
+
attention_mask=attention_mask,
|
| 1109 |
+
inputs_embeds=inputs_embeds,
|
| 1110 |
+
output_attentions=output_attentions,
|
| 1111 |
+
output_hidden_states=output_hidden_states,
|
| 1112 |
+
return_dict=return_dict,
|
| 1113 |
+
)
|
| 1114 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1115 |
+
encoder_outputs = BaseModelOutput(
|
| 1116 |
+
last_hidden_state=encoder_outputs[0],
|
| 1117 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1118 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1119 |
+
)
|
| 1120 |
+
|
| 1121 |
+
hidden_states = encoder_outputs[0]
|
| 1122 |
+
|
| 1123 |
+
if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1124 |
+
# get decoder inputs from shifting lm labels to the right
|
| 1125 |
+
decoder_input_ids = self._shift_right(labels)
|
| 1126 |
+
|
| 1127 |
+
# Decode
|
| 1128 |
+
decoder_outputs = self.decoder(
|
| 1129 |
+
input_ids=decoder_input_ids,
|
| 1130 |
+
attention_mask=decoder_attention_mask,
|
| 1131 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1132 |
+
past_key_values=past_key_values,
|
| 1133 |
+
encoder_hidden_states=hidden_states,
|
| 1134 |
+
encoder_attention_mask=attention_mask,
|
| 1135 |
+
use_cache=use_cache,
|
| 1136 |
+
output_attentions=output_attentions,
|
| 1137 |
+
output_hidden_states=output_hidden_states,
|
| 1138 |
+
return_dict=return_dict,
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
sequence_output = decoder_outputs[0]
|
| 1142 |
+
|
| 1143 |
+
lm_logits = self.lm_head(sequence_output)
|
| 1144 |
+
|
| 1145 |
+
loss = None
|
| 1146 |
+
if labels is not None:
|
| 1147 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
| 1148 |
+
# move labels to correct device to enable PP
|
| 1149 |
+
labels = labels.to(lm_logits.device)
|
| 1150 |
+
loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
|
| 1151 |
+
|
| 1152 |
+
if not return_dict:
|
| 1153 |
+
output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
|
| 1154 |
+
return ((loss,) + output) if loss is not None else output
|
| 1155 |
+
|
| 1156 |
+
return Seq2SeqLMOutput(
|
| 1157 |
+
loss=loss,
|
| 1158 |
+
logits=lm_logits,
|
| 1159 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1160 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1161 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1162 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1163 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1164 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1165 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1166 |
+
)
|
| 1167 |
+
|
| 1168 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.prepare_decoder_input_ids_from_labels
|
| 1169 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 1170 |
+
return self._shift_right(labels)
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
@auto_docstring
|
| 1174 |
+
class MT5EncoderModel(MT5PreTrainedModel):
|
| 1175 |
+
r"""
|
| 1176 |
+
Examples:
|
| 1177 |
+
|
| 1178 |
+
```python
|
| 1179 |
+
>>> from transformers import MT5EncoderModel, AutoTokenizer
|
| 1180 |
+
|
| 1181 |
+
>>> model = MT5EncoderModel.from_pretrained("google/mt5-small")
|
| 1182 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
|
| 1183 |
+
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
|
| 1184 |
+
>>> input_ids = tokenizer(article, return_tensors="pt").input_ids
|
| 1185 |
+
>>> outputs = model(input_ids)
|
| 1186 |
+
>>> hidden_state = outputs.last_hidden_state
|
| 1187 |
+
```"""
|
| 1188 |
+
|
| 1189 |
+
model_type = "mt5"
|
| 1190 |
+
config: MT5Config
|
| 1191 |
+
_tied_weights_keys = {
|
| 1192 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 1193 |
+
}
|
| 1194 |
+
|
| 1195 |
+
# Copied from transformers.models.t5.modeling_t5.T5EncoderModel.__init__ with T5->MT5
|
| 1196 |
+
def __init__(self, config: MT5Config):
|
| 1197 |
+
super().__init__(config)
|
| 1198 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1199 |
+
|
| 1200 |
+
encoder_config = config
|
| 1201 |
+
encoder_config.use_cache = False
|
| 1202 |
+
encoder_config.is_encoder_decoder = False
|
| 1203 |
+
self.encoder = MT5Stack(encoder_config)
|
| 1204 |
+
|
| 1205 |
+
# Initialize weights and apply final processing
|
| 1206 |
+
self.post_init()
|
| 1207 |
+
|
| 1208 |
+
# Copied from transformers.models.t5.modeling_t5.T5EncoderModel.get_input_embeddings
|
| 1209 |
+
def get_input_embeddings(self):
|
| 1210 |
+
return self.shared
|
| 1211 |
+
|
| 1212 |
+
# Copied from transformers.models.t5.modeling_t5.T5EncoderModel.set_input_embeddings
|
| 1213 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1214 |
+
self.shared = new_embeddings
|
| 1215 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 1216 |
+
|
| 1217 |
+
@auto_docstring
|
| 1218 |
+
# Copied from transformers.models.t5.modeling_t5.T5EncoderModel.forward with google-t5/->google/, T5->MT5, t5->mt5
|
| 1219 |
+
def forward(
|
| 1220 |
+
self,
|
| 1221 |
+
input_ids: torch.LongTensor | None = None,
|
| 1222 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 1223 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1224 |
+
output_attentions: bool | None = None,
|
| 1225 |
+
output_hidden_states: bool | None = None,
|
| 1226 |
+
return_dict: bool | None = None,
|
| 1227 |
+
**kwargs,
|
| 1228 |
+
) -> tuple[torch.FloatTensor] | BaseModelOutput:
|
| 1229 |
+
r"""
|
| 1230 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1231 |
+
Indices of input sequence tokens in the vocabulary. MT5 is a model with relative position embeddings so you
|
| 1232 |
+
should be able to pad the inputs on both the right and the left.
|
| 1233 |
+
|
| 1234 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1235 |
+
[`PreTrainedTokenizer.__call__`] for detail.
|
| 1236 |
+
|
| 1237 |
+
To know more on how to prepare `input_ids` for pretraining take a look a [MT5 Training](./mt5#training).
|
| 1238 |
+
|
| 1239 |
+
Example:
|
| 1240 |
+
|
| 1241 |
+
```python
|
| 1242 |
+
>>> from transformers import AutoTokenizer, MT5EncoderModel
|
| 1243 |
+
|
| 1244 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
|
| 1245 |
+
>>> model = MT5EncoderModel.from_pretrained("google/mt5-small")
|
| 1246 |
+
>>> input_ids = tokenizer(
|
| 1247 |
+
... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
|
| 1248 |
+
... ).input_ids # Batch size 1
|
| 1249 |
+
>>> outputs = model(input_ids=input_ids)
|
| 1250 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1251 |
+
```"""
|
| 1252 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1253 |
+
|
| 1254 |
+
encoder_outputs = self.encoder(
|
| 1255 |
+
input_ids=input_ids,
|
| 1256 |
+
attention_mask=attention_mask,
|
| 1257 |
+
inputs_embeds=inputs_embeds,
|
| 1258 |
+
output_attentions=output_attentions,
|
| 1259 |
+
output_hidden_states=output_hidden_states,
|
| 1260 |
+
return_dict=return_dict,
|
| 1261 |
+
)
|
| 1262 |
+
|
| 1263 |
+
return encoder_outputs
|
| 1264 |
+
|
| 1265 |
+
|
| 1266 |
+
@auto_docstring(
|
| 1267 |
+
custom_intro="""
|
| 1268 |
+
MT5 model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
|
| 1269 |
+
tasks.
|
| 1270 |
+
"""
|
| 1271 |
+
)
|
| 1272 |
+
class MT5ForSequenceClassification(MT5PreTrainedModel):
|
| 1273 |
+
_keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
|
| 1274 |
+
|
| 1275 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForSequenceClassification.__init__ with T5->MT5
|
| 1276 |
+
def __init__(self, config: MT5Config):
|
| 1277 |
+
super().__init__(config)
|
| 1278 |
+
self.transformer = MT5Model(config)
|
| 1279 |
+
self.classification_head = MT5ClassificationHead(config)
|
| 1280 |
+
|
| 1281 |
+
# Initialize weights and apply final processing
|
| 1282 |
+
self.post_init()
|
| 1283 |
+
|
| 1284 |
+
@auto_docstring
|
| 1285 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForSequenceClassification.forward with T5->MT5, t5->mt5
|
| 1286 |
+
def forward(
|
| 1287 |
+
self,
|
| 1288 |
+
input_ids: torch.LongTensor | None = None,
|
| 1289 |
+
attention_mask: torch.Tensor | None = None,
|
| 1290 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1291 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 1292 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 1293 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1294 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 1295 |
+
labels: torch.LongTensor | None = None,
|
| 1296 |
+
use_cache: bool | None = None,
|
| 1297 |
+
output_attentions: bool | None = None,
|
| 1298 |
+
output_hidden_states: bool | None = None,
|
| 1299 |
+
return_dict: bool | None = None,
|
| 1300 |
+
**kwargs,
|
| 1301 |
+
) -> tuple | Seq2SeqSequenceClassifierOutput:
|
| 1302 |
+
r"""
|
| 1303 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1304 |
+
Indices of input sequence tokens in the vocabulary. MT5 is a model with relative position embeddings so you
|
| 1305 |
+
should be able to pad the inputs on both the right and the left.
|
| 1306 |
+
|
| 1307 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1308 |
+
[`PreTrainedTokenizer.__call__`] for detail.
|
| 1309 |
+
|
| 1310 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1311 |
+
|
| 1312 |
+
To know more on how to prepare `input_ids` for pretraining take a look a [MT5 Training](./mt5#training).
|
| 1313 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1314 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1315 |
+
|
| 1316 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1317 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1318 |
+
|
| 1319 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1320 |
+
|
| 1321 |
+
MT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 1322 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 1323 |
+
|
| 1324 |
+
To know more on how to prepare `decoder_input_ids` for pretraining take a look at [MT5
|
| 1325 |
+
Training](./mt5#training).
|
| 1326 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1327 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1328 |
+
be used by default.
|
| 1329 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1330 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1331 |
+
config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1332 |
+
"""
|
| 1333 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1334 |
+
if labels is not None:
|
| 1335 |
+
use_cache = False
|
| 1336 |
+
|
| 1337 |
+
if input_ids is None and inputs_embeds is not None:
|
| 1338 |
+
raise NotImplementedError(
|
| 1339 |
+
f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
|
| 1340 |
+
)
|
| 1341 |
+
|
| 1342 |
+
# Copied from models.bart.modeling_bart.BartModel.forward different to other models, MT5 automatically creates
|
| 1343 |
+
# decoder_input_ids from input_ids if no decoder_input_ids are provided
|
| 1344 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1345 |
+
if input_ids is None:
|
| 1346 |
+
raise ValueError(
|
| 1347 |
+
"If no `decoder_input_ids` or `decoder_inputs_embeds` are "
|
| 1348 |
+
"passed, `input_ids` cannot be `None`. Please pass either "
|
| 1349 |
+
"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
|
| 1350 |
+
)
|
| 1351 |
+
decoder_input_ids = self._shift_right(input_ids)
|
| 1352 |
+
|
| 1353 |
+
outputs = self.transformer(
|
| 1354 |
+
input_ids,
|
| 1355 |
+
attention_mask=attention_mask,
|
| 1356 |
+
decoder_input_ids=decoder_input_ids,
|
| 1357 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1358 |
+
encoder_outputs=encoder_outputs,
|
| 1359 |
+
inputs_embeds=inputs_embeds,
|
| 1360 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1361 |
+
use_cache=use_cache,
|
| 1362 |
+
output_attentions=output_attentions,
|
| 1363 |
+
output_hidden_states=output_hidden_states,
|
| 1364 |
+
return_dict=return_dict,
|
| 1365 |
+
)
|
| 1366 |
+
sequence_output = outputs[0]
|
| 1367 |
+
|
| 1368 |
+
eos_mask = input_ids.eq(self.config.eos_token_id).to(sequence_output.device)
|
| 1369 |
+
|
| 1370 |
+
torch_compilable_check(
|
| 1371 |
+
torch.unique_consecutive(eos_mask.sum(1)).numel() == 1,
|
| 1372 |
+
"All examples must have the same number of <eos> tokens.",
|
| 1373 |
+
)
|
| 1374 |
+
batch_size, _, hidden_size = sequence_output.shape
|
| 1375 |
+
sentence_representation = sequence_output[eos_mask, :].view(batch_size, -1, hidden_size)[:, -1, :]
|
| 1376 |
+
logits = self.classification_head(sentence_representation)
|
| 1377 |
+
|
| 1378 |
+
loss = None
|
| 1379 |
+
if labels is not None:
|
| 1380 |
+
labels = labels.to(logits.device)
|
| 1381 |
+
if self.config.problem_type is None:
|
| 1382 |
+
if self.config.num_labels == 1:
|
| 1383 |
+
self.config.problem_type = "regression"
|
| 1384 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1385 |
+
self.config.problem_type = "single_label_classification"
|
| 1386 |
+
else:
|
| 1387 |
+
self.config.problem_type = "multi_label_classification"
|
| 1388 |
+
|
| 1389 |
+
if self.config.problem_type == "regression":
|
| 1390 |
+
loss_fct = MSELoss()
|
| 1391 |
+
if self.config.num_labels == 1:
|
| 1392 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1393 |
+
else:
|
| 1394 |
+
loss = loss_fct(logits, labels)
|
| 1395 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1396 |
+
loss_fct = CrossEntropyLoss()
|
| 1397 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 1398 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1399 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1400 |
+
loss = loss_fct(logits, labels)
|
| 1401 |
+
if not return_dict:
|
| 1402 |
+
output = (logits,) + outputs[1:]
|
| 1403 |
+
return ((loss,) + output) if loss is not None else output
|
| 1404 |
+
|
| 1405 |
+
return Seq2SeqSequenceClassifierOutput(
|
| 1406 |
+
loss=loss,
|
| 1407 |
+
logits=logits,
|
| 1408 |
+
past_key_values=outputs.past_key_values,
|
| 1409 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1410 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1411 |
+
cross_attentions=outputs.cross_attentions,
|
| 1412 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1413 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1414 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1415 |
+
)
|
| 1416 |
+
|
| 1417 |
+
|
| 1418 |
+
@auto_docstring
|
| 1419 |
+
class MT5ForTokenClassification(MT5PreTrainedModel):
|
| 1420 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.__init__ with T5->MT5
|
| 1421 |
+
def __init__(self, config: MT5Config):
|
| 1422 |
+
super().__init__(config)
|
| 1423 |
+
self.num_labels = config.num_labels
|
| 1424 |
+
|
| 1425 |
+
self.transformer = MT5EncoderModel(config)
|
| 1426 |
+
self.dropout = nn.Dropout(config.classifier_dropout)
|
| 1427 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1428 |
+
|
| 1429 |
+
# Initialize weights and apply final processing
|
| 1430 |
+
self.post_init()
|
| 1431 |
+
|
| 1432 |
+
@auto_docstring
|
| 1433 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.forward with T5->MT5
|
| 1434 |
+
def forward(
|
| 1435 |
+
self,
|
| 1436 |
+
input_ids: torch.Tensor | None = None,
|
| 1437 |
+
attention_mask: torch.Tensor | None = None,
|
| 1438 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1439 |
+
labels: torch.Tensor | None = None,
|
| 1440 |
+
output_attentions: bool | None = None,
|
| 1441 |
+
output_hidden_states: bool | None = None,
|
| 1442 |
+
return_dict: bool | None = None,
|
| 1443 |
+
**kwargs,
|
| 1444 |
+
) -> tuple[torch.Tensor] | TokenClassifierOutput:
|
| 1445 |
+
r"""
|
| 1446 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1447 |
+
Indices of input sequence tokens in the vocabulary. MT5 is a model with relative position embeddings so you
|
| 1448 |
+
should be able to pad the inputs on both the right and the left.
|
| 1449 |
+
|
| 1450 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1451 |
+
[`PreTrainedTokenizer.__call__`] for detail.
|
| 1452 |
+
|
| 1453 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1454 |
+
|
| 1455 |
+
To know more on how to prepare `input_ids` for pretraining take a look a [MT5 Training](./t5#training).
|
| 1456 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1457 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1458 |
+
"""
|
| 1459 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1460 |
+
|
| 1461 |
+
outputs = self.transformer(
|
| 1462 |
+
input_ids,
|
| 1463 |
+
attention_mask=attention_mask,
|
| 1464 |
+
inputs_embeds=inputs_embeds,
|
| 1465 |
+
output_attentions=output_attentions,
|
| 1466 |
+
output_hidden_states=output_hidden_states,
|
| 1467 |
+
return_dict=return_dict,
|
| 1468 |
+
)
|
| 1469 |
+
|
| 1470 |
+
hidden_states = outputs[0]
|
| 1471 |
+
hidden_states = self.dropout(hidden_states)
|
| 1472 |
+
logits = self.classifier(hidden_states)
|
| 1473 |
+
|
| 1474 |
+
loss = None
|
| 1475 |
+
if labels is not None:
|
| 1476 |
+
loss_fct = CrossEntropyLoss()
|
| 1477 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1478 |
+
|
| 1479 |
+
if not return_dict:
|
| 1480 |
+
output = (logits, outputs[2:-1])
|
| 1481 |
+
return ((loss,) + output) if loss is not None else output
|
| 1482 |
+
|
| 1483 |
+
return TokenClassifierOutput(
|
| 1484 |
+
loss=loss,
|
| 1485 |
+
logits=logits,
|
| 1486 |
+
hidden_states=outputs.hidden_states,
|
| 1487 |
+
attentions=outputs.attentions,
|
| 1488 |
+
)
|
| 1489 |
+
|
| 1490 |
+
|
| 1491 |
+
@auto_docstring
|
| 1492 |
+
class MT5ForQuestionAnswering(MT5PreTrainedModel):
|
| 1493 |
+
_keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
|
| 1494 |
+
_tied_weights_keys = {
|
| 1495 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 1496 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 1497 |
+
}
|
| 1498 |
+
|
| 1499 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.__init__ with T5->MT5
|
| 1500 |
+
def __init__(self, config: MT5Config):
|
| 1501 |
+
super().__init__(config)
|
| 1502 |
+
self.model_dim = config.d_model
|
| 1503 |
+
|
| 1504 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1505 |
+
|
| 1506 |
+
encoder_config = copy.deepcopy(config)
|
| 1507 |
+
encoder_config.is_decoder = False
|
| 1508 |
+
encoder_config.use_cache = False
|
| 1509 |
+
self.encoder = MT5Stack(encoder_config)
|
| 1510 |
+
|
| 1511 |
+
decoder_config = copy.deepcopy(config)
|
| 1512 |
+
decoder_config.is_decoder = True
|
| 1513 |
+
decoder_config.num_layers = config.num_decoder_layers
|
| 1514 |
+
self.decoder = MT5Stack(decoder_config)
|
| 1515 |
+
|
| 1516 |
+
self.num_labels = config.num_labels
|
| 1517 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1518 |
+
|
| 1519 |
+
# Initialize weights and apply final processing
|
| 1520 |
+
self.post_init()
|
| 1521 |
+
|
| 1522 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_input_embeddings
|
| 1523 |
+
def get_input_embeddings(self):
|
| 1524 |
+
return self.shared
|
| 1525 |
+
|
| 1526 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.set_input_embeddings
|
| 1527 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1528 |
+
self.shared = new_embeddings
|
| 1529 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
| 1530 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
| 1531 |
+
|
| 1532 |
+
@auto_docstring
|
| 1533 |
+
# Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.forward
|
| 1534 |
+
def forward(
|
| 1535 |
+
self,
|
| 1536 |
+
input_ids: torch.LongTensor | None = None,
|
| 1537 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 1538 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1539 |
+
decoder_attention_mask: torch.BoolTensor | None = None,
|
| 1540 |
+
encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
|
| 1541 |
+
start_positions: torch.LongTensor | None = None,
|
| 1542 |
+
end_positions: torch.LongTensor | None = None,
|
| 1543 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1544 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 1545 |
+
use_cache: bool | None = None,
|
| 1546 |
+
output_attentions: bool | None = None,
|
| 1547 |
+
output_hidden_states: bool | None = None,
|
| 1548 |
+
return_dict: bool | None = None,
|
| 1549 |
+
**kwargs,
|
| 1550 |
+
) -> tuple[torch.FloatTensor] | Seq2SeqQuestionAnsweringModelOutput:
|
| 1551 |
+
r"""
|
| 1552 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1553 |
+
Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
|
| 1554 |
+
should be able to pad the inputs on both the right and the left.
|
| 1555 |
+
|
| 1556 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1557 |
+
[`PreTrainedTokenizer.__call__`] for detail.
|
| 1558 |
+
|
| 1559 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1560 |
+
|
| 1561 |
+
To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
|
| 1562 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1563 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1564 |
+
|
| 1565 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1566 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1567 |
+
|
| 1568 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1569 |
+
|
| 1570 |
+
T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 1571 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 1572 |
+
|
| 1573 |
+
To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
|
| 1574 |
+
Training](./t5#training).
|
| 1575 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1576 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1577 |
+
be used by default.
|
| 1578 |
+
"""
|
| 1579 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1580 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1581 |
+
if start_positions is not None and end_positions is not None:
|
| 1582 |
+
use_cache = False
|
| 1583 |
+
|
| 1584 |
+
# Copied from models.bart.modeling_bart.BartModel.forward
|
| 1585 |
+
# different to other models, T5 automatically creates decoder_input_ids from
|
| 1586 |
+
# input_ids if no decoder_input_ids are provided
|
| 1587 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1588 |
+
if input_ids is None:
|
| 1589 |
+
raise ValueError(
|
| 1590 |
+
"If no `decoder_input_ids` or `decoder_inputs_embeds` are "
|
| 1591 |
+
"passed, `input_ids` cannot be `None`. Please pass either "
|
| 1592 |
+
"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
|
| 1593 |
+
)
|
| 1594 |
+
decoder_input_ids = self._shift_right(input_ids)
|
| 1595 |
+
|
| 1596 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1597 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1598 |
+
|
| 1599 |
+
# Encode if needed (training, first prediction pass)
|
| 1600 |
+
if encoder_outputs is None:
|
| 1601 |
+
encoder_outputs = self.encoder(
|
| 1602 |
+
input_ids=input_ids,
|
| 1603 |
+
attention_mask=attention_mask,
|
| 1604 |
+
inputs_embeds=inputs_embeds,
|
| 1605 |
+
output_attentions=output_attentions,
|
| 1606 |
+
output_hidden_states=output_hidden_states,
|
| 1607 |
+
return_dict=return_dict,
|
| 1608 |
+
)
|
| 1609 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1610 |
+
encoder_outputs = BaseModelOutput(
|
| 1611 |
+
last_hidden_state=encoder_outputs[0],
|
| 1612 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1613 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1614 |
+
)
|
| 1615 |
+
|
| 1616 |
+
hidden_states = encoder_outputs[0]
|
| 1617 |
+
|
| 1618 |
+
# Decode
|
| 1619 |
+
decoder_outputs = self.decoder(
|
| 1620 |
+
input_ids=decoder_input_ids,
|
| 1621 |
+
attention_mask=decoder_attention_mask,
|
| 1622 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1623 |
+
past_key_values=None,
|
| 1624 |
+
encoder_hidden_states=hidden_states,
|
| 1625 |
+
encoder_attention_mask=attention_mask,
|
| 1626 |
+
use_cache=use_cache,
|
| 1627 |
+
output_attentions=output_attentions,
|
| 1628 |
+
output_hidden_states=output_hidden_states,
|
| 1629 |
+
return_dict=return_dict,
|
| 1630 |
+
)
|
| 1631 |
+
|
| 1632 |
+
sequence_output = decoder_outputs[0]
|
| 1633 |
+
|
| 1634 |
+
logits = self.qa_outputs(sequence_output)
|
| 1635 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1636 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1637 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1638 |
+
|
| 1639 |
+
total_loss = None
|
| 1640 |
+
if start_positions is not None and end_positions is not None:
|
| 1641 |
+
# If we are on multi-GPU, split add a dimension
|
| 1642 |
+
if len(start_positions.size()) > 1:
|
| 1643 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
| 1644 |
+
if len(end_positions.size()) > 1:
|
| 1645 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
| 1646 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1647 |
+
ignored_index = start_logits.size(1)
|
| 1648 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1649 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1650 |
+
|
| 1651 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1652 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1653 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1654 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1655 |
+
|
| 1656 |
+
if not return_dict:
|
| 1657 |
+
output = (start_logits, end_logits) + decoder_outputs[1:] + encoder_outputs
|
| 1658 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1659 |
+
|
| 1660 |
+
return Seq2SeqQuestionAnsweringModelOutput(
|
| 1661 |
+
loss=total_loss,
|
| 1662 |
+
start_logits=start_logits,
|
| 1663 |
+
end_logits=end_logits,
|
| 1664 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1665 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1666 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1667 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1668 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1669 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1670 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1671 |
+
)
|
| 1672 |
+
|
| 1673 |
+
|
| 1674 |
+
__all__ = [
|
| 1675 |
+
"MT5EncoderModel",
|
| 1676 |
+
"MT5ForConditionalGeneration",
|
| 1677 |
+
"MT5ForQuestionAnswering",
|
| 1678 |
+
"MT5ForSequenceClassification",
|
| 1679 |
+
"MT5ForTokenClassification",
|
| 1680 |
+
"MT5Model",
|
| 1681 |
+
"MT5PreTrainedModel",
|
| 1682 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/run_owt_t5_elftokenized_full_len1024_d768_16gpu_50epochs_C1_toV_exp_elfopt_t5embed_unfixed_adaln_rope_noabspos_stateprobadd_selfcond_ce_fast_lr3e4.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
cd /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/mini_owt_logdirichlet
|
| 5 |
+
|
| 6 |
+
export T5_MODEL_PATH="${T5_MODEL_PATH:-/e2e-data/evad-tech-vla/wanghan58/models/hf/t5-small}"
|
| 7 |
+
export TOKENIZER_PATH="${TOKENIZER_PATH:-${T5_MODEL_PATH}/tokenizer.json}"
|
| 8 |
+
export CMIN="${CMIN:-1}"
|
| 9 |
+
export C_SCHEDULE="${C_SCHEDULE:-exp}"
|
| 10 |
+
if [[ -z "${CMAX:-}" ]]; then
|
| 11 |
+
CMAX="$(TOKENIZER_PATH="${TOKENIZER_PATH}" python3 - <<'PY'
|
| 12 |
+
import os
|
| 13 |
+
from tokenizers import Tokenizer
|
| 14 |
+
print(Tokenizer.from_file(os.environ["TOKENIZER_PATH"]).get_vocab_size())
|
| 15 |
+
PY
|
| 16 |
+
)"
|
| 17 |
+
fi
|
| 18 |
+
export CMAX
|
| 19 |
+
|
| 20 |
+
DATE_TAG="${DATE_TAG:-$(date +%Y%m%d_%H%M%S)}"
|
| 21 |
+
export DATE_TAG
|
| 22 |
+
export RUN_NAME="${RUN_NAME:-owt_t5_elftokenized_full_len1024_C1_toV_exp_d768_l12_h12_gbs512_16gpu_50ep_lr3e4_elfopt_t5embed_unfixed_adaln_rope_noabspos_stateprobadd_selfcond_ce_fast_${DATE_TAG}}"
|
| 23 |
+
export OUT_DIR="${OUT_DIR:-runs/${RUN_NAME}}"
|
| 24 |
+
export LOG_FILE="${LOG_FILE:-logs/${RUN_NAME}.log}"
|
| 25 |
+
|
| 26 |
+
exec bash run_owt_t5_elftokenized_full_len1024_d768_16gpu_50epochs_C1_to1024_pow1_elfopt_t5embed_unfixed_adaln_rope_noabspos_stateprobadd_selfcond_ce_fast_lr3e4.sh
|